diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41a54c0873c13a1034c0e5d1199138410729635e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/keywords/absolutePath.d.ts @@ -0,0 +1,11 @@ +export default addAbsolutePathKeyword; +export type Ajv = import("ajv").default; +export type SchemaValidateFunction = import("ajv").SchemaValidateFunction; +export type AnySchemaObject = import("ajv").AnySchemaObject; +export type SchemaUtilErrorObject = import("../validate").SchemaUtilErrorObject; +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +declare function addAbsolutePathKeyword(ajv: Ajv): Ajv; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/keywords/limit.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/keywords/limit.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..70e371545205f68267064c4d2a4cbd39bb8bde2a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/keywords/limit.d.ts @@ -0,0 +1,14 @@ +export default addLimitKeyword; +export type Ajv = import("ajv").default; +export type Code = import("ajv").Code; +export type Name = import("ajv").Name; +export type KeywordErrorDefinition = import("ajv").KeywordErrorDefinition; +/** @typedef {import("ajv").default} Ajv */ +/** @typedef {import("ajv").Code} Code */ +/** @typedef {import("ajv").Name} Name */ +/** @typedef {import("ajv").KeywordErrorDefinition} KeywordErrorDefinition */ +/** + * @param {Ajv} ajv + * @returns {Ajv} + */ +declare function addLimitKeyword(ajv: Ajv): Ajv; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/keywords/undefinedAsNull.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/keywords/undefinedAsNull.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62a6604cdd5be49e4f2e2e855adcc5e99714a78f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/keywords/undefinedAsNull.d.ts @@ -0,0 +1,15 @@ +export default addUndefinedAsNullKeyword; +export type Ajv = import("ajv").default; +export type SchemaValidateFunction = import("ajv").SchemaValidateFunction; +export type AnySchemaObject = import("ajv").AnySchemaObject; +export type ValidateFunction = import("ajv").ValidateFunction; +/** @typedef {import("ajv").default} Ajv */ +/** @typedef {import("ajv").SchemaValidateFunction} SchemaValidateFunction */ +/** @typedef {import("ajv").AnySchemaObject} AnySchemaObject */ +/** @typedef {import("ajv").ValidateFunction} ValidateFunction */ +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +declare function addUndefinedAsNullKeyword(ajv: Ajv): Ajv; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/util/Range.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/util/Range.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ba97fc1a3649a4f04a587d4cde3a2f7aed3aeeb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/util/Range.d.ts @@ -0,0 +1,79 @@ +export = Range; +/** + * @typedef {[number, boolean]} RangeValue + */ +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ +declare class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator( + side: "left" | "right", + exclusive: boolean + ): ">" | ">=" | "<" | "<="; + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatRight(value: number, logic: boolean, exclusive: boolean): string; + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatLeft(value: number, logic: boolean, exclusive: boolean): string; + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ + static formatRange( + start: number, + end: number, + startExclusive: boolean, + endExclusive: boolean, + logic: boolean + ): string; + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ + static getRangeValue(values: Array, logic: boolean): RangeValue; + /** @type {Array} */ + _left: Array; + /** @type {Array} */ + _right: Array; + /** + * @param {number} value + * @param {boolean=} exclusive + */ + left(value: number, exclusive?: boolean | undefined): void; + /** + * @param {number} value + * @param {boolean=} exclusive + */ + right(value: number, exclusive?: boolean | undefined): void; + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ + format(logic?: boolean): string; +} +declare namespace Range { + export { RangeValue, RangeValueCallback }; +} +type RangeValue = [number, boolean]; +type RangeValueCallback = (rangeValue: RangeValue) => boolean; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/util/hints.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/util/hints.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e43e32a2292b2b0e27a6640fb75779ac7c7c6380 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/util/hints.d.ts @@ -0,0 +1,3 @@ +export function stringHints(schema: Schema, logic: boolean): string[]; +export function numberHints(schema: Schema, logic: boolean): string[]; +export type Schema = import("../validate").Schema; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/util/memorize.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/util/memorize.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5c9968ff46ec2d7d457a0db875c4ff625ff8610c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/declarations/util/memorize.d.ts @@ -0,0 +1,7 @@ +export default memoize; +/** + * @template T + * @param fn {(function(): any) | undefined} + * @returns {function(): T} + */ +declare function memoize(fn: (() => any) | undefined): () => T; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/keywords/absolutePath.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/keywords/absolutePath.js new file mode 100644 index 0000000000000000000000000000000000000000..ee9f44434a2c5e690e93384c560c717fa8896a48 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/keywords/absolutePath.js @@ -0,0 +1,87 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +/** @typedef {import("ajv").default} Ajv */ +/** @typedef {import("ajv").SchemaValidateFunction} SchemaValidateFunction */ +/** @typedef {import("ajv").AnySchemaObject} AnySchemaObject */ +/** @typedef {import("../validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ + +/** + * @param {string} message + * @param {object} schema + * @param {string} data + * @returns {SchemaUtilErrorObject} + */ +function errorMessage(message, schema, data) { + return { + // @ts-ignore + // eslint-disable-next-line no-undefined + dataPath: undefined, + // @ts-ignore + // eslint-disable-next-line no-undefined + schemaPath: undefined, + keyword: "absolutePath", + params: { + absolutePath: data + }, + message, + parentSchema: schema + }; +} + +/** + * @param {boolean} shouldBeAbsolute + * @param {object} schema + * @param {string} data + * @returns {SchemaUtilErrorObject} + */ +function getErrorFor(shouldBeAbsolute, schema, data) { + const message = shouldBeAbsolute ? `The provided value ${JSON.stringify(data)} is not an absolute path!` : `A relative path is expected. However, the provided value ${JSON.stringify(data)} is an absolute path!`; + return errorMessage(message, schema, data); +} + +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +function addAbsolutePathKeyword(ajv) { + ajv.addKeyword({ + keyword: "absolutePath", + type: "string", + errors: true, + /** + * @param {boolean} schema + * @param {AnySchemaObject} parentSchema + * @returns {SchemaValidateFunction} + */ + compile(schema, parentSchema) { + /** @type {SchemaValidateFunction} */ + const callback = data => { + let passes = true; + const isExclamationMarkPresent = data.includes("!"); + if (isExclamationMarkPresent) { + callback.errors = [errorMessage(`The provided value ${JSON.stringify(data)} contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.`, parentSchema, data)]; + passes = false; + } + + // ?:[A-Za-z]:\\ - Windows absolute path + // \\\\ - Windows network absolute path + // \/ - Unix-like OS absolute path + const isCorrectAbsolutePath = schema === /^(?:[A-Za-z]:(\\|\/)|\\\\|\/)/.test(data); + if (!isCorrectAbsolutePath) { + callback.errors = [getErrorFor(schema, parentSchema, data)]; + passes = false; + } + return passes; + }; + callback.errors = []; + return callback; + } + }); + return ajv; +} +var _default = exports.default = addAbsolutePathKeyword; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/keywords/limit.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/keywords/limit.js new file mode 100644 index 0000000000000000000000000000000000000000..127cdea40f843af2b0d23294f4591a2662ccc057 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/keywords/limit.js @@ -0,0 +1,158 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +/** @typedef {import("ajv").default} Ajv */ +/** @typedef {import("ajv").Code} Code */ +/** @typedef {import("ajv").Name} Name */ +/** @typedef {import("ajv").KeywordErrorDefinition} KeywordErrorDefinition */ + +/** + * @param {Ajv} ajv + * @returns {Ajv} + */ +function addLimitKeyword(ajv) { + // eslint-disable-next-line global-require + const { + _, + str, + KeywordCxt, + nil, + Name + } = require("ajv"); + + /** + * @param {Code | Name} x + * @returns {Code | Name} + */ + function par(x) { + return x instanceof Name ? x : _`(${x})`; + } + + /** + * @param {Code} op + * @returns {function(Code, Code): Code} + */ + function mappend(op) { + return (x, y) => x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`; + } + const orCode = mappend(_`||`); + + // boolean OR (||) expression with the passed arguments + /** + * @param {...Code} args + * @returns {Code} + */ + function or(...args) { + return args.reduce(orCode); + } + + /** + * @param {string | number} key + * @returns {Code} + */ + function getProperty(key) { + return _`[${key}]`; + } + const keywords = { + formatMaximum: { + okStr: "<=", + ok: _`<=`, + fail: _`>` + }, + formatMinimum: { + okStr: ">=", + ok: _`>=`, + fail: _`<` + }, + formatExclusiveMaximum: { + okStr: "<", + ok: _`<`, + fail: _`>=` + }, + formatExclusiveMinimum: { + okStr: ">", + ok: _`>`, + fail: _`<=` + } + }; + + /** @type {KeywordErrorDefinition} */ + const error = { + message: ({ + keyword, + schemaCode + }) => str`should be ${keywords[(/** @type {keyof typeof keywords} */keyword)].okStr} ${schemaCode}`, + params: ({ + keyword, + schemaCode + }) => _`{comparison: ${keywords[(/** @type {keyof typeof keywords} */keyword)].okStr}, limit: ${schemaCode}}` + }; + for (const keyword of Object.keys(keywords)) { + ajv.addKeyword({ + keyword, + type: "string", + schemaType: keyword.startsWith("formatExclusive") ? ["string", "boolean"] : ["string", "number"], + $data: true, + error, + code(cxt) { + const { + gen, + data, + schemaCode, + keyword, + it + } = cxt; + const { + opts, + self + } = it; + if (!opts.validateFormats) return; + const fCxt = new KeywordCxt(it, /** @type {any} */ + self.RULES.all.format.definition, "format"); + + /** + * @param {Name} fmt + * @returns {Code} + */ + function compareCode(fmt) { + return _`${fmt}.compare(${data}, ${schemaCode}) ${keywords[(/** @type {keyof typeof keywords} */keyword)].fail} 0`; + } + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", _`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data(or(_`typeof ${fmt} != "object"`, _`${fmt} instanceof RegExp`, _`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) { + return; + } + if (typeof fmtDef !== "object" || fmtDef instanceof RegExp || typeof fmtDef.compare !== "function") { + throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + } + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? _`${opts.code.formats}${getProperty(format)}` : undefined + }); + cxt.fail$data(compareCode(fmt)); + } + if (fCxt.$data) { + validate$DataFormat(); + } else { + validateFormat(); + } + }, + dependencies: ["format"] + }); + } + return ajv; +} +var _default = exports.default = addLimitKeyword; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/keywords/undefinedAsNull.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/keywords/undefinedAsNull.js new file mode 100644 index 0000000000000000000000000000000000000000..97f72a3baeda8bb08db92ca441a873fcbbce5be0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/keywords/undefinedAsNull.js @@ -0,0 +1,36 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +/** @typedef {import("ajv").default} Ajv */ +/** @typedef {import("ajv").SchemaValidateFunction} SchemaValidateFunction */ +/** @typedef {import("ajv").AnySchemaObject} AnySchemaObject */ +/** @typedef {import("ajv").ValidateFunction} ValidateFunction */ + +/** + * + * @param {Ajv} ajv + * @returns {Ajv} + */ +function addUndefinedAsNullKeyword(ajv) { + ajv.addKeyword({ + keyword: "undefinedAsNull", + before: "enum", + modifying: true, + /** @type {SchemaValidateFunction} */ + validate(kwVal, data, metadata, dataCxt) { + if (kwVal && dataCxt && metadata && typeof metadata.enum !== "undefined") { + const idx = dataCxt.parentDataProperty; + if (typeof dataCxt.parentData[idx] === "undefined") { + // eslint-disable-next-line no-param-reassign + dataCxt.parentData[dataCxt.parentDataProperty] = null; + } + } + return true; + } + }); + return ajv; +} +var _default = exports.default = addUndefinedAsNullKeyword; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/util/Range.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/util/Range.js new file mode 100644 index 0000000000000000000000000000000000000000..318ebabd46537de4f2922d4bd1cbaba2d9f8ae9c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/util/Range.js @@ -0,0 +1,143 @@ +"use strict"; + +/** + * @typedef {[number, boolean]} RangeValue + */ + +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ + +class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator(side, exclusive) { + if (side === "left") { + return exclusive ? ">" : ">="; + } + return exclusive ? "<" : "<="; + } + + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatRight(value, logic, exclusive) { + if (logic === false) { + return Range.formatLeft(value, !logic, !exclusive); + } + return `should be ${Range.getOperator("right", exclusive)} ${value}`; + } + + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ + static formatLeft(value, logic, exclusive) { + if (logic === false) { + return Range.formatRight(value, !logic, !exclusive); + } + return `should be ${Range.getOperator("left", exclusive)} ${value}`; + } + + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ + static formatRange(start, end, startExclusive, endExclusive, logic) { + let result = "should be"; + result += ` ${Range.getOperator(logic ? "left" : "right", logic ? startExclusive : !startExclusive)} ${start} `; + result += logic ? "and" : "or"; + result += ` ${Range.getOperator(logic ? "right" : "left", logic ? endExclusive : !endExclusive)} ${end}`; + return result; + } + + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ + static getRangeValue(values, logic) { + let minMax = logic ? Infinity : -Infinity; + let j = -1; + const predicate = logic ? /** @type {RangeValueCallback} */ + ([value]) => value <= minMax : /** @type {RangeValueCallback} */ + ([value]) => value >= minMax; + for (let i = 0; i < values.length; i++) { + if (predicate(values[i])) { + [minMax] = values[i]; + j = i; + } + } + if (j > -1) { + return values[j]; + } + return [Infinity, true]; + } + constructor() { + /** @type {Array} */ + this._left = []; + /** @type {Array} */ + this._right = []; + } + + /** + * @param {number} value + * @param {boolean=} exclusive + */ + left(value, exclusive = false) { + this._left.push([value, exclusive]); + } + + /** + * @param {number} value + * @param {boolean=} exclusive + */ + right(value, exclusive = false) { + this._right.push([value, exclusive]); + } + + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ + format(logic = true) { + const [start, leftExclusive] = Range.getRangeValue(this._left, logic); + const [end, rightExclusive] = Range.getRangeValue(this._right, !logic); + if (!Number.isFinite(start) && !Number.isFinite(end)) { + return ""; + } + const realStart = leftExclusive ? start + 1 : start; + const realEnd = rightExclusive ? end - 1 : end; + + // e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6 + if (realStart === realEnd) { + return `should be ${logic ? "" : "!"}= ${realStart}`; + } + + // e.g. 4 < x < ∞ + if (Number.isFinite(start) && !Number.isFinite(end)) { + return Range.formatLeft(start, logic, leftExclusive); + } + + // e.g. ∞ < x < 4 + if (!Number.isFinite(start) && Number.isFinite(end)) { + return Range.formatRight(end, logic, rightExclusive); + } + return Range.formatRange(start, end, leftExclusive, rightExclusive, logic); + } +} +module.exports = Range; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/util/hints.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/util/hints.js new file mode 100644 index 0000000000000000000000000000000000000000..53783d11bcf16540605a1f41e0b5c9c3db329317 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/util/hints.js @@ -0,0 +1,85 @@ +"use strict"; + +const Range = require("./Range"); + +/** @typedef {import("../validate").Schema} Schema */ + +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ +module.exports.stringHints = function stringHints(schema, logic) { + const hints = []; + let type = "string"; + const currentSchema = { + ...schema + }; + if (!logic) { + const tmpLength = currentSchema.minLength; + const tmpFormat = currentSchema.formatMinimum; + currentSchema.minLength = currentSchema.maxLength; + currentSchema.maxLength = tmpLength; + currentSchema.formatMinimum = currentSchema.formatMaximum; + currentSchema.formatMaximum = tmpFormat; + } + if (typeof currentSchema.minLength === "number") { + if (currentSchema.minLength === 1) { + type = "non-empty string"; + } else { + const length = Math.max(currentSchema.minLength - 1, 0); + hints.push(`should be longer than ${length} character${length > 1 ? "s" : ""}`); + } + } + if (typeof currentSchema.maxLength === "number") { + if (currentSchema.maxLength === 0) { + type = "empty string"; + } else { + const length = currentSchema.maxLength + 1; + hints.push(`should be shorter than ${length} character${length > 1 ? "s" : ""}`); + } + } + if (currentSchema.pattern) { + hints.push(`should${logic ? "" : " not"} match pattern ${JSON.stringify(currentSchema.pattern)}`); + } + if (currentSchema.format) { + hints.push(`should${logic ? "" : " not"} match format ${JSON.stringify(currentSchema.format)}`); + } + if (currentSchema.formatMinimum) { + hints.push(`should be ${currentSchema.formatExclusiveMinimum ? ">" : ">="} ${JSON.stringify(currentSchema.formatMinimum)}`); + } + if (currentSchema.formatMaximum) { + hints.push(`should be ${currentSchema.formatExclusiveMaximum ? "<" : "<="} ${JSON.stringify(currentSchema.formatMaximum)}`); + } + return [type].concat(hints); +}; + +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ +module.exports.numberHints = function numberHints(schema, logic) { + const hints = [schema.type === "integer" ? "integer" : "number"]; + const range = new Range(); + if (typeof schema.minimum === "number") { + range.left(schema.minimum); + } + if (typeof schema.exclusiveMinimum === "number") { + range.left(schema.exclusiveMinimum, true); + } + if (typeof schema.maximum === "number") { + range.right(schema.maximum); + } + if (typeof schema.exclusiveMaximum === "number") { + range.right(schema.exclusiveMaximum, true); + } + const rangeFormat = range.format(logic); + if (rangeFormat) { + hints.push(rangeFormat); + } + if (typeof schema.multipleOf === "number") { + hints.push(`should${logic ? "" : " not"} be multiple of ${schema.multipleOf}`); + } + return hints; +}; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/util/memorize.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/util/memorize.js new file mode 100644 index 0000000000000000000000000000000000000000..6ec063cd6db321062b32ab7823f817731c154203 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/dist/util/memorize.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +/** + * @template T + * @param fn {(function(): any) | undefined} + * @returns {function(): T} + */ +const memoize = fn => { + let cache = false; + /** @type {T} */ + let result; + return () => { + if (cache) { + return result; + } + result = /** @type {function(): any} */fn(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + // eslint-disable-next-line no-undefined, no-param-reassign + fn = undefined; + return result; + }; +}; +var _default = exports.default = memoize; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_range.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_range.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f10667819f7c4a83a1eec71848da6a5e95f65bbe --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_range.d.ts @@ -0,0 +1,5 @@ +import type { MacroKeywordDefinition } from "ajv"; +import type { GetDefinition } from "./_types"; +declare type RangeKwd = "range" | "exclusiveRange"; +export default function getRangeDef(keyword: RangeKwd): GetDefinition; +export {}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_range.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_range.js new file mode 100644 index 0000000000000000000000000000000000000000..21d4aa46834fd43950ed1b32c7d52b3bc93c7954 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_range.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function getRangeDef(keyword) { + return () => ({ + keyword, + type: "number", + schemaType: "array", + macro: function ([min, max]) { + validateRangeSchema(min, max); + return keyword === "range" + ? { minimum: min, maximum: max } + : { exclusiveMinimum: min, exclusiveMaximum: max }; + }, + metaSchema: { + type: "array", + minItems: 2, + maxItems: 2, + items: { type: "number" }, + }, + }); + function validateRangeSchema(min, max) { + if (min > max || (keyword === "exclusiveRange" && min === max)) { + throw new Error("There are no numbers in range"); + } + } +} +exports.default = getRangeDef; +//# sourceMappingURL=_range.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_range.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_range.js.map new file mode 100644 index 0000000000000000000000000000000000000000..132c83d5440d8a9f73d0f1416740a586287d2337 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_range.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_range.js","sourceRoot":"","sources":["../../src/definitions/_range.ts"],"names":[],"mappings":";;AAKA,SAAwB,WAAW,CAAC,OAAiB;IACnD,OAAO,GAAG,EAAE,CAAC,CAAC;QACZ,OAAO;QACP,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,OAAO;QACnB,KAAK,EAAE,UAAU,CAAC,GAAG,EAAE,GAAG,CAAmB;YAC3C,mBAAmB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;YAC7B,OAAO,OAAO,KAAK,OAAO;gBACxB,CAAC,CAAC,EAAC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAC;gBAC9B,CAAC,CAAC,EAAC,gBAAgB,EAAE,GAAG,EAAE,gBAAgB,EAAE,GAAG,EAAC,CAAA;QACpD,CAAC;QACD,UAAU,EAAE;YACV,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,CAAC;YACX,QAAQ,EAAE,CAAC;YACX,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAC;SACxB;KACF,CAAC,CAAA;IAEF,SAAS,mBAAmB,CAAC,GAAW,EAAE,GAAW;QACnD,IAAI,GAAG,GAAG,GAAG,IAAI,CAAC,OAAO,KAAK,gBAAgB,IAAI,GAAG,KAAK,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAA;SACjD;IACH,CAAC;AACH,CAAC;AAxBD,8BAwBC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_required.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_required.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cac6e5eb1ad72580e0c1f435d688b9272e5484be --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_required.d.ts @@ -0,0 +1,5 @@ +import type { MacroKeywordDefinition } from "ajv"; +import type { GetDefinition } from "./_types"; +declare type RequiredKwd = "anyRequired" | "oneRequired"; +export default function getRequiredDef(keyword: RequiredKwd): GetDefinition; +export {}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_required.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_required.js new file mode 100644 index 0000000000000000000000000000000000000000..27dd2ffbfca3ea4db8b63b284456968c3929a4dd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_required.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function getRequiredDef(keyword) { + return () => ({ + keyword, + type: "object", + schemaType: "array", + macro(schema) { + if (schema.length === 0) + return true; + if (schema.length === 1) + return { required: schema }; + const comb = keyword === "anyRequired" ? "anyOf" : "oneOf"; + return { [comb]: schema.map((p) => ({ required: [p] })) }; + }, + metaSchema: { + type: "array", + items: { type: "string" }, + }, + }); +} +exports.default = getRequiredDef; +//# sourceMappingURL=_required.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_required.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_required.js.map new file mode 100644 index 0000000000000000000000000000000000000000..94211e7a1f7fff2534cb0188a81522b72df18f6d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_required.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_required.js","sourceRoot":"","sources":["../../src/definitions/_required.ts"],"names":[],"mappings":";;AAKA,SAAwB,cAAc,CACpC,OAAoB;IAEpB,OAAO,GAAG,EAAE,CAAC,CAAC;QACZ,OAAO;QACP,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,OAAO;QACnB,KAAK,CAAC,MAAgB;YACpB,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,IAAI,CAAA;YACpC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,EAAC,QAAQ,EAAE,MAAM,EAAC,CAAA;YAClD,MAAM,IAAI,GAAG,OAAO,KAAK,aAAa,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAA;YAC1D,OAAO,EAAC,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAC,CAAC,CAAC,EAAC,CAAA;QACvD,CAAC;QACD,UAAU,EAAE;YACV,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAC;SACxB;KACF,CAAC,CAAA;AACJ,CAAC;AAlBD,iCAkBC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_types.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c36a04cd75ce14748dedb2bcd4564ec7409b05d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_types.d.ts @@ -0,0 +1,5 @@ +import type { KeywordDefinition } from "ajv"; +export interface DefinitionOptions { + defaultMeta?: string | boolean; +} +export declare type GetDefinition = (opts?: DefinitionOptions) => T; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_types.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_types.js new file mode 100644 index 0000000000000000000000000000000000000000..6e5dd982bb9e15e9f5697a7a38156185da9e2a1a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=_types.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_types.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..31f2faccdad88c41ae4a06ae6a7a080a70e564b1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_types.js","sourceRoot":"","sources":["../../src/definitions/_types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_util.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0d91dd2c33e90c55ca2eecb56d90a587b989058 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_util.d.ts @@ -0,0 +1,4 @@ +import type { DefinitionOptions } from "./_types"; +import type { SchemaObject, KeywordCxt, Name } from "ajv"; +export declare function metaSchemaRef({ defaultMeta }?: DefinitionOptions): SchemaObject; +export declare function usePattern({ gen, it: { opts } }: KeywordCxt, pattern: string, flags?: string): Name; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_util.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_util.js new file mode 100644 index 0000000000000000000000000000000000000000..f8d1045cc7ed4e4ed2681947cdc4bd1d0555cfd9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_util.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.usePattern = exports.metaSchemaRef = void 0; +const codegen_1 = require("ajv/dist/compile/codegen"); +const META_SCHEMA_ID = "http://json-schema.org/schema"; +function metaSchemaRef({ defaultMeta } = {}) { + return defaultMeta === false ? {} : { $ref: defaultMeta || META_SCHEMA_ID }; +} +exports.metaSchemaRef = metaSchemaRef; +function usePattern({ gen, it: { opts } }, pattern, flags = opts.unicodeRegExp ? "u" : "") { + const rx = new RegExp(pattern, flags); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._) `new RegExp(${pattern}, ${flags})`, + }); +} +exports.usePattern = usePattern; +//# sourceMappingURL=_util.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_util.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_util.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c9e310bd7224a4d8a06fdb62924878ef0f1147bc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/_util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_util.js","sourceRoot":"","sources":["../../src/definitions/_util.ts"],"names":[],"mappings":";;;AAEA,sDAA0C;AAE1C,MAAM,cAAc,GAAG,+BAA+B,CAAA;AAEtD,SAAgB,aAAa,CAAC,EAAC,WAAW,KAAuB,EAAE;IACjE,OAAO,WAAW,KAAK,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAC,IAAI,EAAE,WAAW,IAAI,cAAc,EAAC,CAAA;AAC3E,CAAC;AAFD,sCAEC;AAED,SAAgB,UAAU,CACxB,EAAC,GAAG,EAAE,EAAE,EAAE,EAAC,IAAI,EAAC,EAAa,EAC7B,OAAe,EACf,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE;IAErC,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IACrC,OAAO,GAAG,CAAC,UAAU,CAAC,SAAS,EAAE;QAC/B,GAAG,EAAE,EAAE,CAAC,QAAQ,EAAE;QAClB,GAAG,EAAE,EAAE;QACP,IAAI,EAAE,IAAA,WAAC,EAAA,cAAc,OAAO,KAAK,KAAK,GAAG;KAC1C,CAAC,CAAA;AACJ,CAAC;AAXD,gCAWC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/allRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/allRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac709be9edbe43747472ba4e2709c5bd2c2cea29 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/allRequired.d.ts @@ -0,0 +1,2 @@ +import type { MacroKeywordDefinition } from "ajv"; +export default function getDef(): MacroKeywordDefinition; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/allRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/allRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..c2a6803fafc6049aa26f1e0a92ccd23135d2f3ae --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/allRequired.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function getDef() { + return { + keyword: "allRequired", + type: "object", + schemaType: "boolean", + macro(schema, parentSchema) { + if (!schema) + return true; + const required = Object.keys(parentSchema.properties); + if (required.length === 0) + return true; + return { required }; + }, + dependencies: ["properties"], + }; +} +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=allRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/allRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/allRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ff7006b34820232991fe83deaad37a19fa4681b8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/allRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"allRequired.js","sourceRoot":"","sources":["../../src/definitions/allRequired.ts"],"names":[],"mappings":";;AAEA,SAAwB,MAAM;IAC5B,OAAO;QACL,OAAO,EAAE,aAAa;QACtB,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,SAAS;QACrB,KAAK,CAAC,MAAe,EAAE,YAAY;YACjC,IAAI,CAAC,MAAM;gBAAE,OAAO,IAAI,CAAA;YACxB,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,CAAA;YACrD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,IAAI,CAAA;YACtC,OAAO,EAAC,QAAQ,EAAC,CAAA;QACnB,CAAC;QACD,YAAY,EAAE,CAAC,YAAY,CAAC;KAC7B,CAAA;AACH,CAAC;AAbD,yBAaC;AAED,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/anyRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/anyRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a14c2cf7c61796a556450e499454bbb1b5b4899b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/anyRequired.d.ts @@ -0,0 +1,4 @@ +import type { MacroKeywordDefinition } from "ajv"; +import type { GetDefinition } from "./_types"; +declare const getDef: GetDefinition; +export default getDef; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/anyRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/anyRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..0870ce39e53517fe982e90e5801b896397fcb747 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/anyRequired.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const _required_1 = __importDefault(require("./_required")); +const getDef = (0, _required_1.default)("anyRequired"); +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=anyRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/anyRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/anyRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..af1a67bff5388cfc98c04643d6705c7d6c8572a2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/anyRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"anyRequired.js","sourceRoot":"","sources":["../../src/definitions/anyRequired.ts"],"names":[],"mappings":";;;;;AAEA,4DAAwC;AAExC,MAAM,MAAM,GAA0C,IAAA,mBAAc,EAAC,aAAa,CAAC,CAAA;AAEnF,kBAAe,MAAM,CAAA;AACrB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepProperties.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepProperties.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed185656fc36afe467faf759ab5a19cffdd74fc1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepProperties.d.ts @@ -0,0 +1,3 @@ +import type { MacroKeywordDefinition } from "ajv"; +import type { DefinitionOptions } from "./_types"; +export default function getDef(opts?: DefinitionOptions): MacroKeywordDefinition; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepProperties.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepProperties.js new file mode 100644 index 0000000000000000000000000000000000000000..a567d7b91d94ecaeba96e5b49e419e268398b5cc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepProperties.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const _util_1 = require("./_util"); +function getDef(opts) { + return { + keyword: "deepProperties", + type: "object", + schemaType: "object", + macro: function (schema) { + const allOf = []; + for (const pointer in schema) + allOf.push(getSchema(pointer, schema[pointer])); + return { allOf }; + }, + metaSchema: { + type: "object", + propertyNames: { type: "string", format: "json-pointer" }, + additionalProperties: (0, _util_1.metaSchemaRef)(opts), + }, + }; +} +exports.default = getDef; +function getSchema(jsonPointer, schema) { + const segments = jsonPointer.split("/"); + const rootSchema = {}; + let pointerSchema = rootSchema; + for (let i = 1; i < segments.length; i++) { + let segment = segments[i]; + const isLast = i === segments.length - 1; + segment = unescapeJsonPointer(segment); + const properties = (pointerSchema.properties = {}); + let items; + if (/[0-9]+/.test(segment)) { + let count = +segment; + items = pointerSchema.items = []; + pointerSchema.type = ["object", "array"]; + while (count--) + items.push({}); + } + else { + pointerSchema.type = "object"; + } + pointerSchema = isLast ? schema : {}; + properties[segment] = pointerSchema; + if (items) + items.push(pointerSchema); + } + return rootSchema; +} +function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); +} +module.exports = getDef; +//# sourceMappingURL=deepProperties.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepProperties.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepProperties.js.map new file mode 100644 index 0000000000000000000000000000000000000000..782bd04aa5e56bb2b7860d8cc640e9a1f02ed66a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepProperties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deepProperties.js","sourceRoot":"","sources":["../../src/definitions/deepProperties.ts"],"names":[],"mappings":";;AAEA,mCAAqC;AAErC,SAAwB,MAAM,CAAC,IAAwB;IACrD,OAAO;QACL,OAAO,EAAE,gBAAgB;QACzB,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,QAAQ;QACpB,KAAK,EAAE,UAAU,MAAoC;YACnD,MAAM,KAAK,GAAG,EAAE,CAAA;YAChB,KAAK,MAAM,OAAO,IAAI,MAAM;gBAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;YAC7E,OAAO,EAAC,KAAK,EAAC,CAAA;QAChB,CAAC;QACD,UAAU,EAAE;YACV,IAAI,EAAE,QAAQ;YACd,aAAa,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAC;YACvD,oBAAoB,EAAE,IAAA,qBAAa,EAAC,IAAI,CAAC;SAC1C;KACF,CAAA;AACH,CAAC;AAhBD,yBAgBC;AAED,SAAS,SAAS,CAAC,WAAmB,EAAE,MAAoB;IAC1D,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACvC,MAAM,UAAU,GAAiB,EAAE,CAAA;IACnC,IAAI,aAAa,GAAiB,UAAU,CAAA;IAC5C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,IAAI,OAAO,GAAW,QAAQ,CAAC,CAAC,CAAC,CAAA;QACjC,MAAM,MAAM,GAAG,CAAC,KAAK,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAA;QACxC,OAAO,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAA;QACtC,MAAM,UAAU,GAA2B,CAAC,aAAa,CAAC,UAAU,GAAG,EAAE,CAAC,CAAA;QAC1E,IAAI,KAAiC,CAAA;QACrC,IAAI,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;YAC1B,IAAI,KAAK,GAAG,CAAC,OAAO,CAAA;YACpB,KAAK,GAAG,aAAa,CAAC,KAAK,GAAG,EAAE,CAAA;YAChC,aAAa,CAAC,IAAI,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAA;YACxC,OAAO,KAAK,EAAE;gBAAE,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;SAC/B;aAAM;YACL,aAAa,CAAC,IAAI,GAAG,QAAQ,CAAA;SAC9B;QACD,aAAa,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAA;QACpC,UAAU,CAAC,OAAO,CAAC,GAAG,aAAa,CAAA;QACnC,IAAI,KAAK;YAAE,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;KACrC;IACD,OAAO,UAAU,CAAA;AACnB,CAAC;AAED,SAAS,mBAAmB,CAAC,GAAW;IACtC,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAA;AACpD,CAAC;AAED,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..79993ed83613369bd974fa83e5f358439de49858 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepRequired.d.ts @@ -0,0 +1,2 @@ +import type { CodeKeywordDefinition } from "ajv"; +export default function getDef(): CodeKeywordDefinition; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..2aa8bbfc8a1bda0ab7ab886ea0a7ee88082871e8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepRequired.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("ajv/dist/compile/codegen"); +function getDef() { + return { + keyword: "deepRequired", + type: "object", + schemaType: "array", + code(ctx) { + const { schema, data } = ctx; + const props = schema.map((jp) => (0, codegen_1._) `(${getData(jp)}) === undefined`); + ctx.fail((0, codegen_1.or)(...props)); + function getData(jsonPointer) { + if (jsonPointer === "") + throw new Error("empty JSON pointer not allowed"); + const segments = jsonPointer.split("/"); + let x = data; + const xs = segments.map((s, i) => i ? (x = (0, codegen_1._) `${x}${(0, codegen_1.getProperty)(unescapeJPSegment(s))}`) : x); + return (0, codegen_1.and)(...xs); + } + }, + metaSchema: { + type: "array", + items: { type: "string", format: "json-pointer" }, + }, + }; +} +exports.default = getDef; +function unescapeJPSegment(s) { + return s.replace(/~1/g, "/").replace(/~0/g, "~"); +} +module.exports = getDef; +//# sourceMappingURL=deepRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a632916cab35cbc11e2367c47e194969e500b2c8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/deepRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deepRequired.js","sourceRoot":"","sources":["../../src/definitions/deepRequired.ts"],"names":[],"mappings":";;AACA,sDAAsE;AAEtE,SAAwB,MAAM;IAC5B,OAAO;QACL,OAAO,EAAE,cAAc;QACvB,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,OAAO;QACnB,IAAI,CAAC,GAAe;YAClB,MAAM,EAAC,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;YAC1B,MAAM,KAAK,GAAI,MAAmB,CAAC,GAAG,CAAC,CAAC,EAAU,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,IAAI,OAAO,CAAC,EAAE,CAAC,iBAAiB,CAAC,CAAA;YACzF,GAAG,CAAC,IAAI,CAAC,IAAA,YAAE,EAAC,GAAG,KAAK,CAAC,CAAC,CAAA;YAEtB,SAAS,OAAO,CAAC,WAAmB;gBAClC,IAAI,WAAW,KAAK,EAAE;oBAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;gBACzE,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;gBACvC,IAAI,CAAC,GAAS,IAAI,CAAA;gBAClB,MAAM,EAAE,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAC/B,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,IAAA,WAAC,EAAA,GAAG,CAAC,GAAG,IAAA,qBAAW,EAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAC1D,CAAA;gBACD,OAAO,IAAA,aAAG,EAAC,GAAG,EAAE,CAAC,CAAA;YACnB,CAAC;QACH,CAAC;QACD,UAAU,EAAE;YACV,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAC;SAChD;KACF,CAAA;AACH,CAAC;AAzBD,yBAyBC;AAED,SAAS,iBAAiB,CAAC,CAAS;IAClC,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAA;AAClD,CAAC;AAED,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/dynamicDefaults.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/dynamicDefaults.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..702fb0abda7928a395b63a2dd849cde32431ad9a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/dynamicDefaults.d.ts @@ -0,0 +1,7 @@ +import type { FuncKeywordDefinition } from "ajv"; +export declare type DynamicDefaultFunc = (args?: Record) => () => any; +declare const DEFAULTS: Record; +declare const getDef: (() => FuncKeywordDefinition) & { + DEFAULTS: typeof DEFAULTS; +}; +export default getDef; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/dynamicDefaults.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/dynamicDefaults.js new file mode 100644 index 0000000000000000000000000000000000000000..eada65ef9753c5760fbe36c847a1f392a68f878a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/dynamicDefaults.js @@ -0,0 +1,84 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const sequences = {}; +const DEFAULTS = { + timestamp: () => () => Date.now(), + datetime: () => () => new Date().toISOString(), + date: () => () => new Date().toISOString().slice(0, 10), + time: () => () => new Date().toISOString().slice(11), + random: () => () => Math.random(), + randomint: (args) => { + var _a; + const max = (_a = args === null || args === void 0 ? void 0 : args.max) !== null && _a !== void 0 ? _a : 2; + return () => Math.floor(Math.random() * max); + }, + seq: (args) => { + var _a; + const name = (_a = args === null || args === void 0 ? void 0 : args.name) !== null && _a !== void 0 ? _a : ""; + sequences[name] || (sequences[name] = 0); + return () => sequences[name]++; + }, +}; +const getDef = Object.assign(_getDef, { DEFAULTS }); +function _getDef() { + return { + keyword: "dynamicDefaults", + type: "object", + schemaType: ["string", "object"], + modifying: true, + valid: true, + compile(schema, _parentSchema, it) { + if (!it.opts.useDefaults || it.compositeRule) + return () => true; + const fs = {}; + for (const key in schema) + fs[key] = getDefault(schema[key]); + const empty = it.opts.useDefaults === "empty"; + return (data) => { + for (const prop in schema) { + if (data[prop] === undefined || (empty && (data[prop] === null || data[prop] === ""))) { + data[prop] = fs[prop](); + } + } + return true; + }; + }, + metaSchema: { + type: "object", + additionalProperties: { + anyOf: [ + { type: "string" }, + { + type: "object", + additionalProperties: false, + required: ["func", "args"], + properties: { + func: { type: "string" }, + args: { type: "object" }, + }, + }, + ], + }, + }, + }; +} +function getDefault(d) { + return typeof d == "object" ? getObjDefault(d) : getStrDefault(d); +} +function getObjDefault({ func, args }) { + const def = DEFAULTS[func]; + assertDefined(func, def); + return def(args); +} +function getStrDefault(d = "") { + const def = DEFAULTS[d]; + assertDefined(d, def); + return def(); +} +function assertDefined(name, def) { + if (!def) + throw new Error(`invalid "dynamicDefaults" keyword property value: ${name}`); +} +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=dynamicDefaults.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/dynamicDefaults.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/dynamicDefaults.js.map new file mode 100644 index 0000000000000000000000000000000000000000..95e8170e6ae7642078634bd441504835096a3224 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/dynamicDefaults.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dynamicDefaults.js","sourceRoot":"","sources":["../../src/definitions/dynamicDefaults.ts"],"names":[],"mappings":";;AAEA,MAAM,SAAS,GAAuC,EAAE,CAAA;AAIxD,MAAM,QAAQ,GAAmD;IAC/D,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;IACjC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;IAC9C,IAAI,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;IACvD,IAAI,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC;IACpD,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE;IACjC,SAAS,EAAE,CAAC,IAAqB,EAAE,EAAE;;QACnC,MAAM,GAAG,GAAG,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,GAAG,mCAAI,CAAC,CAAA;QAC1B,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,CAAC,CAAA;IAC9C,CAAC;IACD,GAAG,EAAE,CAAC,IAAsB,EAAE,EAAE;;QAC9B,MAAM,IAAI,GAAG,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,IAAI,mCAAI,EAAE,CAAA;QAC7B,SAAS,CAAC,IAAI,MAAd,SAAS,CAAC,IAAI,IAAM,CAAC,EAAA;QACrB,OAAO,GAAG,EAAE,CAAE,SAAS,CAAC,IAAI,CAAY,EAAE,CAAA;IAC5C,CAAC;CACF,CAAA;AASD,MAAM,MAAM,GAER,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,EAAC,QAAQ,EAAC,CAAC,CAAA;AAEtC,SAAS,OAAO;IACd,OAAO;QACL,OAAO,EAAE,iBAAiB;QAC1B,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC;QAChC,SAAS,EAAE,IAAI;QACf,KAAK,EAAE,IAAI;QACX,OAAO,CAAC,MAAqB,EAAE,aAAa,EAAE,EAAa;YACzD,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC,aAAa;gBAAE,OAAO,GAAG,EAAE,CAAC,IAAI,CAAA;YAC/D,MAAM,EAAE,GAA8B,EAAE,CAAA;YACxC,KAAK,MAAM,GAAG,IAAI,MAAM;gBAAE,EAAE,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAA;YAC3D,MAAM,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,OAAO,CAAA;YAE7C,OAAO,CAAC,IAAyB,EAAE,EAAE;gBACnC,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE;oBACzB,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,EAAE;wBACrF,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,CAAA;qBACxB;iBACF;gBACD,OAAO,IAAI,CAAA;YACb,CAAC,CAAA;QACH,CAAC;QACD,UAAU,EAAE;YACV,IAAI,EAAE,QAAQ;YACd,oBAAoB,EAAE;gBACpB,KAAK,EAAE;oBACL,EAAC,IAAI,EAAE,QAAQ,EAAC;oBAChB;wBACE,IAAI,EAAE,QAAQ;wBACd,oBAAoB,EAAE,KAAK;wBAC3B,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC;wBAC1B,UAAU,EAAE;4BACV,IAAI,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAC;4BACtB,IAAI,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAC;yBACvB;qBACF;iBACF;aACF;SACF;KACF,CAAA;AACH,CAAC;AAED,SAAS,UAAU,CAAC,CAA6C;IAC/D,OAAO,OAAO,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;AACnE,CAAC;AAED,SAAS,aAAa,CAAC,EAAC,IAAI,EAAE,IAAI,EAAwB;IACxD,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAA;IAC1B,aAAa,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IACxB,OAAO,GAAG,CAAC,IAAI,CAAC,CAAA;AAClB,CAAC;AAED,SAAS,aAAa,CAAC,CAAC,GAAG,EAAE;IAC3B,MAAM,GAAG,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;IACvB,aAAa,CAAC,CAAC,EAAE,GAAG,CAAC,CAAA;IACrB,OAAO,GAAG,EAAE,CAAA;AACd,CAAC;AAED,SAAS,aAAa,CAAC,IAAY,EAAE,GAAwB;IAC3D,IAAI,CAAC,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,qDAAqD,IAAI,EAAE,CAAC,CAAA;AACxF,CAAC;AAED,kBAAe,MAAM,CAAA;AACrB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/exclusiveRange.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/exclusiveRange.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a14c2cf7c61796a556450e499454bbb1b5b4899b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/exclusiveRange.d.ts @@ -0,0 +1,4 @@ +import type { MacroKeywordDefinition } from "ajv"; +import type { GetDefinition } from "./_types"; +declare const getDef: GetDefinition; +export default getDef; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/exclusiveRange.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/exclusiveRange.js new file mode 100644 index 0000000000000000000000000000000000000000..cee3febb94e2223c6df984991e4b5c084bf81e1c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/exclusiveRange.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const _range_1 = __importDefault(require("./_range")); +const getDef = (0, _range_1.default)("exclusiveRange"); +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=exclusiveRange.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/exclusiveRange.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/exclusiveRange.js.map new file mode 100644 index 0000000000000000000000000000000000000000..aa43025a47c36068f03a2f6af2667953025b5ab5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/exclusiveRange.js.map @@ -0,0 +1 @@ +{"version":3,"file":"exclusiveRange.js","sourceRoot":"","sources":["../../src/definitions/exclusiveRange.ts"],"names":[],"mappings":";;;;;AAEA,sDAAkC;AAElC,MAAM,MAAM,GAA0C,IAAA,gBAAW,EAAC,gBAAgB,CAAC,CAAA;AAEnF,kBAAe,MAAM,CAAA;AACrB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/index.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..326d6847e8e160da7f3d2e69d39a4cbfd77a2f7d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/index.d.ts @@ -0,0 +1,6 @@ +import type { Vocabulary, ErrorNoParams } from "ajv"; +import type { DefinitionOptions } from "./_types"; +import { PatternRequiredError } from "./patternRequired"; +import { SelectError } from "./select"; +export default function ajvKeywords(opts?: DefinitionOptions): Vocabulary; +export declare type AjvKeywordsError = PatternRequiredError | SelectError | ErrorNoParams<"range" | "exclusiveRange" | "anyRequired" | "oneRequired" | "allRequired" | "deepProperties" | "deepRequired" | "dynamicDefaults" | "instanceof" | "prohibited" | "regexp" | "transform" | "uniqueItemProperties">; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/index.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/index.js new file mode 100644 index 0000000000000000000000000000000000000000..94ae44e8c4313f5123b14fc870ed88b9ece2ae18 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/index.js @@ -0,0 +1,44 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const typeof_1 = __importDefault(require("./typeof")); +const instanceof_1 = __importDefault(require("./instanceof")); +const range_1 = __importDefault(require("./range")); +const exclusiveRange_1 = __importDefault(require("./exclusiveRange")); +const regexp_1 = __importDefault(require("./regexp")); +const transform_1 = __importDefault(require("./transform")); +const uniqueItemProperties_1 = __importDefault(require("./uniqueItemProperties")); +const allRequired_1 = __importDefault(require("./allRequired")); +const anyRequired_1 = __importDefault(require("./anyRequired")); +const oneRequired_1 = __importDefault(require("./oneRequired")); +const patternRequired_1 = __importDefault(require("./patternRequired")); +const prohibited_1 = __importDefault(require("./prohibited")); +const deepProperties_1 = __importDefault(require("./deepProperties")); +const deepRequired_1 = __importDefault(require("./deepRequired")); +const dynamicDefaults_1 = __importDefault(require("./dynamicDefaults")); +const select_1 = __importDefault(require("./select")); +const definitions = [ + typeof_1.default, + instanceof_1.default, + range_1.default, + exclusiveRange_1.default, + regexp_1.default, + transform_1.default, + uniqueItemProperties_1.default, + allRequired_1.default, + anyRequired_1.default, + oneRequired_1.default, + patternRequired_1.default, + prohibited_1.default, + deepProperties_1.default, + deepRequired_1.default, + dynamicDefaults_1.default, +]; +function ajvKeywords(opts) { + return definitions.map((d) => d(opts)).concat((0, select_1.default)(opts)); +} +exports.default = ajvKeywords; +module.exports = ajvKeywords; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/index.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..07d353026ac641ed79952af8a666e8af17bf0ef4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/definitions/index.ts"],"names":[],"mappings":";;;;;AAEA,sDAAgC;AAChC,8DAAwC;AACxC,oDAA2B;AAC3B,sEAA6C;AAC7C,sDAA6B;AAC7B,4DAAmC;AACnC,kFAAyD;AACzD,gEAAuC;AACvC,gEAAuC;AACvC,gEAAuC;AACvC,wEAAuE;AACvE,8DAAqC;AACrC,sEAA6C;AAC7C,kEAAyC;AACzC,wEAA+C;AAC/C,sDAA+C;AAE/C,MAAM,WAAW,GAAuC;IACtD,gBAAS;IACT,oBAAa;IACb,eAAK;IACL,wBAAc;IACd,gBAAM;IACN,mBAAS;IACT,8BAAoB;IACpB,qBAAW;IACX,qBAAW;IACX,qBAAW;IACX,yBAAe;IACf,oBAAU;IACV,wBAAc;IACd,sBAAY;IACZ,yBAAe;CAChB,CAAA;AAED,SAAwB,WAAW,CAAC,IAAwB;IAC1D,OAAO,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,IAAA,gBAAS,EAAC,IAAI,CAAC,CAAC,CAAA;AAChE,CAAC;AAFD,8BAEC;AAqBD,MAAM,CAAC,OAAO,GAAG,WAAW,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/instanceof.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/instanceof.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05726f1f7ae5485e25c7396839577ca03e8fd8da --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/instanceof.d.ts @@ -0,0 +1,7 @@ +import type { FuncKeywordDefinition } from "ajv"; +declare type Constructor = new (...args: any[]) => any; +declare const CONSTRUCTORS: Record; +declare const getDef: (() => FuncKeywordDefinition) & { + CONSTRUCTORS: typeof CONSTRUCTORS; +}; +export default getDef; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/instanceof.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/instanceof.js new file mode 100644 index 0000000000000000000000000000000000000000..034fb6419c9107c57f3316c1cc0711932c4708db --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/instanceof.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const CONSTRUCTORS = { + Object, + Array, + Function, + Number, + String, + Date, + RegExp, +}; +/* istanbul ignore else */ +if (typeof Buffer != "undefined") + CONSTRUCTORS.Buffer = Buffer; +/* istanbul ignore else */ +if (typeof Promise != "undefined") + CONSTRUCTORS.Promise = Promise; +const getDef = Object.assign(_getDef, { CONSTRUCTORS }); +function _getDef() { + return { + keyword: "instanceof", + schemaType: ["string", "array"], + compile(schema) { + if (typeof schema == "string") { + const C = getConstructor(schema); + return (data) => data instanceof C; + } + if (Array.isArray(schema)) { + const constructors = schema.map(getConstructor); + return (data) => { + for (const C of constructors) { + if (data instanceof C) + return true; + } + return false; + }; + } + /* istanbul ignore next */ + throw new Error("ajv implementation error"); + }, + metaSchema: { + anyOf: [{ type: "string" }, { type: "array", items: { type: "string" } }], + }, + }; +} +function getConstructor(c) { + const C = CONSTRUCTORS[c]; + if (C) + return C; + throw new Error(`invalid "instanceof" keyword value ${c}`); +} +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=instanceof.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/instanceof.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/instanceof.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d401cd777b1fe6881c3ead3735d40713fa817a28 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/instanceof.js.map @@ -0,0 +1 @@ +{"version":3,"file":"instanceof.js","sourceRoot":"","sources":["../../src/definitions/instanceof.ts"],"names":[],"mappings":";;AAIA,MAAM,YAAY,GAA4C;IAC5D,MAAM;IACN,KAAK;IACL,QAAQ;IACR,MAAM;IACN,MAAM;IACN,IAAI;IACJ,MAAM;CACP,CAAA;AAED,0BAA0B;AAC1B,IAAI,OAAO,MAAM,IAAI,WAAW;IAAE,YAAY,CAAC,MAAM,GAAG,MAAM,CAAA;AAE9D,0BAA0B;AAC1B,IAAI,OAAO,OAAO,IAAI,WAAW;IAAE,YAAY,CAAC,OAAO,GAAG,OAAO,CAAA;AAEjE,MAAM,MAAM,GAER,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,EAAC,YAAY,EAAC,CAAC,CAAA;AAE1C,SAAS,OAAO;IACd,OAAO;QACL,OAAO,EAAE,YAAY;QACrB,UAAU,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC;QAC/B,OAAO,CAAC,MAAyB;YAC/B,IAAI,OAAO,MAAM,IAAI,QAAQ,EAAE;gBAC7B,MAAM,CAAC,GAAG,cAAc,CAAC,MAAM,CAAC,CAAA;gBAChC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,YAAY,CAAC,CAAA;aACnC;YAED,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;gBACzB,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAA;gBAC/C,OAAO,CAAC,IAAI,EAAE,EAAE;oBACd,KAAK,MAAM,CAAC,IAAI,YAAY,EAAE;wBAC5B,IAAI,IAAI,YAAY,CAAC;4BAAE,OAAO,IAAI,CAAA;qBACnC;oBACD,OAAO,KAAK,CAAA;gBACd,CAAC,CAAA;aACF;YAED,0BAA0B;YAC1B,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;QAC7C,CAAC;QACD,UAAU,EAAE;YACV,KAAK,EAAE,CAAC,EAAC,IAAI,EAAE,QAAQ,EAAC,EAAE,EAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAC,EAAC,CAAC;SACpE;KACF,CAAA;AACH,CAAC;AAED,SAAS,cAAc,CAAC,CAAS;IAC/B,MAAM,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAAA;IACzB,IAAI,CAAC;QAAE,OAAO,CAAC,CAAA;IACf,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,EAAE,CAAC,CAAA;AAC5D,CAAC;AAED,kBAAe,MAAM,CAAA;AACrB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/oneRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/oneRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a14c2cf7c61796a556450e499454bbb1b5b4899b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/oneRequired.d.ts @@ -0,0 +1,4 @@ +import type { MacroKeywordDefinition } from "ajv"; +import type { GetDefinition } from "./_types"; +declare const getDef: GetDefinition; +export default getDef; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/oneRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/oneRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..ae46c30cc52bc6517391414886b1f6a484c1ac1c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/oneRequired.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const _required_1 = __importDefault(require("./_required")); +const getDef = (0, _required_1.default)("oneRequired"); +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=oneRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/oneRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/oneRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..134a1d934727910d69f0b31c91239a73827cbde9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/oneRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"oneRequired.js","sourceRoot":"","sources":["../../src/definitions/oneRequired.ts"],"names":[],"mappings":";;;;;AAEA,4DAAwC;AAExC,MAAM,MAAM,GAA0C,IAAA,mBAAc,EAAC,aAAa,CAAC,CAAA;AAEnF,kBAAe,MAAM,CAAA;AACrB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/patternRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/patternRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..95b8eb525dc44292f1ce513c444f47106d081237 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/patternRequired.d.ts @@ -0,0 +1,5 @@ +import type { CodeKeywordDefinition, ErrorObject } from "ajv"; +export declare type PatternRequiredError = ErrorObject<"patternRequired", { + missingPattern: string; +}>; +export default function getDef(): CodeKeywordDefinition; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/patternRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/patternRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..ca24e642f27eb64b324848939f8171f61b49cfed --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/patternRequired.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("ajv/dist/compile/codegen"); +const _util_1 = require("./_util"); +const error = { + message: ({ params: { missingPattern } }) => (0, codegen_1.str) `should have property matching pattern '${missingPattern}'`, + params: ({ params: { missingPattern } }) => (0, codegen_1._) `{missingPattern: ${missingPattern}}`, +}; +function getDef() { + return { + keyword: "patternRequired", + type: "object", + schemaType: "array", + error, + code(cxt) { + const { gen, schema, data } = cxt; + if (schema.length === 0) + return; + const valid = gen.let("valid", true); + for (const pat of schema) + validateProperties(pat); + function validateProperties(pattern) { + const matched = gen.let("matched", false); + gen.forIn("key", data, (key) => { + gen.assign(matched, (0, codegen_1._) `${(0, _util_1.usePattern)(cxt, pattern)}.test(${key})`); + gen.if(matched, () => gen.break()); + }); + cxt.setParams({ missingPattern: pattern }); + gen.assign(valid, (0, codegen_1.and)(valid, matched)); + cxt.pass(valid); + } + }, + metaSchema: { + type: "array", + items: { type: "string", format: "regex" }, + uniqueItems: true, + }, + }; +} +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=patternRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/patternRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/patternRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..17b095f8149e652deb37a7a69becbf5ddde12c81 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/patternRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"patternRequired.js","sourceRoot":"","sources":["../../src/definitions/patternRequired.ts"],"names":[],"mappings":";;AACA,sDAAoD;AACpD,mCAAkC;AAIlC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,cAAc,EAAC,EAAC,EAAE,EAAE,CACtC,IAAA,aAAG,EAAA,0CAA0C,cAAc,GAAG;IAChE,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,cAAc,EAAC,EAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,oBAAoB,cAAc,GAAG;CAC/E,CAAA;AAED,SAAwB,MAAM;IAC5B,OAAO;QACL,OAAO,EAAE,iBAAiB;QAC1B,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,OAAO;QACnB,KAAK;QACL,IAAI,CAAC,GAAe;YAClB,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;YAC/B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAM;YAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;YACpC,KAAK,MAAM,GAAG,IAAI,MAAM;gBAAE,kBAAkB,CAAC,GAAG,CAAC,CAAA;YAEjD,SAAS,kBAAkB,CAAC,OAAe;gBACzC,MAAM,OAAO,GAAG,GAAG,CAAC,GAAG,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;gBAEzC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE;oBAC7B,GAAG,CAAC,MAAM,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,IAAA,kBAAU,EAAC,GAAG,EAAE,OAAO,CAAC,SAAS,GAAG,GAAG,CAAC,CAAA;oBAChE,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAA;gBACpC,CAAC,CAAC,CAAA;gBAEF,GAAG,CAAC,SAAS,CAAC,EAAC,cAAc,EAAE,OAAO,EAAC,CAAC,CAAA;gBACxC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAA,aAAG,EAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAA;gBACtC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;YACjB,CAAC;QACH,CAAC;QACD,UAAU,EAAE;YACV,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAC;YACxC,WAAW,EAAE,IAAI;SAClB;KACF,CAAA;AACH,CAAC;AA/BD,yBA+BC;AAED,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/prohibited.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/prohibited.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac709be9edbe43747472ba4e2709c5bd2c2cea29 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/prohibited.d.ts @@ -0,0 +1,2 @@ +import type { MacroKeywordDefinition } from "ajv"; +export default function getDef(): MacroKeywordDefinition; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/prohibited.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/prohibited.js new file mode 100644 index 0000000000000000000000000000000000000000..9a497460d5aa106f37a77cf8c9ae6724299111cf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/prohibited.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function getDef() { + return { + keyword: "prohibited", + type: "object", + schemaType: "array", + macro: function (schema) { + if (schema.length === 0) + return true; + if (schema.length === 1) + return { not: { required: schema } }; + return { not: { anyOf: schema.map((p) => ({ required: [p] })) } }; + }, + metaSchema: { + type: "array", + items: { type: "string" }, + }, + }; +} +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=prohibited.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/prohibited.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/prohibited.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1a2deec1e0813b348437e684e1b18915aba7c7ae --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/prohibited.js.map @@ -0,0 +1 @@ +{"version":3,"file":"prohibited.js","sourceRoot":"","sources":["../../src/definitions/prohibited.ts"],"names":[],"mappings":";;AAEA,SAAwB,MAAM;IAC5B,OAAO;QACL,OAAO,EAAE,YAAY;QACrB,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,OAAO;QACnB,KAAK,EAAE,UAAU,MAAgB;YAC/B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,IAAI,CAAA;YACpC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,EAAC,GAAG,EAAE,EAAC,QAAQ,EAAE,MAAM,EAAC,EAAC,CAAA;YACzD,OAAO,EAAC,GAAG,EAAE,EAAC,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAC,CAAC,CAAC,EAAC,EAAC,CAAA;QAC7D,CAAC;QACD,UAAU,EAAE;YACV,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAC;SACxB;KACF,CAAA;AACH,CAAC;AAfD,yBAeC;AAED,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/range.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/range.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a14c2cf7c61796a556450e499454bbb1b5b4899b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/range.d.ts @@ -0,0 +1,4 @@ +import type { MacroKeywordDefinition } from "ajv"; +import type { GetDefinition } from "./_types"; +declare const getDef: GetDefinition; +export default getDef; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/range.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/range.js new file mode 100644 index 0000000000000000000000000000000000000000..aa75c51b9add3a6dbdbc87f47727a79355e257e5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/range.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const _range_1 = __importDefault(require("./_range")); +const getDef = (0, _range_1.default)("range"); +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=range.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/range.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/range.js.map new file mode 100644 index 0000000000000000000000000000000000000000..7d9dd5877f2583b4f291fabf95b1062c3c402b2c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/range.js.map @@ -0,0 +1 @@ +{"version":3,"file":"range.js","sourceRoot":"","sources":["../../src/definitions/range.ts"],"names":[],"mappings":";;;;;AAEA,sDAAkC;AAElC,MAAM,MAAM,GAA0C,IAAA,gBAAW,EAAC,OAAO,CAAC,CAAA;AAE1E,kBAAe,MAAM,CAAA;AACrB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/regexp.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/regexp.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..79993ed83613369bd974fa83e5f358439de49858 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/regexp.d.ts @@ -0,0 +1,2 @@ +import type { CodeKeywordDefinition } from "ajv"; +export default function getDef(): CodeKeywordDefinition; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/regexp.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/regexp.js new file mode 100644 index 0000000000000000000000000000000000000000..b3c5a7cc18cc0c8be94109d5a8c23ad77dc8d693 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/regexp.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("ajv/dist/compile/codegen"); +const _util_1 = require("./_util"); +const regexpMetaSchema = { + type: "object", + properties: { + pattern: { type: "string" }, + flags: { type: "string", nullable: true }, + }, + required: ["pattern"], + additionalProperties: false, +}; +const metaRegexp = /^\/(.*)\/([gimuy]*)$/; +function getDef() { + return { + keyword: "regexp", + type: "string", + schemaType: ["string", "object"], + code(cxt) { + const { data, schema } = cxt; + const regx = getRegExp(schema); + cxt.pass((0, codegen_1._) `${regx}.test(${data})`); + function getRegExp(sch) { + if (typeof sch == "object") + return (0, _util_1.usePattern)(cxt, sch.pattern, sch.flags); + const rx = metaRegexp.exec(sch); + if (rx) + return (0, _util_1.usePattern)(cxt, rx[1], rx[2]); + throw new Error("cannot parse string into RegExp"); + } + }, + metaSchema: { + anyOf: [{ type: "string" }, regexpMetaSchema], + }, + }; +} +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=regexp.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/regexp.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/regexp.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d389e474d01b0d26debc48ced3fabc7fbe4b7cf9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/regexp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"regexp.js","sourceRoot":"","sources":["../../src/definitions/regexp.ts"],"names":[],"mappings":";;AACA,sDAA0C;AAC1C,mCAAkC;AAOlC,MAAM,gBAAgB,GAAiC;IACrD,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACV,OAAO,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAC;QACzB,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAC;KACxC;IACD,QAAQ,EAAE,CAAC,SAAS,CAAC;IACrB,oBAAoB,EAAE,KAAK;CAC5B,CAAA;AAED,MAAM,UAAU,GAAG,sBAAsB,CAAA;AAEzC,SAAwB,MAAM;IAC5B,OAAO;QACL,OAAO,EAAE,QAAQ;QACjB,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC;QAChC,IAAI,CAAC,GAAe;YAClB,MAAM,EAAC,IAAI,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;YAC1B,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,CAAA;YAC9B,GAAG,CAAC,IAAI,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,SAAS,IAAI,GAAG,CAAC,CAAA;YAElC,SAAS,SAAS,CAAC,GAA0B;gBAC3C,IAAI,OAAO,GAAG,IAAI,QAAQ;oBAAE,OAAO,IAAA,kBAAU,EAAC,GAAG,EAAE,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,CAAC,CAAA;gBAC1E,MAAM,EAAE,GAAG,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBAC/B,IAAI,EAAE;oBAAE,OAAO,IAAA,kBAAU,EAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;gBAC5C,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAA;YACpD,CAAC;QACH,CAAC;QACD,UAAU,EAAE;YACV,KAAK,EAAE,CAAC,EAAC,IAAI,EAAE,QAAQ,EAAC,EAAE,gBAAgB,CAAC;SAC5C;KACF,CAAA;AACH,CAAC;AArBD,yBAqBC;AAED,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/select.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/select.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d12fc65d11a5384818c8af83dd2443cee8ecfdf2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/select.d.ts @@ -0,0 +1,7 @@ +import type { KeywordDefinition, ErrorObject } from "ajv"; +import type { DefinitionOptions } from "./_types"; +export declare type SelectError = ErrorObject<"select", { + failingCase?: string; + failingDefault?: true; +}>; +export default function getDef(opts?: DefinitionOptions): KeywordDefinition[]; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/select.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/select.js new file mode 100644 index 0000000000000000000000000000000000000000..bce677bf88a206ae08137c8f707679799cf8b77f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/select.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("ajv/dist/compile/codegen"); +const _util_1 = require("./_util"); +const error = { + message: ({ params: { schemaProp } }) => schemaProp + ? (0, codegen_1.str) `should match case "${schemaProp}" schema` + : (0, codegen_1.str) `should match default case schema`, + params: ({ params: { schemaProp } }) => schemaProp ? (0, codegen_1._) `{failingCase: ${schemaProp}}` : (0, codegen_1._) `{failingDefault: true}`, +}; +function getDef(opts) { + const metaSchema = (0, _util_1.metaSchemaRef)(opts); + return [ + { + keyword: "select", + schemaType: ["string", "number", "boolean", "null"], + $data: true, + error, + dependencies: ["selectCases"], + code(cxt) { + const { gen, schemaCode, parentSchema } = cxt; + cxt.block$data(codegen_1.nil, () => { + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + const value = gen.const("value", (0, codegen_1._) `${schemaCode} === null ? "null" : ${schemaCode}`); + gen.if(false); // optimizer should remove it from generated code + for (const schemaProp in parentSchema.selectCases) { + cxt.setParams({ schemaProp }); + gen.elseIf((0, codegen_1._) `"" + ${value} == ${schemaProp}`); // intentional ==, to match numbers and booleans + const schCxt = cxt.subschema({ keyword: "selectCases", schemaProp }, schValid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + gen.assign(valid, schValid); + } + gen.else(); + if (parentSchema.selectDefault !== undefined) { + cxt.setParams({ schemaProp: undefined }); + const schCxt = cxt.subschema({ keyword: "selectDefault" }, schValid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + gen.assign(valid, schValid); + } + gen.endIf(); + cxt.pass(valid); + }); + }, + }, + { + keyword: "selectCases", + dependencies: ["select"], + metaSchema: { + type: "object", + additionalProperties: metaSchema, + }, + }, + { + keyword: "selectDefault", + dependencies: ["select", "selectCases"], + metaSchema, + }, + ]; +} +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=select.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/select.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/select.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1e5a035516ffd048b5397a82b06716c86ff5b01a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/select.js.map @@ -0,0 +1 @@ +{"version":3,"file":"select.js","sourceRoot":"","sources":["../../src/definitions/select.ts"],"names":[],"mappings":";;AACA,sDAA0D;AAE1D,mCAAqC;AAIrC,MAAM,KAAK,GAA2B;IACpC,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,UAAU,EAAC,EAAC,EAAE,EAAE,CAClC,UAAU;QACR,CAAC,CAAC,IAAA,aAAG,EAAA,sBAAsB,UAAU,UAAU;QAC/C,CAAC,CAAC,IAAA,aAAG,EAAA,kCAAkC;IAC3C,MAAM,EAAE,CAAC,EAAC,MAAM,EAAE,EAAC,UAAU,EAAC,EAAC,EAAE,EAAE,CACjC,UAAU,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,iBAAiB,UAAU,GAAG,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,wBAAwB;CAC3E,CAAA;AAED,SAAwB,MAAM,CAAC,IAAwB;IACrD,MAAM,UAAU,GAAG,IAAA,qBAAa,EAAC,IAAI,CAAC,CAAA;IAEtC,OAAO;QACL;YACE,OAAO,EAAE,QAAQ;YACjB,UAAU,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,CAAC;YACnD,KAAK,EAAE,IAAI;YACX,KAAK;YACL,YAAY,EAAE,CAAC,aAAa,CAAC;YAC7B,IAAI,CAAC,GAAe;gBAClB,MAAM,EAAC,GAAG,EAAE,UAAU,EAAE,YAAY,EAAC,GAAG,GAAG,CAAA;gBAC3C,GAAG,CAAC,UAAU,CAAC,aAAG,EAAE,GAAG,EAAE;oBACvB,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;oBACpC,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;oBACnC,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,UAAU,wBAAwB,UAAU,EAAE,CAAC,CAAA;oBACpF,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA,CAAC,iDAAiD;oBAC/D,KAAK,MAAM,UAAU,IAAI,YAAY,CAAC,WAAW,EAAE;wBACjD,GAAG,CAAC,SAAS,CAAC,EAAC,UAAU,EAAC,CAAC,CAAA;wBAC3B,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,QAAQ,KAAK,OAAO,UAAU,EAAE,CAAC,CAAA,CAAC,gDAAgD;wBAC9F,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,aAAa,EAAE,UAAU,EAAC,EAAE,QAAQ,CAAC,CAAA;wBAC5E,GAAG,CAAC,cAAc,CAAC,MAAM,EAAE,cAAI,CAAC,CAAA;wBAChC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;qBAC5B;oBACD,GAAG,CAAC,IAAI,EAAE,CAAA;oBACV,IAAI,YAAY,CAAC,aAAa,KAAK,SAAS,EAAE;wBAC5C,GAAG,CAAC,SAAS,CAAC,EAAC,UAAU,EAAE,SAAS,EAAC,CAAC,CAAA;wBACtC,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,EAAC,OAAO,EAAE,eAAe,EAAC,EAAE,QAAQ,CAAC,CAAA;wBAClE,GAAG,CAAC,cAAc,CAAC,MAAM,EAAE,cAAI,CAAC,CAAA;wBAChC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;qBAC5B;oBACD,GAAG,CAAC,KAAK,EAAE,CAAA;oBACX,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;gBACjB,CAAC,CAAC,CAAA;YACJ,CAAC;SACF;QACD;YACE,OAAO,EAAE,aAAa;YACtB,YAAY,EAAE,CAAC,QAAQ,CAAC;YACxB,UAAU,EAAE;gBACV,IAAI,EAAE,QAAQ;gBACd,oBAAoB,EAAE,UAAU;aACjC;SACF;QACD;YACE,OAAO,EAAE,eAAe;YACxB,YAAY,EAAE,CAAC,QAAQ,EAAE,aAAa,CAAC;YACvC,UAAU;SACX;KACF,CAAA;AACH,CAAC;AAlDD,yBAkDC;AAED,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/transform.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/transform.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..551c46eaad3a2e6efcf95d2ea3840111af0dce5f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/transform.d.ts @@ -0,0 +1,13 @@ +import type { CodeKeywordDefinition } from "ajv"; +declare type TransformName = "trimStart" | "trimEnd" | "trimLeft" | "trimRight" | "trim" | "toLowerCase" | "toUpperCase" | "toEnumCase"; +interface TransformConfig { + hash: Record; +} +declare type Transform = (s: string, cfg?: TransformConfig) => string; +declare const transform: { + [key in TransformName]: Transform; +}; +declare const getDef: (() => CodeKeywordDefinition) & { + transform: typeof transform; +}; +export default getDef; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/transform.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/transform.js new file mode 100644 index 0000000000000000000000000000000000000000..17128de40368dccfb506db1f15537cc66a5e46e4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/transform.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("ajv/dist/compile/codegen"); +const transform = { + trimStart: (s) => s.trimStart(), + trimEnd: (s) => s.trimEnd(), + trimLeft: (s) => s.trimStart(), + trimRight: (s) => s.trimEnd(), + trim: (s) => s.trim(), + toLowerCase: (s) => s.toLowerCase(), + toUpperCase: (s) => s.toUpperCase(), + toEnumCase: (s, cfg) => (cfg === null || cfg === void 0 ? void 0 : cfg.hash[configKey(s)]) || s, +}; +const getDef = Object.assign(_getDef, { transform }); +function _getDef() { + return { + keyword: "transform", + schemaType: "array", + before: "enum", + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { parentData, parentDataProperty } = it; + const tNames = schema; + if (!tNames.length) + return; + let cfg; + if (tNames.includes("toEnumCase")) { + const config = getEnumCaseCfg(parentSchema); + cfg = gen.scopeValue("obj", { ref: config, code: (0, codegen_1.stringify)(config) }); + } + gen.if((0, codegen_1._) `typeof ${data} == "string" && ${parentData} !== undefined`, () => { + gen.assign(data, transformExpr(tNames.slice())); + gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, data); + }); + function transformExpr(ts) { + if (!ts.length) + return data; + const t = ts.pop(); + if (!(t in transform)) + throw new Error(`transform: unknown transformation ${t}`); + const func = gen.scopeValue("func", { + ref: transform[t], + code: (0, codegen_1._) `require("ajv-keywords/dist/definitions/transform").transform${(0, codegen_1.getProperty)(t)}`, + }); + const arg = transformExpr(ts); + return cfg && t === "toEnumCase" ? (0, codegen_1._) `${func}(${arg}, ${cfg})` : (0, codegen_1._) `${func}(${arg})`; + } + }, + metaSchema: { + type: "array", + items: { type: "string", enum: Object.keys(transform) }, + }, + }; +} +function getEnumCaseCfg(parentSchema) { + // build hash table to enum values + const cfg = { hash: {} }; + // requires `enum` in the same schema as transform + if (!parentSchema.enum) + throw new Error('transform: "toEnumCase" requires "enum"'); + for (const v of parentSchema.enum) { + if (typeof v !== "string") + continue; + const k = configKey(v); + // requires all `enum` values have unique keys + if (cfg.hash[k]) { + throw new Error('transform: "toEnumCase" requires all lowercased "enum" values to be unique'); + } + cfg.hash[k] = v; + } + return cfg; +} +function configKey(s) { + return s.toLowerCase(); +} +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=transform.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/transform.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/transform.js.map new file mode 100644 index 0000000000000000000000000000000000000000..82220dcffd67045ee2f9e129f44274665e1b70f8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/transform.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transform.js","sourceRoot":"","sources":["../../src/definitions/transform.ts"],"names":[],"mappings":";;AACA,sDAAkE;AAkBlE,MAAM,SAAS,GAAwC;IACrD,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE;IAC/B,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE;IAC3B,QAAQ,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE;IAC9B,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE;IAC7B,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE;IACrB,WAAW,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE;IACnC,WAAW,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE;IACnC,UAAU,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAI,CAAC;CACrD,CAAA;AAED,MAAM,MAAM,GAER,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,EAAC,SAAS,EAAC,CAAC,CAAA;AAEvC,SAAS,OAAO;IACd,OAAO;QACL,OAAO,EAAE,WAAW;QACpB,UAAU,EAAE,OAAO;QACnB,MAAM,EAAE,MAAM;QACd,IAAI,CAAC,GAAe;YAClB,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,EAAC,GAAG,GAAG,CAAA;YACjD,MAAM,EAAC,UAAU,EAAE,kBAAkB,EAAC,GAAG,EAAE,CAAA;YAC3C,MAAM,MAAM,GAAa,MAAM,CAAA;YAC/B,IAAI,CAAC,MAAM,CAAC,MAAM;gBAAE,OAAM;YAC1B,IAAI,GAAqB,CAAA;YACzB,IAAI,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE;gBACjC,MAAM,MAAM,GAAG,cAAc,CAAC,YAAY,CAAC,CAAA;gBAC3C,GAAG,GAAG,GAAG,CAAC,UAAU,CAAC,KAAK,EAAE,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,IAAA,mBAAS,EAAC,MAAM,CAAC,EAAC,CAAC,CAAA;aACpE;YACD,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,UAAU,IAAI,mBAAmB,UAAU,gBAAgB,EAAE,GAAG,EAAE;gBACxE,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAA;gBAC/C,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,UAAU,IAAI,kBAAkB,GAAG,EAAE,IAAI,CAAC,CAAA;YAC3D,CAAC,CAAC,CAAA;YAEF,SAAS,aAAa,CAAC,EAAY;gBACjC,IAAI,CAAC,EAAE,CAAC,MAAM;oBAAE,OAAO,IAAI,CAAA;gBAC3B,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,EAAY,CAAA;gBAC5B,IAAI,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,EAAE,CAAC,CAAA;gBAChF,MAAM,IAAI,GAAG,GAAG,CAAC,UAAU,CAAC,MAAM,EAAE;oBAClC,GAAG,EAAE,SAAS,CAAC,CAAkB,CAAC;oBAClC,IAAI,EAAE,IAAA,WAAC,EAAA,+DAA+D,IAAA,qBAAW,EAAC,CAAC,CAAC,EAAE;iBACvF,CAAC,CAAA;gBACF,MAAM,GAAG,GAAG,aAAa,CAAC,EAAE,CAAC,CAAA;gBAC7B,OAAO,GAAG,IAAI,CAAC,KAAK,YAAY,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,IAAI,GAAG,KAAK,GAAG,GAAG,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,IAAI,GAAG,GAAG,CAAA;YACpF,CAAC;QACH,CAAC;QACD,UAAU,EAAE;YACV,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAC;SACtD;KACF,CAAA;AACH,CAAC;AAED,SAAS,cAAc,CAAC,YAA6B;IACnD,kCAAkC;IAClC,MAAM,GAAG,GAAoB,EAAC,IAAI,EAAE,EAAE,EAAC,CAAA;IAEvC,kDAAkD;IAClD,IAAI,CAAC,YAAY,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAA;IAClF,KAAK,MAAM,CAAC,IAAI,YAAY,CAAC,IAAI,EAAE;QACjC,IAAI,OAAO,CAAC,KAAK,QAAQ;YAAE,SAAQ;QACnC,MAAM,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAA;QACtB,8CAA8C;QAC9C,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAA;SAC9F;QACD,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;KAChB;IAED,OAAO,GAAG,CAAA;AACZ,CAAC;AAED,SAAS,SAAS,CAAC,CAAS;IAC1B,OAAO,CAAC,CAAC,WAAW,EAAE,CAAA;AACxB,CAAC;AAED,kBAAe,MAAM,CAAA;AACrB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/typeof.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/typeof.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..79993ed83613369bd974fa83e5f358439de49858 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/typeof.d.ts @@ -0,0 +1,2 @@ +import type { CodeKeywordDefinition } from "ajv"; +export default function getDef(): CodeKeywordDefinition; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/typeof.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/typeof.js new file mode 100644 index 0000000000000000000000000000000000000000..5bb2b02028adafc995e93b8021fc538bbf9c4093 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/typeof.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const codegen_1 = require("ajv/dist/compile/codegen"); +const TYPES = ["undefined", "string", "number", "object", "function", "boolean", "symbol"]; +function getDef() { + return { + keyword: "typeof", + schemaType: ["string", "array"], + code(cxt) { + const { data, schema, schemaValue } = cxt; + cxt.fail(typeof schema == "string" + ? (0, codegen_1._) `typeof ${data} != ${schema}` + : (0, codegen_1._) `${schemaValue}.indexOf(typeof ${data}) < 0`); + }, + metaSchema: { + anyOf: [ + { type: "string", enum: TYPES }, + { type: "array", items: { type: "string", enum: TYPES } }, + ], + }, + }; +} +exports.default = getDef; +module.exports = getDef; +//# sourceMappingURL=typeof.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/typeof.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/typeof.js.map new file mode 100644 index 0000000000000000000000000000000000000000..918d3ff1eb24dc6bc00bf461bebc6c6ed3a0bb72 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/typeof.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typeof.js","sourceRoot":"","sources":["../../src/definitions/typeof.ts"],"names":[],"mappings":";;AACA,sDAA0C;AAE1C,MAAM,KAAK,GAAG,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAA;AAE1F,SAAwB,MAAM;IAC5B,OAAO;QACL,OAAO,EAAE,QAAQ;QACjB,UAAU,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC;QAC/B,IAAI,CAAC,GAAe;YAClB,MAAM,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAC,GAAG,GAAG,CAAA;YACvC,GAAG,CAAC,IAAI,CACN,OAAO,MAAM,IAAI,QAAQ;gBACvB,CAAC,CAAC,IAAA,WAAC,EAAA,UAAU,IAAI,OAAO,MAAM,EAAE;gBAChC,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,WAAW,mBAAmB,IAAI,OAAO,CAClD,CAAA;QACH,CAAC;QACD,UAAU,EAAE;YACV,KAAK,EAAE;gBACL,EAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAC;gBAC7B,EAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAC,EAAC;aACtD;SACF;KACF,CAAA;AACH,CAAC;AAnBD,yBAmBC;AAED,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/uniqueItemProperties.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/uniqueItemProperties.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d83655951a5f7301b6d242f611a7ea7f5bd771a8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/uniqueItemProperties.d.ts @@ -0,0 +1,2 @@ +import type { FuncKeywordDefinition } from "ajv"; +export default function getDef(): FuncKeywordDefinition; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/uniqueItemProperties.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/uniqueItemProperties.js new file mode 100644 index 0000000000000000000000000000000000000000..1758209a74a6f63d72a0fe05c17c35794c8c772c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/uniqueItemProperties.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const equal = require("fast-deep-equal"); +const SCALAR_TYPES = ["number", "integer", "string", "boolean", "null"]; +function getDef() { + return { + keyword: "uniqueItemProperties", + type: "array", + schemaType: "array", + compile(keys, parentSchema) { + const scalar = getScalarKeys(keys, parentSchema); + return (data) => { + if (data.length <= 1) + return true; + for (let k = 0; k < keys.length; k++) { + const key = keys[k]; + if (scalar[k]) { + const hash = {}; + for (const x of data) { + if (!x || typeof x != "object") + continue; + let p = x[key]; + if (p && typeof p == "object") + continue; + if (typeof p == "string") + p = '"' + p; + if (hash[p]) + return false; + hash[p] = true; + } + } + else { + for (let i = data.length; i--;) { + const x = data[i]; + if (!x || typeof x != "object") + continue; + for (let j = i; j--;) { + const y = data[j]; + if (y && typeof y == "object" && equal(x[key], y[key])) + return false; + } + } + } + } + return true; + }; + }, + metaSchema: { + type: "array", + items: { type: "string" }, + }, + }; +} +exports.default = getDef; +function getScalarKeys(keys, schema) { + return keys.map((key) => { + var _a, _b, _c; + const t = (_c = (_b = (_a = schema.items) === null || _a === void 0 ? void 0 : _a.properties) === null || _b === void 0 ? void 0 : _b[key]) === null || _c === void 0 ? void 0 : _c.type; + return Array.isArray(t) + ? !t.includes("object") && !t.includes("array") + : SCALAR_TYPES.includes(t); + }); +} +module.exports = getDef; +//# sourceMappingURL=uniqueItemProperties.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/uniqueItemProperties.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/uniqueItemProperties.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c0619c26b1cce0c05827748df6bb6b33650c85c4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/definitions/uniqueItemProperties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uniqueItemProperties.js","sourceRoot":"","sources":["../../src/definitions/uniqueItemProperties.ts"],"names":[],"mappings":";;AACA,yCAAyC;AAEzC,MAAM,YAAY,GAAG,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,CAAC,CAAA;AAEvE,SAAwB,MAAM;IAC5B,OAAO;QACL,OAAO,EAAE,sBAAsB;QAC/B,IAAI,EAAE,OAAO;QACb,UAAU,EAAE,OAAO;QACnB,OAAO,CAAC,IAAc,EAAE,YAA6B;YACnD,MAAM,MAAM,GAAG,aAAa,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;YAEhD,OAAO,CAAC,IAAI,EAAE,EAAE;gBACd,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC;oBAAE,OAAO,IAAI,CAAA;gBACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;oBACpC,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;oBACnB,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE;wBACb,MAAM,IAAI,GAAwB,EAAE,CAAA;wBACpC,KAAK,MAAM,CAAC,IAAI,IAAI,EAAE;4BACpB,IAAI,CAAC,CAAC,IAAI,OAAO,CAAC,IAAI,QAAQ;gCAAE,SAAQ;4BACxC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAA;4BACd,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI,QAAQ;gCAAE,SAAQ;4BACvC,IAAI,OAAO,CAAC,IAAI,QAAQ;gCAAE,CAAC,GAAG,GAAG,GAAG,CAAC,CAAA;4BACrC,IAAI,IAAI,CAAC,CAAC,CAAC;gCAAE,OAAO,KAAK,CAAA;4BACzB,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAA;yBACf;qBACF;yBAAM;wBACL,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,GAAI;4BAC/B,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;4BACjB,IAAI,CAAC,CAAC,IAAI,OAAO,CAAC,IAAI,QAAQ;gCAAE,SAAQ;4BACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,GAAI;gCACrB,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;gCACjB,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC;oCAAE,OAAO,KAAK,CAAA;6BACrE;yBACF;qBACF;iBACF;gBACD,OAAO,IAAI,CAAA;YACb,CAAC,CAAA;QACH,CAAC;QACD,UAAU,EAAE;YACV,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,EAAC,IAAI,EAAE,QAAQ,EAAC;SACxB;KACF,CAAA;AACH,CAAC;AAzCD,yBAyCC;AAED,SAAS,aAAa,CAAC,IAAc,EAAE,MAAuB;IAC5D,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE;;QACtB,MAAM,CAAC,GAAG,MAAA,MAAA,MAAA,MAAM,CAAC,KAAK,0CAAE,UAAU,0CAAG,GAAG,CAAC,0CAAE,IAAI,CAAA;QAC/C,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;YACrB,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC;YAC/C,CAAC,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;IAC9B,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/index.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc5b7a943d45244788fac48ee58fc97cc486f2e3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/index.d.ts @@ -0,0 +1,4 @@ +import type { Plugin } from "ajv"; +export { AjvKeywordsError } from "./definitions"; +declare const ajvKeywords: Plugin; +export default ajvKeywords; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/index.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d0d3d8b2bbe6885cbe7f9d8af00681a17a6aec4a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/index.js @@ -0,0 +1,32 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const keywords_1 = __importDefault(require("./keywords")); +const ajvKeywords = (ajv, keyword) => { + if (Array.isArray(keyword)) { + for (const k of keyword) + get(k)(ajv); + return ajv; + } + if (keyword) { + get(keyword)(ajv); + return ajv; + } + for (keyword in keywords_1.default) + get(keyword)(ajv); + return ajv; +}; +ajvKeywords.get = get; +function get(keyword) { + const defFunc = keywords_1.default[keyword]; + if (!defFunc) + throw new Error("Unknown keyword " + keyword); + return defFunc; +} +exports.default = ajvKeywords; +module.exports = ajvKeywords; +// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access +module.exports.default = ajvKeywords; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/index.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2f472f1e35e26bf2b3eaadb743a2e1a8b4a6ebcc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAEA,0DAAgC;AAIhC,MAAM,WAAW,GAA8B,CAAC,GAAQ,EAAE,OAA2B,EAAO,EAAE;IAC5F,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAC1B,KAAK,MAAM,CAAC,IAAI,OAAO;YAAE,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;QACpC,OAAO,GAAG,CAAA;KACX;IACD,IAAI,OAAO,EAAE;QACX,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAA;QACjB,OAAO,GAAG,CAAA;KACX;IACD,KAAK,OAAO,IAAI,kBAAO;QAAE,GAAG,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAA;IAC1C,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED,WAAW,CAAC,GAAG,GAAG,GAAG,CAAA;AAErB,SAAS,GAAG,CAAC,OAAe;IAC1B,MAAM,OAAO,GAAG,kBAAO,CAAC,OAAO,CAAC,CAAA;IAChC,IAAI,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,GAAG,OAAO,CAAC,CAAA;IAC3D,OAAO,OAAO,CAAA;AAChB,CAAC;AAED,kBAAe,WAAW,CAAA;AAC1B,MAAM,CAAC,OAAO,GAAG,WAAW,CAAA;AAE5B,sEAAsE;AACtE,MAAM,CAAC,OAAO,CAAC,OAAO,GAAG,WAAW,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/allRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/allRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..97dd12137af06568339c61a5f35e2ac154a4b697 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/allRequired.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const allRequired: Plugin; +export default allRequired; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/allRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/allRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..aaf65637757b8f3c7f571eadfaa94e605419bda9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/allRequired.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const allRequired_1 = __importDefault(require("../definitions/allRequired")); +const allRequired = (ajv) => ajv.addKeyword((0, allRequired_1.default)()); +exports.default = allRequired; +module.exports = allRequired; +//# sourceMappingURL=allRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/allRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/allRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e19effd330da4ae0821c24eb06d63e662288b6dd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/allRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"allRequired.js","sourceRoot":"","sources":["../../src/keywords/allRequired.ts"],"names":[],"mappings":";;;;;AACA,6EAA+C;AAE/C,MAAM,WAAW,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,qBAAM,GAAE,CAAC,CAAA;AAExE,kBAAe,WAAW,CAAA;AAC1B,MAAM,CAAC,OAAO,GAAG,WAAW,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/anyRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/anyRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..55e0fb1f23b6ac33ee26ac9d4b385f38400ccd1c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/anyRequired.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const anyRequired: Plugin; +export default anyRequired; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/anyRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/anyRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..700dc0daaf000c79f77646c28de43680db7b0954 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/anyRequired.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const anyRequired_1 = __importDefault(require("../definitions/anyRequired")); +const anyRequired = (ajv) => ajv.addKeyword((0, anyRequired_1.default)()); +exports.default = anyRequired; +module.exports = anyRequired; +//# sourceMappingURL=anyRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/anyRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/anyRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e1986e0535c6dac5a001466c3e113b03a72376c1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/anyRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"anyRequired.js","sourceRoot":"","sources":["../../src/keywords/anyRequired.ts"],"names":[],"mappings":";;;;;AACA,6EAA+C;AAE/C,MAAM,WAAW,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,qBAAM,GAAE,CAAC,CAAA;AAExE,kBAAe,WAAW,CAAA;AAC1B,MAAM,CAAC,OAAO,GAAG,WAAW,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepProperties.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepProperties.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8209c8d10c9dc52c15dc4eba04c2c0f97f843dd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepProperties.d.ts @@ -0,0 +1,4 @@ +import type { Plugin } from "ajv"; +import type { DefinitionOptions } from "../definitions/_types"; +declare const deepProperties: Plugin; +export default deepProperties; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepProperties.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepProperties.js new file mode 100644 index 0000000000000000000000000000000000000000..bd207d8bba575f9c0f6141e2c6eeef8945ba43c3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepProperties.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const deepProperties_1 = __importDefault(require("../definitions/deepProperties")); +const deepProperties = (ajv, opts) => ajv.addKeyword((0, deepProperties_1.default)(opts)); +exports.default = deepProperties; +module.exports = deepProperties; +//# sourceMappingURL=deepProperties.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepProperties.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepProperties.js.map new file mode 100644 index 0000000000000000000000000000000000000000..23ee8f3d6eebc715313424522133e390b93aa25d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepProperties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deepProperties.js","sourceRoot":"","sources":["../../src/keywords/deepProperties.ts"],"names":[],"mappings":";;;;;AACA,mFAAkD;AAGlD,MAAM,cAAc,GAA8B,CAAC,GAAG,EAAE,IAAwB,EAAE,EAAE,CAClF,GAAG,CAAC,UAAU,CAAC,IAAA,wBAAM,EAAC,IAAI,CAAC,CAAC,CAAA;AAE9B,kBAAe,cAAc,CAAA;AAC7B,MAAM,CAAC,OAAO,GAAG,cAAc,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..113062baeb251588e685a7646f7f1c4d044da4a5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepRequired.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const deepRequired: Plugin; +export default deepRequired; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..2077831640ae43078f119b259bd7dba123068e62 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepRequired.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const deepRequired_1 = __importDefault(require("../definitions/deepRequired")); +const deepRequired = (ajv) => ajv.addKeyword((0, deepRequired_1.default)()); +exports.default = deepRequired; +module.exports = deepRequired; +//# sourceMappingURL=deepRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4b808c1c8600c8f92e8e299a96040e5cf42076cb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/deepRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deepRequired.js","sourceRoot":"","sources":["../../src/keywords/deepRequired.ts"],"names":[],"mappings":";;;;;AACA,+EAAgD;AAEhD,MAAM,YAAY,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,sBAAM,GAAE,CAAC,CAAA;AAEzE,kBAAe,YAAY,CAAA;AAC3B,MAAM,CAAC,OAAO,GAAG,YAAY,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/dynamicDefaults.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/dynamicDefaults.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b5e84757d667474584b5bb4f689be41d27bf3878 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/dynamicDefaults.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const dynamicDefaults: Plugin; +export default dynamicDefaults; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/dynamicDefaults.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/dynamicDefaults.js new file mode 100644 index 0000000000000000000000000000000000000000..3df22076cdbf2d74e702cab84c1bc711f4973aa3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/dynamicDefaults.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const dynamicDefaults_1 = __importDefault(require("../definitions/dynamicDefaults")); +const dynamicDefaults = (ajv) => ajv.addKeyword((0, dynamicDefaults_1.default)()); +exports.default = dynamicDefaults; +module.exports = dynamicDefaults; +//# sourceMappingURL=dynamicDefaults.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/dynamicDefaults.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/dynamicDefaults.js.map new file mode 100644 index 0000000000000000000000000000000000000000..f87302ae3bac1c4d151ea136d511d605f7720d23 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/dynamicDefaults.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dynamicDefaults.js","sourceRoot":"","sources":["../../src/keywords/dynamicDefaults.ts"],"names":[],"mappings":";;;;;AACA,qFAAmD;AAEnD,MAAM,eAAe,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,yBAAM,GAAE,CAAC,CAAA;AAE5E,kBAAe,eAAe,CAAA;AAC9B,MAAM,CAAC,OAAO,GAAG,eAAe,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/exclusiveRange.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/exclusiveRange.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..23ca1acbc7fa480249109f9704cb88743e7ea62e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/exclusiveRange.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const exclusiveRange: Plugin; +export default exclusiveRange; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/exclusiveRange.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/exclusiveRange.js new file mode 100644 index 0000000000000000000000000000000000000000..5788996fe0420e72e26bbe7d6770efeba9e7e85f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/exclusiveRange.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const exclusiveRange_1 = __importDefault(require("../definitions/exclusiveRange")); +const exclusiveRange = (ajv) => ajv.addKeyword((0, exclusiveRange_1.default)()); +exports.default = exclusiveRange; +module.exports = exclusiveRange; +//# sourceMappingURL=exclusiveRange.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/exclusiveRange.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/exclusiveRange.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a12321b7abbaf0f3c37bfa705bb4eda5010a5290 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/exclusiveRange.js.map @@ -0,0 +1 @@ +{"version":3,"file":"exclusiveRange.js","sourceRoot":"","sources":["../../src/keywords/exclusiveRange.ts"],"names":[],"mappings":";;;;;AACA,mFAAkD;AAElD,MAAM,cAAc,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,wBAAM,GAAE,CAAC,CAAA;AAE3E,kBAAe,cAAc,CAAA;AAC7B,MAAM,CAAC,OAAO,GAAG,cAAc,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/index.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98fd14ec5f7db62b1397a8a41628806df754f018 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/index.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const ajvKeywords: Record | undefined>; +export default ajvKeywords; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/index.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d2b7d86a9f5d4703d998ab8b23824cbb2bfb403b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/index.js @@ -0,0 +1,43 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const typeof_1 = __importDefault(require("./typeof")); +const instanceof_1 = __importDefault(require("./instanceof")); +const range_1 = __importDefault(require("./range")); +const exclusiveRange_1 = __importDefault(require("./exclusiveRange")); +const regexp_1 = __importDefault(require("./regexp")); +const transform_1 = __importDefault(require("./transform")); +const uniqueItemProperties_1 = __importDefault(require("./uniqueItemProperties")); +const allRequired_1 = __importDefault(require("./allRequired")); +const anyRequired_1 = __importDefault(require("./anyRequired")); +const oneRequired_1 = __importDefault(require("./oneRequired")); +const patternRequired_1 = __importDefault(require("./patternRequired")); +const prohibited_1 = __importDefault(require("./prohibited")); +const deepProperties_1 = __importDefault(require("./deepProperties")); +const deepRequired_1 = __importDefault(require("./deepRequired")); +const dynamicDefaults_1 = __importDefault(require("./dynamicDefaults")); +const select_1 = __importDefault(require("./select")); +// TODO type +const ajvKeywords = { + typeof: typeof_1.default, + instanceof: instanceof_1.default, + range: range_1.default, + exclusiveRange: exclusiveRange_1.default, + regexp: regexp_1.default, + transform: transform_1.default, + uniqueItemProperties: uniqueItemProperties_1.default, + allRequired: allRequired_1.default, + anyRequired: anyRequired_1.default, + oneRequired: oneRequired_1.default, + patternRequired: patternRequired_1.default, + prohibited: prohibited_1.default, + deepProperties: deepProperties_1.default, + deepRequired: deepRequired_1.default, + dynamicDefaults: dynamicDefaults_1.default, + select: select_1.default, +}; +exports.default = ajvKeywords; +module.exports = ajvKeywords; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/index.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b91d99ec4ee2bab8db74397e01f7660ebb7be071 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/keywords/index.ts"],"names":[],"mappings":";;;;;AACA,sDAAmC;AACnC,8DAA2C;AAC3C,oDAA2B;AAC3B,sEAA6C;AAC7C,sDAA6B;AAC7B,4DAAmC;AACnC,kFAAyD;AACzD,gEAAuC;AACvC,gEAAuC;AACvC,gEAAuC;AACvC,wEAA+C;AAC/C,8DAAqC;AACrC,sEAA6C;AAC7C,kEAAyC;AACzC,wEAA+C;AAC/C,sDAA6B;AAE7B,YAAY;AACZ,MAAM,WAAW,GAA4C;IAC3D,MAAM,EAAE,gBAAY;IACpB,UAAU,EAAE,oBAAgB;IAC5B,KAAK,EAAL,eAAK;IACL,cAAc,EAAd,wBAAc;IACd,MAAM,EAAN,gBAAM;IACN,SAAS,EAAT,mBAAS;IACT,oBAAoB,EAApB,8BAAoB;IACpB,WAAW,EAAX,qBAAW;IACX,WAAW,EAAX,qBAAW;IACX,WAAW,EAAX,qBAAW;IACX,eAAe,EAAf,yBAAe;IACf,UAAU,EAAV,oBAAU;IACV,cAAc,EAAd,wBAAc;IACd,YAAY,EAAZ,sBAAY;IACZ,eAAe,EAAf,yBAAe;IACf,MAAM,EAAN,gBAAM;CACP,CAAA;AAED,kBAAe,WAAW,CAAA;AAC1B,MAAM,CAAC,OAAO,GAAG,WAAW,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/instanceof.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/instanceof.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fa300cf9e1bbea98fc6cf402f3142bd0b4a1fa0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/instanceof.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const instanceofPlugin: Plugin; +export default instanceofPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/instanceof.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/instanceof.js new file mode 100644 index 0000000000000000000000000000000000000000..e5e2784d7c98e5dd2d444450fd511c48212b2043 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/instanceof.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const instanceof_1 = __importDefault(require("../definitions/instanceof")); +const instanceofPlugin = (ajv) => ajv.addKeyword((0, instanceof_1.default)()); +exports.default = instanceofPlugin; +module.exports = instanceofPlugin; +//# sourceMappingURL=instanceof.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/instanceof.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/instanceof.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b33b115471c145f3327d830ff40a0502d4195307 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/instanceof.js.map @@ -0,0 +1 @@ +{"version":3,"file":"instanceof.js","sourceRoot":"","sources":["../../src/keywords/instanceof.ts"],"names":[],"mappings":";;;;;AACA,2EAA8C;AAE9C,MAAM,gBAAgB,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,oBAAM,GAAE,CAAC,CAAA;AAE7E,kBAAe,gBAAgB,CAAA;AAC/B,MAAM,CAAC,OAAO,GAAG,gBAAgB,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/oneRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/oneRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2aaa0f56fdbcfcf379393deee5c2d0a97e237496 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/oneRequired.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const oneRequired: Plugin; +export default oneRequired; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/oneRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/oneRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..c62e1ebdbeb746a2e5a279f2a1c799774d488445 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/oneRequired.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const oneRequired_1 = __importDefault(require("../definitions/oneRequired")); +const oneRequired = (ajv) => ajv.addKeyword((0, oneRequired_1.default)()); +exports.default = oneRequired; +module.exports = oneRequired; +//# sourceMappingURL=oneRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/oneRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/oneRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9dc8aa0cdc3afc6c17aff8bde4e31515853fe609 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/oneRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"oneRequired.js","sourceRoot":"","sources":["../../src/keywords/oneRequired.ts"],"names":[],"mappings":";;;;;AACA,6EAA+C;AAE/C,MAAM,WAAW,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,qBAAM,GAAE,CAAC,CAAA;AAExE,kBAAe,WAAW,CAAA;AAC1B,MAAM,CAAC,OAAO,GAAG,WAAW,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/patternRequired.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/patternRequired.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..565f5c09c284959230a0dbcedf0a61f34fc856a7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/patternRequired.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const patternRequired: Plugin; +export default patternRequired; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/patternRequired.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/patternRequired.js new file mode 100644 index 0000000000000000000000000000000000000000..fc6a1ab6ea14d895749b44cb195c49c9b3c3c706 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/patternRequired.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const patternRequired_1 = __importDefault(require("../definitions/patternRequired")); +const patternRequired = (ajv) => ajv.addKeyword((0, patternRequired_1.default)()); +exports.default = patternRequired; +module.exports = patternRequired; +//# sourceMappingURL=patternRequired.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/patternRequired.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/patternRequired.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c446c4dcdf3fc1834f84fef87633154874a25a0b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/patternRequired.js.map @@ -0,0 +1 @@ +{"version":3,"file":"patternRequired.js","sourceRoot":"","sources":["../../src/keywords/patternRequired.ts"],"names":[],"mappings":";;;;;AACA,qFAAmD;AAEnD,MAAM,eAAe,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,yBAAM,GAAE,CAAC,CAAA;AAE5E,kBAAe,eAAe,CAAA;AAC9B,MAAM,CAAC,OAAO,GAAG,eAAe,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/prohibited.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/prohibited.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..19f2ccb1cbdcf399815ffe6c16f067442d9998c2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/prohibited.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const prohibited: Plugin; +export default prohibited; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/prohibited.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/prohibited.js new file mode 100644 index 0000000000000000000000000000000000000000..08414f917ba3800de9705829d3fe2b78314790ca --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/prohibited.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const prohibited_1 = __importDefault(require("../definitions/prohibited")); +const prohibited = (ajv) => ajv.addKeyword((0, prohibited_1.default)()); +exports.default = prohibited; +module.exports = prohibited; +//# sourceMappingURL=prohibited.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/prohibited.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/prohibited.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5c2b190e5272cde9718273f84d0d8a35416a41a4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/prohibited.js.map @@ -0,0 +1 @@ +{"version":3,"file":"prohibited.js","sourceRoot":"","sources":["../../src/keywords/prohibited.ts"],"names":[],"mappings":";;;;;AACA,2EAA8C;AAE9C,MAAM,UAAU,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,oBAAM,GAAE,CAAC,CAAA;AAEvE,kBAAe,UAAU,CAAA;AACzB,MAAM,CAAC,OAAO,GAAG,UAAU,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/range.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/range.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e9bd230ee492d45641ae141f58b1e7a4406c9e0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/range.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const range: Plugin; +export default range; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/range.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/range.js new file mode 100644 index 0000000000000000000000000000000000000000..915f28d9e1b15e1f3368f11736b7bfc2e1d6ca4e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/range.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const range_1 = __importDefault(require("../definitions/range")); +const range = (ajv) => ajv.addKeyword((0, range_1.default)()); +exports.default = range; +module.exports = range; +//# sourceMappingURL=range.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/range.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/range.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b07eb26b1a5a56be98ab0fbc5c69e360c20def0c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/range.js.map @@ -0,0 +1 @@ +{"version":3,"file":"range.js","sourceRoot":"","sources":["../../src/keywords/range.ts"],"names":[],"mappings":";;;;;AACA,iEAAyC;AAEzC,MAAM,KAAK,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,eAAM,GAAE,CAAC,CAAA;AAElE,kBAAe,KAAK,CAAA;AACpB,MAAM,CAAC,OAAO,GAAG,KAAK,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/regexp.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/regexp.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c64f089e899f66323d8d2ff9eeb13cd264601fa --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/regexp.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const regexp: Plugin; +export default regexp; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/regexp.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/regexp.js new file mode 100644 index 0000000000000000000000000000000000000000..7eb75832f7b92bc8d51107307531a1dcbd950d6e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/regexp.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const regexp_1 = __importDefault(require("../definitions/regexp")); +const regexp = (ajv) => ajv.addKeyword((0, regexp_1.default)()); +exports.default = regexp; +module.exports = regexp; +//# sourceMappingURL=regexp.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/regexp.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/regexp.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a004f5e8eef8b546215e977c008f714484d77a92 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/regexp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"regexp.js","sourceRoot":"","sources":["../../src/keywords/regexp.ts"],"names":[],"mappings":";;;;;AACA,mEAA0C;AAE1C,MAAM,MAAM,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,gBAAM,GAAE,CAAC,CAAA;AAEnE,kBAAe,MAAM,CAAA;AACrB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/select.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/select.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7f9abaa2b65343408b42c13907dbc5595b176fe --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/select.d.ts @@ -0,0 +1,4 @@ +import type { Plugin } from "ajv"; +import type { DefinitionOptions } from "../definitions/_types"; +declare const select: Plugin; +export default select; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/select.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/select.js new file mode 100644 index 0000000000000000000000000000000000000000..eff7205cae69987152862165043dd51999c11cdb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/select.js @@ -0,0 +1,13 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const select_1 = __importDefault(require("../definitions/select")); +const select = (ajv, opts) => { + (0, select_1.default)(opts).forEach((d) => ajv.addKeyword(d)); + return ajv; +}; +exports.default = select; +module.exports = select; +//# sourceMappingURL=select.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/select.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/select.js.map new file mode 100644 index 0000000000000000000000000000000000000000..55b294c9c2d633e4ed98d0b1b54853d4b9c00086 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/select.js.map @@ -0,0 +1 @@ +{"version":3,"file":"select.js","sourceRoot":"","sources":["../../src/keywords/select.ts"],"names":[],"mappings":";;;;;AACA,mEAA2C;AAG3C,MAAM,MAAM,GAA8B,CAAC,GAAG,EAAE,IAAwB,EAAE,EAAE;IAC1E,IAAA,gBAAO,EAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;IAC/C,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA;AAED,kBAAe,MAAM,CAAA;AACrB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/transform.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/transform.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8734ed08fc5fce538de7125a934f59f69f593ab6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/transform.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const transform: Plugin; +export default transform; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/transform.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/transform.js new file mode 100644 index 0000000000000000000000000000000000000000..bdf9ef1d87f2a736987ab88dab63ec2b25342cd5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/transform.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const transform_1 = __importDefault(require("../definitions/transform")); +const transform = (ajv) => ajv.addKeyword((0, transform_1.default)()); +exports.default = transform; +module.exports = transform; +//# sourceMappingURL=transform.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/transform.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/transform.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ef0e67509b88532aec8b8d8cae0783c17e594848 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/transform.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transform.js","sourceRoot":"","sources":["../../src/keywords/transform.ts"],"names":[],"mappings":";;;;;AACA,yEAA6C;AAE7C,MAAM,SAAS,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,mBAAM,GAAE,CAAC,CAAA;AAEtE,kBAAe,SAAS,CAAA;AACxB,MAAM,CAAC,OAAO,GAAG,SAAS,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/typeof.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/typeof.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57aff4b9258b6a619604d6e01300afe5610df6c2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/typeof.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const typeofPlugin: Plugin; +export default typeofPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/typeof.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/typeof.js new file mode 100644 index 0000000000000000000000000000000000000000..6cabc3affe9852c9061b9c33961f0c059bc0ccf3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/typeof.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const typeof_1 = __importDefault(require("../definitions/typeof")); +const typeofPlugin = (ajv) => ajv.addKeyword((0, typeof_1.default)()); +exports.default = typeofPlugin; +module.exports = typeofPlugin; +//# sourceMappingURL=typeof.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/typeof.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/typeof.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ec70622180d1f06db86b6afb153b46c4cd90de74 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/typeof.js.map @@ -0,0 +1 @@ +{"version":3,"file":"typeof.js","sourceRoot":"","sources":["../../src/keywords/typeof.ts"],"names":[],"mappings":";;;;;AACA,mEAA0C;AAE1C,MAAM,YAAY,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,gBAAM,GAAE,CAAC,CAAA;AAEzE,kBAAe,YAAY,CAAA;AAC3B,MAAM,CAAC,OAAO,GAAG,YAAY,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/uniqueItemProperties.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/uniqueItemProperties.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff06feaccc2072a5398f5d28b14fca70be964c7e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/uniqueItemProperties.d.ts @@ -0,0 +1,3 @@ +import type { Plugin } from "ajv"; +declare const uniqueItemProperties: Plugin; +export default uniqueItemProperties; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/uniqueItemProperties.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/uniqueItemProperties.js new file mode 100644 index 0000000000000000000000000000000000000000..a638fcc482fde03fe54bc967f8fcc7693c594fd6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/uniqueItemProperties.js @@ -0,0 +1,10 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const uniqueItemProperties_1 = __importDefault(require("../definitions/uniqueItemProperties")); +const uniqueItemProperties = (ajv) => ajv.addKeyword((0, uniqueItemProperties_1.default)()); +exports.default = uniqueItemProperties; +module.exports = uniqueItemProperties; +//# sourceMappingURL=uniqueItemProperties.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/uniqueItemProperties.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/uniqueItemProperties.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b62fdd2fb851cf3564d545b8adb4009ed16ff0be --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/dist/keywords/uniqueItemProperties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uniqueItemProperties.js","sourceRoot":"","sources":["../../src/keywords/uniqueItemProperties.ts"],"names":[],"mappings":";;;;;AACA,+FAAwD;AAExD,MAAM,oBAAoB,GAAsB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,IAAA,8BAAM,GAAE,CAAC,CAAA;AAEjF,kBAAe,oBAAoB,CAAA;AACnC,MAAM,CAAC,OAAO,GAAG,oBAAoB,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_range.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_range.ts new file mode 100644 index 0000000000000000000000000000000000000000..38cb9a0d4365dcd929e326bf7fffc14811d04805 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_range.ts @@ -0,0 +1,30 @@ +import type {MacroKeywordDefinition} from "ajv" +import type {GetDefinition} from "./_types" + +type RangeKwd = "range" | "exclusiveRange" + +export default function getRangeDef(keyword: RangeKwd): GetDefinition { + return () => ({ + keyword, + type: "number", + schemaType: "array", + macro: function ([min, max]: [number, number]) { + validateRangeSchema(min, max) + return keyword === "range" + ? {minimum: min, maximum: max} + : {exclusiveMinimum: min, exclusiveMaximum: max} + }, + metaSchema: { + type: "array", + minItems: 2, + maxItems: 2, + items: {type: "number"}, + }, + }) + + function validateRangeSchema(min: number, max: number): void { + if (min > max || (keyword === "exclusiveRange" && min === max)) { + throw new Error("There are no numbers in range") + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_required.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_required.ts new file mode 100644 index 0000000000000000000000000000000000000000..ddf9395421f9a651e89d3f0228a6512072589580 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_required.ts @@ -0,0 +1,24 @@ +import type {MacroKeywordDefinition} from "ajv" +import type {GetDefinition} from "./_types" + +type RequiredKwd = "anyRequired" | "oneRequired" + +export default function getRequiredDef( + keyword: RequiredKwd +): GetDefinition { + return () => ({ + keyword, + type: "object", + schemaType: "array", + macro(schema: string[]) { + if (schema.length === 0) return true + if (schema.length === 1) return {required: schema} + const comb = keyword === "anyRequired" ? "anyOf" : "oneOf" + return {[comb]: schema.map((p) => ({required: [p]}))} + }, + metaSchema: { + type: "array", + items: {type: "string"}, + }, + }) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_types.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_types.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3f54248ee43b3b540e1b5172941f2befde8eb66 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_types.ts @@ -0,0 +1,7 @@ +import type {KeywordDefinition} from "ajv" + +export interface DefinitionOptions { + defaultMeta?: string | boolean +} + +export type GetDefinition = (opts?: DefinitionOptions) => T diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_util.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_util.ts new file mode 100644 index 0000000000000000000000000000000000000000..68bcc01b2b709eda31694ff13785840152f390c1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/_util.ts @@ -0,0 +1,22 @@ +import type {DefinitionOptions} from "./_types" +import type {SchemaObject, KeywordCxt, Name} from "ajv" +import {_} from "ajv/dist/compile/codegen" + +const META_SCHEMA_ID = "http://json-schema.org/schema" + +export function metaSchemaRef({defaultMeta}: DefinitionOptions = {}): SchemaObject { + return defaultMeta === false ? {} : {$ref: defaultMeta || META_SCHEMA_ID} +} + +export function usePattern( + {gen, it: {opts}}: KeywordCxt, + pattern: string, + flags = opts.unicodeRegExp ? "u" : "" +): Name { + const rx = new RegExp(pattern, flags) + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: _`new RegExp(${pattern}, ${flags})`, + }) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/allRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/allRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..821558f27d8af056567ae3567ea2a4f4776b9565 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/allRequired.ts @@ -0,0 +1,18 @@ +import type {MacroKeywordDefinition} from "ajv" + +export default function getDef(): MacroKeywordDefinition { + return { + keyword: "allRequired", + type: "object", + schemaType: "boolean", + macro(schema: boolean, parentSchema) { + if (!schema) return true + const required = Object.keys(parentSchema.properties) + if (required.length === 0) return true + return {required} + }, + dependencies: ["properties"], + } +} + +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/anyRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/anyRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f715367d01f315a548d42644ed315000509e50f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/anyRequired.ts @@ -0,0 +1,8 @@ +import type {MacroKeywordDefinition} from "ajv" +import type {GetDefinition} from "./_types" +import getRequiredDef from "./_required" + +const getDef: GetDefinition = getRequiredDef("anyRequired") + +export default getDef +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/deepProperties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/deepProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..be294106bc71ca1d9fe280e2346b10a516527c2c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/deepProperties.ts @@ -0,0 +1,52 @@ +import type {MacroKeywordDefinition, SchemaObject, Schema} from "ajv" +import type {DefinitionOptions} from "./_types" +import {metaSchemaRef} from "./_util" + +export default function getDef(opts?: DefinitionOptions): MacroKeywordDefinition { + return { + keyword: "deepProperties", + type: "object", + schemaType: "object", + macro: function (schema: Record) { + const allOf = [] + for (const pointer in schema) allOf.push(getSchema(pointer, schema[pointer])) + return {allOf} + }, + metaSchema: { + type: "object", + propertyNames: {type: "string", format: "json-pointer"}, + additionalProperties: metaSchemaRef(opts), + }, + } +} + +function getSchema(jsonPointer: string, schema: SchemaObject): SchemaObject { + const segments = jsonPointer.split("/") + const rootSchema: SchemaObject = {} + let pointerSchema: SchemaObject = rootSchema + for (let i = 1; i < segments.length; i++) { + let segment: string = segments[i] + const isLast = i === segments.length - 1 + segment = unescapeJsonPointer(segment) + const properties: Record = (pointerSchema.properties = {}) + let items: SchemaObject[] | undefined + if (/[0-9]+/.test(segment)) { + let count = +segment + items = pointerSchema.items = [] + pointerSchema.type = ["object", "array"] + while (count--) items.push({}) + } else { + pointerSchema.type = "object" + } + pointerSchema = isLast ? schema : {} + properties[segment] = pointerSchema + if (items) items.push(pointerSchema) + } + return rootSchema +} + +function unescapeJsonPointer(str: string): string { + return str.replace(/~1/g, "/").replace(/~0/g, "~") +} + +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/deepRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/deepRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..c01b7026703870f3741c517d375a17c7a8bc44f4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/deepRequired.ts @@ -0,0 +1,35 @@ +import type {CodeKeywordDefinition, KeywordCxt} from "ajv" +import {_, or, and, getProperty, Code} from "ajv/dist/compile/codegen" + +export default function getDef(): CodeKeywordDefinition { + return { + keyword: "deepRequired", + type: "object", + schemaType: "array", + code(ctx: KeywordCxt) { + const {schema, data} = ctx + const props = (schema as string[]).map((jp: string) => _`(${getData(jp)}) === undefined`) + ctx.fail(or(...props)) + + function getData(jsonPointer: string): Code { + if (jsonPointer === "") throw new Error("empty JSON pointer not allowed") + const segments = jsonPointer.split("/") + let x: Code = data + const xs = segments.map((s, i) => + i ? (x = _`${x}${getProperty(unescapeJPSegment(s))}`) : x + ) + return and(...xs) + } + }, + metaSchema: { + type: "array", + items: {type: "string", format: "json-pointer"}, + }, + } +} + +function unescapeJPSegment(s: string): string { + return s.replace(/~1/g, "/").replace(/~0/g, "~") +} + +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/dynamicDefaults.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/dynamicDefaults.ts new file mode 100644 index 0000000000000000000000000000000000000000..84cd0c372b22ffa5ae6a430687a3deeffe80739a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/dynamicDefaults.ts @@ -0,0 +1,98 @@ +import type {FuncKeywordDefinition, SchemaCxt} from "ajv" + +const sequences: Record = {} + +export type DynamicDefaultFunc = (args?: Record) => () => any + +const DEFAULTS: Record = { + timestamp: () => () => Date.now(), + datetime: () => () => new Date().toISOString(), + date: () => () => new Date().toISOString().slice(0, 10), + time: () => () => new Date().toISOString().slice(11), + random: () => () => Math.random(), + randomint: (args?: {max?: number}) => { + const max = args?.max ?? 2 + return () => Math.floor(Math.random() * max) + }, + seq: (args?: {name?: string}) => { + const name = args?.name ?? "" + sequences[name] ||= 0 + return () => (sequences[name] as number)++ + }, +} + +interface PropertyDefaultSchema { + func: string + args: Record +} + +type DefaultSchema = Record + +const getDef: (() => FuncKeywordDefinition) & { + DEFAULTS: typeof DEFAULTS +} = Object.assign(_getDef, {DEFAULTS}) + +function _getDef(): FuncKeywordDefinition { + return { + keyword: "dynamicDefaults", + type: "object", + schemaType: ["string", "object"], + modifying: true, + valid: true, + compile(schema: DefaultSchema, _parentSchema, it: SchemaCxt) { + if (!it.opts.useDefaults || it.compositeRule) return () => true + const fs: Record any> = {} + for (const key in schema) fs[key] = getDefault(schema[key]) + const empty = it.opts.useDefaults === "empty" + + return (data: Record) => { + for (const prop in schema) { + if (data[prop] === undefined || (empty && (data[prop] === null || data[prop] === ""))) { + data[prop] = fs[prop]() + } + } + return true + } + }, + metaSchema: { + type: "object", + additionalProperties: { + anyOf: [ + {type: "string"}, + { + type: "object", + additionalProperties: false, + required: ["func", "args"], + properties: { + func: {type: "string"}, + args: {type: "object"}, + }, + }, + ], + }, + }, + } +} + +function getDefault(d: string | PropertyDefaultSchema | undefined): () => any { + return typeof d == "object" ? getObjDefault(d) : getStrDefault(d) +} + +function getObjDefault({func, args}: PropertyDefaultSchema): () => any { + const def = DEFAULTS[func] + assertDefined(func, def) + return def(args) +} + +function getStrDefault(d = ""): () => any { + const def = DEFAULTS[d] + assertDefined(d, def) + return def() +} + +function assertDefined(name: string, def?: DynamicDefaultFunc): asserts def is DynamicDefaultFunc { + if (!def) throw new Error(`invalid "dynamicDefaults" keyword property value: ${name}`) +} + +export default getDef +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/exclusiveRange.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/exclusiveRange.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a4f7361fe66a7220078e6d4d47e87e4910fd617 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/exclusiveRange.ts @@ -0,0 +1,8 @@ +import type {MacroKeywordDefinition} from "ajv" +import type {GetDefinition} from "./_types" +import getRangeDef from "./_range" + +const getDef: GetDefinition = getRangeDef("exclusiveRange") + +export default getDef +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb0a4af77acc7b0886c049aed003a766bf9bedd8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/index.ts @@ -0,0 +1,61 @@ +import type {Vocabulary, KeywordDefinition, ErrorNoParams} from "ajv" +import type {DefinitionOptions, GetDefinition} from "./_types" +import typeofDef from "./typeof" +import instanceofDef from "./instanceof" +import range from "./range" +import exclusiveRange from "./exclusiveRange" +import regexp from "./regexp" +import transform from "./transform" +import uniqueItemProperties from "./uniqueItemProperties" +import allRequired from "./allRequired" +import anyRequired from "./anyRequired" +import oneRequired from "./oneRequired" +import patternRequired, {PatternRequiredError} from "./patternRequired" +import prohibited from "./prohibited" +import deepProperties from "./deepProperties" +import deepRequired from "./deepRequired" +import dynamicDefaults from "./dynamicDefaults" +import selectDef, {SelectError} from "./select" + +const definitions: GetDefinition[] = [ + typeofDef, + instanceofDef, + range, + exclusiveRange, + regexp, + transform, + uniqueItemProperties, + allRequired, + anyRequired, + oneRequired, + patternRequired, + prohibited, + deepProperties, + deepRequired, + dynamicDefaults, +] + +export default function ajvKeywords(opts?: DefinitionOptions): Vocabulary { + return definitions.map((d) => d(opts)).concat(selectDef(opts)) +} + +export type AjvKeywordsError = + | PatternRequiredError + | SelectError + | ErrorNoParams< + | "range" + | "exclusiveRange" + | "anyRequired" + | "oneRequired" + | "allRequired" + | "deepProperties" + | "deepRequired" + | "dynamicDefaults" + | "instanceof" + | "prohibited" + | "regexp" + | "transform" + | "uniqueItemProperties" + > + +module.exports = ajvKeywords diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/instanceof.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/instanceof.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f1c54f574c16341fd3e3180f1faede89091dd06 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/instanceof.ts @@ -0,0 +1,61 @@ +import type {FuncKeywordDefinition} from "ajv" + +type Constructor = new (...args: any[]) => any + +const CONSTRUCTORS: Record = { + Object, + Array, + Function, + Number, + String, + Date, + RegExp, +} + +/* istanbul ignore else */ +if (typeof Buffer != "undefined") CONSTRUCTORS.Buffer = Buffer + +/* istanbul ignore else */ +if (typeof Promise != "undefined") CONSTRUCTORS.Promise = Promise + +const getDef: (() => FuncKeywordDefinition) & { + CONSTRUCTORS: typeof CONSTRUCTORS +} = Object.assign(_getDef, {CONSTRUCTORS}) + +function _getDef(): FuncKeywordDefinition { + return { + keyword: "instanceof", + schemaType: ["string", "array"], + compile(schema: string | string[]) { + if (typeof schema == "string") { + const C = getConstructor(schema) + return (data) => data instanceof C + } + + if (Array.isArray(schema)) { + const constructors = schema.map(getConstructor) + return (data) => { + for (const C of constructors) { + if (data instanceof C) return true + } + return false + } + } + + /* istanbul ignore next */ + throw new Error("ajv implementation error") + }, + metaSchema: { + anyOf: [{type: "string"}, {type: "array", items: {type: "string"}}], + }, + } +} + +function getConstructor(c: string): Constructor { + const C = CONSTRUCTORS[c] + if (C) return C + throw new Error(`invalid "instanceof" keyword value ${c}`) +} + +export default getDef +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/oneRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/oneRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..79c44c97a3f5ecb56648a2b25ad219c96ad59b27 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/oneRequired.ts @@ -0,0 +1,8 @@ +import type {MacroKeywordDefinition} from "ajv" +import type {GetDefinition} from "./_types" +import getRequiredDef from "./_required" + +const getDef: GetDefinition = getRequiredDef("oneRequired") + +export default getDef +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/patternRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/patternRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..63235c52450b04bf4b743b793ae9b50c923ca9a6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/patternRequired.ts @@ -0,0 +1,46 @@ +import type {CodeKeywordDefinition, KeywordCxt, KeywordErrorDefinition, ErrorObject} from "ajv" +import {_, str, and} from "ajv/dist/compile/codegen" +import {usePattern} from "./_util" + +export type PatternRequiredError = ErrorObject<"patternRequired", {missingPattern: string}> + +const error: KeywordErrorDefinition = { + message: ({params: {missingPattern}}) => + str`should have property matching pattern '${missingPattern}'`, + params: ({params: {missingPattern}}) => _`{missingPattern: ${missingPattern}}`, +} + +export default function getDef(): CodeKeywordDefinition { + return { + keyword: "patternRequired", + type: "object", + schemaType: "array", + error, + code(cxt: KeywordCxt) { + const {gen, schema, data} = cxt + if (schema.length === 0) return + const valid = gen.let("valid", true) + for (const pat of schema) validateProperties(pat) + + function validateProperties(pattern: string): void { + const matched = gen.let("matched", false) + + gen.forIn("key", data, (key) => { + gen.assign(matched, _`${usePattern(cxt, pattern)}.test(${key})`) + gen.if(matched, () => gen.break()) + }) + + cxt.setParams({missingPattern: pattern}) + gen.assign(valid, and(valid, matched)) + cxt.pass(valid) + } + }, + metaSchema: { + type: "array", + items: {type: "string", format: "regex"}, + uniqueItems: true, + }, + } +} + +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/prohibited.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/prohibited.ts new file mode 100644 index 0000000000000000000000000000000000000000..659fdda1ed540e02f6790cadf351a682e8878829 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/prohibited.ts @@ -0,0 +1,20 @@ +import type {MacroKeywordDefinition} from "ajv" + +export default function getDef(): MacroKeywordDefinition { + return { + keyword: "prohibited", + type: "object", + schemaType: "array", + macro: function (schema: string[]) { + if (schema.length === 0) return true + if (schema.length === 1) return {not: {required: schema}} + return {not: {anyOf: schema.map((p) => ({required: [p]}))}} + }, + metaSchema: { + type: "array", + items: {type: "string"}, + }, + } +} + +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/range.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/range.ts new file mode 100644 index 0000000000000000000000000000000000000000..c867b7d1d9fea3b1e34a6adfc59bcf1dcfd74b30 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/range.ts @@ -0,0 +1,8 @@ +import type {MacroKeywordDefinition} from "ajv" +import type {GetDefinition} from "./_types" +import getRangeDef from "./_range" + +const getDef: GetDefinition = getRangeDef("range") + +export default getDef +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/regexp.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/regexp.ts new file mode 100644 index 0000000000000000000000000000000000000000..68ddef830f7c70b9ccbce03e42630eb704ae6c10 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/regexp.ts @@ -0,0 +1,45 @@ +import type {CodeKeywordDefinition, KeywordCxt, JSONSchemaType, Name} from "ajv" +import {_} from "ajv/dist/compile/codegen" +import {usePattern} from "./_util" + +interface RegexpSchema { + pattern: string + flags?: string +} + +const regexpMetaSchema: JSONSchemaType = { + type: "object", + properties: { + pattern: {type: "string"}, + flags: {type: "string", nullable: true}, + }, + required: ["pattern"], + additionalProperties: false, +} + +const metaRegexp = /^\/(.*)\/([gimuy]*)$/ + +export default function getDef(): CodeKeywordDefinition { + return { + keyword: "regexp", + type: "string", + schemaType: ["string", "object"], + code(cxt: KeywordCxt) { + const {data, schema} = cxt + const regx = getRegExp(schema) + cxt.pass(_`${regx}.test(${data})`) + + function getRegExp(sch: string | RegexpSchema): Name { + if (typeof sch == "object") return usePattern(cxt, sch.pattern, sch.flags) + const rx = metaRegexp.exec(sch) + if (rx) return usePattern(cxt, rx[1], rx[2]) + throw new Error("cannot parse string into RegExp") + } + }, + metaSchema: { + anyOf: [{type: "string"}, regexpMetaSchema], + }, + } +} + +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/select.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/select.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5cc19f5513434e0210e4e109d7e5ecebe634d8a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/select.ts @@ -0,0 +1,69 @@ +import type {KeywordDefinition, KeywordErrorDefinition, KeywordCxt, ErrorObject} from "ajv" +import {_, str, nil, Name} from "ajv/dist/compile/codegen" +import type {DefinitionOptions} from "./_types" +import {metaSchemaRef} from "./_util" + +export type SelectError = ErrorObject<"select", {failingCase?: string; failingDefault?: true}> + +const error: KeywordErrorDefinition = { + message: ({params: {schemaProp}}) => + schemaProp + ? str`should match case "${schemaProp}" schema` + : str`should match default case schema`, + params: ({params: {schemaProp}}) => + schemaProp ? _`{failingCase: ${schemaProp}}` : _`{failingDefault: true}`, +} + +export default function getDef(opts?: DefinitionOptions): KeywordDefinition[] { + const metaSchema = metaSchemaRef(opts) + + return [ + { + keyword: "select", + schemaType: ["string", "number", "boolean", "null"], + $data: true, + error, + dependencies: ["selectCases"], + code(cxt: KeywordCxt) { + const {gen, schemaCode, parentSchema} = cxt + cxt.block$data(nil, () => { + const valid = gen.let("valid", true) + const schValid = gen.name("_valid") + const value = gen.const("value", _`${schemaCode} === null ? "null" : ${schemaCode}`) + gen.if(false) // optimizer should remove it from generated code + for (const schemaProp in parentSchema.selectCases) { + cxt.setParams({schemaProp}) + gen.elseIf(_`"" + ${value} == ${schemaProp}`) // intentional ==, to match numbers and booleans + const schCxt = cxt.subschema({keyword: "selectCases", schemaProp}, schValid) + cxt.mergeEvaluated(schCxt, Name) + gen.assign(valid, schValid) + } + gen.else() + if (parentSchema.selectDefault !== undefined) { + cxt.setParams({schemaProp: undefined}) + const schCxt = cxt.subschema({keyword: "selectDefault"}, schValid) + cxt.mergeEvaluated(schCxt, Name) + gen.assign(valid, schValid) + } + gen.endIf() + cxt.pass(valid) + }) + }, + }, + { + keyword: "selectCases", + dependencies: ["select"], + metaSchema: { + type: "object", + additionalProperties: metaSchema, + }, + }, + { + keyword: "selectDefault", + dependencies: ["select", "selectCases"], + metaSchema, + }, + ] +} + +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/transform.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/transform.ts new file mode 100644 index 0000000000000000000000000000000000000000..af4ae291be6fe2984446953727d31b83b085f85c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/transform.ts @@ -0,0 +1,98 @@ +import type {CodeKeywordDefinition, AnySchemaObject, KeywordCxt, Code, Name} from "ajv" +import {_, stringify, getProperty} from "ajv/dist/compile/codegen" + +type TransformName = + | "trimStart" + | "trimEnd" + | "trimLeft" + | "trimRight" + | "trim" + | "toLowerCase" + | "toUpperCase" + | "toEnumCase" + +interface TransformConfig { + hash: Record +} + +type Transform = (s: string, cfg?: TransformConfig) => string + +const transform: {[key in TransformName]: Transform} = { + trimStart: (s) => s.trimStart(), + trimEnd: (s) => s.trimEnd(), + trimLeft: (s) => s.trimStart(), + trimRight: (s) => s.trimEnd(), + trim: (s) => s.trim(), + toLowerCase: (s) => s.toLowerCase(), + toUpperCase: (s) => s.toUpperCase(), + toEnumCase: (s, cfg) => cfg?.hash[configKey(s)] || s, +} + +const getDef: (() => CodeKeywordDefinition) & { + transform: typeof transform +} = Object.assign(_getDef, {transform}) + +function _getDef(): CodeKeywordDefinition { + return { + keyword: "transform", + schemaType: "array", + before: "enum", + code(cxt: KeywordCxt) { + const {gen, data, schema, parentSchema, it} = cxt + const {parentData, parentDataProperty} = it + const tNames: string[] = schema + if (!tNames.length) return + let cfg: Name | undefined + if (tNames.includes("toEnumCase")) { + const config = getEnumCaseCfg(parentSchema) + cfg = gen.scopeValue("obj", {ref: config, code: stringify(config)}) + } + gen.if(_`typeof ${data} == "string" && ${parentData} !== undefined`, () => { + gen.assign(data, transformExpr(tNames.slice())) + gen.assign(_`${parentData}[${parentDataProperty}]`, data) + }) + + function transformExpr(ts: string[]): Code { + if (!ts.length) return data + const t = ts.pop() as string + if (!(t in transform)) throw new Error(`transform: unknown transformation ${t}`) + const func = gen.scopeValue("func", { + ref: transform[t as TransformName], + code: _`require("ajv-keywords/dist/definitions/transform").transform${getProperty(t)}`, + }) + const arg = transformExpr(ts) + return cfg && t === "toEnumCase" ? _`${func}(${arg}, ${cfg})` : _`${func}(${arg})` + } + }, + metaSchema: { + type: "array", + items: {type: "string", enum: Object.keys(transform)}, + }, + } +} + +function getEnumCaseCfg(parentSchema: AnySchemaObject): TransformConfig { + // build hash table to enum values + const cfg: TransformConfig = {hash: {}} + + // requires `enum` in the same schema as transform + if (!parentSchema.enum) throw new Error('transform: "toEnumCase" requires "enum"') + for (const v of parentSchema.enum) { + if (typeof v !== "string") continue + const k = configKey(v) + // requires all `enum` values have unique keys + if (cfg.hash[k]) { + throw new Error('transform: "toEnumCase" requires all lowercased "enum" values to be unique') + } + cfg.hash[k] = v + } + + return cfg +} + +function configKey(s: string): string { + return s.toLowerCase() +} + +export default getDef +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/typeof.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/typeof.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8b39fbfe6a98833a3e08525a4a3b830f420b740 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/typeof.ts @@ -0,0 +1,27 @@ +import type {CodeKeywordDefinition, KeywordCxt} from "ajv" +import {_} from "ajv/dist/compile/codegen" + +const TYPES = ["undefined", "string", "number", "object", "function", "boolean", "symbol"] + +export default function getDef(): CodeKeywordDefinition { + return { + keyword: "typeof", + schemaType: ["string", "array"], + code(cxt: KeywordCxt) { + const {data, schema, schemaValue} = cxt + cxt.fail( + typeof schema == "string" + ? _`typeof ${data} != ${schema}` + : _`${schemaValue}.indexOf(typeof ${data}) < 0` + ) + }, + metaSchema: { + anyOf: [ + {type: "string", enum: TYPES}, + {type: "array", items: {type: "string", enum: TYPES}}, + ], + }, + } +} + +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/uniqueItemProperties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/uniqueItemProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b2c6f9450575e55c0a946f72ca136d358c9cac0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/definitions/uniqueItemProperties.ts @@ -0,0 +1,58 @@ +import type {FuncKeywordDefinition, AnySchemaObject} from "ajv" +import equal = require("fast-deep-equal") + +const SCALAR_TYPES = ["number", "integer", "string", "boolean", "null"] + +export default function getDef(): FuncKeywordDefinition { + return { + keyword: "uniqueItemProperties", + type: "array", + schemaType: "array", + compile(keys: string[], parentSchema: AnySchemaObject) { + const scalar = getScalarKeys(keys, parentSchema) + + return (data) => { + if (data.length <= 1) return true + for (let k = 0; k < keys.length; k++) { + const key = keys[k] + if (scalar[k]) { + const hash: Record = {} + for (const x of data) { + if (!x || typeof x != "object") continue + let p = x[key] + if (p && typeof p == "object") continue + if (typeof p == "string") p = '"' + p + if (hash[p]) return false + hash[p] = true + } + } else { + for (let i = data.length; i--; ) { + const x = data[i] + if (!x || typeof x != "object") continue + for (let j = i; j--; ) { + const y = data[j] + if (y && typeof y == "object" && equal(x[key], y[key])) return false + } + } + } + } + return true + } + }, + metaSchema: { + type: "array", + items: {type: "string"}, + }, + } +} + +function getScalarKeys(keys: string[], schema: AnySchemaObject): boolean[] { + return keys.map((key) => { + const t = schema.items?.properties?.[key]?.type + return Array.isArray(t) + ? !t.includes("object") && !t.includes("array") + : SCALAR_TYPES.includes(t) + }) +} + +module.exports = getDef diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..bb580fb3abc22eb620bc8eb536bc227055f75a28 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/index.ts @@ -0,0 +1,32 @@ +import type Ajv from "ajv" +import type {Plugin} from "ajv" +import plugins from "./keywords" + +export {AjvKeywordsError} from "./definitions" + +const ajvKeywords: Plugin = (ajv: Ajv, keyword?: string | string[]): Ajv => { + if (Array.isArray(keyword)) { + for (const k of keyword) get(k)(ajv) + return ajv + } + if (keyword) { + get(keyword)(ajv) + return ajv + } + for (keyword in plugins) get(keyword)(ajv) + return ajv +} + +ajvKeywords.get = get + +function get(keyword: string): Plugin { + const defFunc = plugins[keyword] + if (!defFunc) throw new Error("Unknown keyword " + keyword) + return defFunc +} + +export default ajvKeywords +module.exports = ajvKeywords + +// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access +module.exports.default = ajvKeywords diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/allRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/allRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..30cce4371adeb20b9bdee15209aede089d5af8e2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/allRequired.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/allRequired" + +const allRequired: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default allRequired +module.exports = allRequired diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/anyRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/anyRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..b55b817ef09b50a51f02ceb6ec3ee2b666ef427b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/anyRequired.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/anyRequired" + +const anyRequired: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default anyRequired +module.exports = anyRequired diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/deepProperties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/deepProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..e035531e281552f6e93a4107d4ce411d2b25fbbc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/deepProperties.ts @@ -0,0 +1,9 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/deepProperties" +import type {DefinitionOptions} from "../definitions/_types" + +const deepProperties: Plugin = (ajv, opts?: DefinitionOptions) => + ajv.addKeyword(getDef(opts)) + +export default deepProperties +module.exports = deepProperties diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/deepRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/deepRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..44b19ae2d342597cb0e8160860ea736f5ed544ab --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/deepRequired.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/deepRequired" + +const deepRequired: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default deepRequired +module.exports = deepRequired diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/dynamicDefaults.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/dynamicDefaults.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8f820537b2180f8db2aa986990126f40e86814a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/dynamicDefaults.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/dynamicDefaults" + +const dynamicDefaults: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default dynamicDefaults +module.exports = dynamicDefaults diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/exclusiveRange.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/exclusiveRange.ts new file mode 100644 index 0000000000000000000000000000000000000000..407a374e640af1cc84108dd6684a382c115bcb0e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/exclusiveRange.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/exclusiveRange" + +const exclusiveRange: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default exclusiveRange +module.exports = exclusiveRange diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..edf99963b7686aefbdc17424572d1a38c9933e07 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/index.ts @@ -0,0 +1,40 @@ +import type {Plugin} from "ajv" +import typeofPlugin from "./typeof" +import instanceofPlugin from "./instanceof" +import range from "./range" +import exclusiveRange from "./exclusiveRange" +import regexp from "./regexp" +import transform from "./transform" +import uniqueItemProperties from "./uniqueItemProperties" +import allRequired from "./allRequired" +import anyRequired from "./anyRequired" +import oneRequired from "./oneRequired" +import patternRequired from "./patternRequired" +import prohibited from "./prohibited" +import deepProperties from "./deepProperties" +import deepRequired from "./deepRequired" +import dynamicDefaults from "./dynamicDefaults" +import select from "./select" + +// TODO type +const ajvKeywords: Record | undefined> = { + typeof: typeofPlugin, + instanceof: instanceofPlugin, + range, + exclusiveRange, + regexp, + transform, + uniqueItemProperties, + allRequired, + anyRequired, + oneRequired, + patternRequired, + prohibited, + deepProperties, + deepRequired, + dynamicDefaults, + select, +} + +export default ajvKeywords +module.exports = ajvKeywords diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/instanceof.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/instanceof.ts new file mode 100644 index 0000000000000000000000000000000000000000..98a2463dde5a0944b95e7b3126ab2fa8b63deea8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/instanceof.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/instanceof" + +const instanceofPlugin: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default instanceofPlugin +module.exports = instanceofPlugin diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/oneRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/oneRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..452bb244f39c2d95884068d40c123d5b4d107704 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/oneRequired.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/oneRequired" + +const oneRequired: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default oneRequired +module.exports = oneRequired diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/patternRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/patternRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..f9e4e50c9a853e286c160d76bdacfad7ad3a5213 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/patternRequired.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/patternRequired" + +const patternRequired: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default patternRequired +module.exports = patternRequired diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/prohibited.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/prohibited.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4f057647be094e50001ee585462024ad24aeaab --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/prohibited.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/prohibited" + +const prohibited: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default prohibited +module.exports = prohibited diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/range.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/range.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fd28ce0904e57e995c3206e13e69292f1e44001 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/range.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/range" + +const range: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default range +module.exports = range diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/regexp.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/regexp.ts new file mode 100644 index 0000000000000000000000000000000000000000..48c461cbaf4be6bee6fac0ccaf04a330c62f3b7b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/regexp.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/regexp" + +const regexp: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default regexp +module.exports = regexp diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/select.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/select.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc3bd8162bd73d50adc91573e25550299984463a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/select.ts @@ -0,0 +1,11 @@ +import type {Plugin} from "ajv" +import getDefs from "../definitions/select" +import type {DefinitionOptions} from "../definitions/_types" + +const select: Plugin = (ajv, opts?: DefinitionOptions) => { + getDefs(opts).forEach((d) => ajv.addKeyword(d)) + return ajv +} + +export default select +module.exports = select diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/transform.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/transform.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6335ec40e12d2e10f54128f2969c6a02d08c9f9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/transform.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/transform" + +const transform: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default transform +module.exports = transform diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/typeof.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/typeof.ts new file mode 100644 index 0000000000000000000000000000000000000000..a171c50720fe1c77010bbd21c8603c1df14074ea --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/typeof.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/typeof" + +const typeofPlugin: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default typeofPlugin +module.exports = typeofPlugin diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/uniqueItemProperties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/uniqueItemProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..1dc5fe3e8fc11e3ca6d38c629b81b7c6232fe31b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv-keywords/src/keywords/uniqueItemProperties.ts @@ -0,0 +1,7 @@ +import type {Plugin} from "ajv" +import getDef from "../definitions/uniqueItemProperties" + +const uniqueItemProperties: Plugin = (ajv) => ajv.addKeyword(getDef()) + +export default uniqueItemProperties +module.exports = uniqueItemProperties diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/code.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/code.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0220ad7648c57f5ef2838b251e1280910efe591 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/code.d.ts @@ -0,0 +1,40 @@ +export declare abstract class _CodeOrName { + abstract readonly str: string; + abstract readonly names: UsedNames; + abstract toString(): string; + abstract emptyStr(): boolean; +} +export declare const IDENTIFIER: RegExp; +export declare class Name extends _CodeOrName { + readonly str: string; + constructor(s: string); + toString(): string; + emptyStr(): boolean; + get names(): UsedNames; +} +export declare class _Code extends _CodeOrName { + readonly _items: readonly CodeItem[]; + private _str?; + private _names?; + constructor(code: string | readonly CodeItem[]); + toString(): string; + emptyStr(): boolean; + get str(): string; + get names(): UsedNames; +} +export type CodeItem = Name | string | number | boolean | null; +export type UsedNames = Record; +export type Code = _Code | Name; +export type SafeExpr = Code | number | boolean | null; +export declare const nil: _Code; +type CodeArg = SafeExpr | string | undefined; +export declare function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code; +export declare function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code; +export declare function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void; +export declare function strConcat(c1: Code, c2: Code): Code; +export declare function stringify(x: unknown): Code; +export declare function safeStringify(x: unknown): string; +export declare function getProperty(key: Code | string | number): Code; +export declare function getEsmExportName(key: Code | string | number): Code; +export declare function regexpCode(rx: RegExp): Code; +export {}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/index.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d586a4b49f79d65f71598781c6beed3c9ec332e4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/index.d.ts @@ -0,0 +1,79 @@ +import type { ScopeValueSets, NameValue, ValueScope, ValueScopeName } from "./scope"; +import { _Code, Code, Name } from "./code"; +import { Scope } from "./scope"; +export { _, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code } from "./code"; +export { Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds } from "./scope"; +export type SafeExpr = Code | number | boolean | null; +export type Block = Code | (() => void); +export declare const operators: { + GT: _Code; + GTE: _Code; + LT: _Code; + LTE: _Code; + EQ: _Code; + NEQ: _Code; + NOT: _Code; + OR: _Code; + AND: _Code; + ADD: _Code; +}; +export interface CodeGenOptions { + es5?: boolean; + lines?: boolean; + ownProperties?: boolean; +} +export declare class CodeGen { + readonly _scope: Scope; + readonly _extScope: ValueScope; + readonly _values: ScopeValueSets; + private readonly _nodes; + private readonly _blockStarts; + private readonly _constants; + private readonly opts; + constructor(extScope: ValueScope, opts?: CodeGenOptions); + toString(): string; + name(prefix: string): Name; + scopeName(prefix: string): ValueScopeName; + scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name; + getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined; + scopeRefs(scopeName: Name): Code; + scopeCode(): Code; + private _def; + const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name; + let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name; + var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name; + assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen; + add(lhs: Code, rhs: SafeExpr): CodeGen; + code(c: Block | SafeExpr): CodeGen; + object(...keyValues: [Name | string, SafeExpr | string][]): _Code; + if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen; + elseIf(condition: Code | boolean): CodeGen; + else(): CodeGen; + endIf(): CodeGen; + private _for; + for(iteration: Code, forBody?: Block): CodeGen; + forRange(nameOrPrefix: Name | string, from: SafeExpr, to: SafeExpr, forBody: (index: Name) => void, varKind?: Code): CodeGen; + forOf(nameOrPrefix: Name | string, iterable: Code, forBody: (item: Name) => void, varKind?: Code): CodeGen; + forIn(nameOrPrefix: Name | string, obj: Code, forBody: (item: Name) => void, varKind?: Code): CodeGen; + endFor(): CodeGen; + label(label: Name): CodeGen; + break(label?: Code): CodeGen; + return(value: Block | SafeExpr): CodeGen; + try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen; + throw(error: Code): CodeGen; + block(body?: Block, nodeCount?: number): CodeGen; + endBlock(nodeCount?: number): CodeGen; + func(name: Name, args?: Code, async?: boolean, funcBody?: Block): CodeGen; + endFunc(): CodeGen; + optimize(n?: number): void; + private _leafNode; + private _blockNode; + private _endBlockNode; + private _elseNode; + private get _root(); + private get _currNode(); + private set _currNode(value); +} +export declare function not(x: T): T; +export declare function and(...args: Code[]): Code; +export declare function or(...args: Code[]): Code; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/index.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..baef9cff5623858c70b4b5f37eddc4209d726bf4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/compile/codegen/index.ts"],"names":[],"mappings":";;;AACA,iCAA8F;AAC9F,mCAAuC;AAEvC,+BAA6F;AAArF,yFAAA,CAAC,OAAA;AAAE,2FAAA,GAAG,OAAA;AAAE,iGAAA,SAAS,OAAA;AAAE,2FAAA,GAAG,OAAA;AAAE,mGAAA,WAAW,OAAA;AAAE,iGAAA,SAAS,OAAA;AAAE,kGAAA,UAAU,OAAA;AAAE,4FAAA,IAAI,OAAA;AACxE,iCAA+F;AAAvF,8FAAA,KAAK,OAAA;AAAc,mGAAA,UAAU,OAAA;AAAE,uGAAA,cAAc,OAAA;AAAkB,iGAAA,QAAQ,OAAA;AAQlE,QAAA,SAAS,GAAG;IACvB,EAAE,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IAClB,GAAG,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACpB,EAAE,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IAClB,GAAG,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACpB,EAAE,EAAE,IAAI,YAAK,CAAC,KAAK,CAAC;IACpB,GAAG,EAAE,IAAI,YAAK,CAAC,KAAK,CAAC;IACrB,GAAG,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;IACnB,EAAE,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACnB,GAAG,EAAE,IAAI,YAAK,CAAC,IAAI,CAAC;IACpB,GAAG,EAAE,IAAI,YAAK,CAAC,GAAG,CAAC;CACpB,CAAA;AAED,MAAe,IAAI;IAGjB,aAAa;QACX,OAAO,IAAI,CAAA;IACb,CAAC;IAED,aAAa,CAAC,MAAiB,EAAE,UAAqB;QACpD,OAAO,IAAI,CAAA;IACb,CAAC;CAKF;AAED,MAAM,GAAI,SAAQ,IAAI;IACpB,YACmB,OAAa,EACb,IAAU,EACnB,GAAc;QAEtB,KAAK,EAAE,CAAA;QAJU,YAAO,GAAP,OAAO,CAAM;QACb,SAAI,GAAJ,IAAI,CAAM;QACnB,QAAG,GAAH,GAAG,CAAW;IAGxB,CAAC;IAED,MAAM,CAAC,EAAC,GAAG,EAAE,EAAE,EAAY;QACzB,MAAM,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAA;QACjD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,GAAG,EAAE,CAAA;QAC1D,OAAO,GAAG,OAAO,IAAI,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,GAAG,EAAE,CAAA;IAC9C,CAAC;IAED,aAAa,CAAC,KAAgB,EAAE,SAAoB;QAClD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;YAAE,OAAM;QACjC,IAAI,IAAI,CAAC,GAAG;YAAE,IAAI,CAAC,GAAG,GAAG,YAAY,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,CAAA;QACjE,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,GAAG,YAAY,kBAAW,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAA;IAC9D,CAAC;CACF;AAED,MAAM,MAAO,SAAQ,IAAI;IACvB,YACW,GAAS,EACX,GAAa,EACH,WAAqB;QAEtC,KAAK,EAAE,CAAA;QAJE,QAAG,GAAH,GAAG,CAAM;QACX,QAAG,GAAH,GAAG,CAAU;QACH,gBAAW,GAAX,WAAW,CAAU;IAGxC,CAAC;IAED,MAAM,CAAC,EAAC,EAAE,EAAY;QACpB,OAAO,GAAG,IAAI,CAAC,GAAG,MAAM,IAAI,CAAC,GAAG,GAAG,GAAG,EAAE,CAAA;IAC1C,CAAC;IAED,aAAa,CAAC,KAAgB,EAAE,SAAoB;QAClD,IAAI,IAAI,CAAC,GAAG,YAAY,WAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW;YAAE,OAAM;QACjF,IAAI,CAAC,GAAG,GAAG,YAAY,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,SAAS,CAAC,CAAA;QACnD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,KAAK;QACP,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,YAAY,WAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAC,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAC,CAAA;QACjE,OAAO,YAAY,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,CAAA;IACtC,CAAC;CACF;AAED,MAAM,QAAS,SAAQ,MAAM;IAC3B,YACE,GAAS,EACQ,EAAQ,EACzB,GAAa,EACb,WAAqB;QAErB,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,WAAW,CAAC,CAAA;QAJX,OAAE,GAAF,EAAE,CAAM;IAK3B,CAAC;IAED,MAAM,CAAC,EAAC,EAAE,EAAY;QACpB,OAAO,GAAG,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,EAAE,KAAK,IAAI,CAAC,GAAG,GAAG,GAAG,EAAE,CAAA;IACpD,CAAC;CACF;AAED,MAAM,KAAM,SAAQ,IAAI;IAEtB,YAAqB,KAAW;QAC9B,KAAK,EAAE,CAAA;QADY,UAAK,GAAL,KAAK,CAAM;QADvB,UAAK,GAAc,EAAE,CAAA;IAG9B,CAAC;IAED,MAAM,CAAC,EAAC,EAAE,EAAY;QACpB,OAAO,GAAG,IAAI,CAAC,KAAK,GAAG,GAAG,EAAE,CAAA;IAC9B,CAAC;CACF;AAED,MAAM,KAAM,SAAQ,IAAI;IAEtB,YAAqB,KAAY;QAC/B,KAAK,EAAE,CAAA;QADY,UAAK,GAAL,KAAK,CAAO;QADxB,UAAK,GAAc,EAAE,CAAA;IAG9B,CAAC;IAED,MAAM,CAAC,EAAC,EAAE,EAAY;QACpB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QAChD,OAAO,QAAQ,KAAK,GAAG,GAAG,EAAE,CAAA;IAC9B,CAAC;CACF;AAED,MAAM,KAAM,SAAQ,IAAI;IACtB,YAAqB,KAAW;QAC9B,KAAK,EAAE,CAAA;QADY,UAAK,GAAL,KAAK,CAAM;IAEhC,CAAC;IAED,MAAM,CAAC,EAAC,EAAE,EAAY;QACpB,OAAO,SAAS,IAAI,CAAC,KAAK,GAAG,GAAG,EAAE,CAAA;IACpC,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAA;IACzB,CAAC;CACF;AAED,MAAM,OAAQ,SAAQ,IAAI;IACxB,YAAoB,IAAc;QAChC,KAAK,EAAE,CAAA;QADW,SAAI,GAAJ,IAAI,CAAU;IAElC,CAAC;IAED,MAAM,CAAC,EAAC,EAAE,EAAY;QACpB,OAAO,GAAG,IAAI,CAAC,IAAI,GAAG,GAAG,EAAE,CAAA;IAC7B,CAAC;IAED,aAAa;QACX,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;IAED,aAAa,CAAC,KAAgB,EAAE,SAAoB;QAClD,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,SAAS,CAAC,CAAA;QACrD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,IAAI,YAAY,kBAAW,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAA;IAChE,CAAC;CACF;AAED,MAAe,UAAW,SAAQ,IAAI;IACpC,YAAqB,QAAqB,EAAE;QAC1C,KAAK,EAAE,CAAA;QADY,UAAK,GAAL,KAAK,CAAkB;IAE5C,CAAC;IAED,MAAM,CAAC,IAAe;QACpB,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAA;IAClE,CAAC;IAED,aAAa;QACX,MAAM,EAAC,KAAK,EAAC,GAAG,IAAI,CAAA;QACpB,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAA;QACpB,OAAO,CAAC,EAAE,EAAE,CAAC;YACX,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAA;YAClC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;gBAAE,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC,CAAA;iBACzC,IAAI,CAAC;gBAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;;gBACnB,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;QACzB,CAAC;QACD,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;IAC5C,CAAC;IAED,aAAa,CAAC,KAAgB,EAAE,SAAoB;QAClD,MAAM,EAAC,KAAK,EAAC,GAAG,IAAI,CAAA;QACpB,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAA;QACpB,OAAO,CAAC,EAAE,EAAE,CAAC;YACX,mDAAmD;YACnD,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAA;YAClB,IAAI,CAAC,CAAC,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC;gBAAE,SAAQ;YAC/C,aAAa,CAAC,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,CAAA;YAC7B,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;QACpB,CAAC;QACD,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;IAC5C,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,KAAgB,EAAE,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,CAAA;IACjF,CAAC;CAKF;AAED,MAAe,SAAU,SAAQ,UAAU;IACzC,MAAM,CAAC,IAAe;QACpB,OAAO,GAAG,GAAG,IAAI,CAAC,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG,GAAG,IAAI,CAAC,EAAE,CAAA;IAC3D,CAAC;CACF;AAED,MAAM,IAAK,SAAQ,UAAU;CAAG;AAEhC,MAAM,IAAK,SAAQ,SAAS;;AACV,SAAI,GAAG,MAAM,CAAA;AAG/B,MAAM,EAAG,SAAQ,SAAS;IAGxB,YACU,SAAyB,EACjC,KAAmB;QAEnB,KAAK,CAAC,KAAK,CAAC,CAAA;QAHJ,cAAS,GAAT,SAAS,CAAgB;IAInC,CAAC;IAED,MAAM,CAAC,IAAe;QACpB,IAAI,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QACvD,IAAI,IAAI,CAAC,IAAI;YAAE,IAAI,IAAI,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QACvD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,aAAa;QACX,KAAK,CAAC,aAAa,EAAE,CAAA;QACrB,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAA;QAC3B,IAAI,IAAI,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC,KAAK,CAAA,CAAC,uBAAuB;QAC5D,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAA;QACjB,IAAI,CAAC,EAAE,CAAC;YACN,MAAM,EAAE,GAAG,CAAC,CAAC,aAAa,EAAE,CAAA;YAC5B,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAE,EAAuB,CAAA;QAC7E,CAAC;QACD,IAAI,CAAC,EAAE,CAAC;YACN,IAAI,IAAI,KAAK,KAAK;gBAAE,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA;YACxD,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM;gBAAE,OAAO,IAAI,CAAA;YAClC,OAAO,IAAI,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAA;QAC3D,CAAC;QACD,IAAI,IAAI,KAAK,KAAK,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM;YAAE,OAAO,SAAS,CAAA;QAC1D,OAAO,IAAI,CAAA;IACb,CAAC;IAED,aAAa,CAAC,KAAgB,EAAE,SAAoB;;QAClD,IAAI,CAAC,IAAI,GAAG,MAAA,IAAI,CAAC,IAAI,0CAAE,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;QACtD,IAAI,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC;YAAE,OAAM;QACjE,IAAI,CAAC,SAAS,GAAG,YAAY,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,EAAE,SAAS,CAAC,CAAA;QAC/D,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,KAAK;QACP,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAA;QACzB,YAAY,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAA;QACnC,IAAI,IAAI,CAAC,IAAI;YAAE,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAC/C,OAAO,KAAK,CAAA;IACd,CAAC;;AA7Ce,OAAI,GAAG,IAAI,CAAA;AAoD7B,MAAe,GAAI,SAAQ,SAAS;;AAClB,QAAI,GAAG,KAAK,CAAA;AAG9B,MAAM,OAAQ,SAAQ,GAAG;IACvB,YAAoB,SAAe;QACjC,KAAK,EAAE,CAAA;QADW,cAAS,GAAT,SAAS,CAAM;IAEnC,CAAC;IAED,MAAM,CAAC,IAAe;QACpB,OAAO,OAAO,IAAI,CAAC,SAAS,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACtD,CAAC;IAED,aAAa,CAAC,KAAgB,EAAE,SAAoB;QAClD,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC;YAAE,OAAM;QAClD,IAAI,CAAC,SAAS,GAAG,YAAY,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,EAAE,SAAS,CAAC,CAAA;QAC/D,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,KAAK;QACP,OAAO,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;IACpD,CAAC;CACF;AAED,MAAM,QAAS,SAAQ,GAAG;IACxB,YACmB,OAAa,EACb,IAAU,EACV,IAAc,EACd,EAAY;QAE7B,KAAK,EAAE,CAAA;QALU,YAAO,GAAP,OAAO,CAAM;QACb,SAAI,GAAJ,IAAI,CAAM;QACV,SAAI,GAAJ,IAAI,CAAU;QACd,OAAE,GAAF,EAAE,CAAU;IAG/B,CAAC;IAED,MAAM,CAAC,IAAe;QACpB,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAA;QACtD,MAAM,EAAC,IAAI,EAAE,IAAI,EAAE,EAAE,EAAC,GAAG,IAAI,CAAA;QAC7B,OAAO,OAAO,OAAO,IAAI,IAAI,IAAI,IAAI,KAAK,IAAI,IAAI,EAAE,KAAK,IAAI,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACzF,CAAC;IAED,IAAI,KAAK;QACP,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;QAClD,OAAO,YAAY,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC,CAAA;IACrC,CAAC;CACF;AAED,MAAM,OAAQ,SAAQ,GAAG;IACvB,YACmB,IAAiB,EACjB,OAAa,EACb,IAAU,EACnB,QAAc;QAEtB,KAAK,EAAE,CAAA;QALU,SAAI,GAAJ,IAAI,CAAa;QACjB,YAAO,GAAP,OAAO,CAAM;QACb,SAAI,GAAJ,IAAI,CAAM;QACnB,aAAQ,GAAR,QAAQ,CAAM;IAGxB,CAAC;IAED,MAAM,CAAC,IAAe;QACpB,OAAO,OAAO,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAC/F,CAAC;IAED,aAAa,CAAC,KAAgB,EAAE,SAAoB;QAClD,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC;YAAE,OAAM;QAClD,IAAI,CAAC,QAAQ,GAAG,YAAY,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,SAAS,CAAC,CAAA;QAC7D,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,KAAK;QACP,OAAO,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;IACnD,CAAC;CACF;AAED,MAAM,IAAK,SAAQ,SAAS;IAE1B,YACS,IAAU,EACV,IAAU,EACV,KAAe;QAEtB,KAAK,EAAE,CAAA;QAJA,SAAI,GAAJ,IAAI,CAAM;QACV,SAAI,GAAJ,IAAI,CAAM;QACV,UAAK,GAAL,KAAK,CAAU;IAGxB,CAAC;IAED,MAAM,CAAC,IAAe;QACpB,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAA;QACzC,OAAO,GAAG,MAAM,YAAY,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAC5E,CAAC;;AAZe,SAAI,GAAG,MAAM,CAAA;AAe/B,MAAM,MAAO,SAAQ,UAAU;IAG7B,MAAM,CAAC,IAAe;QACpB,OAAO,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACvC,CAAC;;AAJe,WAAI,GAAG,QAAQ,CAAA;AAOjC,MAAM,GAAI,SAAQ,SAAS;IAIzB,MAAM,CAAC,IAAe;QACpB,IAAI,IAAI,GAAG,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QACrC,IAAI,IAAI,CAAC,KAAK;YAAE,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QAC/C,IAAI,IAAI,CAAC,OAAO;YAAE,IAAI,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QACnD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,aAAa;;QACX,KAAK,CAAC,aAAa,EAAE,CAAA;QACrB,MAAA,IAAI,CAAC,KAAK,0CAAE,aAAa,EAAuB,CAAA;QAChD,MAAA,IAAI,CAAC,OAAO,0CAAE,aAAa,EAAyB,CAAA;QACpD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,aAAa,CAAC,KAAgB,EAAE,SAAoB;;QAClD,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;QACrC,MAAA,IAAI,CAAC,KAAK,0CAAE,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;QAC3C,MAAA,IAAI,CAAC,OAAO,0CAAE,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;QAC7C,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,KAAK;QACP,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAA;QACzB,IAAI,IAAI,CAAC,KAAK;YAAE,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACjD,IAAI,IAAI,CAAC,OAAO;YAAE,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;QACrD,OAAO,KAAK,CAAA;IACd,CAAC;CAKF;AAED,MAAM,KAAM,SAAQ,SAAS;IAE3B,YAAqB,KAAW;QAC9B,KAAK,EAAE,CAAA;QADY,UAAK,GAAL,KAAK,CAAM;IAEhC,CAAC;IAED,MAAM,CAAC,IAAe;QACpB,OAAO,SAAS,IAAI,CAAC,KAAK,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACpD,CAAC;;AAPe,UAAI,GAAG,OAAO,CAAA;AAUhC,MAAM,OAAQ,SAAQ,SAAS;IAE7B,MAAM,CAAC,IAAe;QACpB,OAAO,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IACvC,CAAC;;AAHe,YAAI,GAAG,SAAS,CAAA;AAiClC,MAAa,OAAO;IASlB,YAAY,QAAoB,EAAE,OAAuB,EAAE;QANlD,YAAO,GAAmB,EAAE,CAAA;QAEpB,iBAAY,GAAa,EAAE,CAAA;QAC3B,eAAU,GAAc,EAAE,CAAA;QAIzC,IAAI,CAAC,IAAI,GAAG,EAAC,GAAG,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAC,CAAA;QACjD,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QACzB,IAAI,CAAC,MAAM,GAAG,IAAI,aAAK,CAAC,EAAC,MAAM,EAAE,QAAQ,EAAC,CAAC,CAAA;QAC3C,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA;IAC5B,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACrC,CAAC;IAED,4CAA4C;IAC5C,IAAI,CAAC,MAAc;QACjB,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IACjC,CAAC;IAED,6CAA6C;IAC7C,SAAS,CAAC,MAAc;QACtB,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IACpC,CAAC;IAED,qEAAqE;IACrE,UAAU,CAAC,YAAqC,EAAE,KAAgB;QAChE,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,YAAY,EAAE,KAAK,CAAC,CAAA;QACtD,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,EAAE,CAAC,CAAA;QAC/E,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACZ,OAAO,IAAI,CAAA;IACb,CAAC;IAED,aAAa,CAAC,MAAc,EAAE,QAAiB;QAC7C,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IAClD,CAAC;IAED,8FAA8F;IAC9F,qEAAqE;IACrE,SAAS,CAAC,SAAe;QACvB,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;IAC1D,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAC/C,CAAC;IAEO,IAAI,CACV,OAAa,EACb,YAA2B,EAC3B,GAAc,EACd,QAAkB;QAElB,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAA;QAC7C,IAAI,GAAG,KAAK,SAAS,IAAI,QAAQ;YAAE,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG,CAAA;QAClE,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,CAAC,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;QAC3C,OAAO,IAAI,CAAA;IACb,CAAC;IAED,0CAA0C;IAC1C,KAAK,CAAC,YAA2B,EAAE,GAAa,EAAE,SAAmB;QACnE,OAAO,IAAI,CAAC,IAAI,CAAC,gBAAQ,CAAC,KAAK,EAAE,YAAY,EAAE,GAAG,EAAE,SAAS,CAAC,CAAA;IAChE,CAAC;IAED,iEAAiE;IACjE,GAAG,CAAC,YAA2B,EAAE,GAAc,EAAE,SAAmB;QAClE,OAAO,IAAI,CAAC,IAAI,CAAC,gBAAQ,CAAC,GAAG,EAAE,YAAY,EAAE,GAAG,EAAE,SAAS,CAAC,CAAA;IAC9D,CAAC;IAED,6CAA6C;IAC7C,GAAG,CAAC,YAA2B,EAAE,GAAc,EAAE,SAAmB;QAClE,OAAO,IAAI,CAAC,IAAI,CAAC,gBAAQ,CAAC,GAAG,EAAE,YAAY,EAAE,GAAG,EAAE,SAAS,CAAC,CAAA;IAC9D,CAAC;IAED,kBAAkB;IAClB,MAAM,CAAC,GAAS,EAAE,GAAa,EAAE,WAAqB;QACpD,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC,CAAA;IAC1D,CAAC;IAED,YAAY;IACZ,GAAG,CAAC,GAAS,EAAE,GAAa;QAC1B,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,QAAQ,CAAC,GAAG,EAAE,iBAAS,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;IAC9D,CAAC;IAED,oDAAoD;IACpD,IAAI,CAAC,CAAmB;QACtB,IAAI,OAAO,CAAC,IAAI,UAAU;YAAE,CAAC,EAAE,CAAA;aAC1B,IAAI,CAAC,KAAK,UAAG;YAAE,IAAI,CAAC,SAAS,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAA;QAClD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,kFAAkF;IAClF,MAAM,CAAC,GAAG,SAA+C;QACvD,MAAM,IAAI,GAAe,CAAC,GAAG,CAAC,CAAA;QAC9B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,SAAS,EAAE,CAAC;YACrC,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;gBAAE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;YACnC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;YACd,IAAI,GAAG,KAAK,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;gBACnC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;gBACd,IAAA,iBAAU,EAAC,IAAI,EAAE,KAAK,CAAC,CAAA;YACzB,CAAC;QACH,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QACd,OAAO,IAAI,YAAK,CAAC,IAAI,CAAC,CAAA;IACxB,CAAC;IAED,kFAAkF;IAClF,EAAE,CAAC,SAAyB,EAAE,QAAgB,EAAE,QAAgB;QAC9D,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,CAAA;QAElC,IAAI,QAAQ,IAAI,QAAQ,EAAE,CAAC;YACzB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,KAAK,EAAE,CAAA;QACnD,CAAC;aAAM,IAAI,QAAQ,EAAE,CAAC;YACpB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,KAAK,EAAE,CAAA;QAC7B,CAAC;aAAM,IAAI,QAAQ,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;QAC7D,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,kEAAkE;IAClE,MAAM,CAAC,SAAyB;QAC9B,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,CAAA;IAC1C,CAAC;IAED,6DAA6D;IAC7D,IAAI;QACF,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA;IACnC,CAAC;IAED,qEAAqE;IACrE,KAAK;QACH,OAAO,IAAI,CAAC,aAAa,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;IACrC,CAAC;IAEO,IAAI,CAAC,IAAS,EAAE,OAAe;QACrC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;QACrB,IAAI,OAAO;YAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAA;QACxC,OAAO,IAAI,CAAA;IACb,CAAC;IAED,+DAA+D;IAC/D,GAAG,CAAC,SAAe,EAAE,OAAe;QAClC,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC,CAAA;IACnD,CAAC;IAED,wCAAwC;IACxC,QAAQ,CACN,YAA2B,EAC3B,IAAc,EACd,EAAY,EACZ,OAA8B,EAC9B,UAAgB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG;QAE3D,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAA;QAC7C,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;IAC9E,CAAC;IAED,kEAAkE;IAClE,KAAK,CACH,YAA2B,EAC3B,QAAc,EACd,OAA6B,EAC7B,UAAgB,gBAAQ,CAAC,KAAK;QAE9B,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAA;QAC7C,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;YAClB,MAAM,GAAG,GAAG,QAAQ,YAAY,WAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;YAC5E,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,EAAE,IAAA,QAAC,EAAA,GAAG,GAAG,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE;gBACpD,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAA,QAAC,EAAA,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAA;gBAC/B,OAAO,CAAC,IAAI,CAAC,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,CAAC,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;IACnF,CAAC;IAED,sBAAsB;IACtB,4EAA4E;IAC5E,KAAK,CACH,YAA2B,EAC3B,GAAS,EACT,OAA6B,EAC7B,UAAgB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,KAAK;QAE7D,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,IAAA,QAAC,EAAA,eAAe,GAAG,GAAG,EAAE,OAAO,CAAC,CAAA;QAClE,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAA;QAC7C,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;IAC9E,CAAC;IAED,iBAAiB;IACjB,MAAM;QACJ,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAA;IAChC,CAAC;IAED,oBAAoB;IACpB,KAAK,CAAC,KAAW;QACf,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAA;IACzC,CAAC;IAED,oBAAoB;IACpB,KAAK,CAAC,KAAY;QAChB,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAA;IACzC,CAAC;IAED,qBAAqB;IACrB,MAAM,CAAC,KAAuB;QAC5B,MAAM,IAAI,GAAG,IAAI,MAAM,EAAE,CAAA;QACzB,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;QACrB,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAChB,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAA;QACtF,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAA;IACnC,CAAC;IAED,kBAAkB;IAClB,GAAG,CAAC,OAAc,EAAE,SAA6B,EAAE,WAAmB;QACpE,IAAI,CAAC,SAAS,IAAI,CAAC,WAAW;YAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAA;QAC/F,MAAM,IAAI,GAAG,IAAI,GAAG,EAAE,CAAA;QACtB,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;QACrB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAClB,IAAI,SAAS,EAAE,CAAC;YACd,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;YAC5B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,KAAK,CAAC,CAAA;YAC9C,SAAS,CAAC,KAAK,CAAC,CAAA;QAClB,CAAC;QACD,IAAI,WAAW,EAAE,CAAC;YAChB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,EAAE,CAAA;YAC7C,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;QACxB,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAC3C,CAAC;IAED,oBAAoB;IACpB,KAAK,CAAC,KAAW;QACf,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAA;IACzC,CAAC;IAED,6BAA6B;IAC7B,KAAK,CAAC,IAAY,EAAE,SAAkB;QACpC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;QAC1C,IAAI,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAA;QAC7C,OAAO,IAAI,CAAA;IACb,CAAC;IAED,uCAAuC;IACvC,QAAQ,CAAC,SAAkB;QACzB,MAAM,GAAG,GAAG,IAAI,CAAC,YAAY,CAAC,GAAG,EAAE,CAAA;QACnC,IAAI,GAAG,KAAK,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAA;QAC9E,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,CAAA;QACxC,IAAI,OAAO,GAAG,CAAC,IAAI,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,KAAK,SAAS,CAAC,EAAE,CAAC;YACtE,MAAM,IAAI,KAAK,CAAC,mCAAmC,OAAO,OAAO,SAAS,WAAW,CAAC,CAAA;QACxF,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,CAAA;QACxB,OAAO,IAAI,CAAA;IACb,CAAC;IAED,2DAA2D;IAC3D,IAAI,CAAC,IAAU,EAAE,OAAa,UAAG,EAAE,KAAe,EAAE,QAAgB;QAClE,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAA;QAC5C,IAAI,QAAQ;YAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,OAAO,EAAE,CAAA;QAC3C,OAAO,IAAI,CAAA;IACb,CAAC;IAED,0BAA0B;IAC1B,OAAO;QACL,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;IACjC,CAAC;IAED,QAAQ,CAAC,CAAC,GAAG,CAAC;QACZ,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;YACf,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,CAAA;YAC1B,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,CAAA;QAC7D,CAAC;IACH,CAAC;IAEO,SAAS,CAAC,IAAc;QAC9B,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAC/B,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,UAAU,CAAC,IAAoB;QACrC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAC/B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACxB,CAAC;IAEO,aAAa,CAAC,EAAoB,EAAE,EAAqB;QAC/D,MAAM,CAAC,GAAG,IAAI,CAAC,SAAS,CAAA;QACxB,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,YAAY,EAAE,CAAC,EAAE,CAAC;YAC/C,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAA;YACjB,OAAO,IAAI,CAAA;QACb,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,0BAA0B,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,GAAG,CAAC,CAAA;IACtF,CAAC;IAEO,SAAS,CAAC,IAAe;QAC/B,MAAM,CAAC,GAAG,IAAI,CAAC,SAAS,CAAA;QACxB,IAAI,CAAC,CAAC,CAAC,YAAY,EAAE,CAAC,EAAE,CAAC;YACvB,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAA;QACjD,CAAC;QACD,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,IAAI,GAAG,IAAI,CAAA;QAC9B,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAY,KAAK;QACf,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAS,CAAA;IAC/B,CAAC;IAED,IAAY,SAAS;QACnB,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,CAAA;QACtB,OAAO,EAAE,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;IAC1B,CAAC;IAED,IAAY,SAAS,CAAC,IAAgB;QACpC,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,CAAA;QACtB,EAAE,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,IAAI,CAAA;IAC1B,CAAC;CAKF;AAtUD,0BAsUC;AAED,SAAS,QAAQ,CAAC,KAAgB,EAAE,IAAe;IACjD,KAAK,MAAM,CAAC,IAAI,IAAI;QAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;IACjE,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAS,YAAY,CAAC,KAAgB,EAAE,IAAc;IACpD,OAAO,IAAI,YAAY,kBAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAA;AAC1E,CAAC;AAGD,SAAS,YAAY,CAAC,IAAc,EAAE,KAAgB,EAAE,SAAoB;IAC1E,IAAI,IAAI,YAAY,WAAI;QAAE,OAAO,WAAW,CAAC,IAAI,CAAC,CAAA;IAClD,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IACnC,OAAO,IAAI,YAAK,CACd,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAiB,EAAE,CAAoB,EAAE,EAAE;QAC7D,IAAI,CAAC,YAAY,WAAI;YAAE,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;QACzC,IAAI,CAAC,YAAY,YAAK;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAA;;YAC1C,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QAClB,OAAO,KAAK,CAAA;IACd,CAAC,EAAE,EAAE,CAAC,CACP,CAAA;IAED,SAAS,WAAW,CAAC,CAAO;QAC1B,MAAM,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;QAC1B,IAAI,CAAC,KAAK,SAAS,IAAI,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC;YAAE,OAAO,CAAC,CAAA;QACnD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;QACnB,OAAO,CAAC,CAAA;IACV,CAAC;IAED,SAAS,WAAW,CAAC,CAAW;QAC9B,OAAO,CACL,CAAC,YAAY,YAAK;YAClB,CAAC,CAAC,MAAM,CAAC,IAAI,CACX,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,YAAY,WAAI,IAAI,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,SAAS,CACjF,CACF,CAAA;IACH,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,KAAgB,EAAE,IAAe;IACtD,KAAK,MAAM,CAAC,IAAI,IAAI;QAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;AACnE,CAAC;AAGD,SAAgB,GAAG,CAAC,CAAkB;IACpC,OAAO,OAAO,CAAC,IAAI,SAAS,IAAI,OAAO,CAAC,IAAI,QAAQ,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,QAAC,EAAA,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAA;AACzF,CAAC;AAFD,kBAEC;AAED,MAAM,OAAO,GAAG,OAAO,CAAC,iBAAS,CAAC,GAAG,CAAC,CAAA;AAEtC,wDAAwD;AACxD,SAAgB,GAAG,CAAC,GAAG,IAAY;IACjC,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,CAAC;AAFD,kBAEC;AAED,MAAM,MAAM,GAAG,OAAO,CAAC,iBAAS,CAAC,EAAE,CAAC,CAAA;AAEpC,uDAAuD;AACvD,SAAgB,EAAE,CAAC,GAAG,IAAY;IAChC,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;AAC5B,CAAC;AAFD,gBAEC;AAID,SAAS,OAAO,CAAC,EAAQ;IACvB,OAAO,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,UAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,UAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,QAAC,EAAA,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AACjF,CAAC;AAED,SAAS,GAAG,CAAC,CAAO;IAClB,OAAO,CAAC,YAAY,WAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,QAAC,EAAA,IAAI,CAAC,GAAG,CAAA;AAC1C,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/scope.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/scope.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d953053877f1a646c763426c51b3ca2fe113cb0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/scope.d.ts @@ -0,0 +1,79 @@ +import { Code, Name } from "./code"; +interface NameGroup { + prefix: string; + index: number; +} +export interface NameValue { + ref: ValueReference; + key?: unknown; + code?: Code; +} +export type ValueReference = unknown; +interface ScopeOptions { + prefixes?: Set; + parent?: Scope; +} +interface ValueScopeOptions extends ScopeOptions { + scope: ScopeStore; + es5?: boolean; + lines?: boolean; +} +export type ScopeStore = Record; +type ScopeValues = { + [Prefix in string]?: Map; +}; +export type ScopeValueSets = { + [Prefix in string]?: Set; +}; +export declare enum UsedValueState { + Started = 0, + Completed = 1 +} +export type UsedScopeValues = { + [Prefix in string]?: Map; +}; +export declare const varKinds: { + const: Name; + let: Name; + var: Name; +}; +export declare class Scope { + protected readonly _names: { + [Prefix in string]?: NameGroup; + }; + protected readonly _prefixes?: Set; + protected readonly _parent?: Scope; + constructor({ prefixes, parent }?: ScopeOptions); + toName(nameOrPrefix: Name | string): Name; + name(prefix: string): Name; + protected _newName(prefix: string): string; + private _nameGroup; +} +interface ScopePath { + property: string; + itemIndex: number; +} +export declare class ValueScopeName extends Name { + readonly prefix: string; + value?: NameValue; + scopePath?: Code; + constructor(prefix: string, nameStr: string); + setValue(value: NameValue, { property, itemIndex }: ScopePath): void; +} +interface VSOptions extends ValueScopeOptions { + _n: Code; +} +export declare class ValueScope extends Scope { + protected readonly _values: ScopeValues; + protected readonly _scope: ScopeStore; + readonly opts: VSOptions; + constructor(opts: ValueScopeOptions); + get(): ScopeStore; + name(prefix: string): ValueScopeName; + value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName; + getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined; + scopeRefs(scopeName: Name, values?: ScopeValues | ScopeValueSets): Code; + scopeCode(values?: ScopeValues | ScopeValueSets, usedValues?: UsedScopeValues, getCode?: (n: ValueScopeName) => Code | undefined): Code; + private _reduceValues; +} +export {}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/scope.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/scope.js.map new file mode 100644 index 0000000000000000000000000000000000000000..911769f871e30c9b701a894a5b8b697f2cb6f381 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/codegen/scope.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scope.js","sourceRoot":"","sources":["../../../lib/compile/codegen/scope.ts"],"names":[],"mappings":";;;AAAA,iCAAyC;AAezC,MAAM,UAAW,SAAQ,KAAK;IAE5B,YAAY,IAAoB;QAC9B,KAAK,CAAC,uBAAuB,IAAI,cAAc,CAAC,CAAA;QAChD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAA;IACzB,CAAC;CACF;AAuBD,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,yDAAO,CAAA;IACP,6DAAS,CAAA;AACX,CAAC,EAHW,cAAc,8BAAd,cAAc,QAGzB;AAMY,QAAA,QAAQ,GAAG;IACtB,KAAK,EAAE,IAAI,WAAI,CAAC,OAAO,CAAC;IACxB,GAAG,EAAE,IAAI,WAAI,CAAC,KAAK,CAAC;IACpB,GAAG,EAAE,IAAI,WAAI,CAAC,KAAK,CAAC;CACrB,CAAA;AAED,MAAa,KAAK;IAKhB,YAAY,EAAC,QAAQ,EAAE,MAAM,KAAkB,EAAE;QAJ9B,WAAM,GAAqC,EAAE,CAAA;QAK9D,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QACzB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;IACvB,CAAC;IAED,MAAM,CAAC,YAA2B;QAChC,OAAO,YAAY,YAAY,WAAI,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;IAC9E,CAAC;IAED,IAAI,CAAC,MAAc;QACjB,OAAO,IAAI,WAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;IACxC,CAAC;IAES,QAAQ,CAAC,MAAc;QAC/B,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;QACzD,OAAO,GAAG,MAAM,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,CAAA;IACjC,CAAC;IAEO,UAAU,CAAC,MAAc;;QAC/B,IAAI,CAAA,MAAA,MAAA,IAAI,CAAC,OAAO,0CAAE,SAAS,0CAAE,GAAG,CAAC,MAAM,CAAC,KAAI,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;YAC5F,MAAM,IAAI,KAAK,CAAC,oBAAoB,MAAM,gCAAgC,CAAC,CAAA;QAC7E,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAC,MAAM,EAAE,KAAK,EAAE,CAAC,EAAC,CAAC,CAAA;IACnD,CAAC;CACF;AA7BD,sBA6BC;AAOD,MAAa,cAAe,SAAQ,WAAI;IAKtC,YAAY,MAAc,EAAE,OAAe;QACzC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAED,QAAQ,CAAC,KAAgB,EAAE,EAAC,QAAQ,EAAE,SAAS,EAAY;QACzD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;QAClB,IAAI,CAAC,SAAS,GAAG,IAAA,QAAC,EAAA,IAAI,IAAI,WAAI,CAAC,QAAQ,CAAC,IAAI,SAAS,GAAG,CAAA;IAC1D,CAAC;CACF;AAdD,wCAcC;AAMD,MAAM,IAAI,GAAG,IAAA,QAAC,EAAA,IAAI,CAAA;AAElB,MAAa,UAAW,SAAQ,KAAK;IAKnC,YAAY,IAAuB;QACjC,KAAK,CAAC,IAAI,CAAC,CAAA;QALM,YAAO,GAAgB,EAAE,CAAA;QAM1C,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAA;QACxB,IAAI,CAAC,IAAI,GAAG,EAAC,GAAG,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAG,EAAC,CAAA;IACpD,CAAC;IAED,GAAG;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,IAAI,CAAC,MAAc;QACjB,OAAO,IAAI,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;IAC1D,CAAC;IAED,KAAK,CAAC,YAAqC,EAAE,KAAgB;;QAC3D,IAAI,KAAK,CAAC,GAAG,KAAK,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAA;QACpF,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,YAAY,CAAmB,CAAA;QACxD,MAAM,EAAC,MAAM,EAAC,GAAG,IAAI,CAAA;QACrB,MAAM,QAAQ,GAAG,MAAA,KAAK,CAAC,GAAG,mCAAI,KAAK,CAAC,GAAG,CAAA;QACvC,IAAI,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;QAC7B,IAAI,EAAE,EAAE,CAAC;YACP,MAAM,KAAK,GAAG,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;YAC9B,IAAI,KAAK;gBAAE,OAAO,KAAK,CAAA;QACzB,CAAC;aAAM,CAAC;YACN,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,EAAE,CAAA;QACvC,CAAC;QACD,EAAE,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;QAEtB,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,CAAA;QAC3D,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAA;QAC1B,CAAC,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,GAAG,CAAA;QACxB,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAC,CAAC,CAAA;QACnD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,QAAQ,CAAC,MAAc,EAAE,QAAiB;QACxC,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;QAC/B,IAAI,CAAC,EAAE;YAAE,OAAM;QACf,OAAO,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;IACzB,CAAC;IAED,SAAS,CAAC,SAAe,EAAE,SAAuC,IAAI,CAAC,OAAO;QAC5E,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC,IAAoB,EAAE,EAAE;YACzD,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS;gBAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAI,gBAAgB,CAAC,CAAA;YACzF,OAAO,IAAA,QAAC,EAAA,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,EAAE,CAAA;QACzC,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,SAAS,CACP,SAAuC,IAAI,CAAC,OAAO,EACnD,UAA4B,EAC5B,OAAiD;QAEjD,OAAO,IAAI,CAAC,aAAa,CACvB,MAAM,EACN,CAAC,IAAoB,EAAE,EAAE;YACvB,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;gBAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAI,gBAAgB,CAAC,CAAA;YACrF,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAA;QACxB,CAAC,EACD,UAAU,EACV,OAAO,CACR,CAAA;IACH,CAAC;IAEO,aAAa,CACnB,MAAoC,EACpC,SAAkD,EAClD,aAA8B,EAAE,EAChC,OAAiD;QAEjD,IAAI,IAAI,GAAS,UAAG,CAAA;QACpB,KAAK,MAAM,MAAM,IAAI,MAAM,EAAE,CAAC;YAC5B,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,CAAA;YACzB,IAAI,CAAC,EAAE;gBAAE,SAAQ;YACjB,MAAM,OAAO,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC,CAAA;YACtE,EAAE,CAAC,OAAO,CAAC,CAAC,IAAoB,EAAE,EAAE;gBAClC,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;oBAAE,OAAM;gBAC7B,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,OAAO,CAAC,CAAA;gBACzC,IAAI,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,CAAA;gBACvB,IAAI,CAAC,EAAE,CAAC;oBACN,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,KAAK,CAAA;oBACzD,IAAI,GAAG,IAAA,QAAC,EAAA,GAAG,IAAI,GAAG,GAAG,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAA;gBACxD,CAAC;qBAAM,IAAI,CAAC,CAAC,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAG,IAAI,CAAC,CAAC,EAAE,CAAC;oBACjC,IAAI,GAAG,IAAA,QAAC,EAAA,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAA;gBACtC,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,UAAU,CAAC,IAAI,CAAC,CAAA;gBAC5B,CAAC;gBACD,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,SAAS,CAAC,CAAA;YAC7C,CAAC,CAAC,CAAA;QACJ,CAAC;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAjGD,gCAiGC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/parse.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/parse.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..618c64aea0e5c2a23e145245f5ad9c9d6b24922a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/parse.d.ts @@ -0,0 +1,4 @@ +import type Ajv from "../../core"; +import { SchemaObjectMap } from "./types"; +import { SchemaEnv } from ".."; +export default function compileParser(this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap): SchemaEnv; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/parse.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..8fc94fd0eae5349e3513ce79e3f2ba1a3ffbdc6a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/parse.js @@ -0,0 +1,350 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const types_1 = require("./types"); +const __1 = require(".."); +const codegen_1 = require("../codegen"); +const ref_error_1 = require("../ref_error"); +const names_1 = require("../names"); +const code_1 = require("../../vocabularies/code"); +const ref_1 = require("../../vocabularies/jtd/ref"); +const type_1 = require("../../vocabularies/jtd/type"); +const parseJson_1 = require("../../runtime/parseJson"); +const util_1 = require("../util"); +const timestamp_1 = require("../../runtime/timestamp"); +const genParse = { + elements: parseElements, + values: parseValues, + discriminator: parseDiscriminator, + properties: parseProperties, + optionalProperties: parseProperties, + enum: parseEnum, + type: parseType, + ref: parseRef, +}; +function compileParser(sch, definitions) { + const _sch = __1.getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + const parseName = gen.scopeName("parse"); + const cxt = { + self: this, + gen, + schema: sch.schema, + schemaEnv: sch, + definitions, + data: names_1.default.data, + parseName, + char: gen.name("c"), + }; + let sourceCode; + try { + this._compilations.add(sch); + sch.parseName = parseName; + parserFunction(cxt); + gen.optimize(this.opts.code.optimize); + const parseFuncCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`; + const makeParse = new Function(`${names_1.default.scope}`, sourceCode); + const parse = makeParse(this.scope.get()); + this.scope.value(parseName, { ref: parse }); + sch.parse = parse; + } + catch (e) { + if (sourceCode) + this.logger.error("Error compiling parser, function code:", sourceCode); + delete sch.parse; + delete sch.parseName; + throw e; + } + finally { + this._compilations.delete(sch); + } + return sch; +} +exports.default = compileParser; +const undef = (0, codegen_1._) `undefined`; +function parserFunction(cxt) { + const { gen, parseName, char } = cxt; + gen.func(parseName, (0, codegen_1._) `${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => { + gen.let(names_1.default.data); + gen.let(char); + gen.assign((0, codegen_1._) `${parseName}.message`, undef); + gen.assign((0, codegen_1._) `${parseName}.position`, undef); + gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${names_1.default.jsonPos} || 0`); + gen.const(names_1.default.jsonLen, (0, codegen_1._) `${names_1.default.json}.length`); + parseCode(cxt); + skipWhitespace(cxt); + gen.if(names_1.default.jsonPart, () => { + gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos); + gen.return(names_1.default.data); + }); + gen.if((0, codegen_1._) `${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data)); + jsonSyntaxError(cxt); + }); +} +function parseCode(cxt) { + let form; + for (const key of types_1.jtdForms) { + if (key in cxt.schema) { + form = key; + break; + } + } + if (form) + parseNullable(cxt, genParse[form]); + else + parseEmpty(cxt); +} +const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)); +function parseNullable(cxt, parseForm) { + const { gen, schema, data } = cxt; + if (!schema.nullable) + return parseForm(cxt); + tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)); +} +function parseElements(cxt) { + const { gen, schema, data } = cxt; + parseToken(cxt, "["); + const ix = gen.let("i", 0); + gen.assign(data, (0, codegen_1._) `[]`); + parseItems(cxt, "]", () => { + const el = gen.let("el"); + parseCode({ ...cxt, schema: schema.elements, data: el }); + gen.assign((0, codegen_1._) `${data}[${ix}++]`, el); + }); +} +function parseValues(cxt) { + const { gen, schema, data } = cxt; + parseToken(cxt, "{"); + gen.assign(data, (0, codegen_1._) `{}`); + parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)); +} +function parseItems(cxt, endToken, block) { + tryParseItems(cxt, endToken, block); + parseToken(cxt, endToken); +} +function tryParseItems(cxt, endToken, block) { + const { gen } = cxt; + gen.for((0, codegen_1._) `;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { + block(); + tryParseToken(cxt, ",", () => gen.break(), hasItem); + }); + function hasItem() { + tryParseToken(cxt, endToken, () => { }, jsonSyntaxError); + } +} +function parseKeyValue(cxt, schema) { + const { gen } = cxt; + const key = gen.let("key"); + parseString({ ...cxt, data: key }); + parseToken(cxt, ":"); + parsePropertyValue(cxt, key, schema); +} +function parseDiscriminator(cxt) { + const { gen, data, schema } = cxt; + const { discriminator, mapping } = schema; + parseToken(cxt, "{"); + gen.assign(data, (0, codegen_1._) `{}`); + const startPos = gen.const("pos", names_1.default.jsonPos); + const value = gen.let("value"); + const tag = gen.let("tag"); + tryParseItems(cxt, "}", () => { + const key = gen.let("key"); + parseString({ ...cxt, data: key }); + parseToken(cxt, ":"); + gen.if((0, codegen_1._) `${key} === ${discriminator}`, () => { + parseString({ ...cxt, data: tag }); + gen.assign((0, codegen_1._) `${data}[${key}]`, tag); + gen.break(); + }, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped + ); + }); + gen.assign(names_1.default.jsonPos, startPos); + gen.if((0, codegen_1._) `${tag} === undefined`); + parsingError(cxt, (0, codegen_1.str) `discriminator tag not found`); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); + parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator); + } + gen.else(); + parsingError(cxt, (0, codegen_1.str) `discriminator value not in schema`); + gen.endIf(); +} +function parseProperties(cxt) { + const { gen, data } = cxt; + parseToken(cxt, "{"); + gen.assign(data, (0, codegen_1._) `{}`); + parseSchemaProperties(cxt); +} +function parseSchemaProperties(cxt, discriminator) { + const { gen, schema, data } = cxt; + const { properties, optionalProperties, additionalProperties } = schema; + parseItems(cxt, "}", () => { + const key = gen.let("key"); + parseString({ ...cxt, data: key }); + parseToken(cxt, ":"); + gen.if(false); + parseDefinedProperty(cxt, key, properties); + parseDefinedProperty(cxt, key, optionalProperties); + if (discriminator) { + gen.elseIf((0, codegen_1._) `${key} === ${discriminator}`); + const tag = gen.let("tag"); + parseString({ ...cxt, data: tag }); // can be discarded, it is already assigned + } + gen.else(); + if (additionalProperties) { + parseEmpty({ ...cxt, data: (0, codegen_1._) `${data}[${key}]` }); + } + else { + parsingError(cxt, (0, codegen_1.str) `property ${key} not allowed`); + } + gen.endIf(); + }); + if (properties) { + const hasProp = (0, code_1.hasPropFunc)(gen); + const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._) `${hasProp}.call(${data}, ${p})`)); + gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str) `missing required properties`)); + } +} +function parseDefinedProperty(cxt, key, schemas = {}) { + const { gen } = cxt; + for (const prop in schemas) { + gen.elseIf((0, codegen_1._) `${key} === ${prop}`); + parsePropertyValue(cxt, key, schemas[prop]); + } +} +function parsePropertyValue(cxt, key, schema) { + parseCode({ ...cxt, schema, data: (0, codegen_1._) `${cxt.data}[${key}]` }); +} +function parseType(cxt) { + const { gen, schema, data, self } = cxt; + switch (schema.type) { + case "boolean": + parseBoolean(cxt); + break; + case "string": + parseString(cxt); + break; + case "timestamp": { + parseString(cxt); + const vts = (0, util_1.useFunc)(gen, timestamp_1.default); + const { allowDate, parseDate } = self.opts; + const notValid = allowDate ? (0, codegen_1._) `!${vts}(${data}, true)` : (0, codegen_1._) `!${vts}(${data})`; + const fail = parseDate + ? (0, codegen_1.or)(notValid, (0, codegen_1._) `(${data} = new Date(${data}), false)`, (0, codegen_1._) `isNaN(${data}.valueOf())`) + : notValid; + gen.if(fail, () => parsingError(cxt, (0, codegen_1.str) `invalid timestamp`)); + break; + } + case "float32": + case "float64": + parseNumber(cxt); + break; + default: { + const t = schema.type; + if (!self.opts.int32range && (t === "int32" || t === "uint32")) { + parseNumber(cxt, 16); // 2 ** 53 - max safe integer + if (t === "uint32") { + gen.if((0, codegen_1._) `${data} < 0`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`)); + } + } + else { + const [min, max, maxDigits] = type_1.intRange[t]; + parseNumber(cxt, maxDigits); + gen.if((0, codegen_1._) `${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`)); + } + } + } +} +function parseString(cxt) { + parseToken(cxt, '"'); + parseWith(cxt, parseJson_1.parseJsonString); +} +function parseEnum(cxt) { + const { gen, data, schema } = cxt; + const enumSch = schema.enum; + parseToken(cxt, '"'); + // TODO loopEnum + gen.if(false); + for (const value of enumSch) { + const valueStr = JSON.stringify(value).slice(1); // remove starting quote + gen.elseIf((0, codegen_1._) `${jsonSlice(valueStr.length)} === ${valueStr}`); + gen.assign(data, (0, codegen_1.str) `${value}`); + gen.add(names_1.default.jsonPos, valueStr.length); + } + gen.else(); + jsonSyntaxError(cxt); + gen.endIf(); +} +function parseNumber(cxt, maxDigits) { + const { gen } = cxt; + skipWhitespace(cxt); + gen.if((0, codegen_1._) `"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits)); +} +function parseBooleanToken(bool, fail) { + return (cxt) => { + const { gen, data } = cxt; + tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool)); + }; +} +function parseRef(cxt) { + const { gen, self, definitions, schema, schemaEnv } = cxt; + const { ref } = schema; + const refSchema = definitions[ref]; + if (!refSchema) + throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`); + if (!(0, ref_1.hasRef)(refSchema)) + return parseCode({ ...cxt, schema: refSchema }); + const { root } = schemaEnv; + const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions); + partialParse(cxt, getParser(gen, sch), true); +} +function getParser(gen, sch) { + return sch.parse + ? gen.scopeValue("parse", { ref: sch.parse }) + : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.parse`; +} +function parseEmpty(cxt) { + parseWith(cxt, parseJson_1.parseJson); +} +function parseWith(cxt, parseFunc, args) { + partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args); +} +function partialParse(cxt, parseFunc, args) { + const { gen, data } = cxt; + gen.assign(data, (0, codegen_1._) `${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._) `, ${args}` : codegen_1.nil})`); + gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${parseFunc}.position`); + gen.if((0, codegen_1._) `${data} === undefined`, () => parsingError(cxt, (0, codegen_1._) `${parseFunc}.message`)); +} +function parseToken(cxt, tok) { + tryParseToken(cxt, tok, jsonSyntaxError); +} +function tryParseToken(cxt, tok, fail, success) { + const { gen } = cxt; + const n = tok.length; + skipWhitespace(cxt); + gen.if((0, codegen_1._) `${jsonSlice(n)} === ${tok}`, () => { + gen.add(names_1.default.jsonPos, n); + success === null || success === void 0 ? void 0 : success(cxt); + }, () => fail(cxt)); +} +function skipWhitespace({ gen, char: c }) { + gen.code((0, codegen_1._) `while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`); +} +function jsonSlice(len) { + return len === 1 + ? (0, codegen_1._) `${names_1.default.json}[${names_1.default.jsonPos}]` + : (0, codegen_1._) `${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`; +} +function jsonSyntaxError(cxt) { + parsingError(cxt, (0, codegen_1._) `"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`); +} +function parsingError({ gen, parseName }, msg) { + gen.assign((0, codegen_1._) `${parseName}.message`, msg); + gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos); + gen.return(undef); +} +//# sourceMappingURL=parse.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/parse.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/parse.js.map new file mode 100644 index 0000000000000000000000000000000000000000..87bd922aef155cde52e2a9f0bba94493ad5182bf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/parse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse.js","sourceRoot":"","sources":["../../../lib/compile/jtd/parse.ts"],"names":[],"mappings":";;AAEA,mCAA0D;AAC1D,0BAAgD;AAChD,wCAAmF;AACnF,4CAA0C;AAC1C,oCAAwB;AACxB,kDAAmD;AACnD,oDAAiD;AACjD,sDAA6D;AAC7D,uDAAmF;AACnF,kCAA+B;AAC/B,uDAAoD;AAIpD,MAAM,QAAQ,GAA+B;IAC3C,QAAQ,EAAE,aAAa;IACvB,MAAM,EAAE,WAAW;IACnB,aAAa,EAAE,kBAAkB;IACjC,UAAU,EAAE,eAAe;IAC3B,kBAAkB,EAAE,eAAe;IACnC,IAAI,EAAE,SAAS;IACf,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,QAAQ;CACd,CAAA;AAaD,SAAwB,aAAa,CAEnC,GAAc,EACd,WAA4B;IAE5B,MAAM,IAAI,GAAG,sBAAkB,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAC/C,IAAI,IAAI;QAAE,OAAO,IAAI,CAAA;IACrB,MAAM,EAAC,GAAG,EAAE,KAAK,EAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;IACnC,MAAM,EAAC,aAAa,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IACjC,MAAM,GAAG,GAAG,IAAI,iBAAO,CAAC,IAAI,CAAC,KAAK,EAAE,EAAC,GAAG,EAAE,KAAK,EAAE,aAAa,EAAC,CAAC,CAAA;IAChE,MAAM,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,CAAA;IACxC,MAAM,GAAG,GAAa;QACpB,IAAI,EAAE,IAAI;QACV,GAAG;QACH,MAAM,EAAE,GAAG,CAAC,MAAsB;QAClC,SAAS,EAAE,GAAG;QACd,WAAW;QACX,IAAI,EAAE,eAAC,CAAC,IAAI;QACZ,SAAS;QACT,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC;KACpB,CAAA;IAED,IAAI,UAA8B,CAAA;IAClC,IAAI,CAAC;QACH,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAC3B,GAAG,CAAC,SAAS,GAAG,SAAS,CAAA;QACzB,cAAc,CAAC,GAAG,CAAC,CAAA;QACnB,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QACrC,MAAM,aAAa,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAA;QACpC,UAAU,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,eAAC,CAAC,KAAK,CAAC,UAAU,aAAa,EAAE,CAAA;QAC/D,MAAM,SAAS,GAAG,IAAI,QAAQ,CAAC,GAAG,eAAC,CAAC,KAAK,EAAE,EAAE,UAAU,CAAC,CAAA;QACxD,MAAM,KAAK,GAA8B,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAA;QACpE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,EAAC,GAAG,EAAE,KAAK,EAAC,CAAC,CAAA;QACzC,GAAG,CAAC,KAAK,GAAG,KAAK,CAAA;IACnB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAI,UAAU;YAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,wCAAwC,EAAE,UAAU,CAAC,CAAA;QACvF,OAAO,GAAG,CAAC,KAAK,CAAA;QAChB,OAAO,GAAG,CAAC,SAAS,CAAA;QACpB,MAAM,CAAC,CAAA;IACT,CAAC;YAAS,CAAC;QACT,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IAChC,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AA3CD,gCA2CC;AAED,MAAM,KAAK,GAAG,IAAA,WAAC,EAAA,WAAW,CAAA;AAE1B,SAAS,cAAc,CAAC,GAAa;IACnC,MAAM,EAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAClC,GAAG,CAAC,IAAI,CAAC,SAAS,EAAE,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,IAAI,KAAK,eAAC,CAAC,OAAO,KAAK,eAAC,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE;QACzE,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,CAAC,CAAA;QACf,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACb,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,UAAU,EAAE,KAAK,CAAC,CAAA;QAC1C,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,WAAW,EAAE,KAAK,CAAC,CAAA;QAC3C,GAAG,CAAC,MAAM,CAAC,eAAC,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,OAAO,OAAO,CAAC,CAAA;QAC3C,GAAG,CAAC,KAAK,CAAC,eAAC,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,IAAI,SAAS,CAAC,CAAA;QACzC,SAAS,CAAC,GAAG,CAAC,CAAA;QACd,cAAc,CAAC,GAAG,CAAC,CAAA;QACnB,GAAG,CAAC,EAAE,CAAC,eAAC,CAAC,QAAQ,EAAE,GAAG,EAAE;YACtB,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,WAAW,EAAE,eAAC,CAAC,OAAO,CAAC,CAAA;YAC/C,GAAG,CAAC,MAAM,CAAC,eAAC,CAAC,IAAI,CAAC,CAAA;QACpB,CAAC,CAAC,CAAA;QACF,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,OAAO,QAAQ,eAAC,CAAC,OAAO,EAAE,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,eAAC,CAAC,IAAI,CAAC,CAAC,CAAA;QAClE,eAAe,CAAC,GAAG,CAAC,CAAA;IACtB,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,SAAS,CAAC,GAAa;IAC9B,IAAI,IAAyB,CAAA;IAC7B,KAAK,MAAM,GAAG,IAAI,gBAAQ,EAAE,CAAC;QAC3B,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;YACtB,IAAI,GAAG,GAAG,CAAA;YACV,MAAK;QACP,CAAC;IACH,CAAC;IACD,IAAI,IAAI;QAAE,aAAa,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAA;;QACvC,UAAU,CAAC,GAAG,CAAC,CAAA;AACtB,CAAC;AAED,MAAM,YAAY,GAAG,iBAAiB,CAAC,IAAI,EAAE,iBAAiB,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC,CAAA;AAEvF,SAAS,aAAa,CAAC,GAAa,EAAE,SAAmB;IACvD,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,IAAI,CAAC,MAAM,CAAC,QAAQ;QAAE,OAAO,SAAS,CAAC,GAAG,CAAC,CAAA;IAC3C,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;AACrE,CAAC;AAED,SAAS,aAAa,CAAC,GAAa;IAClC,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;IACpB,MAAM,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;IAC1B,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,IAAI,CAAC,CAAA;IACvB,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE;QACxB,MAAM,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACxB,SAAS,CAAC,EAAC,GAAG,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAC,CAAC,CAAA;QACtD,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAA;IACrC,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,GAAa;IAChC,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;IACpB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,IAAI,CAAC,CAAA;IACvB,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,CAAA;AAC/D,CAAC;AAED,SAAS,UAAU,CAAC,GAAa,EAAE,QAAgB,EAAE,KAAiB;IACpE,aAAa,CAAC,GAAG,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;IACnC,UAAU,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;AAC3B,CAAC;AAED,SAAS,aAAa,CAAC,GAAa,EAAE,QAAgB,EAAE,KAAiB;IACvE,MAAM,EAAC,GAAG,EAAC,GAAG,GAAG,CAAA;IACjB,GAAG,CAAC,GAAG,CAAC,IAAA,WAAC,EAAA,IAAI,eAAC,CAAC,OAAO,IAAI,eAAC,CAAC,OAAO,OAAO,SAAS,CAAC,CAAC,CAAC,MAAM,QAAQ,GAAG,EAAE,GAAG,EAAE;QAC5E,KAAK,EAAE,CAAA;QACP,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,EAAE,OAAO,CAAC,CAAA;IACrD,CAAC,CAAC,CAAA;IAEF,SAAS,OAAO;QACd,aAAa,CAAC,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,GAAE,CAAC,EAAE,eAAe,CAAC,CAAA;IACzD,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,GAAa,EAAE,MAAoB;IACxD,MAAM,EAAC,GAAG,EAAC,GAAG,GAAG,CAAA;IACjB,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;IAC1B,WAAW,CAAC,EAAC,GAAG,GAAG,EAAE,IAAI,EAAE,GAAG,EAAC,CAAC,CAAA;IAChC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;IACpB,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,CAAA;AACtC,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAa;IACvC,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;IAC/B,MAAM,EAAC,aAAa,EAAE,OAAO,EAAC,GAAG,MAAM,CAAA;IACvC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;IACpB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,IAAI,CAAC,CAAA;IACvB,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,eAAC,CAAC,OAAO,CAAC,CAAA;IAC5C,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;IAC9B,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;IAC1B,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE;QAC3B,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAC1B,WAAW,CAAC,EAAC,GAAG,GAAG,EAAE,IAAI,EAAE,GAAG,EAAC,CAAC,CAAA;QAChC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;QACpB,GAAG,CAAC,EAAE,CACJ,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,aAAa,EAAE,EAC9B,GAAG,EAAE;YACH,WAAW,CAAC,EAAC,GAAG,GAAG,EAAE,IAAI,EAAE,GAAG,EAAC,CAAC,CAAA;YAChC,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,IAAI,GAAG,GAAG,EAAE,GAAG,CAAC,CAAA;YACnC,GAAG,CAAC,KAAK,EAAE,CAAA;QACb,CAAC,EACD,GAAG,EAAE,CAAC,UAAU,CAAC,EAAC,GAAG,GAAG,EAAE,IAAI,EAAE,KAAK,EAAC,CAAC,CAAC,2BAA2B;SACpE,CAAA;IACH,CAAC,CAAC,CAAA;IACF,GAAG,CAAC,MAAM,CAAC,eAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAA;IAC/B,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,gBAAgB,CAAC,CAAA;IAC/B,YAAY,CAAC,GAAG,EAAE,IAAA,aAAG,EAAA,6BAA6B,CAAC,CAAA;IACnD,KAAK,MAAM,QAAQ,IAAI,OAAO,EAAE,CAAC;QAC/B,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,QAAQ,EAAE,CAAC,CAAA;QACrC,qBAAqB,CAAC,EAAC,GAAG,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,EAAC,EAAE,aAAa,CAAC,CAAA;IAC3E,CAAC;IACD,GAAG,CAAC,IAAI,EAAE,CAAA;IACV,YAAY,CAAC,GAAG,EAAE,IAAA,aAAG,EAAA,mCAAmC,CAAC,CAAA;IACzD,GAAG,CAAC,KAAK,EAAE,CAAA;AACb,CAAC;AAED,SAAS,eAAe,CAAC,GAAa;IACpC,MAAM,EAAC,GAAG,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IACvB,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;IACpB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,IAAI,CAAC,CAAA;IACvB,qBAAqB,CAAC,GAAG,CAAC,CAAA;AAC5B,CAAC;AAED,SAAS,qBAAqB,CAAC,GAAa,EAAE,aAAsB;IAClE,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,MAAM,EAAC,UAAU,EAAE,kBAAkB,EAAE,oBAAoB,EAAC,GAAG,MAAM,CAAA;IACrE,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE;QACxB,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QAC1B,WAAW,CAAC,EAAC,GAAG,GAAG,EAAE,IAAI,EAAE,GAAG,EAAC,CAAC,CAAA;QAChC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;QACpB,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;QACb,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,UAAU,CAAC,CAAA;QAC1C,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,kBAAkB,CAAC,CAAA;QAClD,IAAI,aAAa,EAAE,CAAC;YAClB,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,aAAa,EAAE,CAAC,CAAA;YAC1C,MAAM,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;YAC1B,WAAW,CAAC,EAAC,GAAG,GAAG,EAAE,IAAI,EAAE,GAAG,EAAC,CAAC,CAAA,CAAC,2CAA2C;QAC9E,CAAC;QACD,GAAG,CAAC,IAAI,EAAE,CAAA;QACV,IAAI,oBAAoB,EAAE,CAAC;YACzB,UAAU,CAAC,EAAC,GAAG,GAAG,EAAE,IAAI,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,IAAI,GAAG,GAAG,EAAC,CAAC,CAAA;QAChD,CAAC;aAAM,CAAC;YACN,YAAY,CAAC,GAAG,EAAE,IAAA,aAAG,EAAA,YAAY,GAAG,cAAc,CAAC,CAAA;QACrD,CAAC;QACD,GAAG,CAAC,KAAK,EAAE,CAAA;IACb,CAAC,CAAC,CAAA;IACF,IAAI,UAAU,EAAE,CAAC;QACf,MAAM,OAAO,GAAG,IAAA,kBAAW,EAAC,GAAG,CAAC,CAAA;QAChC,MAAM,QAAQ,GAAS,IAAA,aAAG,EACxB,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAQ,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,OAAO,SAAS,IAAI,KAAK,CAAC,GAAG,CAAC,CAC/E,CAAA;QACD,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,QAAQ,CAAC,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,IAAA,aAAG,EAAA,6BAA6B,CAAC,CAAC,CAAA;IAClF,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAAC,GAAa,EAAE,GAAS,EAAE,UAA2B,EAAE;IACnF,MAAM,EAAC,GAAG,EAAC,GAAG,GAAG,CAAA;IACjB,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;QAC3B,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,IAAI,EAAE,CAAC,CAAA;QACjC,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,IAAI,CAAiB,CAAC,CAAA;IAC7D,CAAC;AACH,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAa,EAAE,GAAS,EAAE,MAAoB;IACxE,SAAS,CAAC,EAAC,GAAG,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,IAAA,WAAC,EAAA,GAAG,GAAG,CAAC,IAAI,IAAI,GAAG,GAAG,EAAC,CAAC,CAAA;AAC3D,CAAC;AAED,SAAS,SAAS,CAAC,GAAa;IAC9B,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IACrC,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS;YACZ,YAAY,CAAC,GAAG,CAAC,CAAA;YACjB,MAAK;QACP,KAAK,QAAQ;YACX,WAAW,CAAC,GAAG,CAAC,CAAA;YAChB,MAAK;QACP,KAAK,WAAW,CAAC,CAAC,CAAC;YACjB,WAAW,CAAC,GAAG,CAAC,CAAA;YAChB,MAAM,GAAG,GAAG,IAAA,cAAO,EAAC,GAAG,EAAE,mBAAc,CAAC,CAAA;YACxC,MAAM,EAAC,SAAS,EAAE,SAAS,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;YACxC,MAAM,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,IAAI,GAAG,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,IAAI,GAAG,IAAI,IAAI,GAAG,CAAA;YAC5E,MAAM,IAAI,GAAS,SAAS;gBAC1B,CAAC,CAAC,IAAA,YAAE,EAAC,QAAQ,EAAE,IAAA,WAAC,EAAA,IAAI,IAAI,eAAe,IAAI,WAAW,EAAE,IAAA,WAAC,EAAA,SAAS,IAAI,aAAa,CAAC;gBACpF,CAAC,CAAC,QAAQ,CAAA;YACZ,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,IAAA,aAAG,EAAA,mBAAmB,CAAC,CAAC,CAAA;YAC7D,MAAK;QACP,CAAC;QACD,KAAK,SAAS,CAAC;QACf,KAAK,SAAS;YACZ,WAAW,CAAC,GAAG,CAAC,CAAA;YAChB,MAAK;QACP,OAAO,CAAC,CAAC,CAAC;YACR,MAAM,CAAC,GAAG,MAAM,CAAC,IAAe,CAAA;YAChC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC,KAAK,OAAO,IAAI,CAAC,KAAK,QAAQ,CAAC,EAAE,CAAC;gBAC/D,WAAW,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA,CAAC,6BAA6B;gBAClD,IAAI,CAAC,KAAK,QAAQ,EAAE,CAAC;oBACnB,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,MAAM,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,IAAA,aAAG,EAAA,sBAAsB,CAAC,CAAC,CAAA;gBAC5E,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,SAAS,CAAC,GAAG,eAAQ,CAAC,CAAC,CAAC,CAAA;gBACzC,WAAW,CAAC,GAAG,EAAE,SAAS,CAAC,CAAA;gBAC3B,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,MAAM,GAAG,OAAO,IAAI,MAAM,GAAG,EAAE,EAAE,GAAG,EAAE,CACnD,YAAY,CAAC,GAAG,EAAE,IAAA,aAAG,EAAA,sBAAsB,CAAC,CAC7C,CAAA;YACH,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAAC,GAAa;IAChC,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;IACpB,SAAS,CAAC,GAAG,EAAE,2BAAe,CAAC,CAAA;AACjC,CAAC;AAED,SAAS,SAAS,CAAC,GAAa;IAC9B,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,MAAM,EAAC,GAAG,GAAG,CAAA;IAC/B,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAA;IAC3B,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;IACpB,gBAAgB;IAChB,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACb,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA,CAAC,wBAAwB;QACxE,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,QAAQ,EAAE,CAAC,CAAA;QAC5D,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,KAAK,EAAE,CAAC,CAAA;QAC/B,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAA;IACrC,CAAC;IACD,GAAG,CAAC,IAAI,EAAE,CAAA;IACV,eAAe,CAAC,GAAG,CAAC,CAAA;IACpB,GAAG,CAAC,KAAK,EAAE,CAAA;AACb,CAAC;AAED,SAAS,WAAW,CAAC,GAAa,EAAE,SAAkB;IACpD,MAAM,EAAC,GAAG,EAAC,GAAG,GAAG,CAAA;IACjB,cAAc,CAAC,GAAG,CAAC,CAAA;IACnB,GAAG,CAAC,EAAE,CACJ,IAAA,WAAC,EAAA,yBAAyB,SAAS,CAAC,CAAC,CAAC,OAAO,EAC7C,GAAG,EAAE,CAAC,eAAe,CAAC,GAAG,CAAC,EAC1B,GAAG,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE,2BAAe,EAAE,SAAS,CAAC,CACjD,CAAA;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,IAAa,EAAE,IAAc;IACtD,OAAO,CAAC,GAAG,EAAE,EAAE;QACb,MAAM,EAAC,GAAG,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;QACvB,aAAa,CACX,GAAG,EACH,GAAG,IAAI,EAAE,EACT,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,EACf,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAC7B,CAAA;IACH,CAAC,CAAA;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,GAAa;IAC7B,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAC,GAAG,GAAG,CAAA;IACvD,MAAM,EAAC,GAAG,EAAC,GAAG,MAAM,CAAA;IACpB,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,CAAA;IAClC,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,mBAAe,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,EAAE,GAAG,EAAE,iBAAiB,GAAG,EAAE,CAAC,CAAA;IACjG,IAAI,CAAC,IAAA,YAAM,EAAC,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC,EAAC,GAAG,GAAG,EAAE,MAAM,EAAE,SAAS,EAAC,CAAC,CAAA;IACrE,MAAM,EAAC,IAAI,EAAC,GAAG,SAAS,CAAA;IACxB,MAAM,GAAG,GAAG,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,aAAS,CAAC,EAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAC,CAAC,EAAE,WAAW,CAAC,CAAA;IAC3F,YAAY,CAAC,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,CAAA;AAC9C,CAAC;AAED,SAAS,SAAS,CAAC,GAAY,EAAE,GAAc;IAC7C,OAAO,GAAG,CAAC,KAAK;QACd,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,EAAE,EAAC,GAAG,EAAE,GAAG,CAAC,KAAK,EAAC,CAAC;QAC3C,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,CAAC,UAAU,CAAC,SAAS,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,CAAC,QAAQ,CAAA;AACvD,CAAC;AAED,SAAS,UAAU,CAAC,GAAa;IAC/B,SAAS,CAAC,GAAG,EAAE,qBAAS,CAAC,CAAA;AAC3B,CAAC;AAED,SAAS,SAAS,CAAC,GAAa,EAAE,SAAyB,EAAE,IAAe;IAC1E,YAAY,CAAC,GAAG,EAAE,IAAA,cAAO,EAAC,GAAG,CAAC,GAAG,EAAE,SAAS,CAAC,EAAE,IAAI,CAAC,CAAA;AACtD,CAAC;AAED,SAAS,YAAY,CAAC,GAAa,EAAE,SAAe,EAAE,IAAe;IACnE,MAAM,EAAC,GAAG,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IACvB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,GAAG,SAAS,IAAI,eAAC,CAAC,IAAI,KAAK,eAAC,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,IAAA,WAAC,EAAA,KAAK,IAAI,EAAE,CAAC,CAAC,CAAC,aAAG,GAAG,CAAC,CAAA;IACtF,GAAG,CAAC,MAAM,CAAC,eAAC,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,SAAS,WAAW,CAAC,CAAA;IAC/C,GAAG,CAAC,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,IAAI,gBAAgB,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,IAAA,WAAC,EAAA,GAAG,SAAS,UAAU,CAAC,CAAC,CAAA;AACpF,CAAC;AAED,SAAS,UAAU,CAAC,GAAa,EAAE,GAAW;IAC5C,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,eAAe,CAAC,CAAA;AAC1C,CAAC;AAED,SAAS,aAAa,CAAC,GAAa,EAAE,GAAW,EAAE,IAAc,EAAE,OAAkB;IACnF,MAAM,EAAC,GAAG,EAAC,GAAG,GAAG,CAAA;IACjB,MAAM,CAAC,GAAG,GAAG,CAAC,MAAM,CAAA;IACpB,cAAc,CAAC,GAAG,CAAC,CAAA;IACnB,GAAG,CAAC,EAAE,CACJ,IAAA,WAAC,EAAA,GAAG,SAAS,CAAC,CAAC,CAAC,QAAQ,GAAG,EAAE,EAC7B,GAAG,EAAE;QACH,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;QACrB,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAG,GAAG,CAAC,CAAA;IAChB,CAAC,EACD,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAChB,CAAA;AACH,CAAC;AAED,SAAS,cAAc,CAAC,EAAC,GAAG,EAAE,IAAI,EAAE,CAAC,EAAW;IAC9C,GAAG,CAAC,IAAI,CACN,IAAA,WAAC,EAAA,UAAU,CAAC,IAAI,eAAC,CAAC,IAAI,IAAI,eAAC,CAAC,OAAO,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC,aAAa,CAAC,aAAa,eAAC,CAAC,OAAO,KAAK,CAC7G,CAAA;AACH,CAAC;AAED,SAAS,SAAS,CAAC,GAAkB;IACnC,OAAO,GAAG,KAAK,CAAC;QACd,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,IAAI,IAAI,eAAC,CAAC,OAAO,GAAG;QAC5B,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,eAAC,CAAC,IAAI,UAAU,eAAC,CAAC,OAAO,KAAK,eAAC,CAAC,OAAO,IAAI,GAAG,GAAG,CAAA;AAC3D,CAAC;AAED,SAAS,eAAe,CAAC,GAAa;IACpC,YAAY,CAAC,GAAG,EAAE,IAAA,WAAC,EAAA,yBAAyB,eAAC,CAAC,IAAI,IAAI,eAAC,CAAC,OAAO,GAAG,CAAC,CAAA;AACrE,CAAC;AAED,SAAS,YAAY,CAAC,EAAC,GAAG,EAAE,SAAS,EAAW,EAAE,GAAS;IACzD,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,UAAU,EAAE,GAAG,CAAC,CAAA;IACxC,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,SAAS,WAAW,EAAE,eAAC,CAAC,OAAO,CAAC,CAAA;IAC/C,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AACnB,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/serialize.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/serialize.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0413d716df0dcbe79c101405610a29075c61bfd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/serialize.d.ts @@ -0,0 +1,4 @@ +import type Ajv from "../../core"; +import { SchemaObjectMap } from "./types"; +import { SchemaEnv } from ".."; +export default function compileSerializer(this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap): SchemaEnv; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/serialize.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/serialize.js new file mode 100644 index 0000000000000000000000000000000000000000..341c50078a07361c50496a94a113d08f198160b5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/serialize.js @@ -0,0 +1,229 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const types_1 = require("./types"); +const __1 = require(".."); +const codegen_1 = require("../codegen"); +const ref_error_1 = require("../ref_error"); +const names_1 = require("../names"); +const code_1 = require("../../vocabularies/code"); +const ref_1 = require("../../vocabularies/jtd/ref"); +const util_1 = require("../util"); +const quote_1 = require("../../runtime/quote"); +const genSerialize = { + elements: serializeElements, + values: serializeValues, + discriminator: serializeDiscriminator, + properties: serializeProperties, + optionalProperties: serializeProperties, + enum: serializeString, + type: serializeType, + ref: serializeRef, +}; +function compileSerializer(sch, definitions) { + const _sch = __1.getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + const serializeName = gen.scopeName("serialize"); + const cxt = { + self: this, + gen, + schema: sch.schema, + schemaEnv: sch, + definitions, + data: names_1.default.data, + }; + let sourceCode; + try { + this._compilations.add(sch); + sch.serializeName = serializeName; + gen.func(serializeName, names_1.default.data, false, () => { + gen.let(names_1.default.json, (0, codegen_1.str) ``); + serializeCode(cxt); + gen.return(names_1.default.json); + }); + gen.optimize(this.opts.code.optimize); + const serializeFuncCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`; + const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode); + const serialize = makeSerialize(this.scope.get()); + this.scope.value(serializeName, { ref: serialize }); + sch.serialize = serialize; + } + catch (e) { + if (sourceCode) + this.logger.error("Error compiling serializer, function code:", sourceCode); + delete sch.serialize; + delete sch.serializeName; + throw e; + } + finally { + this._compilations.delete(sch); + } + return sch; +} +exports.default = compileSerializer; +function serializeCode(cxt) { + let form; + for (const key of types_1.jtdForms) { + if (key in cxt.schema) { + form = key; + break; + } + } + serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty); +} +function serializeNullable(cxt, serializeForm) { + const { gen, schema, data } = cxt; + if (!schema.nullable) + return serializeForm(cxt); + gen.if((0, codegen_1._) `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._) `"null"`), () => serializeForm(cxt)); +} +function serializeElements(cxt) { + const { gen, schema, data } = cxt; + gen.add(names_1.default.json, (0, codegen_1.str) `[`); + const first = gen.let("first", true); + gen.forOf("el", data, (el) => { + addComma(cxt, first); + serializeCode({ ...cxt, schema: schema.elements, data: el }); + }); + gen.add(names_1.default.json, (0, codegen_1.str) `]`); +} +function serializeValues(cxt) { + const { gen, schema, data } = cxt; + gen.add(names_1.default.json, (0, codegen_1.str) `{`); + const first = gen.let("first", true); + gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)); + gen.add(names_1.default.json, (0, codegen_1.str) `}`); +} +function serializeKeyValue(cxt, key, schema, first) { + const { gen, data } = cxt; + addComma(cxt, first); + serializeString({ ...cxt, data: key }); + gen.add(names_1.default.json, (0, codegen_1.str) `:`); + const value = gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`); + serializeCode({ ...cxt, schema, data: value }); +} +function serializeDiscriminator(cxt) { + const { gen, schema, data } = cxt; + const { discriminator } = schema; + gen.add(names_1.default.json, (0, codegen_1.str) `{${JSON.stringify(discriminator)}:`); + const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(discriminator)}`); + serializeString({ ...cxt, data: tag }); + gen.if(false); + for (const tagValue in schema.mapping) { + gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); + const sch = schema.mapping[tagValue]; + serializeSchemaProperties({ ...cxt, schema: sch }, discriminator); + } + gen.endIf(); + gen.add(names_1.default.json, (0, codegen_1.str) `}`); +} +function serializeProperties(cxt) { + const { gen } = cxt; + gen.add(names_1.default.json, (0, codegen_1.str) `{`); + serializeSchemaProperties(cxt); + gen.add(names_1.default.json, (0, codegen_1.str) `}`); +} +function serializeSchemaProperties(cxt, discriminator) { + const { gen, schema, data } = cxt; + const { properties, optionalProperties } = schema; + const props = keys(properties); + const optProps = keys(optionalProperties); + const allProps = allProperties(props.concat(optProps)); + let first = !discriminator; + let firstProp; + for (const key of props) { + if (first) + first = false; + else + gen.add(names_1.default.json, (0, codegen_1.str) `,`); + serializeProperty(key, properties[key], keyValue(key)); + } + if (first) + firstProp = gen.let("first", true); + for (const key of optProps) { + const value = keyValue(key); + gen.if((0, codegen_1.and)((0, codegen_1._) `${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => { + addComma(cxt, firstProp); + serializeProperty(key, optionalProperties[key], value); + }); + } + if (schema.additionalProperties) { + gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp))); + } + function keys(ps) { + return ps ? Object.keys(ps) : []; + } + function allProperties(ps) { + if (discriminator) + ps.push(discriminator); + if (new Set(ps).size !== ps.length) { + throw new Error("JTD: properties/optionalProperties/disciminator overlap"); + } + return ps; + } + function keyValue(key) { + return gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`); + } + function serializeProperty(key, propSchema, value) { + gen.add(names_1.default.json, (0, codegen_1.str) `${JSON.stringify(key)}:`); + serializeCode({ ...cxt, schema: propSchema, data: value }); + } + function isAdditional(key, ps) { + return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)) : true; + } +} +function serializeType(cxt) { + const { gen, schema, data } = cxt; + switch (schema.type) { + case "boolean": + gen.add(names_1.default.json, (0, codegen_1._) `${data} ? "true" : "false"`); + break; + case "string": + serializeString(cxt); + break; + case "timestamp": + gen.if((0, codegen_1._) `${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._) `'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt)); + break; + default: + serializeNumber(cxt); + } +} +function serializeString({ gen, data }) { + gen.add(names_1.default.json, (0, codegen_1._) `${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`); +} +function serializeNumber({ gen, data }) { + gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`); +} +function serializeRef(cxt) { + const { gen, self, data, definitions, schema, schemaEnv } = cxt; + const { ref } = schema; + const refSchema = definitions[ref]; + if (!refSchema) + throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`); + if (!(0, ref_1.hasRef)(refSchema)) + return serializeCode({ ...cxt, schema: refSchema }); + const { root } = schemaEnv; + const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions); + gen.add(names_1.default.json, (0, codegen_1._) `${getSerialize(gen, sch)}(${data})`); +} +function getSerialize(gen, sch) { + return sch.serialize + ? gen.scopeValue("serialize", { ref: sch.serialize }) + : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.serialize`; +} +function serializeEmpty({ gen, data }) { + gen.add(names_1.default.json, (0, codegen_1._) `JSON.stringify(${data})`); +} +function addComma({ gen }, first) { + if (first) { + gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str) `,`)); + } + else { + gen.add(names_1.default.json, (0, codegen_1.str) `,`); + } +} +//# sourceMappingURL=serialize.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/serialize.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/serialize.js.map new file mode 100644 index 0000000000000000000000000000000000000000..15c82c7147427d9801eec5d386652a5b5170e7cd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/serialize.js.map @@ -0,0 +1 @@ +{"version":3,"file":"serialize.js","sourceRoot":"","sources":["../../../lib/compile/jtd/serialize.ts"],"names":[],"mappings":";;AAEA,mCAA0D;AAC1D,0BAAgD;AAChD,wCAAwE;AACxE,4CAA0C;AAC1C,oCAAwB;AACxB,kDAAqD;AACrD,oDAAiD;AACjD,kCAA+B;AAC/B,+CAAuC;AAEvC,MAAM,YAAY,GAAkD;IAClE,QAAQ,EAAE,iBAAiB;IAC3B,MAAM,EAAE,eAAe;IACvB,aAAa,EAAE,sBAAsB;IACrC,UAAU,EAAE,mBAAmB;IAC/B,kBAAkB,EAAE,mBAAmB;IACvC,IAAI,EAAE,eAAe;IACrB,IAAI,EAAE,aAAa;IACnB,GAAG,EAAE,YAAY;CAClB,CAAA;AAWD,SAAwB,iBAAiB,CAEvC,GAAc,EACd,WAA4B;IAE5B,MAAM,IAAI,GAAG,sBAAkB,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAC/C,IAAI,IAAI;QAAE,OAAO,IAAI,CAAA;IACrB,MAAM,EAAC,GAAG,EAAE,KAAK,EAAC,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAA;IACnC,MAAM,EAAC,aAAa,EAAC,GAAG,IAAI,CAAC,IAAI,CAAA;IACjC,MAAM,GAAG,GAAG,IAAI,iBAAO,CAAC,IAAI,CAAC,KAAK,EAAE,EAAC,GAAG,EAAE,KAAK,EAAE,aAAa,EAAC,CAAC,CAAA;IAChE,MAAM,aAAa,GAAG,GAAG,CAAC,SAAS,CAAC,WAAW,CAAC,CAAA;IAChD,MAAM,GAAG,GAAiB;QACxB,IAAI,EAAE,IAAI;QACV,GAAG;QACH,MAAM,EAAE,GAAG,CAAC,MAAsB;QAClC,SAAS,EAAE,GAAG;QACd,WAAW;QACX,IAAI,EAAE,eAAC,CAAC,IAAI;KACb,CAAA;IAED,IAAI,UAA8B,CAAA;IAClC,IAAI,CAAC;QACH,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAC3B,GAAG,CAAC,aAAa,GAAG,aAAa,CAAA;QACjC,GAAG,CAAC,IAAI,CAAC,aAAa,EAAE,eAAC,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE;YAC1C,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,EAAE,CAAC,CAAA;YACtB,aAAa,CAAC,GAAG,CAAC,CAAA;YAClB,GAAG,CAAC,MAAM,CAAC,eAAC,CAAC,IAAI,CAAC,CAAA;QACpB,CAAC,CAAC,CAAA;QACF,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QACrC,MAAM,iBAAiB,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAA;QACxC,UAAU,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,eAAC,CAAC,KAAK,CAAC,UAAU,iBAAiB,EAAE,CAAA;QACnE,MAAM,aAAa,GAAG,IAAI,QAAQ,CAAC,GAAG,eAAC,CAAC,KAAK,EAAE,EAAE,UAAU,CAAC,CAAA;QAC5D,MAAM,SAAS,GAA8B,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAA;QAC5E,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,aAAa,EAAE,EAAC,GAAG,EAAE,SAAS,EAAC,CAAC,CAAA;QACjD,GAAG,CAAC,SAAS,GAAG,SAAS,CAAA;IAC3B,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAI,UAAU;YAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,4CAA4C,EAAE,UAAU,CAAC,CAAA;QAC3F,OAAO,GAAG,CAAC,SAAS,CAAA;QACpB,OAAO,GAAG,CAAC,aAAa,CAAA;QACxB,MAAM,CAAC,CAAA;IACT,CAAC;YAAS,CAAC;QACT,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IAChC,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AA7CD,oCA6CC;AAED,SAAS,aAAa,CAAC,GAAiB;IACtC,IAAI,IAAyB,CAAA;IAC7B,KAAK,MAAM,GAAG,IAAI,gBAAQ,EAAE,CAAC;QAC3B,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;YACtB,IAAI,GAAG,GAAG,CAAA;YACV,MAAK;QACP,CAAC;IACH,CAAC;IACD,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAA;AACpE,CAAC;AAED,SAAS,iBAAiB,CAAC,GAAiB,EAAE,aAA2C;IACvF,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,IAAI,CAAC,MAAM,CAAC,QAAQ;QAAE,OAAO,aAAa,CAAC,GAAG,CAAC,CAAA;IAC/C,GAAG,CAAC,EAAE,CACJ,IAAA,WAAC,EAAA,GAAG,IAAI,qBAAqB,IAAI,WAAW,EAC5C,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,QAAQ,CAAC,EAChC,GAAG,EAAE,CAAC,aAAa,CAAC,GAAG,CAAC,CACzB,CAAA;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,GAAiB;IAC1C,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;IACvB,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;IACpC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE;QAC3B,QAAQ,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;QACpB,aAAa,CAAC,EAAC,GAAG,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAC,CAAC,CAAA;IAC5D,CAAC,CAAC,CAAA;IACF,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;AACzB,CAAC;AAED,SAAS,eAAe,CAAC,GAAiB;IACxC,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;IACvB,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;IACpC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAA;IAClF,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;AACzB,CAAC;AAED,SAAS,iBAAiB,CAAC,GAAiB,EAAE,GAAS,EAAE,MAAoB,EAAE,KAAY;IACzF,MAAM,EAAC,GAAG,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IACvB,QAAQ,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IACpB,eAAe,CAAC,EAAC,GAAG,GAAG,EAAE,IAAI,EAAE,GAAG,EAAC,CAAC,CAAA;IACpC,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;IACvB,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,GAAG,IAAA,qBAAW,EAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IAC/D,aAAa,CAAC,EAAC,GAAG,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAC,CAAC,CAAA;AAC9C,CAAC;AAED,SAAS,sBAAsB,CAAC,GAAiB;IAC/C,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,MAAM,EAAC,aAAa,EAAC,GAAG,MAAM,CAAA;IAC9B,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,IAAI,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,GAAG,CAAC,CAAA;IACxD,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,GAAG,IAAA,qBAAW,EAAC,aAAa,CAAC,EAAE,CAAC,CAAA;IACrE,eAAe,CAAC,EAAC,GAAG,GAAG,EAAE,IAAI,EAAE,GAAG,EAAC,CAAC,CAAA;IACpC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACb,KAAK,MAAM,QAAQ,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACtC,GAAG,CAAC,MAAM,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,QAAQ,EAAE,CAAC,CAAA;QACrC,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;QACpC,yBAAyB,CAAC,EAAC,GAAG,GAAG,EAAE,MAAM,EAAE,GAAG,EAAC,EAAE,aAAa,CAAC,CAAA;IACjE,CAAC;IACD,GAAG,CAAC,KAAK,EAAE,CAAA;IACX,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;AACzB,CAAC;AAED,SAAS,mBAAmB,CAAC,GAAiB;IAC5C,MAAM,EAAC,GAAG,EAAC,GAAG,GAAG,CAAA;IACjB,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;IACvB,yBAAyB,CAAC,GAAG,CAAC,CAAA;IAC9B,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;AACzB,CAAC;AAED,SAAS,yBAAyB,CAAC,GAAiB,EAAE,aAAsB;IAC1E,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,MAAM,EAAC,UAAU,EAAE,kBAAkB,EAAC,GAAG,MAAM,CAAA;IAC/C,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,CAAA;IAC9B,MAAM,QAAQ,GAAG,IAAI,CAAC,kBAAkB,CAAC,CAAA;IACzC,MAAM,QAAQ,GAAG,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAA;IACtD,IAAI,KAAK,GAAG,CAAC,aAAa,CAAA;IAC1B,IAAI,SAA2B,CAAA;IAE/B,KAAK,MAAM,GAAG,IAAI,KAAK,EAAE,CAAC;QACxB,IAAI,KAAK;YAAE,KAAK,GAAG,KAAK,CAAA;;YACnB,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;QAC5B,iBAAiB,CAAC,GAAG,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAA;IACxD,CAAC;IACD,IAAI,KAAK;QAAE,SAAS,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;IAC7C,KAAK,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAA;QAC3B,GAAG,CAAC,EAAE,CAAC,IAAA,aAAG,EAAC,IAAA,WAAC,EAAA,GAAG,KAAK,gBAAgB,EAAE,IAAA,oBAAa,EAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE;YACzE,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAC,CAAA;YACxB,iBAAiB,CAAC,GAAG,EAAE,kBAAkB,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAA;QACxD,CAAC,CAAC,CAAA;IACJ,CAAC;IACD,IAAI,MAAM,CAAC,oBAAoB,EAAE,CAAC;QAChC,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,GAAG,EAAE,EAAE,CAC7B,GAAG,CAAC,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE,GAAG,EAAE,CAAC,iBAAiB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,CAAC,CAAC,CACtF,CAAA;IACH,CAAC;IAED,SAAS,IAAI,CAAC,EAAoB;QAChC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;IAClC,CAAC;IAED,SAAS,aAAa,CAAC,EAAY;QACjC,IAAI,aAAa;YAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;QACzC,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC,MAAM,EAAE,CAAC;YACnC,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;QAC5E,CAAC;QACD,OAAO,EAAE,CAAA;IACX,CAAC;IAED,SAAS,QAAQ,CAAC,GAAW;QAC3B,OAAO,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,GAAG,IAAA,qBAAW,EAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IAC1D,CAAC;IAED,SAAS,iBAAiB,CAAC,GAAW,EAAE,UAAwB,EAAE,KAAW;QAC3E,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAC7C,aAAa,CAAC,EAAC,GAAG,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAC,CAAC,CAAA;IAC1D,CAAC;IAED,SAAS,YAAY,CAAC,GAAS,EAAE,EAAY;QAC3C,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,IAAA,aAAG,EAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACrE,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,GAAiB;IACtC,MAAM,EAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAC,GAAG,GAAG,CAAA;IAC/B,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS;YACZ,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,GAAG,IAAI,qBAAqB,CAAC,CAAA;YAC9C,MAAK;QACP,KAAK,QAAQ;YACX,eAAe,CAAC,GAAG,CAAC,CAAA;YACpB,MAAK;QACP,KAAK,WAAW;YACd,GAAG,CAAC,EAAE,CACJ,IAAA,WAAC,EAAA,GAAG,IAAI,kBAAkB,EAC1B,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,SAAS,IAAI,sBAAsB,CAAC,EAC3D,GAAG,EAAE,CAAC,eAAe,CAAC,GAAG,CAAC,CAC3B,CAAA;YACD,MAAK;QACP;YACE,eAAe,CAAC,GAAG,CAAC,CAAA;IACxB,CAAC;AACH,CAAC;AAED,SAAS,eAAe,CAAC,EAAC,GAAG,EAAE,IAAI,EAAe;IAChD,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,GAAG,IAAA,cAAO,EAAC,GAAG,EAAE,eAAK,CAAC,IAAI,IAAI,GAAG,CAAC,CAAA;AACrD,CAAC;AAED,SAAS,eAAe,CAAC,EAAC,GAAG,EAAE,IAAI,EAAe;IAChD,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,QAAQ,IAAI,EAAE,CAAC,CAAA;AAClC,CAAC;AAED,SAAS,YAAY,CAAC,GAAiB;IACrC,MAAM,EAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAC,GAAG,GAAG,CAAA;IAC7D,MAAM,EAAC,GAAG,EAAC,GAAG,MAAM,CAAA;IACpB,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,CAAC,CAAA;IAClC,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,mBAAe,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,EAAE,GAAG,EAAE,iBAAiB,GAAG,EAAE,CAAC,CAAA;IACjG,IAAI,CAAC,IAAA,YAAM,EAAC,SAAS,CAAC;QAAE,OAAO,aAAa,CAAC,EAAC,GAAG,GAAG,EAAE,MAAM,EAAE,SAAS,EAAC,CAAC,CAAA;IACzE,MAAM,EAAC,IAAI,EAAC,GAAG,SAAS,CAAA;IACxB,MAAM,GAAG,GAAG,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,aAAS,CAAC,EAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAC,CAAC,EAAE,WAAW,CAAC,CAAA;IAC/F,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,GAAG,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,CAAA;AACxD,CAAC;AAED,SAAS,YAAY,CAAC,GAAY,EAAE,GAAc;IAChD,OAAO,GAAG,CAAC,SAAS;QAClB,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,EAAC,GAAG,EAAE,GAAG,CAAC,SAAS,EAAC,CAAC;QACnD,CAAC,CAAC,IAAA,WAAC,EAAA,GAAG,GAAG,CAAC,UAAU,CAAC,SAAS,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,CAAC,YAAY,CAAA;AAC3D,CAAC;AAED,SAAS,cAAc,CAAC,EAAC,GAAG,EAAE,IAAI,EAAe;IAC/C,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,WAAC,EAAA,kBAAkB,IAAI,GAAG,CAAC,CAAA;AAC7C,CAAC;AAED,SAAS,QAAQ,CAAC,EAAC,GAAG,EAAe,EAAE,KAAY;IACjD,IAAI,KAAK,EAAE,CAAC;QACV,GAAG,CAAC,EAAE,CACJ,KAAK,EACL,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAC9B,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAC9B,CAAA;IACH,CAAC;SAAM,CAAC;QACN,GAAG,CAAC,GAAG,CAAC,eAAC,CAAC,IAAI,EAAE,IAAA,aAAG,EAAA,GAAG,CAAC,CAAA;IACzB,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/types.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..678986f1bd93cdb821e40d3a0ffcb804df79e95b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/types.d.ts @@ -0,0 +1,6 @@ +import type { SchemaObject } from "../../types"; +export type SchemaObjectMap = { + [Ref in string]?: SchemaObject; +}; +export declare const jtdForms: readonly ["elements", "values", "discriminator", "properties", "optionalProperties", "enum", "type", "ref"]; +export type JTDForm = (typeof jtdForms)[number]; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/types.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/types.js new file mode 100644 index 0000000000000000000000000000000000000000..b9c60a90fdd7ff01af7ea51ccf0fdfe39459bc3f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/types.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.jtdForms = void 0; +exports.jtdForms = [ + "elements", + "values", + "discriminator", + "properties", + "optionalProperties", + "enum", + "type", + "ref", +]; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/types.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..53439e002a07c221fe548ea439001cd8c2487521 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/compile/jtd/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/compile/jtd/types.ts"],"names":[],"mappings":";;;AAIa,QAAA,QAAQ,GAAG;IACtB,UAAU;IACV,QAAQ;IACR,eAAe;IACf,YAAY;IACZ,oBAAoB;IACpB,MAAM;IACN,MAAM;IACN,KAAK;CACG,CAAA"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/index.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf008331f7b7d8ce6a118fe5b215eb9dac6f0823 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/index.d.ts @@ -0,0 +1,2 @@ +import type Ajv from "../../core"; +export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/index.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e86496282031e75f3204b290ad24ae152ce4f243 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/index.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const metaSchema = require("./schema.json"); +const applicator = require("./meta/applicator.json"); +const content = require("./meta/content.json"); +const core = require("./meta/core.json"); +const format = require("./meta/format.json"); +const metadata = require("./meta/meta-data.json"); +const validation = require("./meta/validation.json"); +const META_SUPPORT_DATA = ["/properties"]; +function addMetaSchema2019($data) { + ; + [ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } +} +exports.default = addMetaSchema2019; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/index.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..9b8a36d618eb3433853ee16f063490781a42c2aa --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2019-09/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,+CAA8C;AAC9C,yCAAwC;AACxC,6CAA4C;AAC5C,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAfD,oCAeC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json new file mode 100644 index 0000000000000000000000000000000000000000..c5e91cf2ac8469eccf444cf6501dba80dccb5c63 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json @@ -0,0 +1,53 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/applicator": true + }, + "$recursiveAnchor": true, + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": {"$recursiveRef": "#"}, + "unevaluatedItems": {"$recursiveRef": "#"}, + "items": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}] + }, + "contains": {"$recursiveRef": "#"}, + "additionalProperties": {"$recursiveRef": "#"}, + "unevaluatedProperties": {"$recursiveRef": "#"}, + "properties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { + "$recursiveRef": "#" + } + }, + "propertyNames": {"$recursiveRef": "#"}, + "if": {"$recursiveRef": "#"}, + "then": {"$recursiveRef": "#"}, + "else": {"$recursiveRef": "#"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$recursiveRef": "#"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$recursiveRef": "#"} + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json new file mode 100644 index 0000000000000000000000000000000000000000..b8f63734343046b3d4b74bf8a59f2380dbc67fc3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "contentSchema": {"$recursiveRef": "#"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json new file mode 100644 index 0000000000000000000000000000000000000000..f71adbff04fe9ecc6a828823ad5dfa7366f1a60f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true + }, + "$recursiveAnchor": true, + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json new file mode 100644 index 0000000000000000000000000000000000000000..03ccfce26efeaff5a6e223be5154f238f633c16e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/format": true + }, + "$recursiveAnchor": true, + + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json new file mode 100644 index 0000000000000000000000000000000000000000..0e194326fa133b077af409486ebe1e2dca83feff --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/meta-data": true + }, + "$recursiveAnchor": true, + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..7027a1279a014a74c170a2558100d2ca37eecac0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/validation": true + }, + "$recursiveAnchor": true, + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..54eb7157afed6957bd7074068d7ad99498c668f3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}] + } + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/index.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c232ab05c7f6c2418ccd411f450a1e6674b1d277 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/index.d.ts @@ -0,0 +1,2 @@ +import type Ajv from "../../core"; +export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/index.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d92567564fedbbb77772b660d422ea160780aa6c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/index.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const metaSchema = require("./schema.json"); +const applicator = require("./meta/applicator.json"); +const unevaluated = require("./meta/unevaluated.json"); +const content = require("./meta/content.json"); +const core = require("./meta/core.json"); +const format = require("./meta/format-annotation.json"); +const metadata = require("./meta/meta-data.json"); +const validation = require("./meta/validation.json"); +const META_SUPPORT_DATA = ["/properties"]; +function addMetaSchema2020($data) { + ; + [ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } +} +exports.default = addMetaSchema2020; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/index.js.map b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..eb90027ddeed38faab289da72ad839c711fda361 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../lib/refs/json-schema-2020-12/index.ts"],"names":[],"mappings":";;AAEA,4CAA2C;AAC3C,qDAAoD;AACpD,uDAAsD;AACtD,+CAA8C;AAC9C,yCAAwC;AACxC,wDAAuD;AACvD,kDAAiD;AACjD,qDAAoD;AAEpD,MAAM,iBAAiB,GAAG,CAAC,aAAa,CAAC,CAAA;AAEzC,SAAwB,iBAAiB,CAAY,KAAe;IAClE,CAAC;IAAA;QACC,UAAU;QACV,UAAU;QACV,WAAW;QACX,OAAO;QACP,IAAI;QACJ,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;QACvB,QAAQ;QACR,SAAS,CAAC,IAAI,EAAE,UAAU,CAAC;KAC5B,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAA;IAC7D,OAAO,IAAI,CAAA;IAEX,SAAS,SAAS,CAAC,GAAQ,EAAE,GAAoB;QAC/C,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;IAClE,CAAC;AACH,CAAC;AAhBD,oCAgBC"} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json new file mode 100644 index 0000000000000000000000000000000000000000..674c913dab00c66865d82027bdf7748e157365fa --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json @@ -0,0 +1,48 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/applicator": true + }, + "$dynamicAnchor": "meta", + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": {"$ref": "#/$defs/schemaArray"}, + "items": {"$dynamicRef": "#meta"}, + "contains": {"$dynamicRef": "#meta"}, + "additionalProperties": {"$dynamicRef": "#meta"}, + "properties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "propertyNames": {"$dynamicRef": "#meta"}, + "if": {"$dynamicRef": "#meta"}, + "then": {"$dynamicRef": "#meta"}, + "else": {"$dynamicRef": "#meta"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$dynamicRef": "#meta"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$dynamicRef": "#meta"} + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json new file mode 100644 index 0000000000000000000000000000000000000000..2ae23ddb5cc30cce43646dc58b86f61b1dc7fc4c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentEncoding": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentSchema": {"$dynamicRef": "#meta"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json new file mode 100644 index 0000000000000000000000000000000000000000..4c8e5cb61657ff226186dd96e5dea6e15eb102e1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true + }, + "$dynamicAnchor": "meta", + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": {"$ref": "#/$defs/uriString"}, + "$ref": {"$ref": "#/$defs/uriReferenceString"}, + "$anchor": {"$ref": "#/$defs/anchorString"}, + "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"}, + "$dynamicAnchor": {"$ref": "#/$defs/anchorString"}, + "$vocabulary": { + "type": "object", + "propertyNames": {"$ref": "#/$defs/uriString"}, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"} + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json new file mode 100644 index 0000000000000000000000000000000000000000..83c26e35f0042ebada16aba9b0c42bedd46bcb24 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true + }, + "$dynamicAnchor": "meta", + + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json new file mode 100644 index 0000000000000000000000000000000000000000..11946fb5019a3564afb38270af3d7806af39978c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/meta-data": true + }, + "$dynamicAnchor": "meta", + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json new file mode 100644 index 0000000000000000000000000000000000000000..5e4b203b2c26905ccef5ab90c627aaa19ee708bb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true + }, + "$dynamicAnchor": "meta", + + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": {"$dynamicRef": "#meta"}, + "unevaluatedProperties": {"$dynamicRef": "#meta"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..e0ae13d9d2063403c60e88282701b4b8f6ccd5f5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/validation": true + }, + "$dynamicAnchor": "meta", + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1c68270fdc6e4fa807c75bb32391ce8cb530a497 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json @@ -0,0 +1,55 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/unevaluated"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format-annotation"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { + "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}] + }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/codegen/code.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/codegen/code.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d4de6149f9451273ae7e3ca547cb69baed7877c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/codegen/code.ts @@ -0,0 +1,169 @@ +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +export abstract class _CodeOrName { + abstract readonly str: string + abstract readonly names: UsedNames + abstract toString(): string + abstract emptyStr(): boolean +} + +export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i + +export class Name extends _CodeOrName { + readonly str: string + constructor(s: string) { + super() + if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") + this.str = s + } + + toString(): string { + return this.str + } + + emptyStr(): boolean { + return false + } + + get names(): UsedNames { + return {[this.str]: 1} + } +} + +export class _Code extends _CodeOrName { + readonly _items: readonly CodeItem[] + private _str?: string + private _names?: UsedNames + + constructor(code: string | readonly CodeItem[]) { + super() + this._items = typeof code === "string" ? [code] : code + } + + toString(): string { + return this.str + } + + emptyStr(): boolean { + if (this._items.length > 1) return false + const item = this._items[0] + return item === "" || item === '""' + } + + get str(): string { + return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, "")) + } + + get names(): UsedNames { + return (this._names ??= this._items.reduce((names: UsedNames, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1 + return names + }, {})) + } +} + +export type CodeItem = Name | string | number | boolean | null + +export type UsedNames = Record + +export type Code = _Code | Name + +export type SafeExpr = Code | number | boolean | null + +export const nil = new _Code("") + +type CodeArg = SafeExpr | string | undefined + +export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code { + const code: CodeItem[] = [strs[0]] + let i = 0 + while (i < args.length) { + addCodeArg(code, args[i]) + code.push(strs[++i]) + } + return new _Code(code) +} + +const plus = new _Code("+") + +export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code { + const expr: CodeItem[] = [safeStringify(strs[0])] + let i = 0 + while (i < args.length) { + expr.push(plus) + addCodeArg(expr, args[i]) + expr.push(plus, safeStringify(strs[++i])) + } + optimize(expr) + return new _Code(expr) +} + +export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void { + if (arg instanceof _Code) code.push(...arg._items) + else if (arg instanceof Name) code.push(arg) + else code.push(interpolate(arg)) +} + +function optimize(expr: CodeItem[]): void { + let i = 1 + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]) + if (res !== undefined) { + expr.splice(i - 1, 3, res) + continue + } + expr[i++] = "+" + } + i++ + } +} + +function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined { + if (b === '""') return a + if (a === '""') return b + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') return + if (typeof b != "string") return `${a.slice(0, -1)}${b}"` + if (b[0] === '"') return a.slice(0, -1) + b.slice(1) + return + } + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}` + return +} + +export function strConcat(c1: Code, c2: Code): Code { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}` +} + +// TODO do not allow arrays here +function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string { + return typeof x == "number" || typeof x == "boolean" || x === null + ? x + : safeStringify(Array.isArray(x) ? x.join(",") : x) +} + +export function stringify(x: unknown): Code { + return new _Code(safeStringify(x)) +} + +export function safeStringify(x: unknown): string { + return JSON.stringify(x) + .replace(/\u2028/g, "\\u2028") + .replace(/\u2029/g, "\\u2029") +} + +export function getProperty(key: Code | string | number): Code { + return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]` +} + +//Does best effort to format the name properly +export function getEsmExportName(key: Code | string | number): Code { + if (typeof key == "string" && IDENTIFIER.test(key)) { + return new _Code(`${key}`) + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`) +} + +export function regexpCode(rx: RegExp): Code { + return new _Code(rx.toString()) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/codegen/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/codegen/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a6d1ee58c106245ba8a1b56f929fe3a23f337b8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/codegen/index.ts @@ -0,0 +1,852 @@ +import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope" +import {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from "./code" +import {Scope, varKinds} from "./scope" + +export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code" +export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope" + +// type for expressions that can be safely inserted in code without quotes +export type SafeExpr = Code | number | boolean | null + +// type that is either Code of function that adds code to CodeGen instance using its methods +export type Block = Code | (() => void) + +export const operators = { + GT: new _Code(">"), + GTE: new _Code(">="), + LT: new _Code("<"), + LTE: new _Code("<="), + EQ: new _Code("==="), + NEQ: new _Code("!=="), + NOT: new _Code("!"), + OR: new _Code("||"), + AND: new _Code("&&"), + ADD: new _Code("+"), +} + +abstract class Node { + abstract readonly names: UsedNames + + optimizeNodes(): this | ChildNode | ChildNode[] | undefined { + return this + } + + optimizeNames(_names: UsedNames, _constants: Constants): this | undefined { + return this + } + + // get count(): number { + // return 1 + // } +} + +class Def extends Node { + constructor( + private readonly varKind: Name, + private readonly name: Name, + private rhs?: SafeExpr + ) { + super() + } + + render({es5, _n}: CGOptions): string { + const varKind = es5 ? varKinds.var : this.varKind + const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}` + return `${varKind} ${this.name}${rhs};` + _n + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!names[this.name.str]) return + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants) + return this + } + + get names(): UsedNames { + return this.rhs instanceof _CodeOrName ? this.rhs.names : {} + } +} + +class Assign extends Node { + constructor( + readonly lhs: Code, + public rhs: SafeExpr, + private readonly sideEffects?: boolean + ) { + super() + } + + render({_n}: CGOptions): string { + return `${this.lhs} = ${this.rhs};` + _n + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return + this.rhs = optimizeExpr(this.rhs, names, constants) + return this + } + + get names(): UsedNames { + const names = this.lhs instanceof Name ? {} : {...this.lhs.names} + return addExprNames(names, this.rhs) + } +} + +class AssignOp extends Assign { + constructor( + lhs: Code, + private readonly op: Code, + rhs: SafeExpr, + sideEffects?: boolean + ) { + super(lhs, rhs, sideEffects) + } + + render({_n}: CGOptions): string { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n + } +} + +class Label extends Node { + readonly names: UsedNames = {} + constructor(readonly label: Name) { + super() + } + + render({_n}: CGOptions): string { + return `${this.label}:` + _n + } +} + +class Break extends Node { + readonly names: UsedNames = {} + constructor(readonly label?: Code) { + super() + } + + render({_n}: CGOptions): string { + const label = this.label ? ` ${this.label}` : "" + return `break${label};` + _n + } +} + +class Throw extends Node { + constructor(readonly error: Code) { + super() + } + + render({_n}: CGOptions): string { + return `throw ${this.error};` + _n + } + + get names(): UsedNames { + return this.error.names + } +} + +class AnyCode extends Node { + constructor(private code: SafeExpr) { + super() + } + + render({_n}: CGOptions): string { + return `${this.code};` + _n + } + + optimizeNodes(): this | undefined { + return `${this.code}` ? this : undefined + } + + optimizeNames(names: UsedNames, constants: Constants): this { + this.code = optimizeExpr(this.code, names, constants) + return this + } + + get names(): UsedNames { + return this.code instanceof _CodeOrName ? this.code.names : {} + } +} + +abstract class ParentNode extends Node { + constructor(readonly nodes: ChildNode[] = []) { + super() + } + + render(opts: CGOptions): string { + return this.nodes.reduce((code, n) => code + n.render(opts), "") + } + + optimizeNodes(): this | ChildNode | ChildNode[] | undefined { + const {nodes} = this + let i = nodes.length + while (i--) { + const n = nodes[i].optimizeNodes() + if (Array.isArray(n)) nodes.splice(i, 1, ...n) + else if (n) nodes[i] = n + else nodes.splice(i, 1) + } + return nodes.length > 0 ? this : undefined + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + const {nodes} = this + let i = nodes.length + while (i--) { + // iterating backwards improves 1-pass optimization + const n = nodes[i] + if (n.optimizeNames(names, constants)) continue + subtractNames(names, n.names) + nodes.splice(i, 1) + } + return nodes.length > 0 ? this : undefined + } + + get names(): UsedNames { + return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {}) + } + + // get count(): number { + // return this.nodes.reduce((c, n) => c + n.count, 1) + // } +} + +abstract class BlockNode extends ParentNode { + render(opts: CGOptions): string { + return "{" + opts._n + super.render(opts) + "}" + opts._n + } +} + +class Root extends ParentNode {} + +class Else extends BlockNode { + static readonly kind = "else" +} + +class If extends BlockNode { + static readonly kind = "if" + else?: If | Else + constructor( + private condition: Code | boolean, + nodes?: ChildNode[] + ) { + super(nodes) + } + + render(opts: CGOptions): string { + let code = `if(${this.condition})` + super.render(opts) + if (this.else) code += "else " + this.else.render(opts) + return code + } + + optimizeNodes(): If | ChildNode[] | undefined { + super.optimizeNodes() + const cond = this.condition + if (cond === true) return this.nodes // else is ignored here + let e = this.else + if (e) { + const ns = e.optimizeNodes() + e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined) + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes + if (this.nodes.length) return this + return new If(not(cond), e instanceof If ? [e] : e.nodes) + } + if (cond === false || !this.nodes.length) return undefined + return this + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + this.else = this.else?.optimizeNames(names, constants) + if (!(super.optimizeNames(names, constants) || this.else)) return + this.condition = optimizeExpr(this.condition, names, constants) + return this + } + + get names(): UsedNames { + const names = super.names + addExprNames(names, this.condition) + if (this.else) addNames(names, this.else.names) + return names + } + + // get count(): number { + // return super.count + (this.else?.count || 0) + // } +} + +abstract class For extends BlockNode { + static readonly kind = "for" +} + +class ForLoop extends For { + constructor(private iteration: Code) { + super() + } + + render(opts: CGOptions): string { + return `for(${this.iteration})` + super.render(opts) + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!super.optimizeNames(names, constants)) return + this.iteration = optimizeExpr(this.iteration, names, constants) + return this + } + + get names(): UsedNames { + return addNames(super.names, this.iteration.names) + } +} + +class ForRange extends For { + constructor( + private readonly varKind: Name, + private readonly name: Name, + private readonly from: SafeExpr, + private readonly to: SafeExpr + ) { + super() + } + + render(opts: CGOptions): string { + const varKind = opts.es5 ? varKinds.var : this.varKind + const {name, from, to} = this + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts) + } + + get names(): UsedNames { + const names = addExprNames(super.names, this.from) + return addExprNames(names, this.to) + } +} + +class ForIter extends For { + constructor( + private readonly loop: "of" | "in", + private readonly varKind: Name, + private readonly name: Name, + private iterable: Code + ) { + super() + } + + render(opts: CGOptions): string { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts) + } + + optimizeNames(names: UsedNames, constants: Constants): this | undefined { + if (!super.optimizeNames(names, constants)) return + this.iterable = optimizeExpr(this.iterable, names, constants) + return this + } + + get names(): UsedNames { + return addNames(super.names, this.iterable.names) + } +} + +class Func extends BlockNode { + static readonly kind = "func" + constructor( + public name: Name, + public args: Code, + public async?: boolean + ) { + super() + } + + render(opts: CGOptions): string { + const _async = this.async ? "async " : "" + return `${_async}function ${this.name}(${this.args})` + super.render(opts) + } +} + +class Return extends ParentNode { + static readonly kind = "return" + + render(opts: CGOptions): string { + return "return " + super.render(opts) + } +} + +class Try extends BlockNode { + catch?: Catch + finally?: Finally + + render(opts: CGOptions): string { + let code = "try" + super.render(opts) + if (this.catch) code += this.catch.render(opts) + if (this.finally) code += this.finally.render(opts) + return code + } + + optimizeNodes(): this { + super.optimizeNodes() + this.catch?.optimizeNodes() as Catch | undefined + this.finally?.optimizeNodes() as Finally | undefined + return this + } + + optimizeNames(names: UsedNames, constants: Constants): this { + super.optimizeNames(names, constants) + this.catch?.optimizeNames(names, constants) + this.finally?.optimizeNames(names, constants) + return this + } + + get names(): UsedNames { + const names = super.names + if (this.catch) addNames(names, this.catch.names) + if (this.finally) addNames(names, this.finally.names) + return names + } + + // get count(): number { + // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0) + // } +} + +class Catch extends BlockNode { + static readonly kind = "catch" + constructor(readonly error: Name) { + super() + } + + render(opts: CGOptions): string { + return `catch(${this.error})` + super.render(opts) + } +} + +class Finally extends BlockNode { + static readonly kind = "finally" + render(opts: CGOptions): string { + return "finally" + super.render(opts) + } +} + +type StartBlockNode = If | For | Func | Return | Try + +type LeafNode = Def | Assign | Label | Break | Throw | AnyCode + +type ChildNode = StartBlockNode | LeafNode + +type EndBlockNodeType = + | typeof If + | typeof Else + | typeof For + | typeof Func + | typeof Return + | typeof Catch + | typeof Finally + +type Constants = Record + +export interface CodeGenOptions { + es5?: boolean + lines?: boolean + ownProperties?: boolean +} + +interface CGOptions extends CodeGenOptions { + _n: "\n" | "" +} + +export class CodeGen { + readonly _scope: Scope + readonly _extScope: ValueScope + readonly _values: ScopeValueSets = {} + private readonly _nodes: ParentNode[] + private readonly _blockStarts: number[] = [] + private readonly _constants: Constants = {} + private readonly opts: CGOptions + + constructor(extScope: ValueScope, opts: CodeGenOptions = {}) { + this.opts = {...opts, _n: opts.lines ? "\n" : ""} + this._extScope = extScope + this._scope = new Scope({parent: extScope}) + this._nodes = [new Root()] + } + + toString(): string { + return this._root.render(this.opts) + } + + // returns unique name in the internal scope + name(prefix: string): Name { + return this._scope.name(prefix) + } + + // reserves unique name in the external scope + scopeName(prefix: string): ValueScopeName { + return this._extScope.name(prefix) + } + + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name { + const name = this._extScope.value(prefixOrName, value) + const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()) + vs.add(name) + return name + } + + getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { + return this._extScope.getValue(prefix, keyOrRef) + } + + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName: Name): Code { + return this._extScope.scopeRefs(scopeName, this._values) + } + + scopeCode(): Code { + return this._extScope.scopeCode(this._values) + } + + private _def( + varKind: Name, + nameOrPrefix: Name | string, + rhs?: SafeExpr, + constant?: boolean + ): Name { + const name = this._scope.toName(nameOrPrefix) + if (rhs !== undefined && constant) this._constants[name.str] = rhs + this._leafNode(new Def(varKind, name, rhs)) + return name + } + + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.const, nameOrPrefix, rhs, _constant) + } + + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.let, nameOrPrefix, rhs, _constant) + } + + // `var` declaration with optional assignment + var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { + return this._def(varKinds.var, nameOrPrefix, rhs, _constant) + } + + // assignment code + assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen { + return this._leafNode(new Assign(lhs, rhs, sideEffects)) + } + + // `+=` code + add(lhs: Code, rhs: SafeExpr): CodeGen { + return this._leafNode(new AssignOp(lhs, operators.ADD, rhs)) + } + + // appends passed SafeExpr to code or executes Block + code(c: Block | SafeExpr): CodeGen { + if (typeof c == "function") c() + else if (c !== nil) this._leafNode(new AnyCode(c)) + return this + } + + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues: [Name | string, SafeExpr | string][]): _Code { + const code: CodeItem[] = ["{"] + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(",") + code.push(key) + if (key !== value || this.opts.es5) { + code.push(":") + addCodeArg(code, value) + } + } + code.push("}") + return new _Code(code) + } + + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen { + this._blockNode(new If(condition)) + + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf() + } else if (thenBody) { + this.code(thenBody).endIf() + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body') + } + return this + } + + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition: Code | boolean): CodeGen { + return this._elseNode(new If(condition)) + } + + // `else` clause - only valid after `if` or `else if` clauses + else(): CodeGen { + return this._elseNode(new Else()) + } + + // end `if` statement (needed if gen.if was used only with condition) + endIf(): CodeGen { + return this._endBlockNode(If, Else) + } + + private _for(node: For, forBody?: Block): CodeGen { + this._blockNode(node) + if (forBody) this.code(forBody).endFor() + return this + } + + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration: Code, forBody?: Block): CodeGen { + return this._for(new ForLoop(iteration), forBody) + } + + // `for` statement for a range of values + forRange( + nameOrPrefix: Name | string, + from: SafeExpr, + to: SafeExpr, + forBody: (index: Name) => void, + varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let + ): CodeGen { + const name = this._scope.toName(nameOrPrefix) + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)) + } + + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf( + nameOrPrefix: Name | string, + iterable: Code, + forBody: (item: Name) => void, + varKind: Code = varKinds.const + ): CodeGen { + const name = this._scope.toName(nameOrPrefix) + if (this.opts.es5) { + const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable) + return this.forRange("_i", 0, _`${arr}.length`, (i) => { + this.var(name, _`${arr}[${i}]`) + forBody(name) + }) + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)) + } + + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn( + nameOrPrefix: Name | string, + obj: Code, + forBody: (item: Name) => void, + varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const + ): CodeGen { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody) + } + const name = this._scope.toName(nameOrPrefix) + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)) + } + + // end `for` loop + endFor(): CodeGen { + return this._endBlockNode(For) + } + + // `label` statement + label(label: Name): CodeGen { + return this._leafNode(new Label(label)) + } + + // `break` statement + break(label?: Code): CodeGen { + return this._leafNode(new Break(label)) + } + + // `return` statement + return(value: Block | SafeExpr): CodeGen { + const node = new Return() + this._blockNode(node) + this.code(value) + if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node') + return this._endBlockNode(Return) + } + + // `try` statement + try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen { + if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"') + const node = new Try() + this._blockNode(node) + this.code(tryBody) + if (catchCode) { + const error = this.name("e") + this._currNode = node.catch = new Catch(error) + catchCode(error) + } + if (finallyCode) { + this._currNode = node.finally = new Finally() + this.code(finallyCode) + } + return this._endBlockNode(Catch, Finally) + } + + // `throw` statement + throw(error: Code): CodeGen { + return this._leafNode(new Throw(error)) + } + + // start self-balancing block + block(body?: Block, nodeCount?: number): CodeGen { + this._blockStarts.push(this._nodes.length) + if (body) this.code(body).endBlock(nodeCount) + return this + } + + // end the current self-balancing block + endBlock(nodeCount?: number): CodeGen { + const len = this._blockStarts.pop() + if (len === undefined) throw new Error("CodeGen: not in self-balancing block") + const toClose = this._nodes.length - len + if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`) + } + this._nodes.length = len + return this + } + + // `function` heading (or definition if funcBody is passed) + func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen { + this._blockNode(new Func(name, args, async)) + if (funcBody) this.code(funcBody).endFunc() + return this + } + + // end function definition + endFunc(): CodeGen { + return this._endBlockNode(Func) + } + + optimize(n = 1): void { + while (n-- > 0) { + this._root.optimizeNodes() + this._root.optimizeNames(this._root.names, this._constants) + } + } + + private _leafNode(node: LeafNode): CodeGen { + this._currNode.nodes.push(node) + return this + } + + private _blockNode(node: StartBlockNode): void { + this._currNode.nodes.push(node) + this._nodes.push(node) + } + + private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen { + const n = this._currNode + if (n instanceof N1 || (N2 && n instanceof N2)) { + this._nodes.pop() + return this + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`) + } + + private _elseNode(node: If | Else): CodeGen { + const n = this._currNode + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"') + } + this._currNode = n.else = node + return this + } + + private get _root(): Root { + return this._nodes[0] as Root + } + + private get _currNode(): ParentNode { + const ns = this._nodes + return ns[ns.length - 1] + } + + private set _currNode(node: ParentNode) { + const ns = this._nodes + ns[ns.length - 1] = node + } + + // get nodeCount(): number { + // return this._root.count + // } +} + +function addNames(names: UsedNames, from: UsedNames): UsedNames { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0) + return names +} + +function addExprNames(names: UsedNames, from: SafeExpr): UsedNames { + return from instanceof _CodeOrName ? addNames(names, from.names) : names +} + +function optimizeExpr(expr: T, names: UsedNames, constants: Constants): T +function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr { + if (expr instanceof Name) return replaceName(expr) + if (!canOptimize(expr)) return expr + return new _Code( + expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => { + if (c instanceof Name) c = replaceName(c) + if (c instanceof _Code) items.push(...c._items) + else items.push(c) + return items + }, []) + ) + + function replaceName(n: Name): SafeExpr { + const c = constants[n.str] + if (c === undefined || names[n.str] !== 1) return n + delete names[n.str] + return c + } + + function canOptimize(e: SafeExpr): e is _Code { + return ( + e instanceof _Code && + e._items.some( + (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined + ) + ) + } +} + +function subtractNames(names: UsedNames, from: UsedNames): void { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0) +} + +export function not(x: T): T +export function not(x: Code | SafeExpr): Code | SafeExpr { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}` +} + +const andCode = mappend(operators.AND) + +// boolean AND (&&) expression with the passed arguments +export function and(...args: Code[]): Code { + return args.reduce(andCode) +} + +const orCode = mappend(operators.OR) + +// boolean OR (||) expression with the passed arguments +export function or(...args: Code[]): Code { + return args.reduce(orCode) +} + +type MAppend = (x: Code, y: Code) => Code + +function mappend(op: Code): MAppend { + return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`) +} + +function par(x: Code): Code { + return x instanceof Name ? x : _`(${x})` +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/codegen/scope.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/codegen/scope.ts new file mode 100644 index 0000000000000000000000000000000000000000..511992297d08f661ef4cf826eba9fbdbf0854db0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/codegen/scope.ts @@ -0,0 +1,215 @@ +import {_, nil, Code, Name} from "./code" + +interface NameGroup { + prefix: string + index: number +} + +export interface NameValue { + ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure + key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used + code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`) +} + +export type ValueReference = unknown // possibly make CodeGen parameterized type on this type + +class ValueError extends Error { + readonly value?: NameValue + constructor(name: ValueScopeName) { + super(`CodeGen: "code" for ${name} not defined`) + this.value = name.value + } +} + +interface ScopeOptions { + prefixes?: Set + parent?: Scope +} + +interface ValueScopeOptions extends ScopeOptions { + scope: ScopeStore + es5?: boolean + lines?: boolean +} + +export type ScopeStore = Record + +type ScopeValues = { + [Prefix in string]?: Map +} + +export type ScopeValueSets = { + [Prefix in string]?: Set +} + +export enum UsedValueState { + Started, + Completed, +} + +export type UsedScopeValues = { + [Prefix in string]?: Map +} + +export const varKinds = { + const: new Name("const"), + let: new Name("let"), + var: new Name("var"), +} + +export class Scope { + protected readonly _names: {[Prefix in string]?: NameGroup} = {} + protected readonly _prefixes?: Set + protected readonly _parent?: Scope + + constructor({prefixes, parent}: ScopeOptions = {}) { + this._prefixes = prefixes + this._parent = parent + } + + toName(nameOrPrefix: Name | string): Name { + return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix) + } + + name(prefix: string): Name { + return new Name(this._newName(prefix)) + } + + protected _newName(prefix: string): string { + const ng = this._names[prefix] || this._nameGroup(prefix) + return `${prefix}${ng.index++}` + } + + private _nameGroup(prefix: string): NameGroup { + if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`) + } + return (this._names[prefix] = {prefix, index: 0}) + } +} + +interface ScopePath { + property: string + itemIndex: number +} + +export class ValueScopeName extends Name { + readonly prefix: string + value?: NameValue + scopePath?: Code + + constructor(prefix: string, nameStr: string) { + super(nameStr) + this.prefix = prefix + } + + setValue(value: NameValue, {property, itemIndex}: ScopePath): void { + this.value = value + this.scopePath = _`.${new Name(property)}[${itemIndex}]` + } +} + +interface VSOptions extends ValueScopeOptions { + _n: Code +} + +const line = _`\n` + +export class ValueScope extends Scope { + protected readonly _values: ScopeValues = {} + protected readonly _scope: ScopeStore + readonly opts: VSOptions + + constructor(opts: ValueScopeOptions) { + super(opts) + this._scope = opts.scope + this.opts = {...opts, _n: opts.lines ? line : nil} + } + + get(): ScopeStore { + return this._scope + } + + name(prefix: string): ValueScopeName { + return new ValueScopeName(prefix, this._newName(prefix)) + } + + value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName { + if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value") + const name = this.toName(nameOrPrefix) as ValueScopeName + const {prefix} = name + const valueKey = value.key ?? value.ref + let vs = this._values[prefix] + if (vs) { + const _name = vs.get(valueKey) + if (_name) return _name + } else { + vs = this._values[prefix] = new Map() + } + vs.set(valueKey, name) + + const s = this._scope[prefix] || (this._scope[prefix] = []) + const itemIndex = s.length + s[itemIndex] = value.ref + name.setValue(value, {property: prefix, itemIndex}) + return name + } + + getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { + const vs = this._values[prefix] + if (!vs) return + return vs.get(keyOrRef) + } + + scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code { + return this._reduceValues(values, (name: ValueScopeName) => { + if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`) + return _`${scopeName}${name.scopePath}` + }) + } + + scopeCode( + values: ScopeValues | ScopeValueSets = this._values, + usedValues?: UsedScopeValues, + getCode?: (n: ValueScopeName) => Code | undefined + ): Code { + return this._reduceValues( + values, + (name: ValueScopeName) => { + if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`) + return name.value.code + }, + usedValues, + getCode + ) + } + + private _reduceValues( + values: ScopeValues | ScopeValueSets, + valueCode: (n: ValueScopeName) => Code | undefined, + usedValues: UsedScopeValues = {}, + getCode?: (n: ValueScopeName) => Code | undefined + ): Code { + let code: Code = nil + for (const prefix in values) { + const vs = values[prefix] + if (!vs) continue + const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()) + vs.forEach((name: ValueScopeName) => { + if (nameSet.has(name)) return + nameSet.set(name, UsedValueState.Started) + let c = valueCode(name) + if (c) { + const def = this.opts.es5 ? varKinds.var : varKinds.const + code = _`${code}${def} ${name} = ${c};${this.opts._n}` + } else if ((c = getCode?.(name))) { + code = _`${code}${c}${this.opts._n}` + } else { + throw new ValueError(name) + } + nameSet.set(name, UsedValueState.Completed) + }) + } + return code + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/errors.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..18424a0fc62917fa720aee28e97280865f8bf1f5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/errors.ts @@ -0,0 +1,184 @@ +import type {KeywordErrorCxt, KeywordErrorDefinition} from "../types" +import type {SchemaCxt} from "./index" +import {CodeGen, _, str, strConcat, Code, Name} from "./codegen" +import {SafeExpr} from "./codegen/code" +import {getErrorPath, Type} from "./util" +import N from "./names" + +export const keywordError: KeywordErrorDefinition = { + message: ({keyword}) => str`must pass "${keyword}" keyword validation`, +} + +export const keyword$DataError: KeywordErrorDefinition = { + message: ({keyword, schemaType}) => + schemaType + ? str`"${keyword}" keyword must be ${schemaType} ($data)` + : str`"${keyword}" keyword is invalid ($data)`, +} + +export interface ErrorPaths { + instancePath?: Code + schemaPath?: string + parentSchema?: boolean +} + +export function reportError( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition = keywordError, + errorPaths?: ErrorPaths, + overrideAllErrors?: boolean +): void { + const {it} = cxt + const {gen, compositeRule, allErrors} = it + const errObj = errorObjectCode(cxt, error, errorPaths) + if (overrideAllErrors ?? (compositeRule || allErrors)) { + addError(gen, errObj) + } else { + returnErrors(it, _`[${errObj}]`) + } +} + +export function reportExtraError( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition = keywordError, + errorPaths?: ErrorPaths +): void { + const {it} = cxt + const {gen, compositeRule, allErrors} = it + const errObj = errorObjectCode(cxt, error, errorPaths) + addError(gen, errObj) + if (!(compositeRule || allErrors)) { + returnErrors(it, N.vErrors) + } +} + +export function resetErrorsCount(gen: CodeGen, errsCount: Name): void { + gen.assign(N.errors, errsCount) + gen.if(_`${N.vErrors} !== null`, () => + gen.if( + errsCount, + () => gen.assign(_`${N.vErrors}.length`, errsCount), + () => gen.assign(N.vErrors, null) + ) + ) +} + +export function extendErrors({ + gen, + keyword, + schemaValue, + data, + errsCount, + it, +}: KeywordErrorCxt): void { + /* istanbul ignore if */ + if (errsCount === undefined) throw new Error("ajv implementation error") + const err = gen.name("err") + gen.forRange("i", errsCount, N.errors, (i) => { + gen.const(err, _`${N.vErrors}[${i}]`) + gen.if(_`${err}.instancePath === undefined`, () => + gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath)) + ) + gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`) + if (it.opts.verbose) { + gen.assign(_`${err}.schema`, schemaValue) + gen.assign(_`${err}.data`, data) + } + }) +} + +function addError(gen: CodeGen, errObj: Code): void { + const err = gen.const("err", errObj) + gen.if( + _`${N.vErrors} === null`, + () => gen.assign(N.vErrors, _`[${err}]`), + _`${N.vErrors}.push(${err})` + ) + gen.code(_`${N.errors}++`) +} + +function returnErrors(it: SchemaCxt, errs: Code): void { + const {gen, validateName, schemaEnv} = it + if (schemaEnv.$async) { + gen.throw(_`new ${it.ValidationError as Name}(${errs})`) + } else { + gen.assign(_`${validateName}.errors`, errs) + gen.return(false) + } +} + +const E = { + keyword: new Name("keyword"), + schemaPath: new Name("schemaPath"), // also used in JTD errors + params: new Name("params"), + propertyName: new Name("propertyName"), + message: new Name("message"), + schema: new Name("schema"), + parentSchema: new Name("parentSchema"), +} + +function errorObjectCode( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition, + errorPaths?: ErrorPaths +): Code { + const {createErrors} = cxt.it + if (createErrors === false) return _`{}` + return errorObject(cxt, error, errorPaths) +} + +function errorObject( + cxt: KeywordErrorCxt, + error: KeywordErrorDefinition, + errorPaths: ErrorPaths = {} +): Code { + const {gen, it} = cxt + const keyValues: [Name, SafeExpr | string][] = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths), + ] + extraErrorProps(cxt, error, keyValues) + return gen.object(...keyValues) +} + +function errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] { + const instPath = instancePath + ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}` + : errorPath + return [N.instancePath, strConcat(N.instancePath, instPath)] +} + +function errorSchemaPath( + {keyword, it: {errSchemaPath}}: KeywordErrorCxt, + {schemaPath, parentSchema}: ErrorPaths +): [Name, string | Code] { + let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}` + if (schemaPath) { + schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}` + } + return [E.schemaPath, schPath] +} + +function extraErrorProps( + cxt: KeywordErrorCxt, + {params, message}: KeywordErrorDefinition, + keyValues: [Name, SafeExpr | string][] +): void { + const {keyword, data, schemaValue, it} = cxt + const {opts, propertyName, topSchemaRef, schemaPath} = it + keyValues.push( + [E.keyword, keyword], + [E.params, typeof params == "function" ? params(cxt) : params || _`{}`] + ) + if (opts.messages) { + keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]) + } + if (opts.verbose) { + keyValues.push( + [E.schema, schemaValue], + [E.parentSchema, _`${topSchemaRef}${schemaPath}`], + [N.data, data] + ) + } + if (propertyName) keyValues.push([E.propertyName, propertyName]) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfc39345526afe62f8c1d52eabf5b25b7959537f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/index.ts @@ -0,0 +1,324 @@ +import type { + AnySchema, + AnySchemaObject, + AnyValidateFunction, + AsyncValidateFunction, + EvaluatedProperties, + EvaluatedItems, +} from "../types" +import type Ajv from "../core" +import type {InstanceOptions} from "../core" +import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen" +import ValidationError from "../runtime/validation_error" +import N from "./names" +import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve" +import {schemaHasRulesButRef, unescapeFragment} from "./util" +import {validateFunctionCode} from "./validate" +import {URIComponent} from "fast-uri" +import {JSONType} from "./rules" + +export type SchemaRefs = { + [Ref in string]?: SchemaEnv | AnySchema +} + +export interface SchemaCxt { + readonly gen: CodeGen + readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error + readonly data: Name // Name with reference to the current part of data instance + readonly parentData: Name // should be used in keywords modifying data + readonly parentDataProperty: Code | number // should be used in keywords modifying data + readonly dataNames: Name[] + readonly dataPathArr: (Code | number)[] + readonly dataLevel: number // the level of the currently validated data, + // it can be used to access both the property names and the data on all levels from the top. + dataTypes: JSONType[] // data types applied to the current part of data instance + definedProperties: Set // set of properties to keep track of for required checks + readonly topSchemaRef: Code + readonly validateName: Name + evaluated?: Name + readonly ValidationError?: Name + readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt + readonly schemaEnv: SchemaEnv + readonly rootId: string + baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref) + readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema + readonly errSchemaPath: string // this is actual string, should not be changed to Code + readonly errorPath: Code + readonly propertyName?: Name + readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword, + // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`). + // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true. + // You only need to use it if you have many steps in your keywords and potentially can define multiple errors. + props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function + items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function + jtdDiscriminator?: string + jtdMetadata?: boolean + readonly createErrors?: boolean + readonly opts: InstanceOptions // Ajv instance option. + readonly self: Ajv // current Ajv instance +} + +export interface SchemaObjCxt extends SchemaCxt { + readonly schema: AnySchemaObject +} +interface SchemaEnvArgs { + readonly schema: AnySchema + readonly schemaId?: "$id" | "id" + readonly root?: SchemaEnv + readonly baseId?: string + readonly schemaPath?: string + readonly localRefs?: LocalRefs + readonly meta?: boolean +} + +export class SchemaEnv implements SchemaEnvArgs { + readonly schema: AnySchema + readonly schemaId?: "$id" | "id" + readonly root: SchemaEnv + baseId: string // TODO possibly, it should be readonly + schemaPath?: string + localRefs?: LocalRefs + readonly meta?: boolean + readonly $async?: boolean // true if the current schema is asynchronous. + readonly refs: SchemaRefs = {} + readonly dynamicAnchors: {[Ref in string]?: true} = {} + validate?: AnyValidateFunction + validateName?: ValueScopeName + serialize?: (data: unknown) => string + serializeName?: ValueScopeName + parse?: (data: string) => unknown + parseName?: ValueScopeName + + constructor(env: SchemaEnvArgs) { + let schema: AnySchemaObject | undefined + if (typeof env.schema == "object") schema = env.schema + this.schema = env.schema + this.schemaId = env.schemaId + this.root = env.root || this + this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"]) + this.schemaPath = env.schemaPath + this.localRefs = env.localRefs + this.meta = env.meta + this.$async = schema?.$async + this.refs = {} + } +} + +// let codeSize = 0 +// let nodeCount = 0 + +// Compiles schema in SchemaEnv +export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv { + // TODO refactor - remove compilations + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + let _ValidationError + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: ValidationError, + code: _`require("ajv/dist/runtime/validation_error").default`, + }) + } + + const validateName = gen.scopeName("validate") + sch.validateName = validateName + + const schemaCxt: SchemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: N.data, + parentData: N.parentData, + parentDataProperty: N.parentDataProperty, + dataNames: [N.data], + dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: new Set(), + topSchemaRef: gen.scopeValue( + "schema", + this.opts.code.source === true + ? {ref: sch.schema, code: stringify(sch.schema)} + : {ref: sch.schema} + ), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: _`""`, + opts: this.opts, + self: this, + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + validateFunctionCode(schemaCxt) + gen.optimize(this.opts.code.optimize) + // gen.optimize(1) + const validateCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}` + // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch) + // console.log("\n\n\n *** \n", sourceCode) + const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode) + const validate: AnyValidateFunction = makeValidate(this, this.scope.get()) + this.scope.value(validateName, {ref: validate}) + + validate.errors = null + validate.schema = sch.schema + validate.schemaEnv = sch + if (sch.$async) (validate as AsyncValidateFunction).$async = true + if (this.opts.code.source === true) { + validate.source = {validateName, validateCode, scopeValues: gen._values} + } + if (this.opts.unevaluated) { + const {props, items} = schemaCxt + validate.evaluated = { + props: props instanceof Name ? undefined : props, + items: items instanceof Name ? undefined : items, + dynamicProps: props instanceof Name, + dynamicItems: items instanceof Name, + } + if (validate.source) validate.source.evaluated = stringify(validate.evaluated) + } + sch.validate = validate + return sch + } catch (e) { + delete sch.validate + delete sch.validateName + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode) + // console.log("\n\n\n *** \n", sourceCode, this.opts) + throw e + } finally { + this._compilations.delete(sch) + } +} + +export function resolveRef( + this: Ajv, + root: SchemaEnv, + baseId: string, + ref: string +): AnySchema | SchemaEnv | undefined { + ref = resolveUrl(this.opts.uriResolver, baseId, ref) + const schOrFunc = root.refs[ref] + if (schOrFunc) return schOrFunc + + let _sch = resolve.call(this, root, ref) + if (_sch === undefined) { + const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv + const {schemaId} = this.opts + if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId}) + } + + if (_sch === undefined) return + return (root.refs[ref] = inlineOrCompile.call(this, _sch)) +} + +function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv { + if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema + return sch.validate ? sch : compileSchema.call(this, sch) +} + +// Index of schema compilation in the currently compiled list +export function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) return sch + } +} + +function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId +} + +// resolve and compile the references ($ref) +// TODO returns AnySchemaObject (if the schema can be inlined) or validation function +function resolve( + this: Ajv, + root: SchemaEnv, // information about the root schema for the current schema + ref: string // reference to resolve +): SchemaEnv | undefined { + let sch + while (typeof (sch = this.refs[ref]) == "string") ref = sch + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref) +} + +// Resolve schema, its root and baseId +export function resolveSchema( + this: Ajv, + root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it + ref: string // reference to resolve +): SchemaEnv | undefined { + const p = this.opts.uriResolver.parse(ref) + const refPath = _getFullPath(this.opts.uriResolver, p) + let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined) + // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root) + } + + const id = normalizeId(refPath) + const schOrRef = this.refs[id] || this.schemas[id] + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef) + if (typeof sch?.schema !== "object") return + return getJsonPointer.call(this, p, sch) + } + + if (typeof schOrRef?.schema !== "object") return + if (!schOrRef.validate) compileSchema.call(this, schOrRef) + if (id === normalizeId(ref)) { + const {schema} = schOrRef + const {schemaId} = this.opts + const schId = schema[schemaId] + if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId) + return new SchemaEnv({schema, schemaId, root, baseId}) + } + return getJsonPointer.call(this, p, schOrRef) +} + +const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions", +]) + +function getJsonPointer( + this: Ajv, + parsedRef: URIComponent, + {baseId, schema, root}: SchemaEnv +): SchemaEnv | undefined { + if (parsedRef.fragment?.[0] !== "/") return + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return + const partSchema = schema[unescapeFragment(part)] + if (partSchema === undefined) return + schema = partSchema + // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def? + const schId = typeof schema === "object" && schema[this.opts.schemaId] + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = resolveUrl(this.opts.uriResolver, baseId, schId) + } + } + let env: SchemaEnv | undefined + if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) { + const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref) + env = resolveSchema.call(this, root, $ref) + } + // even though resolution failed we need to return SchemaEnv to throw exception + // so that compileAsync loads missing schema. + const {schemaId} = this.opts + env = env || new SchemaEnv({schema, schemaId, root, baseId}) + if (env.schema !== env.root.schema) return env + return undefined +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/jtd/parse.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/jtd/parse.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0141c770c7029ce1d41db61bcd9a19fbd0c08d5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/jtd/parse.ts @@ -0,0 +1,411 @@ +import type Ajv from "../../core" +import type {SchemaObject} from "../../types" +import {jtdForms, JTDForm, SchemaObjectMap} from "./types" +import {SchemaEnv, getCompilingSchema} from ".." +import {_, str, and, or, nil, not, CodeGen, Code, Name, SafeExpr} from "../codegen" +import MissingRefError from "../ref_error" +import N from "../names" +import {hasPropFunc} from "../../vocabularies/code" +import {hasRef} from "../../vocabularies/jtd/ref" +import {intRange, IntType} from "../../vocabularies/jtd/type" +import {parseJson, parseJsonNumber, parseJsonString} from "../../runtime/parseJson" +import {useFunc} from "../util" +import validTimestamp from "../../runtime/timestamp" + +type GenParse = (cxt: ParseCxt) => void + +const genParse: {[F in JTDForm]: GenParse} = { + elements: parseElements, + values: parseValues, + discriminator: parseDiscriminator, + properties: parseProperties, + optionalProperties: parseProperties, + enum: parseEnum, + type: parseType, + ref: parseRef, +} + +interface ParseCxt { + readonly gen: CodeGen + readonly self: Ajv // current Ajv instance + readonly schemaEnv: SchemaEnv + readonly definitions: SchemaObjectMap + schema: SchemaObject + data: Code + parseName: Name + char: Name +} + +export default function compileParser( + this: Ajv, + sch: SchemaEnv, + definitions: SchemaObjectMap +): SchemaEnv { + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + const parseName = gen.scopeName("parse") + const cxt: ParseCxt = { + self: this, + gen, + schema: sch.schema as SchemaObject, + schemaEnv: sch, + definitions, + data: N.data, + parseName, + char: gen.name("c"), + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + sch.parseName = parseName + parserFunction(cxt) + gen.optimize(this.opts.code.optimize) + const parseFuncCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}` + const makeParse = new Function(`${N.scope}`, sourceCode) + const parse: (json: string) => unknown = makeParse(this.scope.get()) + this.scope.value(parseName, {ref: parse}) + sch.parse = parse + } catch (e) { + if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode) + delete sch.parse + delete sch.parseName + throw e + } finally { + this._compilations.delete(sch) + } + return sch +} + +const undef = _`undefined` + +function parserFunction(cxt: ParseCxt): void { + const {gen, parseName, char} = cxt + gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => { + gen.let(N.data) + gen.let(char) + gen.assign(_`${parseName}.message`, undef) + gen.assign(_`${parseName}.position`, undef) + gen.assign(N.jsonPos, _`${N.jsonPos} || 0`) + gen.const(N.jsonLen, _`${N.json}.length`) + parseCode(cxt) + skipWhitespace(cxt) + gen.if(N.jsonPart, () => { + gen.assign(_`${parseName}.position`, N.jsonPos) + gen.return(N.data) + }) + gen.if(_`${N.jsonPos} === ${N.jsonLen}`, () => gen.return(N.data)) + jsonSyntaxError(cxt) + }) +} + +function parseCode(cxt: ParseCxt): void { + let form: JTDForm | undefined + for (const key of jtdForms) { + if (key in cxt.schema) { + form = key + break + } + } + if (form) parseNullable(cxt, genParse[form]) + else parseEmpty(cxt) +} + +const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError)) + +function parseNullable(cxt: ParseCxt, parseForm: GenParse): void { + const {gen, schema, data} = cxt + if (!schema.nullable) return parseForm(cxt) + tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)) +} + +function parseElements(cxt: ParseCxt): void { + const {gen, schema, data} = cxt + parseToken(cxt, "[") + const ix = gen.let("i", 0) + gen.assign(data, _`[]`) + parseItems(cxt, "]", () => { + const el = gen.let("el") + parseCode({...cxt, schema: schema.elements, data: el}) + gen.assign(_`${data}[${ix}++]`, el) + }) +} + +function parseValues(cxt: ParseCxt): void { + const {gen, schema, data} = cxt + parseToken(cxt, "{") + gen.assign(data, _`{}`) + parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)) +} + +function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void { + tryParseItems(cxt, endToken, block) + parseToken(cxt, endToken) +} + +function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void { + const {gen} = cxt + gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { + block() + tryParseToken(cxt, ",", () => gen.break(), hasItem) + }) + + function hasItem(): void { + tryParseToken(cxt, endToken, () => {}, jsonSyntaxError) + } +} + +function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void { + const {gen} = cxt + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + parsePropertyValue(cxt, key, schema) +} + +function parseDiscriminator(cxt: ParseCxt): void { + const {gen, data, schema} = cxt + const {discriminator, mapping} = schema + parseToken(cxt, "{") + gen.assign(data, _`{}`) + const startPos = gen.const("pos", N.jsonPos) + const value = gen.let("value") + const tag = gen.let("tag") + tryParseItems(cxt, "}", () => { + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + gen.if( + _`${key} === ${discriminator}`, + () => { + parseString({...cxt, data: tag}) + gen.assign(_`${data}[${key}]`, tag) + gen.break() + }, + () => parseEmpty({...cxt, data: value}) // can be discarded/skipped + ) + }) + gen.assign(N.jsonPos, startPos) + gen.if(_`${tag} === undefined`) + parsingError(cxt, str`discriminator tag not found`) + for (const tagValue in mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + parseSchemaProperties({...cxt, schema: mapping[tagValue]}, discriminator) + } + gen.else() + parsingError(cxt, str`discriminator value not in schema`) + gen.endIf() +} + +function parseProperties(cxt: ParseCxt): void { + const {gen, data} = cxt + parseToken(cxt, "{") + gen.assign(data, _`{}`) + parseSchemaProperties(cxt) +} + +function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void { + const {gen, schema, data} = cxt + const {properties, optionalProperties, additionalProperties} = schema + parseItems(cxt, "}", () => { + const key = gen.let("key") + parseString({...cxt, data: key}) + parseToken(cxt, ":") + gen.if(false) + parseDefinedProperty(cxt, key, properties) + parseDefinedProperty(cxt, key, optionalProperties) + if (discriminator) { + gen.elseIf(_`${key} === ${discriminator}`) + const tag = gen.let("tag") + parseString({...cxt, data: tag}) // can be discarded, it is already assigned + } + gen.else() + if (additionalProperties) { + parseEmpty({...cxt, data: _`${data}[${key}]`}) + } else { + parsingError(cxt, str`property ${key} not allowed`) + } + gen.endIf() + }) + if (properties) { + const hasProp = hasPropFunc(gen) + const allProps: Code = and( + ...Object.keys(properties).map((p): Code => _`${hasProp}.call(${data}, ${p})`) + ) + gen.if(not(allProps), () => parsingError(cxt, str`missing required properties`)) + } +} + +function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void { + const {gen} = cxt + for (const prop in schemas) { + gen.elseIf(_`${key} === ${prop}`) + parsePropertyValue(cxt, key, schemas[prop] as SchemaObject) + } +} + +function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void { + parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`}) +} + +function parseType(cxt: ParseCxt): void { + const {gen, schema, data, self} = cxt + switch (schema.type) { + case "boolean": + parseBoolean(cxt) + break + case "string": + parseString(cxt) + break + case "timestamp": { + parseString(cxt) + const vts = useFunc(gen, validTimestamp) + const {allowDate, parseDate} = self.opts + const notValid = allowDate ? _`!${vts}(${data}, true)` : _`!${vts}(${data})` + const fail: Code = parseDate + ? or(notValid, _`(${data} = new Date(${data}), false)`, _`isNaN(${data}.valueOf())`) + : notValid + gen.if(fail, () => parsingError(cxt, str`invalid timestamp`)) + break + } + case "float32": + case "float64": + parseNumber(cxt) + break + default: { + const t = schema.type as IntType + if (!self.opts.int32range && (t === "int32" || t === "uint32")) { + parseNumber(cxt, 16) // 2 ** 53 - max safe integer + if (t === "uint32") { + gen.if(_`${data} < 0`, () => parsingError(cxt, str`integer out of range`)) + } + } else { + const [min, max, maxDigits] = intRange[t] + parseNumber(cxt, maxDigits) + gen.if(_`${data} < ${min} || ${data} > ${max}`, () => + parsingError(cxt, str`integer out of range`) + ) + } + } + } +} + +function parseString(cxt: ParseCxt): void { + parseToken(cxt, '"') + parseWith(cxt, parseJsonString) +} + +function parseEnum(cxt: ParseCxt): void { + const {gen, data, schema} = cxt + const enumSch = schema.enum + parseToken(cxt, '"') + // TODO loopEnum + gen.if(false) + for (const value of enumSch) { + const valueStr = JSON.stringify(value).slice(1) // remove starting quote + gen.elseIf(_`${jsonSlice(valueStr.length)} === ${valueStr}`) + gen.assign(data, str`${value}`) + gen.add(N.jsonPos, valueStr.length) + } + gen.else() + jsonSyntaxError(cxt) + gen.endIf() +} + +function parseNumber(cxt: ParseCxt, maxDigits?: number): void { + const {gen} = cxt + skipWhitespace(cxt) + gen.if( + _`"-0123456789".indexOf(${jsonSlice(1)}) < 0`, + () => jsonSyntaxError(cxt), + () => parseWith(cxt, parseJsonNumber, maxDigits) + ) +} + +function parseBooleanToken(bool: boolean, fail: GenParse): GenParse { + return (cxt) => { + const {gen, data} = cxt + tryParseToken( + cxt, + `${bool}`, + () => fail(cxt), + () => gen.assign(data, bool) + ) + } +} + +function parseRef(cxt: ParseCxt): void { + const {gen, self, definitions, schema, schemaEnv} = cxt + const {ref} = schema + const refSchema = definitions[ref] + if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) + if (!hasRef(refSchema)) return parseCode({...cxt, schema: refSchema}) + const {root} = schemaEnv + const sch = compileParser.call(self, new SchemaEnv({schema: refSchema, root}), definitions) + partialParse(cxt, getParser(gen, sch), true) +} + +function getParser(gen: CodeGen, sch: SchemaEnv): Code { + return sch.parse + ? gen.scopeValue("parse", {ref: sch.parse}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.parse` +} + +function parseEmpty(cxt: ParseCxt): void { + parseWith(cxt, parseJson) +} + +function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void { + partialParse(cxt, useFunc(cxt.gen, parseFunc), args) +} + +function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void { + const {gen, data} = cxt + gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`) + gen.assign(N.jsonPos, _`${parseFunc}.position`) + gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`)) +} + +function parseToken(cxt: ParseCxt, tok: string): void { + tryParseToken(cxt, tok, jsonSyntaxError) +} + +function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void { + const {gen} = cxt + const n = tok.length + skipWhitespace(cxt) + gen.if( + _`${jsonSlice(n)} === ${tok}`, + () => { + gen.add(N.jsonPos, n) + success?.(cxt) + }, + () => fail(cxt) + ) +} + +function skipWhitespace({gen, char: c}: ParseCxt): void { + gen.code( + _`while((${c}=${N.json}[${N.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${N.jsonPos}++;` + ) +} + +function jsonSlice(len: number | Name): Code { + return len === 1 + ? _`${N.json}[${N.jsonPos}]` + : _`${N.json}.slice(${N.jsonPos}, ${N.jsonPos}+${len})` +} + +function jsonSyntaxError(cxt: ParseCxt): void { + parsingError(cxt, _`"unexpected token " + ${N.json}[${N.jsonPos}]`) +} + +function parsingError({gen, parseName}: ParseCxt, msg: Code): void { + gen.assign(_`${parseName}.message`, msg) + gen.assign(_`${parseName}.position`, N.jsonPos) + gen.return(undef) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/jtd/serialize.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/jtd/serialize.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d228826d4344cfb4e64f20f494ff9102b736d33 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/jtd/serialize.ts @@ -0,0 +1,266 @@ +import type Ajv from "../../core" +import type {SchemaObject} from "../../types" +import {jtdForms, JTDForm, SchemaObjectMap} from "./types" +import {SchemaEnv, getCompilingSchema} from ".." +import {_, str, and, getProperty, CodeGen, Code, Name} from "../codegen" +import MissingRefError from "../ref_error" +import N from "../names" +import {isOwnProperty} from "../../vocabularies/code" +import {hasRef} from "../../vocabularies/jtd/ref" +import {useFunc} from "../util" +import quote from "../../runtime/quote" + +const genSerialize: {[F in JTDForm]: (cxt: SerializeCxt) => void} = { + elements: serializeElements, + values: serializeValues, + discriminator: serializeDiscriminator, + properties: serializeProperties, + optionalProperties: serializeProperties, + enum: serializeString, + type: serializeType, + ref: serializeRef, +} + +interface SerializeCxt { + readonly gen: CodeGen + readonly self: Ajv // current Ajv instance + readonly schemaEnv: SchemaEnv + readonly definitions: SchemaObjectMap + schema: SchemaObject + data: Code +} + +export default function compileSerializer( + this: Ajv, + sch: SchemaEnv, + definitions: SchemaObjectMap +): SchemaEnv { + const _sch = getCompilingSchema.call(this, sch) + if (_sch) return _sch + const {es5, lines} = this.opts.code + const {ownProperties} = this.opts + const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) + const serializeName = gen.scopeName("serialize") + const cxt: SerializeCxt = { + self: this, + gen, + schema: sch.schema as SchemaObject, + schemaEnv: sch, + definitions, + data: N.data, + } + + let sourceCode: string | undefined + try { + this._compilations.add(sch) + sch.serializeName = serializeName + gen.func(serializeName, N.data, false, () => { + gen.let(N.json, str``) + serializeCode(cxt) + gen.return(N.json) + }) + gen.optimize(this.opts.code.optimize) + const serializeFuncCode = gen.toString() + sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` + const makeSerialize = new Function(`${N.scope}`, sourceCode) + const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) + this.scope.value(serializeName, {ref: serialize}) + sch.serialize = serialize + } catch (e) { + if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) + delete sch.serialize + delete sch.serializeName + throw e + } finally { + this._compilations.delete(sch) + } + return sch +} + +function serializeCode(cxt: SerializeCxt): void { + let form: JTDForm | undefined + for (const key of jtdForms) { + if (key in cxt.schema) { + form = key + break + } + } + serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty) +} + +function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void { + const {gen, schema, data} = cxt + if (!schema.nullable) return serializeForm(cxt) + gen.if( + _`${data} === undefined || ${data} === null`, + () => gen.add(N.json, _`"null"`), + () => serializeForm(cxt) + ) +} + +function serializeElements(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + gen.add(N.json, str`[`) + const first = gen.let("first", true) + gen.forOf("el", data, (el) => { + addComma(cxt, first) + serializeCode({...cxt, schema: schema.elements, data: el}) + }) + gen.add(N.json, str`]`) +} + +function serializeValues(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + gen.add(N.json, str`{`) + const first = gen.let("first", true) + gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)) + gen.add(N.json, str`}`) +} + +function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void { + const {gen, data} = cxt + addComma(cxt, first) + serializeString({...cxt, data: key}) + gen.add(N.json, str`:`) + const value = gen.const("value", _`${data}${getProperty(key)}`) + serializeCode({...cxt, schema, data: value}) +} + +function serializeDiscriminator(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + const {discriminator} = schema + gen.add(N.json, str`{${JSON.stringify(discriminator)}:`) + const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`) + serializeString({...cxt, data: tag}) + gen.if(false) + for (const tagValue in schema.mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + const sch = schema.mapping[tagValue] + serializeSchemaProperties({...cxt, schema: sch}, discriminator) + } + gen.endIf() + gen.add(N.json, str`}`) +} + +function serializeProperties(cxt: SerializeCxt): void { + const {gen} = cxt + gen.add(N.json, str`{`) + serializeSchemaProperties(cxt) + gen.add(N.json, str`}`) +} + +function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void { + const {gen, schema, data} = cxt + const {properties, optionalProperties} = schema + const props = keys(properties) + const optProps = keys(optionalProperties) + const allProps = allProperties(props.concat(optProps)) + let first = !discriminator + let firstProp: Name | undefined + + for (const key of props) { + if (first) first = false + else gen.add(N.json, str`,`) + serializeProperty(key, properties[key], keyValue(key)) + } + if (first) firstProp = gen.let("first", true) + for (const key of optProps) { + const value = keyValue(key) + gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () => { + addComma(cxt, firstProp) + serializeProperty(key, optionalProperties[key], value) + }) + } + if (schema.additionalProperties) { + gen.forIn("key", data, (key) => + gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)) + ) + } + + function keys(ps?: SchemaObjectMap): string[] { + return ps ? Object.keys(ps) : [] + } + + function allProperties(ps: string[]): string[] { + if (discriminator) ps.push(discriminator) + if (new Set(ps).size !== ps.length) { + throw new Error("JTD: properties/optionalProperties/disciminator overlap") + } + return ps + } + + function keyValue(key: string): Name { + return gen.const("value", _`${data}${getProperty(key)}`) + } + + function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void { + gen.add(N.json, str`${JSON.stringify(key)}:`) + serializeCode({...cxt, schema: propSchema, data: value}) + } + + function isAdditional(key: Name, ps: string[]): Code | true { + return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true + } +} + +function serializeType(cxt: SerializeCxt): void { + const {gen, schema, data} = cxt + switch (schema.type) { + case "boolean": + gen.add(N.json, _`${data} ? "true" : "false"`) + break + case "string": + serializeString(cxt) + break + case "timestamp": + gen.if( + _`${data} instanceof Date`, + () => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`), + () => serializeString(cxt) + ) + break + default: + serializeNumber(cxt) + } +} + +function serializeString({gen, data}: SerializeCxt): void { + gen.add(N.json, _`${useFunc(gen, quote)}(${data})`) +} + +function serializeNumber({gen, data}: SerializeCxt): void { + gen.add(N.json, _`"" + ${data}`) +} + +function serializeRef(cxt: SerializeCxt): void { + const {gen, self, data, definitions, schema, schemaEnv} = cxt + const {ref} = schema + const refSchema = definitions[ref] + if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) + if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema}) + const {root} = schemaEnv + const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions) + gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`) +} + +function getSerialize(gen: CodeGen, sch: SchemaEnv): Code { + return sch.serialize + ? gen.scopeValue("serialize", {ref: sch.serialize}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize` +} + +function serializeEmpty({gen, data}: SerializeCxt): void { + gen.add(N.json, _`JSON.stringify(${data})`) +} + +function addComma({gen}: SerializeCxt, first?: Name): void { + if (first) { + gen.if( + first, + () => gen.assign(first, false), + () => gen.add(N.json, str`,`) + ) + } else { + gen.add(N.json, str`,`) + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/jtd/types.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/jtd/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..1258050fdf426a085097c3858c513b95447ded94 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/jtd/types.ts @@ -0,0 +1,16 @@ +import type {SchemaObject} from "../../types" + +export type SchemaObjectMap = {[Ref in string]?: SchemaObject} + +export const jtdForms = [ + "elements", + "values", + "discriminator", + "properties", + "optionalProperties", + "enum", + "type", + "ref", +] as const + +export type JTDForm = (typeof jtdForms)[number] diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/names.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/names.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4b242e175f08c9705f80e0daaec11ab6662e06a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/names.ts @@ -0,0 +1,27 @@ +import {Name} from "./codegen" + +const names = { + // validation function arguments + data: new Name("data"), // data passed to validation function + // args passed from referencing schema + valCxt: new Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new Name("instancePath"), + parentData: new Name("parentData"), + parentDataProperty: new Name("parentDataProperty"), + rootData: new Name("rootData"), // root data - same as the data passed to the first/top validation function + dynamicAnchors: new Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new Name("vErrors"), // null or array of validation errors + errors: new Name("errors"), // counter of validation errors + this: new Name("this"), + // "globals" + self: new Name("self"), + scope: new Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new Name("json"), + jsonPos: new Name("jsonPos"), + jsonLen: new Name("jsonLen"), + jsonPart: new Name("jsonPart"), +} + +export default names diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/ref_error.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/ref_error.ts new file mode 100644 index 0000000000000000000000000000000000000000..386bf04995827ca2e6653fee7d4095049a753955 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/ref_error.ts @@ -0,0 +1,13 @@ +import {resolveUrl, normalizeId, getFullPath} from "./resolve" +import type {UriResolver} from "../types" + +export default class MissingRefError extends Error { + readonly missingRef: string + readonly missingSchema: string + + constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`) + this.missingRef = resolveUrl(resolver, baseId, ref) + this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef)) + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/resolve.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/resolve.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8c4aca394a7a3f46f7977c2e66a7ab570213e80 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/resolve.ts @@ -0,0 +1,149 @@ +import type {AnySchema, AnySchemaObject, UriResolver} from "../types" +import type Ajv from "../ajv" +import type {URIComponent} from "fast-uri" +import {eachItem} from "./util" +import * as equal from "fast-deep-equal" +import * as traverse from "json-schema-traverse" + +// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution +export type LocalRefs = {[Ref in string]?: AnySchemaObject} + +// TODO refactor to use keyword definitions +const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const", +]) + +export function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean { + if (typeof schema == "boolean") return true + if (limit === true) return !hasRef(schema) + if (!limit) return false + return countKeys(schema) <= limit +} + +const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor", +]) + +function hasRef(schema: AnySchemaObject): boolean { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true + const sch = schema[key] + if (Array.isArray(sch) && sch.some(hasRef)) return true + if (typeof sch == "object" && hasRef(sch)) return true + } + return false +} + +function countKeys(schema: AnySchemaObject): number { + let count = 0 + for (const key in schema) { + if (key === "$ref") return Infinity + count++ + if (SIMPLE_INLINED.has(key)) continue + if (typeof schema[key] == "object") { + eachItem(schema[key], (sch) => (count += countKeys(sch))) + } + if (count === Infinity) return Infinity + } + return count +} + +export function getFullPath(resolver: UriResolver, id = "", normalize?: boolean): string { + if (normalize !== false) id = normalizeId(id) + const p = resolver.parse(id) + return _getFullPath(resolver, p) +} + +export function _getFullPath(resolver: UriResolver, p: URIComponent): string { + const serialized = resolver.serialize(p) + return serialized.split("#")[0] + "#" +} + +const TRAILING_SLASH_HASH = /#\/?$/ +export function normalizeId(id: string | undefined): string { + return id ? id.replace(TRAILING_SLASH_HASH, "") : "" +} + +export function resolveUrl(resolver: UriResolver, baseId: string, id: string): string { + id = normalizeId(id) + return resolver.resolve(baseId, id) +} + +const ANCHOR = /^[a-z_][-a-z0-9._]*$/i + +export function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs { + if (typeof schema == "boolean") return {} + const {schemaId, uriResolver} = this.opts + const schId = normalizeId(schema[schemaId] || baseId) + const baseIds: {[JsonPtr in string]?: string} = {"": schId} + const pathPrefix = getFullPath(uriResolver, schId, false) + const localRefs: LocalRefs = {} + const schemaRefs: Set = new Set() + + traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === undefined) return + const fullPath = pathPrefix + jsonPtr + let innerBaseId = baseIds[parentJsonPtr] + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]) + addAnchor.call(this, sch.$anchor) + addAnchor.call(this, sch.$dynamicAnchor) + baseIds[jsonPtr] = innerBaseId + + function addRef(this: Ajv, ref: string): string { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _resolve = this.opts.uriResolver.resolve + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref) + if (schemaRefs.has(ref)) throw ambiguos(ref) + schemaRefs.add(ref) + let schOrRef = this.refs[ref] + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef] + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref) + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref) + localRefs[ref] = sch + } else { + this.refs[ref] = fullPath + } + } + return ref + } + + function addAnchor(this: Ajv, anchor: unknown): void { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`) + addRef.call(this, `#${anchor}`) + } + } + }) + + return localRefs + + function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void { + if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref) + } + + function ambiguos(ref: string): Error { + return new Error(`reference "${ref}" resolves to more than one schema`) + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/rules.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/rules.ts new file mode 100644 index 0000000000000000000000000000000000000000..7dbf7ab9e08317ff4e893317d07962bb6df43327 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/rules.ts @@ -0,0 +1,50 @@ +import type {AddedKeywordDefinition} from "../types" + +const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"] as const + +export type JSONType = (typeof _jsonTypes)[number] + +const jsonTypes: Set = new Set(_jsonTypes) + +export function isJSONType(x: unknown): x is JSONType { + return typeof x == "string" && jsonTypes.has(x) +} + +type ValidationTypes = { + [K in JSONType]: boolean | RuleGroup | undefined +} + +export interface ValidationRules { + rules: RuleGroup[] + post: RuleGroup + all: {[Key in string]?: boolean | Rule} // rules that have to be validated + keywords: {[Key in string]?: boolean} // all known keywords (superset of "all") + types: ValidationTypes +} + +export interface RuleGroup { + type?: JSONType + rules: Rule[] +} + +// This interface wraps KeywordDefinition because definition can have multiple keywords +export interface Rule { + keyword: string + definition: AddedKeywordDefinition +} + +export function getRules(): ValidationRules { + const groups: Record<"number" | "string" | "array" | "object", RuleGroup> = { + number: {type: "number", rules: []}, + string: {type: "string", rules: []}, + array: {type: "array", rules: []}, + object: {type: "object", rules: []}, + } + return { + types: {...groups, integer: true, boolean: true, null: true}, + rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object], + post: {rules: []}, + all: {}, + keywords: {}, + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/util.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/util.ts new file mode 100644 index 0000000000000000000000000000000000000000..cefae51c2bfcc01fed2b40bcbe3425c9d1c53d18 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/util.ts @@ -0,0 +1,213 @@ +import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types" +import type {SchemaCxt, SchemaObjCxt} from "." +import {_, getProperty, Code, Name, CodeGen} from "./codegen" +import {_Code} from "./codegen/code" +import type {Rule, ValidationRules} from "./rules" + +// TODO refactor to use Set +export function toHash(arr: T[]): {[K in T]?: true} { + const hash: {[K in T]?: true} = {} + for (const item of arr) hash[item] = true + return hash +} + +export function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void { + if (typeof schema == "boolean") return schema + if (Object.keys(schema).length === 0) return true + checkUnknownRules(it, schema) + return !schemaHasRules(schema, it.self.RULES.all) +} + +export function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void { + const {opts, self} = it + if (!opts.strictSchema) return + if (typeof schema === "boolean") return + const rules = self.RULES.keywords + for (const key in schema) { + if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`) + } +} + +export function schemaHasRules( + schema: AnySchema, + rules: {[Key in string]?: boolean | Rule} +): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (rules[key]) return true + return false +} + +export function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true + return false +} + +export function schemaRefOrVal( + {topSchemaRef, schemaPath}: SchemaObjCxt, + schema: unknown, + keyword: string, + $data?: string | false +): Code | number | boolean { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema + if (typeof schema == "string") return _`${schema}` + } + return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}` +} + +export function unescapeFragment(str: string): string { + return unescapeJsonPointer(decodeURIComponent(str)) +} + +export function escapeFragment(str: string | number): string { + return encodeURIComponent(escapeJsonPointer(str)) +} + +export function escapeJsonPointer(str: string | number): string { + if (typeof str == "number") return `${str}` + return str.replace(/~/g, "~0").replace(/\//g, "~1") +} + +export function unescapeJsonPointer(str: string): string { + return str.replace(/~1/g, "/").replace(/~0/g, "~") +} + +export function eachItem(xs: T | T[], f: (x: T) => void): void { + if (Array.isArray(xs)) { + for (const x of xs) f(x) + } else { + f(xs) + } +} + +type SomeEvaluated = EvaluatedProperties | EvaluatedItems + +type MergeEvaluatedFunc = ( + gen: CodeGen, + from: Name | T, + to: Name | Exclude | undefined, + toName?: typeof Name +) => Name | T + +interface MakeMergeFuncArgs { + mergeNames: (gen: CodeGen, from: Name, to: Name) => void + mergeToName: (gen: CodeGen, from: T, to: Name) => void + mergeValues: (from: T, to: Exclude) => T + resultToName: (gen: CodeGen, res?: T) => Name +} + +function makeMergeEvaluated({ + mergeNames, + mergeToName, + mergeValues, + resultToName, +}: MakeMergeFuncArgs): MergeEvaluatedFunc { + return (gen, from, to, toName) => { + const res = + to === undefined + ? from + : to instanceof Name + ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) + : from instanceof Name + ? (mergeToName(gen, to, from), from) + : mergeValues(from, to) + return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res + } +} + +interface MergeEvaluated { + props: MergeEvaluatedFunc + items: MergeEvaluatedFunc +} + +export const mergeEvaluated: MergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => + gen.if(_`${to} !== true && ${from} !== undefined`, () => { + gen.if( + _`${from} === true`, + () => gen.assign(to, true), + () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`) + ) + }), + mergeToName: (gen, from, to) => + gen.if(_`${to} !== true`, () => { + if (from === true) { + gen.assign(to, true) + } else { + gen.assign(to, _`${to} || {}`) + setEvaluated(gen, to, from) + } + }), + mergeValues: (from, to) => (from === true ? true : {...from, ...to}), + resultToName: evaluatedPropsToName, + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => + gen.if(_`${to} !== true && ${from} !== undefined`, () => + gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`) + ), + mergeToName: (gen, from, to) => + gen.if(_`${to} !== true`, () => + gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`) + ), + mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), + resultToName: (gen, items) => gen.var("items", items), + }), +} + +export function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name { + if (ps === true) return gen.var("props", true) + const props = gen.var("props", _`{}`) + if (ps !== undefined) setEvaluated(gen, props, ps) + return props +} + +export function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void { + Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true)) +} + +const snippets: {[S in string]?: _Code} = {} + +export function useFunc(gen: CodeGen, f: {code: string}): Name { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)), + }) +} + +export enum Type { + Num, + Str, +} + +export function getErrorPath( + dataProp: Name | string | number, + dataPropType?: Type, + jsPropertySyntax?: boolean +): Code | string { + // let path + if (dataProp instanceof Name) { + const isNumber = dataPropType === Type.Num + return jsPropertySyntax + ? isNumber + ? _`"[" + ${dataProp} + "]"` + : _`"['" + ${dataProp} + "']"` + : isNumber + ? _`"/" + ${dataProp}` + : _`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")` // TODO maybe use global escapePointer + } + return jsPropertySyntax ? getProperty(dataProp).toString() : "/" + escapeJsonPointer(dataProp) +} + +export function checkStrictMode( + it: SchemaCxt, + msg: string, + mode: boolean | "log" = it.opts.strictSchema +): void { + if (!mode) return + msg = `strict mode: ${msg}` + if (mode === true) throw new Error(msg) + it.self.logger.warn(msg) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/applicability.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/applicability.ts new file mode 100644 index 0000000000000000000000000000000000000000..478b704ac571d7b34deb19ef84aa0e2dd08973e3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/applicability.ts @@ -0,0 +1,22 @@ +import type {AnySchemaObject} from "../../types" +import type {SchemaObjCxt} from ".." +import type {JSONType, RuleGroup, Rule} from "../rules" + +export function schemaHasRulesForType( + {schema, self}: SchemaObjCxt, + type: JSONType +): boolean | undefined { + const group = self.RULES.types[type] + return group && group !== true && shouldUseGroup(schema, group) +} + +export function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean { + return group.rules.some((rule) => shouldUseRule(schema, rule)) +} + +export function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined { + return ( + schema[rule.keyword] !== undefined || + rule.definition.implements?.some((kwd) => schema[kwd] !== undefined) + ) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/boolSchema.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/boolSchema.ts new file mode 100644 index 0000000000000000000000000000000000000000..156355016d62249d16c6dc19a89c28b5ff6972c7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/boolSchema.ts @@ -0,0 +1,47 @@ +import type {KeywordErrorDefinition, KeywordErrorCxt} from "../../types" +import type {SchemaCxt} from ".." +import {reportError} from "../errors" +import {_, Name} from "../codegen" +import N from "../names" + +const boolError: KeywordErrorDefinition = { + message: "boolean schema is false", +} + +export function topBoolOrEmptySchema(it: SchemaCxt): void { + const {gen, schema, validateName} = it + if (schema === false) { + falseSchemaError(it, false) + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(N.data) + } else { + gen.assign(_`${validateName}.errors`, null) + gen.return(true) + } +} + +export function boolOrEmptySchema(it: SchemaCxt, valid: Name): void { + const {gen, schema} = it + if (schema === false) { + gen.var(valid, false) // TODO var + falseSchemaError(it) + } else { + gen.var(valid, true) // TODO var + } +} + +function falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void { + const {gen, data} = it + // TODO maybe some other interface should be used for non-keyword validation errors... + const cxt: KeywordErrorCxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it, + } + reportError(cxt, boolError, undefined, overrideAllErrors) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/dataType.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/dataType.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8142b3e1f55194a06de0ab489ee01e00136df25 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/dataType.ts @@ -0,0 +1,230 @@ +import type { + KeywordErrorDefinition, + KeywordErrorCxt, + ErrorObject, + AnySchemaObject, +} from "../../types" +import type {SchemaObjCxt} from ".." +import {isJSONType, JSONType} from "../rules" +import {schemaHasRulesForType} from "./applicability" +import {reportError} from "../errors" +import {_, nil, and, not, operators, Code, Name} from "../codegen" +import {toHash, schemaRefOrVal} from "../util" + +export enum DataType { + Correct, + Wrong, +} + +export function getSchemaTypes(schema: AnySchemaObject): JSONType[] { + const types = getJSONTypes(schema.type) + const hasNull = types.includes("null") + if (hasNull) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false") + } else { + if (!types.length && schema.nullable !== undefined) { + throw new Error('"nullable" cannot be used without "type"') + } + if (schema.nullable === true) types.push("null") + } + return types +} + +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents +export function getJSONTypes(ts: unknown | unknown[]): JSONType[] { + const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : [] + if (types.every(isJSONType)) return types + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")) +} + +export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean { + const {gen, data, opts} = it + const coerceTo = coerceToTypes(types, opts.coerceTypes) + const checkTypes = + types.length > 0 && + !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0])) + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong) + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo) + else reportTypeError(it) + }) + } + return checkTypes +} + +const COERCIBLE: Set = new Set(["string", "number", "integer", "boolean", "null"]) +function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] { + return coerceTypes + ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) + : [] +} + +function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void { + const {gen, data, opts} = it + const dataType = gen.let("dataType", _`typeof ${data}`) + const coerced = gen.let("coerced", _`undefined`) + if (opts.coerceTypes === "array") { + gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => + gen + .assign(data, _`${data}[0]`) + .assign(dataType, _`typeof ${data}`) + .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)) + ) + } + gen.if(_`${coerced} !== undefined`) + for (const t of coerceTo) { + if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { + coerceSpecificType(t) + } + } + gen.else() + reportTypeError(it) + gen.endIf() + + gen.if(_`${coerced} !== undefined`, () => { + gen.assign(data, coerced) + assignParentData(it, coerced) + }) + + function coerceSpecificType(t: string): void { + switch (t) { + case "string": + gen + .elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`) + .assign(coerced, _`"" + ${data}`) + .elseIf(_`${data} === null`) + .assign(coerced, _`""`) + return + case "number": + gen + .elseIf( + _`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})` + ) + .assign(coerced, _`+${data}`) + return + case "integer": + gen + .elseIf( + _`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))` + ) + .assign(coerced, _`+${data}`) + return + case "boolean": + gen + .elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`) + .assign(coerced, false) + .elseIf(_`${data} === "true" || ${data} === 1`) + .assign(coerced, true) + return + case "null": + gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`) + gen.assign(coerced, null) + return + + case "array": + gen + .elseIf( + _`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null` + ) + .assign(coerced, _`[${data}]`) + } + } +} + +function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void { + // TODO use gen.property + gen.if(_`${parentData} !== undefined`, () => + gen.assign(_`${parentData}[${parentDataProperty}]`, expr) + ) +} + +export function checkDataType( + dataType: JSONType, + data: Name, + strictNums?: boolean | "log", + correct = DataType.Correct +): Code { + const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ + let cond: Code + switch (dataType) { + case "null": + return _`${data} ${EQ} null` + case "array": + cond = _`Array.isArray(${data})` + break + case "object": + cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})` + break + case "integer": + cond = numCond(_`!(${data} % 1) && !isNaN(${data})`) + break + case "number": + cond = numCond() + break + default: + return _`typeof ${data} ${EQ} ${dataType}` + } + return correct === DataType.Correct ? cond : not(cond) + + function numCond(_cond: Code = nil): Code { + return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil) + } +} + +export function checkDataTypes( + dataTypes: JSONType[], + data: Name, + strictNums?: boolean | "log", + correct?: DataType +): Code { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct) + } + let cond: Code + const types = toHash(dataTypes) + if (types.array && types.object) { + const notObj = _`typeof ${data} != "object"` + cond = types.null ? notObj : _`!${data} || ${notObj}` + delete types.null + delete types.array + delete types.object + } else { + cond = nil + } + if (types.number) delete types.integer + for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct)) + return cond +} + +export type TypeError = ErrorObject<"type", {type: string}> + +const typeError: KeywordErrorDefinition = { + message: ({schema}) => `must be ${schema}`, + params: ({schema, schemaValue}) => + typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`, +} + +export function reportTypeError(it: SchemaObjCxt): void { + const cxt = getTypeErrorContext(it) + reportError(cxt, typeError) +} + +function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt { + const {gen, data, schema} = it + const schemaCode = schemaRefOrVal(it, schema, "type") + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it, + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/defaults.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/defaults.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ad3d4df8291bdfd7aec74833bec4b0b4c91f36f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/defaults.ts @@ -0,0 +1,32 @@ +import type {SchemaObjCxt} from ".." +import {_, getProperty, stringify} from "../codegen" +import {checkStrictMode} from "../util" + +export function assignDefaults(it: SchemaObjCxt, ty?: string): void { + const {properties, items} = it.schema + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default) + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i: number) => assignDefault(it, i, sch.default)) + } +} + +function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void { + const {gen, compositeRule, data, opts} = it + if (defaultValue === undefined) return + const childData = _`${data}${getProperty(prop)}` + if (compositeRule) { + checkStrictMode(it, `default is ignored for: ${childData}`) + return + } + + let condition = _`${childData} === undefined` + if (opts.useDefaults === "empty") { + condition = _`${condition} || ${childData} === null || ${childData} === ""` + } + // `${childData} === undefined` + + // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "") + gen.if(condition, _`${childData} = ${stringify(defaultValue)}`) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..15ecabd85169e3f19b56b7547982643383068552 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/index.ts @@ -0,0 +1,582 @@ +import type { + AddedKeywordDefinition, + AnySchema, + AnySchemaObject, + KeywordErrorCxt, + KeywordCxtParams, +} from "../../types" +import type {SchemaCxt, SchemaObjCxt} from ".." +import type {InstanceOptions} from "../../core" +import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema" +import {coerceAndCheckDataType, getSchemaTypes} from "./dataType" +import {shouldUseGroup, shouldUseRule} from "./applicability" +import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType" +import {assignDefaults} from "./defaults" +import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword" +import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema" +import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen" +import N from "../names" +import {resolveUrl} from "../resolve" +import { + schemaRefOrVal, + schemaHasRulesButRef, + checkUnknownRules, + checkStrictMode, + unescapeJsonPointer, + mergeEvaluated, +} from "../util" +import type {JSONType, Rule, RuleGroup} from "../rules" +import { + ErrorPaths, + reportError, + reportExtraError, + resetErrorsCount, + keyword$DataError, +} from "../errors" + +// schema compilation - generates validation function, subschemaCode (below) is used for subschemas +export function validateFunctionCode(it: SchemaCxt): void { + if (isSchemaObj(it)) { + checkKeywords(it) + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it) + return + } + } + validateFunction(it, () => topBoolOrEmptySchema(it)) +} + +function validateFunction( + {gen, validateName, schema, schemaEnv, opts}: SchemaCxt, + body: Block +): void { + if (opts.code.es5) { + gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => { + gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`) + destructureValCxtES5(gen, opts) + gen.code(body) + }) + } else { + gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => + gen.code(funcSourceUrl(schema, opts)).code(body) + ) + } +} + +function destructureValCxt(opts: InstanceOptions): Code { + return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${ + N.data + }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}` +} + +function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void { + gen.if( + N.valCxt, + () => { + gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`) + gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`) + gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`) + gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`) + if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`) + }, + () => { + gen.var(N.instancePath, _`""`) + gen.var(N.parentData, _`undefined`) + gen.var(N.parentDataProperty, _`undefined`) + gen.var(N.rootData, N.data) + if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`) + } + ) +} + +function topSchemaObjCode(it: SchemaObjCxt): void { + const {schema, opts, gen} = it + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it) + checkNoDefault(it) + gen.let(N.vErrors, null) + gen.let(N.errors, 0) + if (opts.unevaluated) resetEvaluated(it) + typeAndKeywords(it) + returnResults(it) + }) + return +} + +function resetEvaluated(it: SchemaObjCxt): void { + // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated + const {gen, validateName} = it + it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`) + gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`)) + gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`)) +} + +function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code { + const schId = typeof schema == "object" && schema[opts.schemaId] + return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil +} + +// schema compilation - this function is used recursively to generate code for sub-schemas +function subschemaCode(it: SchemaCxt, valid: Name): void { + if (isSchemaObj(it)) { + checkKeywords(it) + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid) + return + } + } + boolOrEmptySchema(it, valid) +} + +function schemaCxtHasRules({schema, self}: SchemaCxt): boolean { + if (typeof schema == "boolean") return !schema + for (const key in schema) if (self.RULES.all[key]) return true + return false +} + +function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt { + return typeof it.schema != "boolean" +} + +function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void { + const {schema, gen, opts} = it + if (opts.$comment && schema.$comment) commentKeyword(it) + updateContext(it) + checkAsyncSchema(it) + const errsCount = gen.const("_errs", N.errors) + typeAndKeywords(it, errsCount) + // TODO var + gen.var(valid, _`${errsCount} === ${N.errors}`) +} + +function checkKeywords(it: SchemaObjCxt): void { + checkUnknownRules(it) + checkRefsAndKeywords(it) +} + +function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount) + const types = getSchemaTypes(it.schema) + const checkedTypes = coerceAndCheckDataType(it, types) + schemaKeywords(it, types, !checkedTypes, errsCount) +} + +function checkRefsAndKeywords(it: SchemaObjCxt): void { + const {schema, errSchemaPath, opts, self} = it + if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) { + self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`) + } +} + +function checkNoDefault(it: SchemaObjCxt): void { + const {schema, opts} = it + if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { + checkStrictMode(it, "default is ignored in the schema root") + } +} + +function updateContext(it: SchemaObjCxt): void { + const schId = it.schema[it.opts.schemaId] + if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId) +} + +function checkAsyncSchema(it: SchemaObjCxt): void { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema") +} + +function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void { + const msg = schema.$comment + if (opts.$comment === true) { + gen.code(_`${N.self}.logger.log(${msg})`) + } else if (typeof opts.$comment == "function") { + const schemaPath = str`${errSchemaPath}/$comment` + const rootName = gen.scopeValue("root", {ref: schemaEnv.root}) + gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`) + } +} + +function returnResults(it: SchemaCxt): void { + const {gen, schemaEnv, validateName, ValidationError, opts} = it + if (schemaEnv.$async) { + // TODO assign unevaluated + gen.if( + _`${N.errors} === 0`, + () => gen.return(N.data), + () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`) + ) + } else { + gen.assign(_`${validateName}.errors`, N.vErrors) + if (opts.unevaluated) assignEvaluated(it) + gen.return(_`${N.errors} === 0`) + } +} + +function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void { + if (props instanceof Name) gen.assign(_`${evaluated}.props`, props) + if (items instanceof Name) gen.assign(_`${evaluated}.items`, items) +} + +function schemaKeywords( + it: SchemaObjCxt, + types: JSONType[], + typeErrors: boolean, + errsCount?: Name +): void { + const {gen, schema, data, allErrors, opts, self} = it + const {RULES} = self + if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast + return + } + if (!opts.jtd) checkStrictTypes(it, types) + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group) + groupKeywords(RULES.post) + }) + + function groupKeywords(group: RuleGroup): void { + if (!shouldUseGroup(schema, group)) return + if (group.type) { + gen.if(checkDataType(group.type, data, opts.strictNumbers)) + iterateKeywords(it, group) + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else() + reportTypeError(it) + } + gen.endIf() + } else { + iterateKeywords(it, group) + } + // TODO make it "ok" call? + if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`) + } +} + +function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void { + const { + gen, + schema, + opts: {useDefaults}, + } = it + if (useDefaults) assignDefaults(it, group.type) + gen.block(() => { + for (const rule of group.rules) { + if (shouldUseRule(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type) + } + } + }) +} + +function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void { + if (it.schemaEnv.meta || !it.opts.strictTypes) return + checkContextTypes(it, types) + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types) + checkKeywordTypes(it, it.dataTypes) +} + +function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void { + if (!types.length) return + if (!it.dataTypes.length) { + it.dataTypes = types + return + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`) + } + }) + narrowSchemaTypes(it, types) +} + +function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword") + } +} + +function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void { + const rules = it.self.RULES.all + for (const keyword in rules) { + const rule = rules[keyword] + if (typeof rule == "object" && shouldUseRule(it.schema, rule)) { + const {type} = rule.definition + if (type.length && !type.some((t) => hasApplicableType(ts, t))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`) + } + } + } +} + +function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean { + return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")) +} + +function includesType(ts: JSONType[], t: JSONType): boolean { + return ts.includes(t) || (t === "integer" && ts.includes("number")) +} + +function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void { + const ts: JSONType[] = [] + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) ts.push(t) + else if (withTypes.includes("integer") && t === "number") ts.push("integer") + } + it.dataTypes = ts +} + +function strictTypesError(it: SchemaObjCxt, msg: string): void { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath + msg += ` at "${schemaPath}" (strictTypes)` + checkStrictMode(it, msg, it.opts.strictTypes) +} + +export class KeywordCxt implements KeywordErrorCxt { + readonly gen: CodeGen + readonly allErrors?: boolean + readonly keyword: string + readonly data: Name // Name referencing the current level of the data instance + readonly $data?: string | false + schema: any // keyword value in the schema + readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value + readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) + readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema + readonly parentSchema: AnySchemaObject + readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, + // requires option trackErrors in keyword definition + params: KeywordCxtParams // object to pass parameters to error messages from keyword code + readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) + readonly def: AddedKeywordDefinition + + constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { + validateKeywordUsage(it, def, keyword) + this.gen = it.gen + this.allErrors = it.allErrors + this.keyword = keyword + this.data = it.data + this.schema = it.schema[keyword] + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data + this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) + this.schemaType = def.schemaType + this.parentSchema = it.schema + this.params = {} + this.it = it + this.def = def + + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) + } else { + this.schemaCode = this.schemaValue + if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) + } + } + + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", N.errors) + } + } + + result(condition: Code, successAction?: () => void, failAction?: () => void): void { + this.failResult(not(condition), successAction, failAction) + } + + failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { + this.gen.if(condition) + if (failAction) failAction() + else this.error() + if (successAction) { + this.gen.else() + successAction() + if (this.allErrors) this.gen.endIf() + } else { + if (this.allErrors) this.gen.endIf() + else this.gen.else() + } + } + + pass(condition: Code, failAction?: () => void): void { + this.failResult(not(condition), undefined, failAction) + } + + fail(condition?: Code): void { + if (condition === undefined) { + this.error() + if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize + return + } + this.gen.if(condition) + this.error() + if (this.allErrors) this.gen.endIf() + else this.gen.else() + } + + fail$data(condition: Code): void { + if (!this.$data) return this.fail(condition) + const {schemaCode} = this + this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) + } + + error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { + if (errorParams) { + this.setParams(errorParams) + this._error(append, errorPaths) + this.setParams({}) + return + } + this._error(append, errorPaths) + } + + private _error(append?: boolean, errorPaths?: ErrorPaths): void { + ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) + } + + $dataError(): void { + reportError(this, this.def.$dataError || keyword$DataError) + } + + reset(): void { + if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') + resetErrorsCount(this.gen, this.errsCount) + } + + ok(cond: Code | boolean): void { + if (!this.allErrors) this.gen.if(cond) + } + + setParams(obj: KeywordCxtParams, assign?: true): void { + if (assign) Object.assign(this.params, obj) + else this.params = obj + } + + block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { + this.gen.block(() => { + this.check$data(valid, $dataValid) + codeBlock() + }) + } + + check$data(valid: Name = nil, $dataValid: Code = nil): void { + if (!this.$data) return + const {gen, schemaCode, schemaType, def} = this + gen.if(or(_`${schemaCode} === undefined`, $dataValid)) + if (valid !== nil) gen.assign(valid, true) + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()) + this.$dataError() + if (valid !== nil) gen.assign(valid, false) + } + gen.else() + } + + invalid$data(): Code { + const {gen, schemaCode, schemaType, def, it} = this + return or(wrong$DataType(), invalid$DataSchema()) + + function wrong$DataType(): Code { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") + const st = Array.isArray(schemaType) ? schemaType : [schemaType] + return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` + } + return nil + } + + function invalid$DataSchema(): Code { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone + return _`!${validateSchemaRef}(${schemaCode})` + } + return nil + } + } + + subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { + const subschema = getSubschema(this.it, appl) + extendSubschemaData(subschema, this.it, appl) + extendSubschemaMode(subschema, appl) + const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} + subschemaCode(nextContext, valid) + return nextContext + } + + mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { + const {it, gen} = this + if (!it.opts.unevaluated) return + if (it.props !== true && schemaCxt.props !== undefined) { + it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) + } + if (it.items !== true && schemaCxt.items !== undefined) { + it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) + } + } + + mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { + const {it, gen} = this + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) + return true + } + } +} + +function keywordCode( + it: SchemaObjCxt, + keyword: string, + def: AddedKeywordDefinition, + ruleType?: JSONType +): void { + const cxt = new KeywordCxt(it, def, keyword) + if ("code" in def) { + def.code(cxt, ruleType) + } else if (cxt.$data && def.validate) { + funcKeywordCode(cxt, def) + } else if ("macro" in def) { + macroKeywordCode(cxt, def) + } else if (def.compile || def.validate) { + funcKeywordCode(cxt, def) + } +} + +const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/ +const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/ +export function getData( + $data: string, + {dataLevel, dataNames, dataPathArr}: SchemaCxt +): Code | number { + let jsonPointer + let data: Code + if ($data === "") return N.rootData + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`) + jsonPointer = $data + data = N.rootData + } else { + const matches = RELATIVE_JSON_POINTER.exec($data) + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`) + const up: number = +matches[1] + jsonPointer = matches[2] + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)) + return dataPathArr[dataLevel - up] + } + if (up > dataLevel) throw new Error(errorMsg("data", up)) + data = dataNames[dataLevel - up] + if (!jsonPointer) return data + } + + let expr = data + const segments = jsonPointer.split("/") + for (const segment of segments) { + if (segment) { + data = _`${data}${getProperty(unescapeJsonPointer(segment))}` + expr = _`${expr} && ${data}` + } + } + return expr + + function errorMsg(pointerType: string, up: number): string { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}` + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/keyword.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/keyword.ts new file mode 100644 index 0000000000000000000000000000000000000000..f854aa71083ca28c01f8064fdca177a847e6f308 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/keyword.ts @@ -0,0 +1,171 @@ +import type {KeywordCxt} from "." +import type { + AnySchema, + SchemaValidateFunction, + AnyValidateFunction, + AddedKeywordDefinition, + MacroKeywordDefinition, + FuncKeywordDefinition, +} from "../../types" +import type {SchemaObjCxt} from ".." +import {_, nil, not, stringify, Code, Name, CodeGen} from "../codegen" +import N from "../names" +import type {JSONType} from "../rules" +import {callValidateCode} from "../../vocabularies/code" +import {extendErrors} from "../errors" + +type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction + +export function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void { + const {gen, keyword, schema, parentSchema, it} = cxt + const macroSchema = def.macro.call(it.self, schema, parentSchema, it) + const schemaRef = useKeyword(gen, keyword, macroSchema) + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true) + + const valid = gen.name("valid") + cxt.subschema( + { + schema: macroSchema, + schemaPath: nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true, + }, + valid + ) + cxt.pass(valid, () => cxt.error(true)) +} + +export function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void { + const {gen, keyword, schema, parentSchema, $data, it} = cxt + checkAsyncKeyword(it, def) + const validate = + !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate + const validateRef = useKeyword(gen, keyword, validate) + const valid = gen.let("valid") + cxt.block$data(valid, validateKeyword) + cxt.ok(def.valid ?? valid) + + function validateKeyword(): void { + if (def.errors === false) { + assignValid() + if (def.modifying) modifyData(cxt) + reportErrs(() => cxt.error()) + } else { + const ruleErrs = def.async ? validateAsync() : validateSync() + if (def.modifying) modifyData(cxt) + reportErrs(() => addErrs(cxt, ruleErrs)) + } + } + + function validateAsync(): Name { + const ruleErrs = gen.let("ruleErrs", null) + gen.try( + () => assignValid(_`await `), + (e) => + gen.assign(valid, false).if( + _`${e} instanceof ${it.ValidationError as Name}`, + () => gen.assign(ruleErrs, _`${e}.errors`), + () => gen.throw(e) + ) + ) + return ruleErrs + } + + function validateSync(): Code { + const validateErrs = _`${validateRef}.errors` + gen.assign(validateErrs, null) + assignValid(nil) + return validateErrs + } + + function assignValid(_await: Code = def.async ? _`await ` : nil): void { + const passCxt = it.opts.passContext ? N.this : N.self + const passSchema = !(("compile" in def && !$data) || def.schema === false) + gen.assign( + valid, + _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`, + def.modifying + ) + } + + function reportErrs(errors: () => void): void { + gen.if(not(def.valid ?? valid), errors) + } +} + +function modifyData(cxt: KeywordCxt): void { + const {gen, data, it} = cxt + gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`)) +} + +function addErrs(cxt: KeywordCxt, errs: Code): void { + const {gen} = cxt + gen.if( + _`Array.isArray(${errs})`, + () => { + gen + .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) + .assign(N.errors, _`${N.vErrors}.length`) + extendErrors(cxt) + }, + () => cxt.error() + ) +} + +function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema") +} + +function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name { + if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`) + return gen.scopeValue( + "keyword", + typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)} + ) +} + +export function validSchemaType( + schema: unknown, + schemaType: JSONType[], + allowUndefined = false +): boolean { + // TODO add tests + return ( + !schemaType.length || + schemaType.some((st) => + st === "array" + ? Array.isArray(schema) + : st === "object" + ? schema && typeof schema == "object" && !Array.isArray(schema) + : typeof schema == st || (allowUndefined && typeof schema == "undefined") + ) + ) +} + +export function validateKeywordUsage( + {schema, opts, self, errSchemaPath}: SchemaObjCxt, + def: AddedKeywordDefinition, + keyword: string +): void { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error") + } + + const deps = def.dependencies + if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`) + } + + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]) + if (!valid) { + const msg = + `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + + self.errorsText(def.validateSchema.errors) + if (opts.validateSchema === "log") self.logger.error(msg) + else throw new Error(msg) + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/subschema.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/subschema.ts new file mode 100644 index 0000000000000000000000000000000000000000..9072ed7743decf23950a40033cb2c2f6ec1845e4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/compile/validate/subschema.ts @@ -0,0 +1,135 @@ +import type {AnySchema} from "../../types" +import type {SchemaObjCxt} from ".." +import {_, str, getProperty, Code, Name} from "../codegen" +import {escapeFragment, getErrorPath, Type} from "../util" +import type {JSONType} from "../rules" + +export interface SubschemaContext { + // TODO use Optional? align with SchemCxt property types + schema: AnySchema + schemaPath: Code + errSchemaPath: string + topSchemaRef?: Code + errorPath?: Code + dataLevel?: number + dataTypes?: JSONType[] + data?: Name + parentData?: Name + parentDataProperty?: Code | number + dataNames?: Name[] + dataPathArr?: (Code | number)[] + propertyName?: Name + jtdDiscriminator?: string + jtdMetadata?: boolean + compositeRule?: true + createErrors?: boolean + allErrors?: boolean +} + +export type SubschemaArgs = Partial<{ + keyword: string + schemaProp: string | number + schema: AnySchema + schemaPath: Code + errSchemaPath: string + topSchemaRef: Code + data: Name | Code + dataProp: Code | string | number + dataTypes: JSONType[] + definedProperties: Set + propertyName: Name + dataPropType: Type + jtdDiscriminator: string + jtdMetadata: boolean + compositeRule: true + createErrors: boolean + allErrors: boolean +}> + +export function getSubschema( + it: SchemaObjCxt, + {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs +): SubschemaContext { + if (keyword !== undefined && schema !== undefined) { + throw new Error('both "keyword" and "schema" passed, only one allowed') + } + + if (keyword !== undefined) { + const sch = it.schema[keyword] + return schemaProp === undefined + ? { + schema: sch, + schemaPath: _`${it.schemaPath}${getProperty(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + } + : { + schema: sch[schemaProp], + schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`, + } + } + + if (schema !== undefined) { + if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"') + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath, + } + } + + throw new Error('either "keyword" or "schema" must be passed') +} + +export function extendSubschemaData( + subschema: SubschemaContext, + it: SchemaObjCxt, + {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs +): void { + if (data !== undefined && dataProp !== undefined) { + throw new Error('both "data" and "dataProp" passed, only one allowed') + } + + const {gen} = it + + if (dataProp !== undefined) { + const {errorPath, dataPathArr, opts} = it + const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true) + dataContextProps(nextData) + subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}` + subschema.parentDataProperty = _`${dataProp}` + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty] + } + + if (data !== undefined) { + const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once? + dataContextProps(nextData) + if (propertyName !== undefined) subschema.propertyName = propertyName + // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr + } + + if (dataTypes) subschema.dataTypes = dataTypes + + function dataContextProps(_nextData: Name): void { + subschema.data = _nextData + subschema.dataLevel = it.dataLevel + 1 + subschema.dataTypes = [] + it.definedProperties = new Set() + subschema.parentData = it.data + subschema.dataNames = [...it.dataNames, _nextData] + } +} + +export function extendSubschemaMode( + subschema: SubschemaContext, + {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs +): void { + if (compositeRule !== undefined) subschema.compositeRule = compositeRule + if (createErrors !== undefined) subschema.createErrors = createErrors + if (allErrors !== undefined) subschema.allErrors = allErrors + subschema.jtdDiscriminator = jtdDiscriminator // not inherited + subschema.jtdMetadata = jtdMetadata // not inherited +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/data.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/data.json new file mode 100644 index 0000000000000000000000000000000000000000..9ffc9f5ce05484799308bc4c78fd3a8822e9af53 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/data.json @@ -0,0 +1,13 @@ +{ + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", + "type": "object", + "required": ["$data"], + "properties": { + "$data": { + "type": "string", + "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}] + } + }, + "additionalProperties": false +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6ea7195f019ef1b91c45517db08f42daa2f0673 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts @@ -0,0 +1,28 @@ +import type Ajv from "../../core" +import type {AnySchemaObject} from "../../types" +import * as metaSchema from "./schema.json" +import * as applicator from "./meta/applicator.json" +import * as content from "./meta/content.json" +import * as core from "./meta/core.json" +import * as format from "./meta/format.json" +import * as metadata from "./meta/meta-data.json" +import * as validation from "./meta/validation.json" + +const META_SUPPORT_DATA = ["/properties"] + +export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv { + ;[ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) + return this + + function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json new file mode 100644 index 0000000000000000000000000000000000000000..c5e91cf2ac8469eccf444cf6501dba80dccb5c63 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/applicator.json @@ -0,0 +1,53 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/applicator": true + }, + "$recursiveAnchor": true, + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": {"$recursiveRef": "#"}, + "unevaluatedItems": {"$recursiveRef": "#"}, + "items": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}] + }, + "contains": {"$recursiveRef": "#"}, + "additionalProperties": {"$recursiveRef": "#"}, + "unevaluatedProperties": {"$recursiveRef": "#"}, + "properties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { + "$recursiveRef": "#" + } + }, + "propertyNames": {"$recursiveRef": "#"}, + "if": {"$recursiveRef": "#"}, + "then": {"$recursiveRef": "#"}, + "else": {"$recursiveRef": "#"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$recursiveRef": "#"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$recursiveRef": "#"} + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json new file mode 100644 index 0000000000000000000000000000000000000000..b8f63734343046b3d4b74bf8a59f2380dbc67fc3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "contentSchema": {"$recursiveRef": "#"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json new file mode 100644 index 0000000000000000000000000000000000000000..f71adbff04fe9ecc6a828823ad5dfa7366f1a60f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/core.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true + }, + "$recursiveAnchor": true, + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json new file mode 100644 index 0000000000000000000000000000000000000000..03ccfce26efeaff5a6e223be5154f238f633c16e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/format.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/format": true + }, + "$recursiveAnchor": true, + + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json new file mode 100644 index 0000000000000000000000000000000000000000..0e194326fa133b077af409486ebe1e2dca83feff --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/meta-data": true + }, + "$recursiveAnchor": true, + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..7027a1279a014a74c170a2558100d2ca37eecac0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/validation": true + }, + "$recursiveAnchor": true, + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..54eb7157afed6957bd7074068d7ad99498c668f3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2019-09/schema.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": {"$recursiveRef": "#"}, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { + "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}] + } + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e850d08b5cdc8ec9f41ff69581c11844c9c60af --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/index.ts @@ -0,0 +1,30 @@ +import type Ajv from "../../core" +import type {AnySchemaObject} from "../../types" +import * as metaSchema from "./schema.json" +import * as applicator from "./meta/applicator.json" +import * as unevaluated from "./meta/unevaluated.json" +import * as content from "./meta/content.json" +import * as core from "./meta/core.json" +import * as format from "./meta/format-annotation.json" +import * as metadata from "./meta/meta-data.json" +import * as validation from "./meta/validation.json" + +const META_SUPPORT_DATA = ["/properties"] + +export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv { + ;[ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation), + ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) + return this + + function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json new file mode 100644 index 0000000000000000000000000000000000000000..674c913dab00c66865d82027bdf7748e157365fa --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/applicator.json @@ -0,0 +1,48 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/applicator": true + }, + "$dynamicAnchor": "meta", + + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": {"$ref": "#/$defs/schemaArray"}, + "items": {"$dynamicRef": "#meta"}, + "contains": {"$dynamicRef": "#meta"}, + "additionalProperties": {"$dynamicRef": "#meta"}, + "properties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "default": {} + }, + "propertyNames": {"$dynamicRef": "#meta"}, + "if": {"$dynamicRef": "#meta"}, + "then": {"$dynamicRef": "#meta"}, + "else": {"$dynamicRef": "#meta"}, + "allOf": {"$ref": "#/$defs/schemaArray"}, + "anyOf": {"$ref": "#/$defs/schemaArray"}, + "oneOf": {"$ref": "#/$defs/schemaArray"}, + "not": {"$dynamicRef": "#meta"} + }, + "$defs": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$dynamicRef": "#meta"} + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json new file mode 100644 index 0000000000000000000000000000000000000000..2ae23ddb5cc30cce43646dc58b86f61b1dc7fc4c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/content.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Content vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "contentEncoding": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentSchema": {"$dynamicRef": "#meta"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json new file mode 100644 index 0000000000000000000000000000000000000000..4c8e5cb61657ff226186dd96e5dea6e15eb102e1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/core.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true + }, + "$dynamicAnchor": "meta", + + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": {"$ref": "#/$defs/uriString"}, + "$ref": {"$ref": "#/$defs/uriReferenceString"}, + "$anchor": {"$ref": "#/$defs/anchorString"}, + "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"}, + "$dynamicAnchor": {"$ref": "#/$defs/anchorString"}, + "$vocabulary": { + "type": "object", + "propertyNames": {"$ref": "#/$defs/uriString"}, + "additionalProperties": { + "type": "boolean" + } + }, + "$comment": { + "type": "string" + }, + "$defs": { + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"} + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json new file mode 100644 index 0000000000000000000000000000000000000000..83c26e35f0042ebada16aba9b0c42bedd46bcb24 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/format-annotation.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true + }, + "$dynamicAnchor": "meta", + + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { + "format": {"type": "string"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json new file mode 100644 index 0000000000000000000000000000000000000000..11946fb5019a3564afb38270af3d7806af39978c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/meta-data.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/meta-data": true + }, + "$dynamicAnchor": "meta", + + "title": "Meta-data vocabulary meta-schema", + + "type": ["object", "boolean"], + "properties": { + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json new file mode 100644 index 0000000000000000000000000000000000000000..5e4b203b2c26905ccef5ab90c627aaa19ee708bb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/unevaluated.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true + }, + "$dynamicAnchor": "meta", + + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": {"$dynamicRef": "#meta"}, + "unevaluatedProperties": {"$dynamicRef": "#meta"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json new file mode 100644 index 0000000000000000000000000000000000000000..e0ae13d9d2063403c60e88282701b4b8f6ccd5f5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/meta/validation.json @@ -0,0 +1,90 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/validation": true + }, + "$dynamicAnchor": "meta", + + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { + "anyOf": [ + {"$ref": "#/$defs/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/$defs/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/$defs/nonNegativeInteger"}, + "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": {"$ref": "#/$defs/nonNegativeInteger"}, + "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": {"$ref": "#/$defs/nonNegativeInteger"}, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"}, + "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/$defs/stringArray"}, + "dependentRequired": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..1c68270fdc6e4fa807c75bb32391ce8cb530a497 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-2020-12/schema.json @@ -0,0 +1,55 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + + "title": "Core and Validation specifications meta-schema", + "allOf": [ + {"$ref": "meta/core"}, + {"$ref": "meta/applicator"}, + {"$ref": "meta/unevaluated"}, + {"$ref": "meta/validation"}, + {"$ref": "meta/meta-data"}, + {"$ref": "meta/format-annotation"}, + {"$ref": "meta/content"} + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": {"$dynamicRef": "#meta"}, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { + "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}] + }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-draft-06.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-draft-06.json new file mode 100644 index 0000000000000000000000000000000000000000..5410064ba8df9315d61a34a66245311f1d18db8e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-draft-06.json @@ -0,0 +1,137 @@ +{ + "$schema": "http://json-schema.org/draft-06/schema#", + "$id": "http://json-schema.org/draft-06/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "examples": { + "type": "array", + "items": {} + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": {} + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": {}, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": {} +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-draft-07.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-draft-07.json new file mode 100644 index 0000000000000000000000000000000000000000..6a74851043623c67cbe2e1cd206da447aff752c3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-draft-07.json @@ -0,0 +1,151 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}] + }, + "simpleTypes": { + "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + "stringArray": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": {"$ref": "#/definitions/nonNegativeInteger"}, + "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": {"$ref": "#"}, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}], + "default": true + }, + "maxItems": {"$ref": "#/definitions/nonNegativeInteger"}, + "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": {"$ref": "#"}, + "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"}, + "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"}, + "required": {"$ref": "#/definitions/stringArray"}, + "additionalProperties": {"$ref": "#"}, + "definitions": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": {"$ref": "#"}, + "propertyNames": {"format": "regex"}, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}] + } + }, + "propertyNames": {"$ref": "#"}, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + {"$ref": "#/definitions/simpleTypes"}, + { + "type": "array", + "items": {"$ref": "#/definitions/simpleTypes"}, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": {"type": "string"}, + "contentMediaType": {"type": "string"}, + "contentEncoding": {"type": "string"}, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"} + }, + "default": true +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-secure.json b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-secure.json new file mode 100644 index 0000000000000000000000000000000000000000..3968abd5d97e7b2cf87db34d5eb211c090b8700f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/json-schema-secure.json @@ -0,0 +1,88 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#", + "title": "Meta-schema for the security assessment of JSON Schemas", + "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#"} + } + }, + "dependencies": { + "patternProperties": { + "description": "prevent slow validation of large property names", + "required": ["propertyNames"], + "properties": { + "propertyNames": { + "required": ["maxLength"] + } + } + }, + "uniqueItems": { + "description": "prevent slow validation of large non-scalar arrays", + "if": { + "properties": { + "uniqueItems": {"const": true}, + "items": { + "properties": { + "type": { + "anyOf": [ + { + "enum": ["object", "array"] + }, + { + "type": "array", + "contains": {"enum": ["object", "array"]} + } + ] + } + } + } + } + }, + "then": { + "required": ["maxItems"] + } + }, + "pattern": { + "description": "prevent slow pattern matching of large strings", + "required": ["maxLength"] + }, + "format": { + "description": "prevent slow format validation of large strings", + "required": ["maxLength"] + } + }, + "properties": { + "additionalItems": {"$ref": "#"}, + "additionalProperties": {"$ref": "#"}, + "dependencies": { + "additionalProperties": { + "anyOf": [{"type": "array"}, {"$ref": "#"}] + } + }, + "items": { + "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}] + }, + "definitions": { + "additionalProperties": {"$ref": "#"} + }, + "patternProperties": { + "additionalProperties": {"$ref": "#"} + }, + "properties": { + "additionalProperties": {"$ref": "#"} + }, + "if": {"$ref": "#"}, + "then": {"$ref": "#"}, + "else": {"$ref": "#"}, + "allOf": {"$ref": "#/definitions/schemaArray"}, + "anyOf": {"$ref": "#/definitions/schemaArray"}, + "oneOf": {"$ref": "#/definitions/schemaArray"}, + "not": {"$ref": "#"}, + "contains": {"$ref": "#"}, + "propertyNames": {"$ref": "#"} + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/jtd-schema.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/jtd-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0198128985137b24b13e40e6f41431f37b86647 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/refs/jtd-schema.ts @@ -0,0 +1,130 @@ +import {SchemaObject} from "../types" + +type MetaSchema = (root: boolean) => SchemaObject + +const shared: MetaSchema = (root) => { + const sch: SchemaObject = { + nullable: {type: "boolean"}, + metadata: { + optionalProperties: { + union: {elements: {ref: "schema"}}, + }, + additionalProperties: true, + }, + } + if (root) sch.definitions = {values: {ref: "schema"}} + return sch +} + +const emptyForm: MetaSchema = (root) => ({ + optionalProperties: shared(root), +}) + +const refForm: MetaSchema = (root) => ({ + properties: { + ref: {type: "string"}, + }, + optionalProperties: shared(root), +}) + +const typeForm: MetaSchema = (root) => ({ + properties: { + type: { + enum: [ + "boolean", + "timestamp", + "string", + "float32", + "float64", + "int8", + "uint8", + "int16", + "uint16", + "int32", + "uint32", + ], + }, + }, + optionalProperties: shared(root), +}) + +const enumForm: MetaSchema = (root) => ({ + properties: { + enum: {elements: {type: "string"}}, + }, + optionalProperties: shared(root), +}) + +const elementsForm: MetaSchema = (root) => ({ + properties: { + elements: {ref: "schema"}, + }, + optionalProperties: shared(root), +}) + +const propertiesForm: MetaSchema = (root) => ({ + properties: { + properties: {values: {ref: "schema"}}, + }, + optionalProperties: { + optionalProperties: {values: {ref: "schema"}}, + additionalProperties: {type: "boolean"}, + ...shared(root), + }, +}) + +const optionalPropertiesForm: MetaSchema = (root) => ({ + properties: { + optionalProperties: {values: {ref: "schema"}}, + }, + optionalProperties: { + additionalProperties: {type: "boolean"}, + ...shared(root), + }, +}) + +const discriminatorForm: MetaSchema = (root) => ({ + properties: { + discriminator: {type: "string"}, + mapping: { + values: { + metadata: { + union: [propertiesForm(false), optionalPropertiesForm(false)], + }, + }, + }, + }, + optionalProperties: shared(root), +}) + +const valuesForm: MetaSchema = (root) => ({ + properties: { + values: {ref: "schema"}, + }, + optionalProperties: shared(root), +}) + +const schema: MetaSchema = (root) => ({ + metadata: { + union: [ + emptyForm, + refForm, + typeForm, + enumForm, + elementsForm, + propertiesForm, + optionalPropertiesForm, + discriminatorForm, + valuesForm, + ].map((s) => s(root)), + }, +}) + +const jtdMetaSchema: SchemaObject = { + definitions: { + schema: schema(false), + }, + ...schema(true), +} + +export default jtdMetaSchema diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/equal.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/equal.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cb00631a2363720e822255d0911a54439512c3c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/equal.ts @@ -0,0 +1,7 @@ +// https://github.com/ajv-validator/ajv/issues/889 +import * as equal from "fast-deep-equal" + +type Equal = typeof equal & {code: string} +;(equal as Equal).code = 'require("ajv/dist/runtime/equal").default' + +export default equal as Equal diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/parseJson.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/parseJson.ts new file mode 100644 index 0000000000000000000000000000000000000000..472e5e50786f2cff1092ac1353508ac0fcebce9e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/parseJson.ts @@ -0,0 +1,177 @@ +const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/ + +export function parseJson(s: string, pos: number): unknown { + let endPos: number | undefined + parseJson.message = undefined + let matches: RegExpExecArray | null + if (pos) s = s.slice(pos) + try { + parseJson.position = pos + s.length + return JSON.parse(s) + } catch (e) { + matches = rxParseJson.exec((e as Error).message) + if (!matches) { + parseJson.message = "unexpected end" + return undefined + } + endPos = +matches[1] + const c = s[endPos] + s = s.slice(0, endPos) + parseJson.position = pos + endPos + try { + return JSON.parse(s) + } catch (e1) { + parseJson.message = `unexpected token ${c}` + return undefined + } + } +} + +parseJson.message = undefined as string | undefined +parseJson.position = 0 as number +parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson' + +export function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined { + let numStr = "" + let c: string + parseJsonNumber.message = undefined + if (s[pos] === "-") { + numStr += "-" + pos++ + } + if (s[pos] === "0") { + numStr += "0" + pos++ + } else { + if (!parseDigits(maxDigits)) { + errorMessage() + return undefined + } + } + if (maxDigits) { + parseJsonNumber.position = pos + return +numStr + } + if (s[pos] === ".") { + numStr += "." + pos++ + if (!parseDigits()) { + errorMessage() + return undefined + } + } + if (((c = s[pos]), c === "e" || c === "E")) { + numStr += "e" + pos++ + if (((c = s[pos]), c === "+" || c === "-")) { + numStr += c + pos++ + } + if (!parseDigits()) { + errorMessage() + return undefined + } + } + parseJsonNumber.position = pos + return +numStr + + function parseDigits(maxLen?: number): boolean { + let digit = false + while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) { + digit = true + numStr += c + pos++ + } + return digit + } + + function errorMessage(): void { + parseJsonNumber.position = pos + parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end" + } +} + +parseJsonNumber.message = undefined as string | undefined +parseJsonNumber.position = 0 as number +parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber' + +const escapedChars: {[X in string]?: string} = { + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + '"': '"', + "/": "/", + "\\": "\\", +} + +const CODE_A: number = "a".charCodeAt(0) +const CODE_0: number = "0".charCodeAt(0) + +export function parseJsonString(s: string, pos: number): string | undefined { + let str = "" + let c: string | undefined + parseJsonString.message = undefined + // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition + while (true) { + c = s[pos++] + if (c === '"') break + if (c === "\\") { + c = s[pos] + if (c in escapedChars) { + str += escapedChars[c] + pos++ + } else if (c === "u") { + pos++ + let count = 4 + let code = 0 + while (count--) { + code <<= 4 + c = s[pos] + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (c === undefined) { + errorMessage("unexpected end") + return undefined + } + c = c.toLowerCase() + if (c >= "a" && c <= "f") { + code += c.charCodeAt(0) - CODE_A + 10 + } else if (c >= "0" && c <= "9") { + code += c.charCodeAt(0) - CODE_0 + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + pos++ + } + str += String.fromCharCode(code) + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + } else if (c === undefined) { + errorMessage("unexpected end") + return undefined + } else { + if (c.charCodeAt(0) >= 0x20) { + str += c + } else { + errorMessage(`unexpected token ${c}`) + return undefined + } + } + } + parseJsonString.position = pos + return str + + function errorMessage(msg: string): void { + parseJsonString.position = pos + parseJsonString.message = msg + } +} + +parseJsonString.message = undefined as string | undefined +parseJsonString.position = 0 as number +parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString' diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/quote.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/quote.ts new file mode 100644 index 0000000000000000000000000000000000000000..1160e6a23807cf7fc0f4d036ddc45bd962562275 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/quote.ts @@ -0,0 +1,31 @@ +const rxEscapable = + // eslint-disable-next-line no-control-regex, no-misleading-character-class + /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g + +const escaped: {[K in string]?: string} = { + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': '\\"', + "\\": "\\\\", +} + +export default function quote(s: string): string { + rxEscapable.lastIndex = 0 + return ( + '"' + + (rxEscapable.test(s) + ? s.replace(rxEscapable, (a) => { + const c = escaped[a] + return typeof c === "string" + ? c + : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4) + }) + : s) + + '"' + ) +} + +quote.code = 'require("ajv/dist/runtime/quote").default' diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/re2.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/re2.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c769bc7aefc5aa1924e2be877d39bc59670ab3f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/re2.ts @@ -0,0 +1,6 @@ +import * as re2 from "re2" + +type Re2 = typeof re2 & {code: string} +;(re2 as Re2).code = 'require("ajv/dist/runtime/re2").default' + +export default re2 as Re2 diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/timestamp.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/timestamp.ts new file mode 100644 index 0000000000000000000000000000000000000000..1625f9a40f4443fde14743a6a8ecb6c1dc8fb819 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/timestamp.ts @@ -0,0 +1,46 @@ +const DT_SEPARATOR = /t|\s/i +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ +const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + +export default function validTimestamp(str: string, allowDate: boolean): boolean { + // http://tools.ietf.org/html/rfc3339#section-5.6 + const dt: string[] = str.split(DT_SEPARATOR) + return ( + (dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) || + (allowDate && dt.length === 1 && validDate(dt[0])) + ) +} + +function validDate(str: string): boolean { + const matches: string[] | null = DATE.exec(str) + if (!matches) return false + const y: number = +matches[1] + const m: number = +matches[2] + const d: number = +matches[3] + return ( + m >= 1 && + m <= 12 && + d >= 1 && + (d <= DAYS[m] || + // leap year: https://tools.ietf.org/html/rfc3339#appendix-C + (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))) + ) +} + +function validTime(str: string): boolean { + const matches: string[] | null = TIME.exec(str) + if (!matches) return false + const hr: number = +matches[1] + const min: number = +matches[2] + const sec: number = +matches[3] + const tzH: number = +(matches[4] || 0) + const tzM: number = +(matches[5] || 0) + return ( + (hr <= 23 && min <= 59 && sec <= 59) || + // leap second + (hr - tzH === 23 && min - tzM === 59 && sec === 60) + ) +} + +validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default' diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/ucs2length.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/ucs2length.ts new file mode 100644 index 0000000000000000000000000000000000000000..47d8292b83fde4619bdbf28b89e6720824a97164 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/ucs2length.ts @@ -0,0 +1,20 @@ +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +export default function ucs2length(str: string): number { + const len = str.length + let length = 0 + let pos = 0 + let value: number + while (pos < len) { + length++ + value = str.charCodeAt(pos++) + if (value >= 0xd800 && value <= 0xdbff && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos) + if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate + } + } + return length +} + +ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default' diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/uri.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/uri.ts new file mode 100644 index 0000000000000000000000000000000000000000..5450549cd5a3968f163460d3c0fb1aeb7ffc2b2c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/uri.ts @@ -0,0 +1,6 @@ +import * as uri from "fast-uri" + +type URI = typeof uri & {code: string} +;(uri as URI).code = 'require("ajv/dist/runtime/uri").default' + +export default uri as URI diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/validation_error.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/validation_error.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d19a46a2245c667f479d7ee51d1d9558cd9ae90 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/runtime/validation_error.ts @@ -0,0 +1,13 @@ +import type {ErrorObject} from "../types" + +export default class ValidationError extends Error { + readonly errors: Partial[] + readonly ajv: true + readonly validation: true + + constructor(errors: Partial[]) { + super("validation failed") + this.errors = errors + this.ajv = this.validation = true + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/standalone/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/standalone/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6129ce9e5ebab51fe4f53ffa86dbacd12878ed9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/standalone/index.ts @@ -0,0 +1,100 @@ +import type AjvCore from "../core" +import type {AnyValidateFunction, SourceCode} from "../types" +import type {SchemaEnv} from "../compile" +import {UsedScopeValues, UsedValueState, ValueScopeName, varKinds} from "../compile/codegen/scope" +import {_, nil, _Code, Code, getProperty, getEsmExportName} from "../compile/codegen/code" + +function standaloneCode( + ajv: AjvCore, + refsOrFunc?: {[K in string]?: string} | AnyValidateFunction +): string { + if (!ajv.opts.code.source) { + throw new Error("moduleCode: ajv instance must have code.source option") + } + const {_n} = ajv.scope.opts + return typeof refsOrFunc == "function" + ? funcExportCode(refsOrFunc.source) + : refsOrFunc !== undefined + ? multiExportsCode(refsOrFunc, getValidate) + : multiExportsCode(ajv.schemas, (sch) => + sch.meta ? undefined : ajv.compile(sch.schema) + ) + + function getValidate(id: string): AnyValidateFunction { + const v = ajv.getSchema(id) + if (!v) throw new Error(`moduleCode: no schema with id ${id}`) + return v + } + + function funcExportCode(source?: SourceCode): string { + const usedValues: UsedScopeValues = {} + const n = source?.validateName + const vCode = validateCode(usedValues, source) + if (ajv.opts.code.esm) { + // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value + return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}` + } + return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}` + } + + function multiExportsCode( + schemas: {[K in string]?: T}, + getValidateFunc: (schOrId: T) => AnyValidateFunction | undefined + ): string { + const usedValues: UsedScopeValues = {} + let code = _`"use strict";` + for (const name in schemas) { + const v = getValidateFunc(schemas[name] as T) + if (v) { + const vCode = validateCode(usedValues, v.source) + const exportSyntax = ajv.opts.code.esm + ? _`export const ${getEsmExportName(name)}` + : _`exports${getProperty(name)}` + code = _`${code}${_n}${exportSyntax} = ${v.source?.validateName};${_n}${vCode}` + } + } + return `${code}` + } + + function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code { + if (!s) throw new Error('moduleCode: function does not have "source" property') + if (usedState(s.validateName) === UsedValueState.Completed) return nil + setUsedState(s.validateName, UsedValueState.Started) + + const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode) + const code = new _Code(`${scopeCode}${_n}${s.validateCode}`) + return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code + + function refValidateCode(n: ValueScopeName): Code | undefined { + const vRef = n.value?.ref + if (n.prefix === "validate" && typeof vRef == "function") { + const v = vRef as AnyValidateFunction + return validateCode(usedValues, v.source) + } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") { + const {validate, validateName} = vRef as SchemaEnv + if (!validateName) throw new Error("ajv internal error") + const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const + const wrapper = _`${def} ${n} = {validate: ${validateName}};` + if (usedState(validateName) === UsedValueState.Started) return wrapper + const vCode = validateCode(usedValues, validate?.source) + return _`${wrapper}${_n}${vCode}` + } + return undefined + } + + function usedState(name: ValueScopeName): UsedValueState | undefined { + return usedValues[name.prefix]?.get(name) + } + + function setUsedState(name: ValueScopeName, state: UsedValueState): void { + const {prefix} = name + const names = (usedValues[prefix] = usedValues[prefix] || new Map()) + names.set(name, state) + } + } +} + +module.exports = exports = standaloneCode +Object.defineProperty(exports, "__esModule", {value: true}) + +export default standaloneCode diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/standalone/instance.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/standalone/instance.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4b2c30b58f0ebc89b4c8e1010e5976216c0042f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/standalone/instance.ts @@ -0,0 +1,36 @@ +import Ajv, {AnySchema, AnyValidateFunction, ErrorObject} from "../core" +import standaloneCode from "." +import * as requireFromString from "require-from-string" + +export default class AjvPack { + errors?: ErrorObject[] | null // errors from the last validation + constructor(readonly ajv: Ajv) {} + + validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise { + return Ajv.prototype.validate.call(this, schemaKeyRef, data) + } + + compile(schema: AnySchema, meta?: boolean): AnyValidateFunction { + return this.getStandalone(this.ajv.compile(schema, meta)) + } + + getSchema(keyRef: string): AnyValidateFunction | undefined { + const v = this.ajv.getSchema(keyRef) + if (!v) return undefined + return this.getStandalone(v) + } + + private getStandalone(v: AnyValidateFunction): AnyValidateFunction { + return requireFromString(standaloneCode(this.ajv, v)) as AnyValidateFunction + } + + addSchema(...args: Parameters): AjvPack { + this.ajv.addSchema.call(this.ajv, ...args) + return this + } + + addKeyword(...args: Parameters): AjvPack { + this.ajv.addKeyword.call(this.ajv, ...args) + return this + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/types/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/types/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..39bc51b0b99d79b09e3e5f0e2d0d48e7bf37c069 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/types/index.ts @@ -0,0 +1,244 @@ +import {URIComponent} from "fast-uri" +import type {CodeGen, Code, Name, ScopeValueSets, ValueScopeName} from "../compile/codegen" +import type {SchemaEnv, SchemaCxt, SchemaObjCxt} from "../compile" +import type {JSONType} from "../compile/rules" +import type {KeywordCxt} from "../compile/validate" +import type Ajv from "../core" + +interface _SchemaObject { + id?: string + $id?: string + $schema?: string + [x: string]: any // TODO +} + +export interface SchemaObject extends _SchemaObject { + id?: string + $id?: string + $schema?: string + $async?: false + [x: string]: any // TODO +} + +export interface AsyncSchema extends _SchemaObject { + $async: true +} + +export type AnySchemaObject = SchemaObject | AsyncSchema + +export type Schema = SchemaObject | boolean + +export type AnySchema = Schema | AsyncSchema + +export type SchemaMap = {[Key in string]?: AnySchema} + +export interface SourceCode { + validateName: ValueScopeName + validateCode: string + scopeValues: ScopeValueSets + evaluated?: Code +} + +export interface DataValidationCxt { + instancePath: string + parentData: {[K in T]: any} // object or array + parentDataProperty: T // string or number + rootData: Record | any[] + dynamicAnchors: {[Ref in string]?: ValidateFunction} +} + +export interface ValidateFunction { + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents + (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T + errors?: null | ErrorObject[] + evaluated?: Evaluated + schema: AnySchema + schemaEnv: SchemaEnv + source?: SourceCode +} + +export interface JTDParser { + (json: string): T | undefined + message?: string + position?: number +} + +export type EvaluatedProperties = {[K in string]?: true} | true + +export type EvaluatedItems = number | true + +export interface Evaluated { + // determined at compile time if staticProps/Items is true + props?: EvaluatedProperties + items?: EvaluatedItems + // whether props/items determined at compile time + dynamicProps: boolean + dynamicItems: boolean +} + +export interface AsyncValidateFunction extends ValidateFunction { + (...args: Parameters>): Promise + $async: true +} + +export type AnyValidateFunction = ValidateFunction | AsyncValidateFunction + +export interface ErrorObject, S = unknown> { + keyword: K + instancePath: string + schemaPath: string + params: P + // Added to validation errors of "propertyNames" keyword schema + propertyName?: string + // Excluded if option `messages` set to false. + message?: string + // These are added with the `verbose` option. + schema?: S + parentSchema?: AnySchemaObject + data?: unknown +} + +export type ErrorNoParams = ErrorObject, S> + +interface _KeywordDef { + keyword: string | string[] + type?: JSONType | JSONType[] // data types that keyword applies to + schemaType?: JSONType | JSONType[] // allowed type(s) of keyword value in the schema + allowUndefined?: boolean // used for keywords that can be invoked by other keywords, not being present in the schema + $data?: boolean // keyword supports [$data reference](../../docs/guide/combining-schemas.md#data-reference) + implements?: string[] // other schema keywords that this keyword implements + before?: string // keyword should be executed before this keyword (should be applicable to the same type) + post?: boolean // keyword should be executed after other keywords without post flag + metaSchema?: AnySchemaObject // meta-schema for keyword schema value - it is better to use schemaType where applicable + validateSchema?: AnyValidateFunction // compiled keyword metaSchema - should not be passed + dependencies?: string[] // keywords that must be present in the same schema + error?: KeywordErrorDefinition + $dataError?: KeywordErrorDefinition +} + +export interface CodeKeywordDefinition extends _KeywordDef { + code: (cxt: KeywordCxt, ruleType?: string) => void + trackErrors?: boolean +} + +export type MacroKeywordFunc = ( + schema: any, + parentSchema: AnySchemaObject, + it: SchemaCxt +) => AnySchema + +export type CompileKeywordFunc = ( + schema: any, + parentSchema: AnySchemaObject, + it: SchemaObjCxt +) => DataValidateFunction + +export interface DataValidateFunction { + (...args: Parameters): boolean | Promise + errors?: Partial[] +} + +export interface SchemaValidateFunction { + ( + schema: any, + data: any, + parentSchema?: AnySchemaObject, + dataCxt?: DataValidationCxt + ): boolean | Promise + errors?: Partial[] +} + +export interface FuncKeywordDefinition extends _KeywordDef { + validate?: SchemaValidateFunction | DataValidateFunction + compile?: CompileKeywordFunc + // schema: false makes validate not to expect schema (DataValidateFunction) + schema?: boolean // requires "validate" + modifying?: boolean + async?: boolean + valid?: boolean + errors?: boolean | "full" +} + +export interface MacroKeywordDefinition extends FuncKeywordDefinition { + macro: MacroKeywordFunc +} + +export type KeywordDefinition = + | CodeKeywordDefinition + | FuncKeywordDefinition + | MacroKeywordDefinition + +export type AddedKeywordDefinition = KeywordDefinition & { + type: JSONType[] + schemaType: JSONType[] +} + +export interface KeywordErrorDefinition { + message: string | Code | ((cxt: KeywordErrorCxt) => string | Code) + params?: Code | ((cxt: KeywordErrorCxt) => Code) +} + +export type Vocabulary = (KeywordDefinition | string)[] + +export interface KeywordErrorCxt { + gen: CodeGen + keyword: string + data: Name + $data?: string | false + schema: any // TODO + parentSchema?: AnySchemaObject + schemaCode: Code | number | boolean + schemaValue: Code | number | boolean + schemaType?: JSONType[] + errsCount?: Name + params: KeywordCxtParams + it: SchemaCxt +} + +export type KeywordCxtParams = {[P in string]?: Code | string | number} + +export type FormatValidator = (data: T) => boolean + +export type FormatCompare = (data1: T, data2: T) => number | undefined + +export type AsyncFormatValidator = (data: T) => Promise + +export interface FormatDefinition { + type?: T extends string ? "string" | undefined : "number" + validate: FormatValidator | (T extends string ? string | RegExp : never) + async?: false | undefined + compare?: FormatCompare +} + +export interface AsyncFormatDefinition { + type?: T extends string ? "string" | undefined : "number" + validate: AsyncFormatValidator + async: true + compare?: FormatCompare +} + +export type AddedFormat = + | true + | RegExp + | FormatValidator + | FormatDefinition + | FormatDefinition + | AsyncFormatDefinition + | AsyncFormatDefinition + +export type Format = AddedFormat | string + +export interface RegExpEngine { + (pattern: string, u: string): RegExpLike + code: string +} + +export interface RegExpLike { + test: (s: string) => boolean +} + +export interface UriResolver { + parse(uri: string): URIComponent + resolve(base: string, path: string): string + serialize(component: URIComponent): string +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/types/json-schema.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/types/json-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..065c972e54a179b74e9dee48fdea8a1c2d45c8a1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/types/json-schema.ts @@ -0,0 +1,187 @@ +/* eslint-disable @typescript-eslint/no-empty-interface */ +type StrictNullChecksWrapper = undefined extends null + ? `strictNullChecks must be true in tsconfig to use ${Name}` + : Type + +type UnionToIntersection = (U extends any ? (_: U) => void : never) extends (_: infer I) => void + ? I + : never + +export type SomeJSONSchema = UncheckedJSONSchemaType + +type UncheckedPartialSchema = Partial> + +export type PartialSchema = StrictNullChecksWrapper<"PartialSchema", UncheckedPartialSchema> + +type JSONType = IsPartial extends true + ? T | undefined + : T + +interface NumberKeywords { + minimum?: number + maximum?: number + exclusiveMinimum?: number + exclusiveMaximum?: number + multipleOf?: number + format?: string +} + +interface StringKeywords { + minLength?: number + maxLength?: number + pattern?: string + format?: string +} + +type UncheckedJSONSchemaType = ( + | // these two unions allow arbitrary unions of types + { + anyOf: readonly UncheckedJSONSchemaType[] + } + | { + oneOf: readonly UncheckedJSONSchemaType[] + } + // this union allows for { type: (primitive)[] } style schemas + | ({ + type: readonly (T extends number + ? JSONType<"number" | "integer", IsPartial> + : T extends string + ? JSONType<"string", IsPartial> + : T extends boolean + ? JSONType<"boolean", IsPartial> + : never)[] + } & UnionToIntersection< + T extends number + ? NumberKeywords + : T extends string + ? StringKeywords + : T extends boolean + ? // eslint-disable-next-line @typescript-eslint/ban-types + {} + : never + >) + // this covers "normal" types; it's last so typescript looks to it first for errors + | ((T extends number + ? { + type: JSONType<"number" | "integer", IsPartial> + } & NumberKeywords + : T extends string + ? { + type: JSONType<"string", IsPartial> + } & StringKeywords + : T extends boolean + ? { + type: JSONType<"boolean", IsPartial> + } + : T extends readonly [any, ...any[]] + ? { + // JSON AnySchema for tuple + type: JSONType<"array", IsPartial> + items: { + readonly [K in keyof T]-?: UncheckedJSONSchemaType & Nullable + } & {length: T["length"]} + minItems: T["length"] + } & ({maxItems: T["length"]} | {additionalItems: false}) + : T extends readonly any[] + ? { + type: JSONType<"array", IsPartial> + items: UncheckedJSONSchemaType + contains?: UncheckedPartialSchema + minItems?: number + maxItems?: number + minContains?: number + maxContains?: number + uniqueItems?: true + additionalItems?: never + } + : T extends Record + ? { + // JSON AnySchema for records and dictionaries + // "required" is not optional because it is often forgotten + // "properties" are optional for more concise dictionary schemas + // "patternProperties" and can be only used with interfaces that have string index + type: JSONType<"object", IsPartial> + additionalProperties?: boolean | UncheckedJSONSchemaType + unevaluatedProperties?: boolean | UncheckedJSONSchemaType + properties?: IsPartial extends true + ? Partial> + : UncheckedPropertiesSchema + patternProperties?: Record> + propertyNames?: Omit, "type"> & {type?: "string"} + dependencies?: {[K in keyof T]?: readonly (keyof T)[] | UncheckedPartialSchema} + dependentRequired?: {[K in keyof T]?: readonly (keyof T)[]} + dependentSchemas?: {[K in keyof T]?: UncheckedPartialSchema} + minProperties?: number + maxProperties?: number + } & (IsPartial extends true // "required" is not necessary if it's a non-partial type with no required keys // are listed it only asserts that optional cannot be listed. // "required" type does not guarantee that all required properties + ? {required: readonly (keyof T)[]} + : [UncheckedRequiredMembers] extends [never] + ? {required?: readonly UncheckedRequiredMembers[]} + : {required: readonly UncheckedRequiredMembers[]}) + : T extends null + ? { + type: JSONType<"null", IsPartial> + nullable: true + } + : never) & { + allOf?: readonly UncheckedPartialSchema[] + anyOf?: readonly UncheckedPartialSchema[] + oneOf?: readonly UncheckedPartialSchema[] + if?: UncheckedPartialSchema + then?: UncheckedPartialSchema + else?: UncheckedPartialSchema + not?: UncheckedPartialSchema + }) +) & { + [keyword: string]: any + $id?: string + $ref?: string + $defs?: Record> + definitions?: Record> +} + +export type JSONSchemaType = StrictNullChecksWrapper< + "JSONSchemaType", + UncheckedJSONSchemaType +> + +type Known = + | {[key: string]: Known} + | [Known, ...Known[]] + | Known[] + | number + | string + | boolean + | null + +type UncheckedPropertiesSchema = { + [K in keyof T]-?: (UncheckedJSONSchemaType & Nullable) | {$ref: string} +} + +export type PropertiesSchema = StrictNullChecksWrapper< + "PropertiesSchema", + UncheckedPropertiesSchema +> + +type UncheckedRequiredMembers = { + [K in keyof T]-?: undefined extends T[K] ? never : K +}[keyof T] + +export type RequiredMembers = StrictNullChecksWrapper< + "RequiredMembers", + UncheckedRequiredMembers +> + +type Nullable = undefined extends T + ? { + nullable: true + const?: null // any non-null value would fail `const: null`, `null` would fail any other value in const + enum?: readonly (T | null)[] // `null` must be explicitly included in "enum" for `null` to pass + default?: T | null + } + : { + nullable?: false + const?: T + enum?: readonly T[] + default?: T + } diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/types/jtd-schema.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/types/jtd-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..61b2bde81d5f5d407971855d0a2c8125aeb53463 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/types/jtd-schema.ts @@ -0,0 +1,273 @@ +/** numeric strings */ +type NumberType = "float32" | "float64" | "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" + +/** string strings */ +type StringType = "string" | "timestamp" + +/** Generic JTD Schema without inference of the represented type */ +export type SomeJTDSchemaType = ( + | // ref + {ref: string} + // primitives + | {type: NumberType | StringType | "boolean"} + // enum + | {enum: string[]} + // elements + | {elements: SomeJTDSchemaType} + // values + | {values: SomeJTDSchemaType} + // properties + | { + properties: Record + optionalProperties?: Record + additionalProperties?: boolean + } + | { + properties?: Record + optionalProperties: Record + additionalProperties?: boolean + } + // discriminator + | {discriminator: string; mapping: Record} + // empty + // NOTE see the end of + // https://github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492 + // eslint-disable-next-line @typescript-eslint/ban-types + | {} +) & { + nullable?: boolean + metadata?: Record + definitions?: Record +} + +/** required keys of an object, not undefined */ +type RequiredKeys = { + [K in keyof T]-?: undefined extends T[K] ? never : K +}[keyof T] + +/** optional or undifined-able keys of an object */ +type OptionalKeys = { + [K in keyof T]-?: undefined extends T[K] ? K : never +}[keyof T] + +/** type is true if T is a union type */ +type IsUnion_ = false extends ( + T extends unknown ? ([U] extends [T] ? false : true) : never +) + ? false + : true +type IsUnion = IsUnion_ + +/** type is true if T is identically E */ +type TypeEquality = [T] extends [E] ? ([E] extends [T] ? true : false) : false + +/** type is true if T or null is identically E or null*/ +type NullTypeEquality = TypeEquality + +/** gets only the string literals of a type or null if a type isn't a string literal */ +type EnumString = [T] extends [never] + ? null + : T extends string + ? string extends T + ? null + : T + : null + +/** true if type is a union of string literals */ +type IsEnum = null extends EnumString ? false : true + +/** true only if all types are array types (not tuples) */ +// NOTE relies on the fact that tuples don't have an index at 0.5, but arrays +// have an index at every number +type IsElements = false extends IsUnion + ? [T] extends [readonly unknown[]] + ? undefined extends T[0.5] + ? false + : true + : false + : false + +/** true if the the type is a values type */ +type IsValues = false extends IsUnion ? TypeEquality : false + +/** true if type is a properties type and Union is false, or type is a discriminator type and Union is true */ +type IsRecord = Union extends IsUnion + ? null extends EnumString + ? false + : true + : false + +/** true if type represents an empty record */ +type IsEmptyRecord = [T] extends [Record] + ? [T] extends [never] + ? false + : true + : false + +/** actual schema */ +export type JTDSchemaType = Record> = ( + | // refs - where null wasn't specified, must match exactly + (null extends EnumString + ? never + : + | ({[K in keyof D]: [T] extends [D[K]] ? {ref: K} : never}[keyof D] & {nullable?: false}) + // nulled refs - if ref is nullable and nullable is specified, then it can + // match either null or non-null definitions + | (null extends T + ? { + [K in keyof D]: [Exclude] extends [Exclude] + ? {ref: K} + : never + }[keyof D] & {nullable: true} + : never)) + // empty - empty schemas also treat nullable differently in that it's now fully ignored + | (unknown extends T ? {nullable?: boolean} : never) + // all other types // numbers - only accepts the type number + | ((true extends NullTypeEquality + ? {type: NumberType} + : // booleans - accepts the type boolean + true extends NullTypeEquality + ? {type: "boolean"} + : // strings - only accepts the type string + true extends NullTypeEquality + ? {type: StringType} + : // strings - only accepts the type Date + true extends NullTypeEquality + ? {type: "timestamp"} + : // enums - only accepts union of string literals + // TODO we can't actually check that everything in the union was specified + true extends IsEnum> + ? {enum: EnumString>[]} + : // arrays - only accepts arrays, could be array of unions to be resolved later + true extends IsElements> + ? T extends readonly (infer E)[] + ? { + elements: JTDSchemaType + } + : never + : // empty properties + true extends IsEmptyRecord> + ? + | {properties: Record; optionalProperties?: Record} + | {optionalProperties: Record} + : // values + true extends IsValues> + ? T extends Record + ? { + values: JTDSchemaType + } + : never + : // properties + true extends IsRecord, false> + ? ([RequiredKeys>] extends [never] + ? { + properties?: Record + } + : { + properties: {[K in RequiredKeys]: JTDSchemaType} + }) & + ([OptionalKeys>] extends [never] + ? { + optionalProperties?: Record + } + : { + optionalProperties: { + [K in OptionalKeys]: JTDSchemaType, D> + } + }) & { + additionalProperties?: boolean + } + : // discriminator + true extends IsRecord, true> + ? { + [K in keyof Exclude]-?: Exclude[K] extends string + ? { + discriminator: K + mapping: { + // TODO currently allows descriminator to be present in schema + [M in Exclude[K]]: JTDSchemaType< + Omit ? T : never, K>, + D + > + } + } + : never + }[keyof Exclude] + : never) & + (null extends T + ? { + nullable: true + } + : {nullable?: false})) +) & { + // extra properties + metadata?: Record + // TODO these should only be allowed at the top level + definitions?: {[K in keyof D]: JTDSchemaType} +} + +type JTDDataDef> = + | // ref + (S extends {ref: string} + ? D extends {[K in S["ref"]]: infer V} + ? JTDDataDef + : never + : // type + S extends {type: NumberType} + ? number + : S extends {type: "boolean"} + ? boolean + : S extends {type: "string"} + ? string + : S extends {type: "timestamp"} + ? string | Date + : // enum + S extends {enum: readonly (infer E)[]} + ? string extends E + ? never + : [E] extends [string] + ? E + : never + : // elements + S extends {elements: infer E} + ? JTDDataDef[] + : // properties + S extends { + properties: Record + optionalProperties?: Record + additionalProperties?: boolean + } + ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< + S["optionalProperties"][K], + D + > + } & ([S["additionalProperties"]] extends [true] ? Record : unknown) + : S extends { + properties?: Record + optionalProperties: Record + additionalProperties?: boolean + } + ? {-readonly [K in keyof S["properties"]]-?: JTDDataDef} & { + -readonly [K in keyof S["optionalProperties"]]+?: JTDDataDef< + S["optionalProperties"][K], + D + > + } & ([S["additionalProperties"]] extends [true] ? Record : unknown) + : // values + S extends {values: infer V} + ? Record> + : // discriminator + S extends {discriminator: infer M; mapping: Record} + ? [M] extends [string] + ? { + [K in keyof S["mapping"]]: JTDDataDef & {[KM in M]: K} + }[keyof S["mapping"]] + : never + : // empty + unknown) + | (S extends {nullable: true} ? null : never) + +export type JTDDataType = S extends {definitions: Record} + ? JTDDataDef + : JTDDataDef> diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..755e5b3daf551d68ffbe3bd45884ee650094a46d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts @@ -0,0 +1,56 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" + +export type AdditionalItemsError = ErrorObject<"additionalItems", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "additionalItems" as const, + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error, + code(cxt: KeywordCxt) { + const {parentSchema, it} = cxt + const {items} = parentSchema + if (!Array.isArray(items)) { + checkStrictMode(it, '"additionalItems" is ignored when "items" is not an array of schemas') + return + } + validateAdditionalItems(cxt, items) + }, +} + +export function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void { + const {gen, schema, data, keyword, it} = cxt + it.items = true + const len = gen.const("len", _`${data}.length`) + if (schema === false) { + cxt.setParams({len: items.length}) + cxt.pass(_`${len} <= ${items.length}`) + } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.var("valid", _`${len} <= ${items.length}`) // TODO var + gen.if(not(valid), () => validateItems(valid)) + cxt.ok(valid) + } + + function validateItems(valid: Name): void { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid) + if (!it.allErrors) gen.if(not(valid), () => gen.break()) + }) + } +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfb511ce5100f4902f0f9c17ce7d7886e95fcabc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts @@ -0,0 +1,118 @@ +import type { + CodeKeywordDefinition, + AddedKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import {allSchemaProperties, usePattern, isOwnProperty} from "../code" +import {_, nil, or, not, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import type {SubschemaArgs} from "../../compile/validate/subschema" +import {alwaysValidSchema, schemaRefOrVal, Type} from "../../compile/util" + +export type AdditionalPropertiesError = ErrorObject< + "additionalProperties", + {additionalProperty: string}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: "must NOT have additional properties", + params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, +} + +const def: CodeKeywordDefinition & AddedKeywordDefinition = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error, + code(cxt) { + const {gen, schema, parentSchema, data, errsCount, it} = cxt + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error") + const {allErrors, opts} = it + it.props = true + if (opts.removeAdditional !== "all" && alwaysValidSchema(it, schema)) return + const props = allSchemaProperties(parentSchema.properties) + const patProps = allSchemaProperties(parentSchema.patternProperties) + checkAdditionalProperties() + cxt.ok(_`${errsCount} === ${N.errors}`) + + function checkAdditionalProperties(): void { + gen.forIn("key", data, (key: Name) => { + if (!props.length && !patProps.length) additionalPropertyCode(key) + else gen.if(isAdditional(key), () => additionalPropertyCode(key)) + }) + } + + function isAdditional(key: Name): Code { + let definedProp: Code + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = schemaRefOrVal(it, parentSchema.properties, "properties") + definedProp = isOwnProperty(gen, propsSchema as Code, key) + } else if (props.length) { + definedProp = or(...props.map((p) => _`${key} === ${p}`)) + } else { + definedProp = nil + } + if (patProps.length) { + definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`)) + } + return not(definedProp) + } + + function deleteAdditional(key: Name): void { + gen.code(_`delete ${data}[${key}]`) + } + + function additionalPropertyCode(key: Name): void { + if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { + deleteAdditional(key) + return + } + + if (schema === false) { + cxt.setParams({additionalProperty: key}) + cxt.error() + if (!allErrors) gen.break() + return + } + + if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.name("valid") + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false) + gen.if(not(valid), () => { + cxt.reset() + deleteAdditional(key) + }) + } else { + applyAdditionalSchema(key, valid) + if (!allErrors) gen.if(not(valid), () => gen.break()) + } + } + } + + function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void { + const subschema: SubschemaArgs = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: Type.Str, + } + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false, + }) + } + cxt.subschema(subschema, valid) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/allOf.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/allOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..cdfa86ff431396a7cf68b937cb9baa69d4e79f29 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/allOf.ts @@ -0,0 +1,22 @@ +import type {CodeKeywordDefinition, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "allOf", + schemaType: "array", + code(cxt: KeywordCxt) { + const {gen, schema, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const valid = gen.name("valid") + schema.forEach((sch: AnySchema, i: number) => { + if (alwaysValidSchema(it, sch)) return + const schCxt = cxt.subschema({keyword: "allOf", schemaProp: i}, valid) + cxt.ok(valid) + cxt.mergeEvaluated(schCxt) + }) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd331b5ae98a72f1a6d79aacdf2d4babd16bde35 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/anyOf.ts @@ -0,0 +1,14 @@ +import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" +import {validateUnion} from "../code" + +export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]> + +const def: CodeKeywordDefinition = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: validateUnion, + error: {message: "must match a schema in anyOf"}, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/contains.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/contains.ts new file mode 100644 index 0000000000000000000000000000000000000000..d88675c6c2a21db9fa9e0ce497646fda1bf5d5a6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/contains.ts @@ -0,0 +1,109 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode, Type} from "../../compile/util" + +export type ContainsError = ErrorObject< + "contains", + {minContains: number; maxContains?: number}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: ({params: {min, max}}) => + max === undefined + ? str`must contain at least ${min} valid item(s)` + : str`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({params: {min, max}}) => + max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, data, it} = cxt + let min: number + let max: number | undefined + const {minContains, maxContains} = parentSchema + if (it.opts.next) { + min = minContains === undefined ? 1 : minContains + max = maxContains + } else { + min = 1 + } + const len = gen.const("len", _`${data}.length`) + cxt.setParams({min, max}) + if (max === undefined && min === 0) { + checkStrictMode(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`) + return + } + if (max !== undefined && min > max) { + checkStrictMode(it, `"minContains" > "maxContains" is always invalid`) + cxt.fail() + return + } + if (alwaysValidSchema(it, schema)) { + let cond = _`${len} >= ${min}` + if (max !== undefined) cond = _`${cond} && ${len} <= ${max}` + cxt.pass(cond) + return + } + + it.items = true + const valid = gen.name("valid") + if (max === undefined && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())) + } else if (min === 0) { + gen.let(valid, true) + if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount) + } else { + gen.let(valid, false) + validateItemsWithCount() + } + cxt.result(valid, () => cxt.reset()) + + function validateItemsWithCount(): void { + const schValid = gen.name("_valid") + const count = gen.let("count", 0) + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))) + } + + function validateItems(_valid: Name, block: () => void): void { + gen.forRange("i", 0, len, (i) => { + cxt.subschema( + { + keyword: "contains", + dataProp: i, + dataPropType: Type.Num, + compositeRule: true, + }, + _valid + ) + block() + }) + } + + function checkLimits(count: Name): void { + gen.code(_`${count}++`) + if (max === undefined) { + gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break()) + } else { + gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break()) + if (min === 1) gen.assign(valid, true) + else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true)) + } + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6761128698689ce1d4699c33a3b128516157eeb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/dependencies.ts @@ -0,0 +1,112 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + SchemaMap, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from "../code" + +export type PropertyDependencies = {[K in string]?: string[]} + +export interface DependenciesErrorParams { + property: string + missingProperty: string + depsCount: number + deps: string // TODO change to string[] +} + +type SchemaDependencies = SchemaMap + +export type DependenciesError = ErrorObject< + "dependencies", + DependenciesErrorParams, + {[K in string]?: string[] | AnySchema} +> + +export const error: KeywordErrorDefinition = { + message: ({params: {property, depsCount, deps}}) => { + const property_ies = depsCount === 1 ? "property" : "properties" + return str`must have ${property_ies} ${deps} when property ${property} is present` + }, + params: ({params: {property, depsCount, deps, missingProperty}}) => + _`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}`, // TODO change to reference +} + +const def: CodeKeywordDefinition = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + const [propDeps, schDeps] = splitDependencies(cxt) + validatePropertyDeps(cxt, propDeps) + validateSchemaDeps(cxt, schDeps) + }, +} + +function splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] { + const propertyDeps: PropertyDependencies = {} + const schemaDeps: SchemaDependencies = {} + for (const key in schema) { + if (key === "__proto__") continue + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps + deps[key] = schema[key] + } + return [propertyDeps, schemaDeps] +} + +export function validatePropertyDeps( + cxt: KeywordCxt, + propertyDeps: {[K in string]?: string[]} = cxt.schema +): void { + const {gen, data, it} = cxt + if (Object.keys(propertyDeps).length === 0) return + const missing = gen.let("missing") + for (const prop in propertyDeps) { + const deps = propertyDeps[prop] as string[] + if (deps.length === 0) continue + const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties) + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", "), + }) + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + checkReportMissingProp(cxt, depProp) + } + }) + } else { + gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`) + reportMissingProp(cxt, missing) + gen.else() + } + } +} + +export function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void { + const {gen, data, keyword, it} = cxt + const valid = gen.name("valid") + for (const prop in schemaDeps) { + if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue + gen.if( + propertyInData(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid) + cxt.mergeValidEvaluated(schCxt, valid) + }, + () => gen.var(valid, true) // TODO var + ) + cxt.ok(valid) + } +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbd3ae45c38f2e0a4c958a83694eaf5844440e7e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/dependentSchemas.ts @@ -0,0 +1,11 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateSchemaDeps} from "./dependencies" + +const def: CodeKeywordDefinition = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => validateSchemaDeps(cxt), +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/if.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/if.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a40d5e3ad2ca0ee8bffb0bc10c361580a15378f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/if.ts @@ -0,0 +1,80 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {SchemaObjCxt} from "../../compile" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode} from "../../compile/util" + +export type IfKeywordError = ErrorObject<"if", {failingKeyword: string}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params}) => str`must match "${params.ifClause}" schema`, + params: ({params}) => _`{failingKeyword: ${params.ifClause}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, parentSchema, it} = cxt + if (parentSchema.then === undefined && parentSchema.else === undefined) { + checkStrictMode(it, '"if" without "then" and "else" is ignored') + } + const hasThen = hasSchema(it, "then") + const hasElse = hasSchema(it, "else") + if (!hasThen && !hasElse) return + + const valid = gen.let("valid", true) + const schValid = gen.name("_valid") + validateIf() + cxt.reset() + + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause") + cxt.setParams({ifClause}) + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)) + } else if (hasThen) { + gen.if(schValid, validateClause("then")) + } else { + gen.if(not(schValid), validateClause("else")) + } + + cxt.pass(valid, () => cxt.error(true)) + + function validateIf(): void { + const schCxt = cxt.subschema( + { + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false, + }, + schValid + ) + cxt.mergeEvaluated(schCxt) + } + + function validateClause(keyword: string, ifClause?: Name): () => void { + return () => { + const schCxt = cxt.subschema({keyword}, schValid) + gen.assign(valid, schValid) + cxt.mergeValidEvaluated(schCxt, valid) + if (ifClause) gen.assign(ifClause, _`${keyword}`) + else cxt.setParams({ifClause: keyword}) + } + } + }, +} + +function hasSchema(it: SchemaObjCxt, keyword: string): boolean { + const schema = it.schema[keyword] + return schema !== undefined && !alwaysValidSchema(it, schema) +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc527169967c8e3ae32b13ee19c9ad20dc5794cc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/index.ts @@ -0,0 +1,53 @@ +import type {ErrorNoParams, Vocabulary} from "../../types" +import additionalItems, {AdditionalItemsError} from "./additionalItems" +import prefixItems from "./prefixItems" +import items from "./items" +import items2020, {ItemsError} from "./items2020" +import contains, {ContainsError} from "./contains" +import dependencies, {DependenciesError} from "./dependencies" +import propertyNames, {PropertyNamesError} from "./propertyNames" +import additionalProperties, {AdditionalPropertiesError} from "./additionalProperties" +import properties from "./properties" +import patternProperties from "./patternProperties" +import notKeyword, {NotKeywordError} from "./not" +import anyOf, {AnyOfError} from "./anyOf" +import oneOf, {OneOfError} from "./oneOf" +import allOf from "./allOf" +import ifKeyword, {IfKeywordError} from "./if" +import thenElse from "./thenElse" + +export default function getApplicator(draft2020 = false): Vocabulary { + const applicator = [ + // any + notKeyword, + anyOf, + oneOf, + allOf, + ifKeyword, + thenElse, + // object + propertyNames, + additionalProperties, + dependencies, + properties, + patternProperties, + ] + // array + if (draft2020) applicator.push(prefixItems, items2020) + else applicator.push(additionalItems, items) + applicator.push(contains) + return applicator +} + +export type ApplicatorKeywordError = + | ErrorNoParams<"false schema"> + | AdditionalItemsError + | ItemsError + | ContainsError + | AdditionalPropertiesError + | DependenciesError + | IfKeywordError + | AnyOfError + | OneOfError + | NotKeywordError + | PropertyNamesError diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/items.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/items.ts new file mode 100644 index 0000000000000000000000000000000000000000..033cb3977342222bc90a44251bc9366b151cff9f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/items.ts @@ -0,0 +1,59 @@ +import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_} from "../../compile/codegen" +import {alwaysValidSchema, mergeEvaluated, checkStrictMode} from "../../compile/util" +import {validateArray} from "../code" + +const def: CodeKeywordDefinition = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt: KeywordCxt) { + const {schema, it} = cxt + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema) + it.items = true + if (alwaysValidSchema(it, schema)) return + cxt.ok(validateArray(cxt)) + }, +} + +export function validateTuple( + cxt: KeywordCxt, + extraItems: string, + schArr: AnySchema[] = cxt.schema +): void { + const {gen, parentSchema, data, keyword, it} = cxt + checkStrictTuple(parentSchema) + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = mergeEvaluated.items(gen, schArr.length, it.items) + } + const valid = gen.name("valid") + const len = gen.const("len", _`${data}.length`) + schArr.forEach((sch: AnySchema, i: number) => { + if (alwaysValidSchema(it, sch)) return + gen.if(_`${len} > ${i}`, () => + cxt.subschema( + { + keyword, + schemaProp: i, + dataProp: i, + }, + valid + ) + ) + cxt.ok(valid) + }) + + function checkStrictTuple(sch: AnySchemaObject): void { + const {opts, errSchemaPath} = it + const l = schArr.length + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false) + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"` + checkStrictMode(it, msg, opts.strictTuples) + } + } +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/items2020.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/items2020.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a99b08d59adc2ce8fc6c785a5ccc34c0960c1f9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/items2020.ts @@ -0,0 +1,36 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {validateArray} from "../code" +import {validateAdditionalItems} from "./additionalItems" + +export type ItemsError = ErrorObject<"items", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error, + code(cxt: KeywordCxt) { + const {schema, parentSchema, it} = cxt + const {prefixItems} = parentSchema + it.items = true + if (alwaysValidSchema(it, schema)) return + if (prefixItems) validateAdditionalItems(cxt, prefixItems) + else cxt.ok(validateArray(cxt)) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/not.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/not.ts new file mode 100644 index 0000000000000000000000000000000000000000..8691db0bf229b778f88a373110311dff1c69c1dc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/not.ts @@ -0,0 +1,38 @@ +import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" + +export type NotKeywordError = ErrorNoParams<"not", AnySchema> + +const def: CodeKeywordDefinition = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt: KeywordCxt) { + const {gen, schema, it} = cxt + if (alwaysValidSchema(it, schema)) { + cxt.fail() + return + } + + const valid = gen.name("valid") + cxt.subschema( + { + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false, + }, + valid + ) + + cxt.failResult( + valid, + () => cxt.reset(), + () => cxt.error() + ) + }, + error: {message: "must NOT be valid"}, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..c25353ffd648c45dce2433c14cb27841763d5435 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/oneOf.ts @@ -0,0 +1,82 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, Name} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" +import {SchemaCxt} from "../../compile" + +export type OneOfError = ErrorObject< + "oneOf", + {passingSchemas: [number, number] | null}, + AnySchema[] +> + +const error: KeywordErrorDefinition = { + message: "must match exactly one schema in oneOf", + params: ({params}) => _`{passingSchemas: ${params.passing}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + if (it.opts.discriminator && parentSchema.discriminator) return + const schArr: AnySchema[] = schema + const valid = gen.let("valid", false) + const passing = gen.let("passing", null) + const schValid = gen.name("_valid") + cxt.setParams({passing}) + // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas + + gen.block(validateOneOf) + + cxt.result( + valid, + () => cxt.reset(), + () => cxt.error(true) + ) + + function validateOneOf(): void { + schArr.forEach((sch: AnySchema, i: number) => { + let schCxt: SchemaCxt | undefined + if (alwaysValidSchema(it, sch)) { + gen.var(schValid, true) + } else { + schCxt = cxt.subschema( + { + keyword: "oneOf", + schemaProp: i, + compositeRule: true, + }, + schValid + ) + } + + if (i > 0) { + gen + .if(_`${schValid} && ${valid}`) + .assign(valid, false) + .assign(passing, _`[${passing}, ${i}]`) + .else() + } + + gen.if(schValid, () => { + gen.assign(valid, true) + gen.assign(passing, i) + if (schCxt) cxt.mergeEvaluated(schCxt, Name) + }) + }) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea624e230dddb3d71320eb5255a2b89bae5f20b0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts @@ -0,0 +1,91 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {allSchemaProperties, usePattern} from "../code" +import {_, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, checkStrictMode} from "../../compile/util" +import {evaluatedPropsToName, Type} from "../../compile/util" +import {AnySchema} from "../../types" + +const def: CodeKeywordDefinition = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt: KeywordCxt) { + const {gen, schema, data, parentSchema, it} = cxt + const {opts} = it + const patterns = allSchemaProperties(schema) + const alwaysValidPatterns = patterns.filter((p) => + alwaysValidSchema(it, schema[p] as AnySchema) + ) + + if ( + patterns.length === 0 || + (alwaysValidPatterns.length === patterns.length && + (!it.opts.unevaluated || it.props === true)) + ) { + return + } + + const checkProperties = + opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties + const valid = gen.name("valid") + if (it.props !== true && !(it.props instanceof Name)) { + it.props = evaluatedPropsToName(gen, it.props) + } + const {props} = it + validatePatternProperties() + + function validatePatternProperties(): void { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat) + if (it.allErrors) { + validateProperties(pat) + } else { + gen.var(valid, true) // TODO var + validateProperties(pat) + gen.if(valid) + } + } + } + + function checkMatchingProperties(pat: string): void { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + checkStrictMode( + it, + `property ${prop} matches pattern ${pat} (use allowMatchingProperties)` + ) + } + } + } + + function validateProperties(pat: string): void { + gen.forIn("key", data, (key) => { + gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat) + if (!alwaysValid) { + cxt.subschema( + { + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: Type.Str, + }, + valid + ) + } + + if (it.opts.unevaluated && props !== true) { + gen.assign(_`${props}[${key}]`, true) + } else if (!alwaysValid && !it.allErrors) { + // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) + // or if all properties were evaluated (props === true) + gen.if(not(valid), () => gen.break()) + } + }) + }) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..008fb2db1d8dd898fa79226d118530af2628c2c8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts @@ -0,0 +1,12 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateTuple} from "./items" + +const def: CodeKeywordDefinition = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => validateTuple(cxt, "items"), +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/properties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/properties.ts new file mode 100644 index 0000000000000000000000000000000000000000..a55b19ce5b77d180ce94cb063946a08d22824bd1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/properties.ts @@ -0,0 +1,57 @@ +import type {CodeKeywordDefinition} from "../../types" +import {KeywordCxt} from "../../compile/validate" +import {propertyInData, allSchemaProperties} from "../code" +import {alwaysValidSchema, toHash, mergeEvaluated} from "../../compile/util" +import apDef from "./additionalProperties" + +const def: CodeKeywordDefinition = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt: KeywordCxt) { + const {gen, schema, parentSchema, data, it} = cxt + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { + apDef.code(new KeywordCxt(it, apDef, "additionalProperties")) + } + const allProps = allSchemaProperties(schema) + for (const prop of allProps) { + it.definedProperties.add(prop) + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = mergeEvaluated.props(gen, toHash(allProps), it.props) + } + const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p])) + if (properties.length === 0) return + const valid = gen.name("valid") + + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop) + } else { + gen.if(propertyInData(gen, data, prop, it.opts.ownProperties)) + applyPropertySchema(prop) + if (!it.allErrors) gen.else().var(valid, true) + gen.endIf() + } + cxt.it.definedProperties.add(prop) + cxt.ok(valid) + } + + function hasDefault(prop: string): boolean | undefined { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined + } + + function applyPropertySchema(prop: string): void { + cxt.subschema( + { + keyword: "properties", + schemaProp: prop, + dataProp: prop, + }, + valid + ) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c54d605258600f3e98d4eeb17e87256be6b9f3f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts @@ -0,0 +1,50 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, not} from "../../compile/codegen" +import {alwaysValidSchema} from "../../compile/util" + +export type PropertyNamesError = ErrorObject<"propertyNames", {propertyName: string}, AnySchema> + +const error: KeywordErrorDefinition = { + message: "property name must be valid", + params: ({params}) => _`{propertyName: ${params.propertyName}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error, + code(cxt: KeywordCxt) { + const {gen, schema, data, it} = cxt + if (alwaysValidSchema(it, schema)) return + const valid = gen.name("valid") + + gen.forIn("key", data, (key) => { + cxt.setParams({propertyName: key}) + cxt.subschema( + { + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true, + }, + valid + ) + gen.if(not(valid), () => { + cxt.error(true) + if (!it.allErrors) gen.break() + }) + }) + + cxt.ok(valid) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts new file mode 100644 index 0000000000000000000000000000000000000000..5055182e89141a257630516d96a52ec2917f72b6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/applicator/thenElse.ts @@ -0,0 +1,13 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({keyword, parentSchema, it}: KeywordCxt) { + if (parentSchema.if === undefined) checkStrictMode(it, `"${keyword}" without "if" is ignored`) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/code.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/code.ts new file mode 100644 index 0000000000000000000000000000000000000000..92cdd5b04ef30e0ed6f3c9025752f0acf59370eb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/code.ts @@ -0,0 +1,168 @@ +import type {AnySchema, SchemaMap} from "../types" +import type {SchemaCxt} from "../compile" +import type {KeywordCxt} from "../compile/validate" +import {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from "../compile/codegen" +import {alwaysValidSchema, Type} from "../compile/util" +import N from "../compile/names" +import {useFunc} from "../compile/util" +export function checkReportMissingProp(cxt: KeywordCxt, prop: string): void { + const {gen, data, it} = cxt + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({missingProperty: _`${prop}`}, true) + cxt.error() + }) +} + +export function checkMissingProp( + {gen, data, it: {opts}}: KeywordCxt, + properties: string[], + missing: Name +): Code { + return or( + ...properties.map((prop) => + and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`) + ) + ) +} + +export function reportMissingProp(cxt: KeywordCxt, missing: Name): void { + cxt.setParams({missingProperty: missing}, true) + cxt.error() +} + +export function hasPropFunc(gen: CodeGen): Name { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: _`Object.prototype.hasOwnProperty`, + }) +} + +export function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code { + return _`${hasPropFunc(gen)}.call(${data}, ${property})` +} + +export function propertyInData( + gen: CodeGen, + data: Name, + property: Name | string, + ownProperties?: boolean +): Code { + const cond = _`${data}${getProperty(property)} !== undefined` + return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond +} + +export function noPropertyInData( + gen: CodeGen, + data: Name, + property: Name | string, + ownProperties?: boolean +): Code { + const cond = _`${data}${getProperty(property)} === undefined` + return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond +} + +export function allSchemaProperties(schemaMap?: SchemaMap): string[] { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [] +} + +export function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] { + return allSchemaProperties(schemaMap).filter( + (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema) + ) +} + +export function callValidateCode( + {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt, + func: Code, + context: Code, + passSchema?: boolean +): Code { + const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data + const valCxt: [Name, Code | number][] = [ + [N.instancePath, strConcat(N.instancePath, errorPath)], + [N.parentData, it.parentData], + [N.parentDataProperty, it.parentDataProperty], + [N.rootData, N.rootData], + ] + if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors]) + const args = _`${dataAndSchema}, ${gen.object(...valCxt)}` + return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})` +} + +const newRegExp = _`new RegExp` + +export function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name { + const u = opts.unicodeRegExp ? "u" : "" + const {regExp} = opts.code + const rx = regExp(pattern, u) + + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: _`${regExp.code === "new RegExp" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`, + }) +} + +export function validateArray(cxt: KeywordCxt): Name { + const {gen, data, keyword, it} = cxt + const valid = gen.name("valid") + if (it.allErrors) { + const validArr = gen.let("valid", true) + validateItems(() => gen.assign(validArr, false)) + return validArr + } + gen.var(valid, true) + validateItems(() => gen.break()) + return valid + + function validateItems(notValid: () => void): void { + const len = gen.const("len", _`${data}.length`) + gen.forRange("i", 0, len, (i) => { + cxt.subschema( + { + keyword, + dataProp: i, + dataPropType: Type.Num, + }, + valid + ) + gen.if(not(valid), notValid) + }) + } +} + +export function validateUnion(cxt: KeywordCxt): void { + const {gen, schema, keyword, it} = cxt + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch)) + if (alwaysValid && !it.opts.unevaluated) return + + const valid = gen.let("valid", false) + const schValid = gen.name("_valid") + + gen.block(() => + schema.forEach((_sch: AnySchema, i: number) => { + const schCxt = cxt.subschema( + { + keyword, + schemaProp: i, + compositeRule: true, + }, + schValid + ) + gen.assign(valid, _`${valid} || ${schValid}`) + const merged = cxt.mergeValidEvaluated(schCxt, schValid) + // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true) + // or if all properties and items were evaluated (it.props === true && it.items === true) + if (!merged) gen.if(not(valid)) + }) + ) + + cxt.result( + valid, + () => cxt.reset(), + () => cxt.error(true) + ) +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/core/id.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/core/id.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa36c4bb20f45046bb46fc998ca39fa2d9589811 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/core/id.ts @@ -0,0 +1,10 @@ +import type {CodeKeywordDefinition} from "../../types" + +const def: CodeKeywordDefinition = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID') + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/core/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/core/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e63e2895d08710745fe5785bbdb1aaf155e05407 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/core/index.ts @@ -0,0 +1,16 @@ +import type {Vocabulary} from "../../types" +import idKeyword from "./id" +import refKeyword from "./ref" + +const core: Vocabulary = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + {keyword: "$comment"}, + "definitions", + idKeyword, + refKeyword, +] + +export default core diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/core/ref.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/core/ref.ts new file mode 100644 index 0000000000000000000000000000000000000000..5d59fbcb2a99564106fdcafe244f693bc88e3ea2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/core/ref.ts @@ -0,0 +1,129 @@ +import type {CodeKeywordDefinition, AnySchema} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import MissingRefError from "../../compile/ref_error" +import {callValidateCode} from "../code" +import {_, nil, stringify, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import {SchemaEnv, resolveRef} from "../../compile" +import {mergeEvaluated} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "$ref", + schemaType: "string", + code(cxt: KeywordCxt): void { + const {gen, schema: $ref, it} = cxt + const {baseId, schemaEnv: env, validateName, opts, self} = it + const {root} = env + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef() + const schOrEnv = resolveRef.call(self, root, baseId, $ref) + if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref) + if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv) + return inlineRefSchema(schOrEnv) + + function callRootRef(): void { + if (env === root) return callRef(cxt, validateName, env, env.$async) + const rootName = gen.scopeValue("root", {ref: root}) + return callRef(cxt, _`${rootName}.validate`, root, root.$async) + } + + function callValidate(sch: SchemaEnv): void { + const v = getValidate(cxt, sch) + callRef(cxt, v, sch, sch.$async) + } + + function inlineRefSchema(sch: AnySchema): void { + const schName = gen.scopeValue( + "schema", + opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch} + ) + const valid = gen.name("valid") + const schCxt = cxt.subschema( + { + schema: sch, + dataTypes: [], + schemaPath: nil, + topSchemaRef: schName, + errSchemaPath: $ref, + }, + valid + ) + cxt.mergeEvaluated(schCxt) + cxt.ok(valid) + } + }, +} + +export function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code { + const {gen} = cxt + return sch.validate + ? gen.scopeValue("validate", {ref: sch.validate}) + : _`${gen.scopeValue("wrapper", {ref: sch})}.validate` +} + +export function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void { + const {gen, it} = cxt + const {allErrors, schemaEnv: env, opts} = it + const passCxt = opts.passContext ? N.this : nil + if ($async) callAsyncRef() + else callSyncRef() + + function callAsyncRef(): void { + if (!env.$async) throw new Error("async schema referenced by sync schema") + const valid = gen.let("valid") + gen.try( + () => { + gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`) + addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result + if (!allErrors) gen.assign(valid, true) + }, + (e) => { + gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e)) + addErrorsFrom(e) + if (!allErrors) gen.assign(valid, false) + } + ) + cxt.ok(valid) + } + + function callSyncRef(): void { + cxt.result( + callValidateCode(cxt, v, passCxt), + () => addEvaluatedFrom(v), + () => addErrorsFrom(v) + ) + } + + function addErrorsFrom(source: Code): void { + const errs = _`${source}.errors` + gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged + gen.assign(N.errors, _`${N.vErrors}.length`) + } + + function addEvaluatedFrom(source: Code): void { + if (!it.opts.unevaluated) return + const schEvaluated = sch?.validate?.evaluated + // TODO refactor + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== undefined) { + it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props) + } + } else { + const props = gen.var("props", _`${source}.evaluated.props`) + it.props = mergeEvaluated.props(gen, props, it.props, Name) + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== undefined) { + it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items) + } + } else { + const items = gen.var("items", _`${source}.evaluated.items`) + it.items = mergeEvaluated.items(gen, items, it.items, Name) + } + } + } +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/discriminator/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/discriminator/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..19ae6049f3464d2dd7518de70a9f10842aa88d66 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/discriminator/index.ts @@ -0,0 +1,113 @@ +import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Name} from "../../compile/codegen" +import {DiscrError, DiscrErrorObj} from "../discriminator/types" +import {resolveRef, SchemaEnv} from "../../compile" +import MissingRefError from "../../compile/ref_error" +import {schemaHasRulesButRef} from "../../compile/util" + +export type DiscriminatorError = DiscrErrorObj | DiscrErrorObj + +const error: KeywordErrorDefinition = { + message: ({params: {discrError, tagName}}) => + discrError === DiscrError.Tag + ? `tag "${tagName}" must be string` + : `value of tag "${tagName}" must be in oneOf`, + params: ({params: {discrError, tag, tagName}}) => + _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + const {gen, data, schema, parentSchema, it} = cxt + const {oneOf} = parentSchema + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option") + } + const tagName = schema.propertyName + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName") + if (schema.mapping) throw new Error("discriminator: mapping is not supported") + if (!oneOf) throw new Error("discriminator: requires oneOf keyword") + const valid = gen.let("valid", false) + const tag = gen.const("tag", _`${data}${getProperty(tagName)}`) + gen.if( + _`typeof ${tag} == "string"`, + () => validateMapping(), + () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName}) + ) + cxt.ok(valid) + + function validateMapping(): void { + const mapping = getMapping() + gen.if(false) + for (const tagValue in mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + gen.assign(valid, applyTagSchema(mapping[tagValue])) + } + gen.else() + cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName}) + gen.endIf() + } + + function applyTagSchema(schemaProp?: number): Name { + const _valid = gen.name("valid") + const schCxt = cxt.subschema({keyword: "oneOf", schemaProp}, _valid) + cxt.mergeEvaluated(schCxt, Name) + return _valid + } + + function getMapping(): {[T in string]?: number} { + const oneOfMapping: {[T in string]?: number} = {} + const topRequired = hasRequired(parentSchema) + let tagRequired = true + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i] + if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) { + const ref = sch.$ref + sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref) + if (sch instanceof SchemaEnv) sch = sch.schema + if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref) + } + const propSch = sch?.properties?.[tagName] + if (typeof propSch != "object") { + throw new Error( + `discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"` + ) + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)) + addMappings(propSch, i) + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`) + return oneOfMapping + + function hasRequired({required}: AnySchemaObject): boolean { + return Array.isArray(required) && required.includes(tagName) + } + + function addMappings(sch: AnySchemaObject, i: number): void { + if (sch.const) { + addMapping(sch.const, i) + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i) + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`) + } + } + + function addMapping(tagValue: unknown, i: number): void { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`) + } + oneOfMapping[tagValue] = i + } + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/discriminator/types.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/discriminator/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..bee5a278508e4926b85cf397fb601a7a3c2a78cb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/discriminator/types.ts @@ -0,0 +1,12 @@ +import type {ErrorObject} from "../../types" + +export enum DiscrError { + Tag = "tag", + Mapping = "mapping", +} + +export type DiscrErrorObj = ErrorObject< + "discriminator", + {error: E; tag: string; tagValue: unknown}, + string +> diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/draft2020.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/draft2020.ts new file mode 100644 index 0000000000000000000000000000000000000000..47fbf0ee6d75112abf222611ca514973833c8b53 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/draft2020.ts @@ -0,0 +1,23 @@ +import type {Vocabulary} from "../types" +import coreVocabulary from "./core" +import validationVocabulary from "./validation" +import getApplicatorVocabulary from "./applicator" +import dynamicVocabulary from "./dynamic" +import nextVocabulary from "./next" +import unevaluatedVocabulary from "./unevaluated" +import formatVocabulary from "./format" +import {metadataVocabulary, contentVocabulary} from "./metadata" + +const draft2020Vocabularies: Vocabulary[] = [ + dynamicVocabulary, + coreVocabulary, + validationVocabulary, + getApplicatorVocabulary(true), + formatVocabulary, + metadataVocabulary, + contentVocabulary, + nextVocabulary, + unevaluatedVocabulary, +] + +export default draft2020Vocabularies diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/draft7.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/draft7.ts new file mode 100644 index 0000000000000000000000000000000000000000..226a644aa428d808c22dfd6808392fada925ae5e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/draft7.ts @@ -0,0 +1,17 @@ +import type {Vocabulary} from "../types" +import coreVocabulary from "./core" +import validationVocabulary from "./validation" +import getApplicatorVocabulary from "./applicator" +import formatVocabulary from "./format" +import {metadataVocabulary, contentVocabulary} from "./metadata" + +const draft7Vocabularies: Vocabulary[] = [ + coreVocabulary, + validationVocabulary, + getApplicatorVocabulary(), + formatVocabulary, + metadataVocabulary, + contentVocabulary, +] + +export default draft7Vocabularies diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca1adb912af0347a3bb8e18ca50cf51405f2ba1f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/dynamicAnchor.ts @@ -0,0 +1,31 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Code} from "../../compile/codegen" +import N from "../../compile/names" +import {SchemaEnv, compileSchema} from "../../compile" +import {getValidate} from "../core/ref" + +const def: CodeKeywordDefinition = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema), +} + +export function dynamicAnchor(cxt: KeywordCxt, anchor: string): void { + const {gen, it} = cxt + it.schemaEnv.root.dynamicAnchors[anchor] = true + const v = _`${N.dynamicAnchors}${getProperty(anchor)}` + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt) + gen.if(_`!${v}`, () => gen.assign(v, validate)) +} + +function _getValidate(cxt: KeywordCxt): Code { + const {schemaEnv, schema, self} = cxt.it + const {root, baseId, localRefs, meta} = schemaEnv.root + const {schemaId} = self.opts + const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta}) + compileSchema.call(self, sch) + return getValidate(cxt, sch) +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a573f33024b4fc5045f17f0c251a3d6c75a22a7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/dynamicRef.ts @@ -0,0 +1,51 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, getProperty, Code, Name} from "../../compile/codegen" +import N from "../../compile/names" +import {callRef} from "../core/ref" + +const def: CodeKeywordDefinition = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +} + +export function dynamicRef(cxt: KeywordCxt, ref: string): void { + const {gen, keyword, it} = cxt + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`) + const anchor = ref.slice(1) + if (it.allErrors) { + _dynamicRef() + } else { + const valid = gen.let("valid", false) + _dynamicRef(valid) + cxt.ok(valid) + } + + function _dynamicRef(valid?: Name): void { + // TODO the assumption here is that `recursiveRef: #` always points to the root + // of the schema object, which is not correct, because there may be $id that + // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. + // Because of that 2 tests in recursiveRef.json fail. + // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). + // (This problem is not tested in JSON-Schema-Test-Suite) + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", _`${N.dynamicAnchors}${getProperty(anchor)}`) + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)) + } else { + _callRef(it.validateName, valid)() + } + } + + function _callRef(validate: Code, valid?: Name): () => void { + return valid + ? () => + gen.block(() => { + callRef(cxt, validate) + gen.let(valid, true) + }) + : () => callRef(cxt, validate) + } +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d521db6638b890151a7a901991f91793553dab0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/index.ts @@ -0,0 +1,9 @@ +import type {Vocabulary} from "../../types" +import dynamicAnchor from "./dynamicAnchor" +import dynamicRef from "./dynamicRef" +import recursiveAnchor from "./recursiveAnchor" +import recursiveRef from "./recursiveRef" + +const dynamic: Vocabulary = [dynamicAnchor, dynamicRef, recursiveAnchor, recursiveRef] + +export default dynamic diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts new file mode 100644 index 0000000000000000000000000000000000000000..25f3db96bf07a2c60fc3eb860ea93ee6337e0137 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/recursiveAnchor.ts @@ -0,0 +1,14 @@ +import type {CodeKeywordDefinition} from "../../types" +import {dynamicAnchor} from "./dynamicAnchor" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) dynamicAnchor(cxt, "") + else checkStrictMode(cxt.it, "$recursiveAnchor: false is ignored") + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts new file mode 100644 index 0000000000000000000000000000000000000000..c84af0f05785affe11983f39f605a53502358c67 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/dynamic/recursiveRef.ts @@ -0,0 +1,10 @@ +import type {CodeKeywordDefinition} from "../../types" +import {dynamicRef} from "./dynamicRef" + +const def: CodeKeywordDefinition = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema), +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/errors.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9ca3f02f040298cd2b2faff35740eaae6ea098e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/errors.ts @@ -0,0 +1,18 @@ +import type {TypeError} from "../compile/validate/dataType" +import type {ApplicatorKeywordError} from "./applicator" +import type {ValidationKeywordError} from "./validation" +import type {FormatError} from "./format/format" +import type {UnevaluatedPropertiesError} from "./unevaluated/unevaluatedProperties" +import type {UnevaluatedItemsError} from "./unevaluated/unevaluatedItems" +import type {DependentRequiredError} from "./validation/dependentRequired" +import type {DiscriminatorError} from "./discriminator" + +export type DefinedError = + | TypeError + | ApplicatorKeywordError + | ValidationKeywordError + | FormatError + | UnevaluatedPropertiesError + | UnevaluatedItemsError + | DependentRequiredError + | DiscriminatorError diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/format/format.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/format/format.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b1c13e764375dbb4dff021426a377f8103ab54f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/format/format.ts @@ -0,0 +1,120 @@ +import type { + AddedFormat, + FormatValidator, + AsyncFormatValidator, + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, nil, or, Code, getProperty, regexpCode} from "../../compile/codegen" + +type FormatValidate = + | FormatValidator + | FormatValidator + | AsyncFormatValidator + | AsyncFormatValidator + | RegExp + | string + | true + +export type FormatError = ErrorObject<"format", {format: string}, string | {$data: string}> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must match format "${schemaCode}"`, + params: ({schemaCode}) => _`{format: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error, + code(cxt: KeywordCxt, ruleType?: string) { + const {gen, data, $data, schema, schemaCode, it} = cxt + const {opts, errSchemaPath, schemaEnv, self} = it + if (!opts.validateFormats) return + + if ($data) validate$DataFormat() + else validateFormat() + + function validate$DataFormat(): void { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats, + }) + const fDef = gen.const("fDef", _`${fmts}[${schemaCode}]`) + const fType = gen.let("fType") + const format = gen.let("format") + // TODO simplify + gen.if( + _`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, + () => gen.assign(fType, _`${fDef}.type || "string"`).assign(format, _`${fDef}.validate`), + () => gen.assign(fType, _`"string"`).assign(format, fDef) + ) + cxt.fail$data(or(unknownFmt(), invalidFmt())) + + function unknownFmt(): Code { + if (opts.strictSchema === false) return nil + return _`${schemaCode} && !${format}` + } + + function invalidFmt(): Code { + const callFormat = schemaEnv.$async + ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` + : _`${format}(${data})` + const validData = _`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))` + return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}` + } + } + + function validateFormat(): void { + const formatDef: AddedFormat | undefined = self.formats[schema] + if (!formatDef) { + unknownFormat() + return + } + if (formatDef === true) return + const [fmtType, format, fmtRef] = getFormat(formatDef) + if (fmtType === ruleType) cxt.pass(validCondition()) + + function unknownFormat(): void { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()) + return + } + throw new Error(unknownMsg()) + + function unknownMsg(): string { + return `unknown format "${schema as string}" ignored in schema at path "${errSchemaPath}"` + } + } + + function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] { + const code = + fmtDef instanceof RegExp + ? regexpCode(fmtDef) + : opts.code.formats + ? _`${opts.code.formats}${getProperty(schema)}` + : undefined + const fmt = gen.scopeValue("formats", {key: schema, ref: fmtDef, code}) + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, _`${fmt}.validate`] + } + + return ["string", fmtDef, fmt] + } + + function validCondition(): Code { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema") + return _`await ${fmtRef}(${data})` + } + return typeof format == "function" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})` + } + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/format/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/format/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..bca2f5b3d817051e07bd768888ed7142e63c4c97 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/format/index.ts @@ -0,0 +1,6 @@ +import type {Vocabulary} from "../../types" +import formatKeyword from "./format" + +const format: Vocabulary = [formatKeyword] + +export default format diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts new file mode 100644 index 0000000000000000000000000000000000000000..f487c97f84332592ca90b09d5c046a87afd57f9b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/discriminator.ts @@ -0,0 +1,89 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, not, getProperty, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" +import {DiscrError, DiscrErrorObj} from "../discriminator/types" + +export type JTDDiscriminatorError = + | _JTDTypeError<"discriminator", "object", string> + | DiscrErrorObj + | DiscrErrorObj + +const error: KeywordErrorDefinition = { + message: (cxt) => { + const {schema, params} = cxt + return params.discrError + ? params.discrError === DiscrError.Tag + ? `tag "${schema}" must be string` + : `value of tag "${schema}" must be in mapping` + : typeErrorMessage(cxt, "object") + }, + params: (cxt) => { + const {schema, params} = cxt + return params.discrError + ? _`{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}` + : typeErrorParams(cxt, "object") + }, +} + +const def: CodeKeywordDefinition = { + keyword: "discriminator", + schemaType: "string", + implements: ["mapping"], + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, parentSchema} = cxt + const [valid, cond] = checkNullableObject(cxt, data) + + gen.if(cond) + validateDiscriminator() + gen.elseIf(not(valid)) + cxt.error() + gen.endIf() + cxt.ok(valid) + + function validateDiscriminator(): void { + const tag = gen.const("tag", _`${data}${getProperty(schema)}`) + gen.if(_`${tag} === undefined`) + cxt.error(false, {discrError: DiscrError.Tag, tag}) + gen.elseIf(_`typeof ${tag} == "string"`) + validateMapping(tag) + gen.else() + cxt.error(false, {discrError: DiscrError.Tag, tag}, {instancePath: schema}) + gen.endIf() + } + + function validateMapping(tag: Name): void { + gen.if(false) + for (const tagValue in parentSchema.mapping) { + gen.elseIf(_`${tag} === ${tagValue}`) + gen.assign(valid, applyTagSchema(tagValue)) + } + gen.else() + cxt.error( + false, + {discrError: DiscrError.Mapping, tag}, + {instancePath: schema, schemaPath: "mapping", parentSchema: true} + ) + gen.endIf() + } + + function applyTagSchema(schemaProp: string): Name { + const _valid = gen.name("valid") + cxt.subschema( + { + keyword: "mapping", + schemaProp, + jtdDiscriminator: schema, + }, + _valid + ) + return _valid + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/elements.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/elements.ts new file mode 100644 index 0000000000000000000000000000000000000000..983af7c0276ed83cf92e5071a2a8a63ef2d522e4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/elements.ts @@ -0,0 +1,32 @@ +import type {CodeKeywordDefinition, SchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema} from "../../compile/util" +import {validateArray} from "../code" +import {_, not} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullable} from "./nullable" +import {typeError, _JTDTypeError} from "./error" + +export type JTDElementsError = _JTDTypeError<"elements", "array", SchemaObject> + +const def: CodeKeywordDefinition = { + keyword: "elements", + schemaType: "object", + error: typeError("array"), + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, it} = cxt + if (alwaysValidSchema(it, schema)) return + const [valid] = checkNullable(cxt) + gen.if(not(valid), () => + gen.if( + _`Array.isArray(${data})`, + () => gen.assign(valid, validateArray(cxt)), + () => cxt.error() + ) + ) + cxt.ok(valid) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/enum.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/enum.ts new file mode 100644 index 0000000000000000000000000000000000000000..75464ff8e13f581679d2b33662f34ac79a23e912 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/enum.ts @@ -0,0 +1,45 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, or, and, Code} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullable} from "./nullable" + +export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]> + +const error: KeywordErrorDefinition = { + message: "must be equal to one of the allowed values", + params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "enum", + schemaType: "array", + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, schemaValue, parentSchema, it} = cxt + if (schema.length === 0) throw new Error("enum must have non-empty array") + if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique") + let valid: Code + const isString = _`typeof ${data} == "string"` + if (schema.length >= it.opts.loopEnum) { + let cond: Code + ;[valid, cond] = checkNullable(cxt, isString) + gen.if(cond, loopEnum) + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`))) + if (parentSchema.nullable) valid = or(_`${data} === null`, valid) + } + cxt.pass(valid) + + function loopEnum(): void { + gen.forOf("v", schemaValue as Code, (v) => + gen.if(_`${valid} = ${data} === ${v}`, () => gen.break()) + ) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/error.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/error.ts new file mode 100644 index 0000000000000000000000000000000000000000..5069322588ebc486795ec075e49777888bbd8cdf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/error.ts @@ -0,0 +1,23 @@ +import type {KeywordErrorDefinition, KeywordErrorCxt, ErrorObject} from "../../types" +import {_, Code} from "../../compile/codegen" + +export type _JTDTypeError = ErrorObject< + K, + {type: T; nullable: boolean}, + S +> + +export function typeError(t: string): KeywordErrorDefinition { + return { + message: (cxt) => typeErrorMessage(cxt, t), + params: (cxt) => typeErrorParams(cxt, t), + } +} + +export function typeErrorMessage({parentSchema}: KeywordErrorCxt, t: string): string { + return parentSchema?.nullable ? `must be ${t} or null` : `must be ${t}` +} + +export function typeErrorParams({parentSchema}: KeywordErrorCxt, t: string): Code { + return _`{type: ${t}, nullable: ${!!parentSchema?.nullable}}` +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7baebc30788d80498e59328809b6b6a312d3315 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/index.ts @@ -0,0 +1,37 @@ +import type {Vocabulary} from "../../types" +import refKeyword from "./ref" +import typeKeyword, {JTDTypeError} from "./type" +import enumKeyword, {JTDEnumError} from "./enum" +import elements, {JTDElementsError} from "./elements" +import properties, {JTDPropertiesError} from "./properties" +import optionalProperties from "./optionalProperties" +import discriminator, {JTDDiscriminatorError} from "./discriminator" +import values, {JTDValuesError} from "./values" +import union from "./union" +import metadata from "./metadata" + +const jtdVocabulary: Vocabulary = [ + "definitions", + refKeyword, + typeKeyword, + enumKeyword, + elements, + properties, + optionalProperties, + discriminator, + values, + union, + metadata, + {keyword: "additionalProperties", schemaType: "boolean"}, + {keyword: "nullable", schemaType: "boolean"}, +] + +export default jtdVocabulary + +export type JTDErrorObject = + | JTDTypeError + | JTDEnumError + | JTDElementsError + | JTDPropertiesError + | JTDDiscriminatorError + | JTDValuesError diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/metadata.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/metadata.ts new file mode 100644 index 0000000000000000000000000000000000000000..19eeb8c7d5b8f6ed1ab794cc0368f67d4be8bb8a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/metadata.ts @@ -0,0 +1,24 @@ +import {KeywordCxt} from "../../ajv" +import type {CodeKeywordDefinition} from "../../types" +import {alwaysValidSchema} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: "metadata", + schemaType: "object", + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, schema, it} = cxt + if (alwaysValidSchema(it, schema)) return + const valid = gen.name("valid") + cxt.subschema({keyword: "metadata", jtdMetadata: true}, valid) + cxt.ok(valid) + }, +} + +export function checkMetadata({it, keyword}: KeywordCxt, metadata?: boolean): void { + if (it.jtdMetadata !== metadata) { + throw new Error(`JTD: "${keyword}" cannot be used in this schema location`) + } +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/nullable.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/nullable.ts new file mode 100644 index 0000000000000000000000000000000000000000..c74b05da72dbd4694ac215d5e5616e9050db283c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/nullable.ts @@ -0,0 +1,21 @@ +import type {KeywordCxt} from "../../compile/validate" +import {_, not, nil, Code, Name} from "../../compile/codegen" + +export function checkNullable( + {gen, data, parentSchema}: KeywordCxt, + cond: Code = nil +): [Name, Code] { + const valid = gen.name("valid") + if (parentSchema.nullable) { + gen.let(valid, _`${data} === null`) + cond = not(valid) + } else { + gen.let(valid, false) + } + return [valid, cond] +} + +export function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] { + const [valid, cond_] = checkNullable(cxt, cond) + return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`] +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e91c8d91874407585b29641f22457822079fd66 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/optionalProperties.ts @@ -0,0 +1,15 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {validateProperties, error} from "./properties" + +const def: CodeKeywordDefinition = { + keyword: "optionalProperties", + schemaType: "object", + error, + code(cxt: KeywordCxt) { + if (cxt.parentSchema.properties) return + validateProperties(cxt) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/properties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/properties.ts new file mode 100644 index 0000000000000000000000000000000000000000..9dd24c5cd62d46a913d644636fc9eacbb7f8a4fe --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/properties.ts @@ -0,0 +1,184 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + SchemaObject, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {propertyInData, allSchemaProperties, isOwnProperty} from "../code" +import {alwaysValidSchema, schemaRefOrVal} from "../../compile/util" +import {_, and, not, Code, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" + +enum PropError { + Additional = "additional", + Missing = "missing", +} + +type PropKeyword = "properties" | "optionalProperties" + +type PropSchema = {[P in string]?: SchemaObject} + +export type JTDPropertiesError = + | _JTDTypeError + | ErrorObject + | ErrorObject + +export const error: KeywordErrorDefinition = { + message: (cxt) => { + const {params} = cxt + return params.propError + ? params.propError === PropError.Additional + ? "must NOT have additional properties" + : `must have property '${params.missingProperty}'` + : typeErrorMessage(cxt, "object") + }, + params: (cxt) => { + const {params} = cxt + return params.propError + ? params.propError === PropError.Additional + ? _`{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}` + : _`{error: ${params.propError}, missingProperty: ${params.missingProperty}}` + : typeErrorParams(cxt, "object") + }, +} + +const def: CodeKeywordDefinition = { + keyword: "properties", + schemaType: "object", + error, + code: validateProperties, +} + +// const error: KeywordErrorDefinition = { +// message: "should NOT have additional properties", +// params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`, +// } + +export function validateProperties(cxt: KeywordCxt): void { + checkMetadata(cxt) + const {gen, data, parentSchema, it} = cxt + const {additionalProperties, nullable} = parentSchema + if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping") + if (commonProperties()) { + throw new Error("JTD: properties and optionalProperties have common members") + } + const [allProps, properties] = schemaProperties("properties") + const [allOptProps, optProperties] = schemaProperties("optionalProperties") + if (properties.length === 0 && optProperties.length === 0 && additionalProperties) { + return + } + + const [valid, cond] = + it.jtdDiscriminator === undefined + ? checkNullableObject(cxt, data) + : [gen.let("valid", false), true] + gen.if(cond, () => + gen.assign(valid, true).block(() => { + validateProps(properties, "properties", true) + validateProps(optProperties, "optionalProperties") + if (!additionalProperties) validateAdditional() + }) + ) + cxt.pass(valid) + + function commonProperties(): boolean { + const props = parentSchema.properties as Record | undefined + const optProps = parentSchema.optionalProperties as Record | undefined + if (!(props && optProps)) return false + for (const p in props) { + if (Object.prototype.hasOwnProperty.call(optProps, p)) return true + } + return false + } + + function schemaProperties(keyword: string): [string[], string[]] { + const schema = parentSchema[keyword] + const allPs = schema ? allSchemaProperties(schema) : [] + if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) { + throw new Error(`JTD: discriminator tag used in ${keyword}`) + } + const ps = allPs.filter((p) => !alwaysValidSchema(it, schema[p])) + return [allPs, ps] + } + + function validateProps(props: string[], keyword: string, required?: boolean): void { + const _valid = gen.var("valid") + for (const prop of props) { + gen.if( + propertyInData(gen, data, prop, it.opts.ownProperties), + () => applyPropertySchema(prop, keyword, _valid), + () => missingProperty(prop) + ) + cxt.ok(_valid) + } + + function missingProperty(prop: string): void { + if (required) { + gen.assign(_valid, false) + cxt.error(false, {propError: PropError.Missing, missingProperty: prop}, {schemaPath: prop}) + } else { + gen.assign(_valid, true) + } + } + } + + function applyPropertySchema(prop: string, keyword: string, _valid: Name): void { + cxt.subschema( + { + keyword, + schemaProp: prop, + dataProp: prop, + }, + _valid + ) + } + + function validateAdditional(): void { + gen.forIn("key", data, (key: Name) => { + const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator) + const addOptProp = isAdditional(key, allOptProps, "optionalProperties") + const extra = + addProp === true ? addOptProp : addOptProp === true ? addProp : and(addProp, addOptProp) + gen.if(extra, () => { + if (it.opts.removeAdditional) { + gen.code(_`delete ${data}[${key}]`) + } else { + cxt.error( + false, + {propError: PropError.Additional, additionalProperty: key}, + {instancePath: key, parentSchema: true} + ) + if (!it.opts.allErrors) gen.break() + } + }) + }) + } + + function isAdditional( + key: Name, + props: string[], + keyword: string, + jtdDiscriminator?: string + ): Code | true { + let additional: Code | boolean + if (props.length > 8) { + // TODO maybe an option instead of hard-coded 8? + const propsSchema = schemaRefOrVal(it, parentSchema[keyword], keyword) + additional = not(isOwnProperty(gen, propsSchema as Code, key)) + if (jtdDiscriminator !== undefined) { + additional = and(additional, _`${key} !== ${jtdDiscriminator}`) + } + } else if (props.length || jtdDiscriminator !== undefined) { + const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props) + additional = and(...ps.map((p) => _`${key} !== ${p}`)) + } else { + additional = true + } + return additional + } +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/ref.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/ref.ts new file mode 100644 index 0000000000000000000000000000000000000000..97646ee1b68885bf004ce2e629421abac07a991d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/ref.ts @@ -0,0 +1,76 @@ +import type {CodeKeywordDefinition, AnySchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {compileSchema, SchemaEnv} from "../../compile" +import {_, not, nil, stringify} from "../../compile/codegen" +import MissingRefError from "../../compile/ref_error" +import N from "../../compile/names" +import {getValidate, callRef} from "../core/ref" +import {checkMetadata} from "./metadata" + +const def: CodeKeywordDefinition = { + keyword: "ref", + schemaType: "string", + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema: ref, parentSchema, it} = cxt + const { + schemaEnv: {root}, + } = it + const valid = gen.name("valid") + if (parentSchema.nullable) { + gen.var(valid, _`${data} === null`) + gen.if(not(valid), validateJtdRef) + } else { + gen.var(valid, false) + validateJtdRef() + } + cxt.ok(valid) + + function validateJtdRef(): void { + const refSchema = (root.schema as AnySchemaObject).definitions?.[ref] + if (!refSchema) { + throw new MissingRefError(it.opts.uriResolver, "", ref, `No definition ${ref}`) + } + if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema) + else inlineRefSchema(refSchema) + } + + function callValidate(schema: AnySchemaObject): void { + const sch = compileSchema.call( + it.self, + new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`}) + ) + const v = getValidate(cxt, sch) + const errsCount = gen.const("_errs", N.errors) + callRef(cxt, v, sch, sch.$async) + gen.assign(valid, _`${errsCount} === ${N.errors}`) + } + + function inlineRefSchema(schema: AnySchemaObject): void { + const schName = gen.scopeValue( + "schema", + it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema} + ) + cxt.subschema( + { + schema, + dataTypes: [], + schemaPath: nil, + topSchemaRef: schName, + errSchemaPath: `/definitions/${ref}`, + }, + valid + ) + } + }, +} + +export function hasRef(schema: AnySchemaObject): boolean { + for (const key in schema) { + let sch: AnySchemaObject + if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true + } + return false +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/type.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/type.ts new file mode 100644 index 0000000000000000000000000000000000000000..17274300b70b11b72977a965a4410f21a8f0f19c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/type.ts @@ -0,0 +1,75 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, nil, or, Code} from "../../compile/codegen" +import validTimestamp from "../../runtime/timestamp" +import {useFunc} from "../../compile/util" +import {checkMetadata} from "./metadata" +import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error" + +export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType> + +export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32" + +export const intRange: {[T in IntType]: [number, number, number]} = { + int8: [-128, 127, 3], + uint8: [0, 255, 3], + int16: [-32768, 32767, 5], + uint16: [0, 65535, 5], + int32: [-2147483648, 2147483647, 10], + uint32: [0, 4294967295, 10], +} + +export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType + +const error: KeywordErrorDefinition = { + message: (cxt) => typeErrorMessage(cxt, cxt.schema), + params: (cxt) => typeErrorParams(cxt, cxt.schema), +} + +function timestampCode(cxt: KeywordCxt): Code { + const {gen, data, it} = cxt + const {timestamp, allowDate} = it.opts + if (timestamp === "date") return _`${data} instanceof Date ` + const vts = useFunc(gen, validTimestamp) + const allowDateArg = allowDate ? _`, true` : nil + const validString = _`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})` + return timestamp === "string" ? validString : or(_`${data} instanceof Date`, validString) +} + +const def: CodeKeywordDefinition = { + keyword: "type", + schemaType: "string", + error, + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {data, schema, parentSchema, it} = cxt + let cond: Code + switch (schema) { + case "boolean": + case "string": + cond = _`typeof ${data} == ${schema}` + break + case "timestamp": { + cond = timestampCode(cxt) + break + } + case "float32": + case "float64": + cond = _`typeof ${data} == "number"` + break + default: { + const sch = schema as IntType + cond = _`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)` + if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) { + if (sch === "uint32") cond = _`${cond} && ${data} >= 0` + } else { + const [min, max] = intRange[sch] + cond = _`${cond} && ${data} >= ${min} && ${data} <= ${max}` + } + } + } + cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/union.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/union.ts new file mode 100644 index 0000000000000000000000000000000000000000..588f07ab4a96bb88512579ce0cc683eaa5925eb2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/union.ts @@ -0,0 +1,12 @@ +import type {CodeKeywordDefinition} from "../../types" +import {validateUnion} from "../code" + +const def: CodeKeywordDefinition = { + keyword: "union", + schemaType: "array", + trackErrors: true, + code: validateUnion, + error: {message: "must match a schema in union"}, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/values.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/values.ts new file mode 100644 index 0000000000000000000000000000000000000000..e64945077647a81d99a6460ae6e86b5394c250c4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/jtd/values.ts @@ -0,0 +1,58 @@ +import type {CodeKeywordDefinition, SchemaObject} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {alwaysValidSchema, Type} from "../../compile/util" +import {not, or, Name} from "../../compile/codegen" +import {checkMetadata} from "./metadata" +import {checkNullableObject} from "./nullable" +import {typeError, _JTDTypeError} from "./error" + +export type JTDValuesError = _JTDTypeError<"values", "object", SchemaObject> + +const def: CodeKeywordDefinition = { + keyword: "values", + schemaType: "object", + error: typeError("object"), + code(cxt: KeywordCxt) { + checkMetadata(cxt) + const {gen, data, schema, it} = cxt + const [valid, cond] = checkNullableObject(cxt, data) + if (alwaysValidSchema(it, schema)) { + gen.if(not(or(cond, valid)), () => cxt.error()) + } else { + gen.if(cond) + gen.assign(valid, validateMap()) + gen.elseIf(not(valid)) + cxt.error() + gen.endIf() + } + cxt.ok(valid) + + function validateMap(): Name | boolean { + const _valid = gen.name("valid") + if (it.allErrors) { + const validMap = gen.let("valid", true) + validateValues(() => gen.assign(validMap, false)) + return validMap + } + gen.var(_valid, true) + validateValues(() => gen.break()) + return _valid + + function validateValues(notValid: () => void): void { + gen.forIn("key", data, (key) => { + cxt.subschema( + { + keyword: "values", + dataProp: key, + dataPropType: Type.Str, + }, + _valid + ) + gen.if(not(_valid), notValid) + }) + } + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/metadata.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/metadata.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9d5af85fe921f9cd553e61da6a09234213f0e5b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/metadata.ts @@ -0,0 +1,17 @@ +import type {Vocabulary} from "../types" + +export const metadataVocabulary: Vocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples", +] + +export const contentVocabulary: Vocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema", +] diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/next.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/next.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e987ad21241259ff0453a45534d0822fa3b7e58 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/next.ts @@ -0,0 +1,8 @@ +import type {Vocabulary} from "../types" +import dependentRequired from "./validation/dependentRequired" +import dependentSchemas from "./applicator/dependentSchemas" +import limitContains from "./validation/limitContains" + +const next: Vocabulary = [dependentRequired, dependentSchemas, limitContains] + +export default next diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/unevaluated/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/unevaluated/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7f0815dbb00cfccd96f8910bea06182f9e19993 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/unevaluated/index.ts @@ -0,0 +1,7 @@ +import type {Vocabulary} from "../../types" +import unevaluatedProperties from "./unevaluatedProperties" +import unevaluatedItems from "./unevaluatedItems" + +const unevaluated: Vocabulary = [unevaluatedProperties, unevaluatedItems] + +export default unevaluated diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..50bf0e7c17873ad2f435a92105745d4aa8ed9d26 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedItems.ts @@ -0,0 +1,47 @@ +import type { + CodeKeywordDefinition, + ErrorObject, + KeywordErrorDefinition, + AnySchema, +} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, not, Name} from "../../compile/codegen" +import {alwaysValidSchema, Type} from "../../compile/util" + +export type UnevaluatedItemsError = ErrorObject<"unevaluatedItems", {limit: number}, AnySchema> + +const error: KeywordErrorDefinition = { + message: ({params: {len}}) => str`must NOT have more than ${len} items`, + params: ({params: {len}}) => _`{limit: ${len}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error, + code(cxt: KeywordCxt) { + const {gen, schema, data, it} = cxt + const items = it.items || 0 + if (items === true) return + const len = gen.const("len", _`${data}.length`) + if (schema === false) { + cxt.setParams({len: items}) + cxt.fail(_`${len} > ${items}`) + } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { + const valid = gen.var("valid", _`${len} <= ${items}`) + gen.if(not(valid), () => validateItems(valid, items)) + cxt.ok(valid) + } + it.items = true + + function validateItems(valid: Name, from: Name | number): void { + gen.forRange("i", from, len, (i) => { + cxt.subschema({keyword: "unevaluatedItems", dataProp: i, dataPropType: Type.Num}, valid) + if (!it.allErrors) gen.if(not(valid), () => gen.break()) + }) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e6868fa326dab80317a39e135a4b4deb1d0f2f4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/unevaluated/unevaluatedProperties.ts @@ -0,0 +1,85 @@ +import type { + CodeKeywordDefinition, + KeywordErrorDefinition, + ErrorObject, + AnySchema, +} from "../../types" +import {_, not, and, Name, Code} from "../../compile/codegen" +import {alwaysValidSchema, Type} from "../../compile/util" +import N from "../../compile/names" + +export type UnevaluatedPropertiesError = ErrorObject< + "unevaluatedProperties", + {unevaluatedProperty: string}, + AnySchema +> + +const error: KeywordErrorDefinition = { + message: "must NOT have unevaluated properties", + params: ({params}) => _`{unevaluatedProperty: ${params.unevaluatedProperty}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error, + code(cxt) { + const {gen, schema, data, errsCount, it} = cxt + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error") + const {allErrors, props} = it + if (props instanceof Name) { + gen.if(_`${props} !== true`, () => + gen.forIn("key", data, (key: Name) => + gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)) + ) + ) + } else if (props !== true) { + gen.forIn("key", data, (key: Name) => + props === undefined + ? unevaluatedPropCode(key) + : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)) + ) + } + it.props = true + cxt.ok(_`${errsCount} === ${N.errors}`) + + function unevaluatedPropCode(key: Name): void { + if (schema === false) { + cxt.setParams({unevaluatedProperty: key}) + cxt.error() + if (!allErrors) gen.break() + return + } + + if (!alwaysValidSchema(it, schema)) { + const valid = gen.name("valid") + cxt.subschema( + { + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: Type.Str, + }, + valid + ) + if (!allErrors) gen.if(not(valid), () => gen.break()) + } + } + + function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code { + return _`!${evaluatedProps} || !${evaluatedProps}[${key}]` + } + + function unevaluatedStatic(evaluatedProps: {[K in string]?: true}, key: Name): Code { + const ps: Code[] = [] + for (const p in evaluatedProps) { + if (evaluatedProps[p] === true) ps.push(_`${key} !== ${p}`) + } + return and(...ps) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/const.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/const.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3b94a5dcd3d0ad993a83088694b9375089f735d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/const.ts @@ -0,0 +1,28 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type ConstError = ErrorObject<"const", {allowedValue: any}> + +const error: KeywordErrorDefinition = { + message: "must be equal to constant", + params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "const", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schemaCode, schema} = cxt + if ($data || (schema && typeof schema == "object")) { + cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`) + } else { + cxt.fail(_`${schema} !== ${data}`) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c616cfa9ac79fabdd5e4d2ff19840adec61f813 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/dependentRequired.ts @@ -0,0 +1,23 @@ +import type {CodeKeywordDefinition, ErrorObject} from "../../types" +import { + validatePropertyDeps, + error, + DependenciesErrorParams, + PropertyDependencies, +} from "../applicator/dependencies" + +export type DependentRequiredError = ErrorObject< + "dependentRequired", + DependenciesErrorParams, + PropertyDependencies +> + +const def: CodeKeywordDefinition = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error, + code: (cxt) => validatePropertyDeps(cxt), +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/enum.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/enum.ts new file mode 100644 index 0000000000000000000000000000000000000000..76377fb02e6a9e8843ba08b2e858a19a067b787b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/enum.ts @@ -0,0 +1,54 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, or, Name, Code} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type EnumError = ErrorObject<"enum", {allowedValues: any[]}, any[] | {$data: string}> + +const error: KeywordErrorDefinition = { + message: "must be equal to one of the allowed values", + params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "enum", + schemaType: "array", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schema, schemaCode, it} = cxt + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array") + const useLoop = schema.length >= it.opts.loopEnum + let eql: Name | undefined + const getEql = (): Name => (eql ??= useFunc(gen, equal)) + + let valid: Code + if (useLoop || $data) { + valid = gen.let("valid") + cxt.block$data(valid, loopEnum) + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error") + const vSchema = gen.const("vSchema", schemaCode) + valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i))) + } + cxt.pass(valid) + + function loopEnum(): void { + gen.assign(valid, false) + gen.forOf("v", schemaCode as Code, (v) => + gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()) + ) + } + + function equalCode(vSchema: Name, i: number): Code { + const sch = schema[i] + return typeof sch === "object" && sch !== null + ? _`${getEql()}(${data}, ${vSchema}[${i}])` + : _`${data} === ${sch}` + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/index.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..3531b19628b7dfb2526a81cd38d6c93ee1a54dbe --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/index.ts @@ -0,0 +1,49 @@ +import type {ErrorObject, Vocabulary} from "../../types" +import limitNumber, {LimitNumberError} from "./limitNumber" +import multipleOf, {MultipleOfError} from "./multipleOf" +import limitLength from "./limitLength" +import pattern, {PatternError} from "./pattern" +import limitProperties from "./limitProperties" +import required, {RequiredError} from "./required" +import limitItems from "./limitItems" +import uniqueItems, {UniqueItemsError} from "./uniqueItems" +import constKeyword, {ConstError} from "./const" +import enumKeyword, {EnumError} from "./enum" + +const validation: Vocabulary = [ + // number + limitNumber, + multipleOf, + // string + limitLength, + pattern, + // object + limitProperties, + required, + // array + limitItems, + uniqueItems, + // any + {keyword: "type", schemaType: ["string", "array"]}, + {keyword: "nullable", schemaType: "boolean"}, + constKeyword, + enumKeyword, +] + +export default validation + +type LimitError = ErrorObject< + "maxItems" | "minItems" | "minProperties" | "maxProperties" | "minLength" | "maxLength", + {limit: number}, + number | {$data: string} +> + +export type ValidationKeywordError = + | LimitError + | LimitNumberError + | MultipleOfError + | PatternError + | RequiredError + | UniqueItemsError + | ConstError + | EnumError diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitContains.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitContains.ts new file mode 100644 index 0000000000000000000000000000000000000000..8bb43c1a4a66f1d8781181cbd07f06edb76aea02 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitContains.ts @@ -0,0 +1,16 @@ +import type {CodeKeywordDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkStrictMode} from "../../compile/util" + +const def: CodeKeywordDefinition = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({keyword, parentSchema, it}: KeywordCxt) { + if (parentSchema.contains === undefined) { + checkStrictMode(it, `"${keyword}" without "contains" is ignored`) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitItems.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..566de8588b3be2fcccdeff56f26338be0dc6fcb4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitItems.ts @@ -0,0 +1,26 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxItems" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} items` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + const op = keyword === "maxItems" ? operators.GT : operators.LT + cxt.fail$data(_`${data}.length ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitLength.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitLength.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4f947259549ad3d0e9fe992e5a92a83696e1177 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitLength.ts @@ -0,0 +1,30 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import ucs2length from "../../runtime/ucs2length" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxLength" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} characters` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode, it} = cxt + const op = keyword === "maxLength" ? operators.GT : operators.LT + const len = + it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})` + cxt.fail$data(_`${len} ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts new file mode 100644 index 0000000000000000000000000000000000000000..5499202efbfec965a9acd8c71e145e79110923d9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitNumber.ts @@ -0,0 +1,42 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators, Code} from "../../compile/codegen" + +const ops = operators + +type Kwd = "maximum" | "minimum" | "exclusiveMaximum" | "exclusiveMinimum" + +type Comparison = "<=" | ">=" | "<" | ">" + +const KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = { + maximum: {okStr: "<=", ok: ops.LTE, fail: ops.GT}, + minimum: {okStr: ">=", ok: ops.GTE, fail: ops.LT}, + exclusiveMaximum: {okStr: "<", ok: ops.LT, fail: ops.GTE}, + exclusiveMinimum: {okStr: ">", ok: ops.GT, fail: ops.LTE}, +} + +export type LimitNumberError = ErrorObject< + Kwd, + {limit: number; comparison: Comparison}, + number | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({keyword, schemaCode}) => str`must be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`, + params: ({keyword, schemaCode}) => + _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts new file mode 100644 index 0000000000000000000000000000000000000000..07fffa8b39a03798262a94da5c55ac6e3e7ce200 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/limitProperties.ts @@ -0,0 +1,26 @@ +import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str, operators} from "../../compile/codegen" + +const error: KeywordErrorDefinition = { + message({keyword, schemaCode}) { + const comp = keyword === "maxProperties" ? "more" : "fewer" + return str`must NOT have ${comp} than ${schemaCode} properties` + }, + params: ({schemaCode}) => _`{limit: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {keyword, data, schemaCode} = cxt + const op = keyword === "maxProperties" ? operators.GT : operators.LT + cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fd79abbd91c41d872ec775441f48b69550e8655 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/multipleOf.ts @@ -0,0 +1,34 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {_, str} from "../../compile/codegen" + +export type MultipleOfError = ErrorObject< + "multipleOf", + {multipleOf: number}, + number | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must be multiple of ${schemaCode}`, + params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, schemaCode, it} = cxt + // const bdt = bad$DataType(schemaCode, def.schemaType, $data) + const prec = it.opts.multipleOfPrecision + const res = gen.let("res") + const invalid = prec + ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` + : _`${res} !== parseInt(${res})` + cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/pattern.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/pattern.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b27b7d3c0dfafad85d8612a19ab1e46e899ec2c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/pattern.ts @@ -0,0 +1,28 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {usePattern} from "../code" +import {_, str} from "../../compile/codegen" + +export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}> + +const error: KeywordErrorDefinition = { + message: ({schemaCode}) => str`must match pattern "${schemaCode}"`, + params: ({schemaCode}) => _`{pattern: ${schemaCode}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt: KeywordCxt) { + const {data, $data, schema, schemaCode, it} = cxt + // TODO regexp should be wrapped in try/catchs + const u = it.opts.unicodeRegExp ? "u" : "" + const regExp = $data ? _`(new RegExp(${schemaCode}, ${u}))` : usePattern(cxt, schema) + cxt.fail$data(_`!${regExp}.test(${data})`) + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/required.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/required.ts new file mode 100644 index 0000000000000000000000000000000000000000..fea7367ed7b8f0cfeee2a73a1cecaca7f8c0c115 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/required.ts @@ -0,0 +1,98 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import { + checkReportMissingProp, + checkMissingProp, + reportMissingProp, + propertyInData, + noPropertyInData, +} from "../code" +import {_, str, nil, not, Name, Code} from "../../compile/codegen" +import {checkStrictMode} from "../../compile/util" + +export type RequiredError = ErrorObject< + "required", + {missingProperty: string}, + string[] | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`, + params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, schema, schemaCode, data, $data, it} = cxt + const {opts} = it + if (!$data && schema.length === 0) return + const useLoop = schema.length >= opts.loopRequired + if (it.allErrors) allErrorsMode() + else exitOnErrorMode() + + if (opts.strictRequired) { + const props = cxt.parentSchema.properties + const {definedProperties} = cxt.it + for (const requiredKey of schema) { + if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)` + checkStrictMode(it, msg, it.opts.strictRequired) + } + } + } + + function allErrorsMode(): void { + if (useLoop || $data) { + cxt.block$data(nil, loopAllRequired) + } else { + for (const prop of schema) { + checkReportMissingProp(cxt, prop) + } + } + } + + function exitOnErrorMode(): void { + const missing = gen.let("missing") + if (useLoop || $data) { + const valid = gen.let("valid", true) + cxt.block$data(valid, () => loopUntilMissing(missing, valid)) + cxt.ok(valid) + } else { + gen.if(checkMissingProp(cxt, schema, missing)) + reportMissingProp(cxt, missing) + gen.else() + } + } + + function loopAllRequired(): void { + gen.forOf("prop", schemaCode as Code, (prop) => { + cxt.setParams({missingProperty: prop}) + gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error()) + }) + } + + function loopUntilMissing(missing: Name, valid: Name): void { + cxt.setParams({missingProperty: missing}) + gen.forOf( + missing, + schemaCode as Code, + () => { + gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties)) + gen.if(not(valid), () => { + cxt.error() + gen.break() + }) + }, + nil + ) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts new file mode 100644 index 0000000000000000000000000000000000000000..765c4d04fc2472b774838d06fe13c15a98b58a9b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts @@ -0,0 +1,79 @@ +import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types" +import type {KeywordCxt} from "../../compile/validate" +import {checkDataTypes, getSchemaTypes, DataType} from "../../compile/validate/dataType" +import {_, str, Name} from "../../compile/codegen" +import {useFunc} from "../../compile/util" +import equal from "../../runtime/equal" + +export type UniqueItemsError = ErrorObject< + "uniqueItems", + {i: number; j: number}, + boolean | {$data: string} +> + +const error: KeywordErrorDefinition = { + message: ({params: {i, j}}) => + str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`, +} + +const def: CodeKeywordDefinition = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error, + code(cxt: KeywordCxt) { + const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt + if (!$data && !schema) return + const valid = gen.let("valid") + const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : [] + cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`) + cxt.ok(valid) + + function validateUniqueItems(): void { + const i = gen.let("i", _`${data}.length`) + const j = gen.let("j") + cxt.setParams({i, j}) + gen.assign(valid, true) + gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)) + } + + function canOptimize(): boolean { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array") + } + + function loopN(i: Name, j: Name): void { + const item = gen.name("item") + const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong) + const indices = gen.const("indices", _`{}`) + gen.for(_`;${i}--;`, () => { + gen.let(item, _`${data}[${i}]`) + gen.if(wrongType, _`continue`) + if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`) + gen + .if(_`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, _`${indices}[${item}]`) + cxt.error() + gen.assign(valid, false).break() + }) + .code(_`${indices}[${item}] = ${i}`) + }) + } + + function loopN2(i: Name, j: Name): void { + const eql = useFunc(gen, equal) + const outer = gen.name("outer") + gen.label(outer).for(_`;${i}--;`, () => + gen.for(_`${j} = ${i}; ${j}--;`, () => + gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error() + gen.assign(valid, false).break(outer) + }) + ) + ) + } + }, +} + +export default def diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/.github/FUNDING.yml b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..44f80f417e337a906a3b9add76031c86d2b711a1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: epoberezkin +tidelift: "npm/json-schema-traverse" diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/.github/workflows/build.yml b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/.github/workflows/build.yml new file mode 100644 index 0000000000000000000000000000000000000000..f8ef5ba80e38fcda634d962658df3168dbc07aee --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/.github/workflows/build.yml @@ -0,0 +1,28 @@ +name: build + +on: + push: + branches: [master] + pull_request: + branches: ["*"] + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [10.x, 12.x, 14.x] + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - run: npm install + - run: npm test + - name: Coveralls + uses: coverallsapp/github-action@master + with: + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/.github/workflows/publish.yml b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/.github/workflows/publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..924825b12dccc025c5b642798312759aef3e3c0a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/.github/workflows/publish.yml @@ -0,0 +1,27 @@ +name: publish + +on: + release: + types: [published] + +jobs: + publish-npm: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v1 + with: + node-version: 14 + registry-url: https://registry.npmjs.org/ + - run: npm install + - run: npm test + - name: Publish beta version to npm + if: "github.event.release.prerelease" + run: npm publish --tag beta + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + - name: Publish to npm + if: "!github.event.release.prerelease" + run: npm publish + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/spec/.eslintrc.yml b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/spec/.eslintrc.yml new file mode 100644 index 0000000000000000000000000000000000000000..3344da7eb323ba9a85c74de6ff6f70738d8bd040 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/spec/.eslintrc.yml @@ -0,0 +1,6 @@ +parserOptions: + ecmaVersion: 6 +globals: + beforeEach: false + describe: false + it: false diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/spec/fixtures/schema.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/spec/fixtures/schema.js new file mode 100644 index 0000000000000000000000000000000000000000..c51430cdc3d34f28f8010c3c7c472f3cfbf84bd0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/spec/fixtures/schema.js @@ -0,0 +1,125 @@ +'use strict'; + +var schema = { + additionalItems: subschema('additionalItems'), + items: subschema('items'), + contains: subschema('contains'), + additionalProperties: subschema('additionalProperties'), + propertyNames: subschema('propertyNames'), + not: subschema('not'), + allOf: [ + subschema('allOf_0'), + subschema('allOf_1'), + { + items: [ + subschema('items_0'), + subschema('items_1'), + ] + } + ], + anyOf: [ + subschema('anyOf_0'), + subschema('anyOf_1'), + ], + oneOf: [ + subschema('oneOf_0'), + subschema('oneOf_1'), + ], + definitions: { + foo: subschema('definitions_foo'), + bar: subschema('definitions_bar'), + }, + properties: { + foo: subschema('properties_foo'), + bar: subschema('properties_bar'), + }, + patternProperties: { + foo: subschema('patternProperties_foo'), + bar: subschema('patternProperties_bar'), + }, + dependencies: { + foo: subschema('dependencies_foo'), + bar: subschema('dependencies_bar'), + }, + required: ['foo', 'bar'] +}; + + +function subschema(keyword) { + var sch = { + properties: {}, + additionalProperties: false, + additionalItems: false, + anyOf: [ + {format: 'email'}, + {format: 'hostname'} + ] + }; + sch.properties['foo_' + keyword] = {title: 'foo'}; + sch.properties['bar_' + keyword] = {title: 'bar'}; + return sch; +} + + +module.exports = { + schema: schema, + + // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex + expectedCalls: [[schema, '', schema, undefined, undefined, undefined, undefined]] + .concat(expectedCalls('additionalItems')) + .concat(expectedCalls('items')) + .concat(expectedCalls('contains')) + .concat(expectedCalls('additionalProperties')) + .concat(expectedCalls('propertyNames')) + .concat(expectedCalls('not')) + .concat(expectedCallsChild('allOf', 0)) + .concat(expectedCallsChild('allOf', 1)) + .concat([ + [schema.allOf[2], '/allOf/2', schema, '', 'allOf', schema, 2], + [schema.allOf[2].items[0], '/allOf/2/items/0', schema, '/allOf/2', 'items', schema.allOf[2], 0], + [schema.allOf[2].items[0].properties.foo_items_0, '/allOf/2/items/0/properties/foo_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'foo_items_0'], + [schema.allOf[2].items[0].properties.bar_items_0, '/allOf/2/items/0/properties/bar_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'bar_items_0'], + [schema.allOf[2].items[0].anyOf[0], '/allOf/2/items/0/anyOf/0', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 0], + [schema.allOf[2].items[0].anyOf[1], '/allOf/2/items/0/anyOf/1', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 1], + + [schema.allOf[2].items[1], '/allOf/2/items/1', schema, '/allOf/2', 'items', schema.allOf[2], 1], + [schema.allOf[2].items[1].properties.foo_items_1, '/allOf/2/items/1/properties/foo_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'foo_items_1'], + [schema.allOf[2].items[1].properties.bar_items_1, '/allOf/2/items/1/properties/bar_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'bar_items_1'], + [schema.allOf[2].items[1].anyOf[0], '/allOf/2/items/1/anyOf/0', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 0], + [schema.allOf[2].items[1].anyOf[1], '/allOf/2/items/1/anyOf/1', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 1] + ]) + .concat(expectedCallsChild('anyOf', 0)) + .concat(expectedCallsChild('anyOf', 1)) + .concat(expectedCallsChild('oneOf', 0)) + .concat(expectedCallsChild('oneOf', 1)) + .concat(expectedCallsChild('definitions', 'foo')) + .concat(expectedCallsChild('definitions', 'bar')) + .concat(expectedCallsChild('properties', 'foo')) + .concat(expectedCallsChild('properties', 'bar')) + .concat(expectedCallsChild('patternProperties', 'foo')) + .concat(expectedCallsChild('patternProperties', 'bar')) + .concat(expectedCallsChild('dependencies', 'foo')) + .concat(expectedCallsChild('dependencies', 'bar')) +}; + + +function expectedCalls(keyword) { + return [ + [schema[keyword], `/${keyword}`, schema, '', keyword, schema, undefined], + [schema[keyword].properties[`foo_${keyword}`], `/${keyword}/properties/foo_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `foo_${keyword}`], + [schema[keyword].properties[`bar_${keyword}`], `/${keyword}/properties/bar_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `bar_${keyword}`], + [schema[keyword].anyOf[0], `/${keyword}/anyOf/0`, schema, `/${keyword}`, 'anyOf', schema[keyword], 0], + [schema[keyword].anyOf[1], `/${keyword}/anyOf/1`, schema, `/${keyword}`, 'anyOf', schema[keyword], 1] + ]; +} + + +function expectedCallsChild(keyword, i) { + return [ + [schema[keyword][i], `/${keyword}/${i}`, schema, '', keyword, schema, i], + [schema[keyword][i].properties[`foo_${keyword}_${i}`], `/${keyword}/${i}/properties/foo_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `foo_${keyword}_${i}`], + [schema[keyword][i].properties[`bar_${keyword}_${i}`], `/${keyword}/${i}/properties/bar_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `bar_${keyword}_${i}`], + [schema[keyword][i].anyOf[0], `/${keyword}/${i}/anyOf/0`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 0], + [schema[keyword][i].anyOf[1], `/${keyword}/${i}/anyOf/1`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 1] + ]; +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/spec/index.spec.js b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/spec/index.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c76b64fc8496ca677ca2d9c0cb620a565530f3fa --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/schema-utils/node_modules/json-schema-traverse/spec/index.spec.js @@ -0,0 +1,171 @@ +'use strict'; + +var traverse = require('../index'); +var assert = require('assert'); + +describe('json-schema-traverse', function() { + var calls; + + beforeEach(function() { + calls = []; + }); + + it('should traverse all keywords containing schemas recursively', function() { + var schema = require('./fixtures/schema').schema; + var expectedCalls = require('./fixtures/schema').expectedCalls; + + traverse(schema, {cb: callback}); + assert.deepStrictEqual(calls, expectedCalls); + }); + + describe('Legacy v0.3.1 API', function() { + it('should traverse all keywords containing schemas recursively', function() { + var schema = require('./fixtures/schema').schema; + var expectedCalls = require('./fixtures/schema').expectedCalls; + + traverse(schema, callback); + assert.deepStrictEqual(calls, expectedCalls); + }); + + it('should work when an options object is provided', function() { + // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex + var schema = require('./fixtures/schema').schema; + var expectedCalls = require('./fixtures/schema').expectedCalls; + + traverse(schema, {}, callback); + assert.deepStrictEqual(calls, expectedCalls); + }); + }); + + + describe('allKeys option', function() { + var schema = { + someObject: { + minimum: 1, + maximum: 2 + } + }; + + it('should traverse objects with allKeys: true option', function() { + // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex + var expectedCalls = [ + [schema, '', schema, undefined, undefined, undefined, undefined], + [schema.someObject, '/someObject', schema, '', 'someObject', schema, undefined] + ]; + + traverse(schema, {allKeys: true, cb: callback}); + assert.deepStrictEqual(calls, expectedCalls); + }); + + + it('should NOT traverse objects with allKeys: false option', function() { + // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex + var expectedCalls = [ + [schema, '', schema, undefined, undefined, undefined, undefined] + ]; + + traverse(schema, {allKeys: false, cb: callback}); + assert.deepStrictEqual(calls, expectedCalls); + }); + + + it('should NOT traverse objects without allKeys option', function() { + // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex + var expectedCalls = [ + [schema, '', schema, undefined, undefined, undefined, undefined] + ]; + + traverse(schema, {cb: callback}); + assert.deepStrictEqual(calls, expectedCalls); + }); + + + it('should NOT travers objects in standard keywords which value is not a schema', function() { + var schema2 = { + const: {foo: 'bar'}, + enum: ['a', 'b'], + required: ['foo'], + another: { + + }, + patternProperties: {}, // will not traverse - no properties + dependencies: true, // will not traverse - invalid + properties: { + smaller: { + type: 'number' + }, + larger: { + type: 'number', + minimum: {$data: '1/smaller'} + } + } + }; + + // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex + var expectedCalls = [ + [schema2, '', schema2, undefined, undefined, undefined, undefined], + [schema2.another, '/another', schema2, '', 'another', schema2, undefined], + [schema2.properties.smaller, '/properties/smaller', schema2, '', 'properties', schema2, 'smaller'], + [schema2.properties.larger, '/properties/larger', schema2, '', 'properties', schema2, 'larger'], + ]; + + traverse(schema2, {allKeys: true, cb: callback}); + assert.deepStrictEqual(calls, expectedCalls); + }); + }); + + describe('pre and post', function() { + var schema = { + type: 'object', + properties: { + name: {type: 'string'}, + age: {type: 'number'} + } + }; + + it('should traverse schema in pre-order', function() { + traverse(schema, {cb: {pre}}); + var expectedCalls = [ + ['pre', schema, '', schema, undefined, undefined, undefined, undefined], + ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'], + ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'], + ]; + assert.deepStrictEqual(calls, expectedCalls); + }); + + it('should traverse schema in post-order', function() { + traverse(schema, {cb: {post}}); + var expectedCalls = [ + ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'], + ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'], + ['post', schema, '', schema, undefined, undefined, undefined, undefined], + ]; + assert.deepStrictEqual(calls, expectedCalls); + }); + + it('should traverse schema in pre- and post-order at the same time', function() { + traverse(schema, {cb: {pre, post}}); + var expectedCalls = [ + ['pre', schema, '', schema, undefined, undefined, undefined, undefined], + ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'], + ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'], + ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'], + ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'], + ['post', schema, '', schema, undefined, undefined, undefined, undefined], + ]; + assert.deepStrictEqual(calls, expectedCalls); + }); + }); + + function callback() { + calls.push(Array.prototype.slice.call(arguments)); + } + + function pre() { + calls.push(['pre'].concat(Array.prototype.slice.call(arguments))); + } + + function post() { + calls.push(['post'].concat(Array.prototype.slice.call(arguments))); + } +}); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/unbox-primitive/.github/FUNDING.yml b/novas/novacore-zephyr/groq-code-cli/node_modules/unbox-primitive/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..30cbba95b0f0b50f1aa0878a87eec108f283a5c9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/unbox-primitive/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/unbox-primitive +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/unbox-primitive/test/index.js b/novas/novacore-zephyr/groq-code-cli/node_modules/unbox-primitive/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bb4fc195f3bbca378ed7eb51a8b828863df21b6a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/unbox-primitive/test/index.js @@ -0,0 +1,59 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var is = require('object-is'); +var forEach = require('for-each'); +var v = require('es-value-fixtures'); + +var unboxPrimitive = require('..'); + +test('primitives', function (t) { + forEach([null, undefined], function (nullValue) { + t['throws']( + // @ts-expect-error + function () { unboxPrimitive(nullValue); }, + TypeError, + inspect(nullValue) + ' is not a primitive' + ); + }); + + // eslint-disable-next-line no-extra-parens + forEach(/** @type {typeof v.nonNullPrimitives} */ ([].concat( + // @ts-expect-error TS sucks with concat + v.nonNullPrimitives, + v.zeroes, + v.infinities, + NaN + )), function (primitive) { + var obj = Object(primitive); + t.ok( + is(unboxPrimitive(obj), primitive), + inspect(obj) + 'unboxes to ' + inspect(primitive) + ); + }); + + t.end(); +}); + +test('objects', function (t) { + // eslint-disable-next-line no-extra-parens + forEach(/** @type {typeof v.objects} */ (/** @type {unknown} */ ([].concat( + // @ts-expect-error TS sucks with concat + v.objects, + {}, + [], + function () {}, + /a/g, + new Date() + ))), function (object) { + t['throws']( + // @ts-expect-error + function () { unboxPrimitive(object); }, + TypeError, + inspect(object) + ' is not a primitive' + ); + }); + + t.end(); +}); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/bin/webpack.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/bin/webpack.js new file mode 100644 index 0000000000000000000000000000000000000000..ba71ec29ef6d892a66f221863327c88bcb4139f6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/bin/webpack.js @@ -0,0 +1,193 @@ +#!/usr/bin/env node + +"use strict"; + +/** + * @param {string} command process to run + * @param {string[]} args command line arguments + * @returns {Promise} promise + */ +const runCommand = (command, args) => { + const cp = require("child_process"); + + return new Promise((resolve, reject) => { + const executedCommand = cp.spawn(command, args, { + stdio: "inherit", + shell: true + }); + + executedCommand.on("error", (error) => { + reject(error); + }); + + executedCommand.on("exit", (code) => { + if (code === 0) { + resolve(); + } else { + reject(); + } + }); + }); +}; + +/** + * @param {string} packageName name of the package + * @returns {boolean} is the package installed? + */ +const isInstalled = (packageName) => { + if (process.versions.pnp) { + return true; + } + + const path = require("path"); + const fs = require("graceful-fs"); + + let dir = __dirname; + + do { + try { + if ( + fs.statSync(path.join(dir, "node_modules", packageName)).isDirectory() + ) { + return true; + } + } catch (_error) { + // Nothing + } + } while (dir !== (dir = path.dirname(dir))); + + // https://github.com/nodejs/node/blob/v18.9.1/lib/internal/modules/cjs/loader.js#L1274 + // eslint-disable-next-line no-warning-comments + // @ts-ignore + for (const internalPath of require("module").globalPaths) { + try { + if (fs.statSync(path.join(internalPath, packageName)).isDirectory()) { + return true; + } + } catch (_error) { + // Nothing + } + } + + return false; +}; + +/** + * @param {CliOption} cli options + * @returns {void} + */ +const runCli = (cli) => { + const path = require("path"); + + const pkgPath = require.resolve(`${cli.package}/package.json`); + + const pkg = require(pkgPath); + + if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) { + import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch( + (err) => { + console.error(err); + process.exitCode = 1; + } + ); + } else { + require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])); + } +}; + +/** + * @typedef {object} CliOption + * @property {string} name display name + * @property {string} package npm package name + * @property {string} binName name of the executable file + * @property {boolean} installed currently installed? + * @property {string} url homepage + */ + +/** @type {CliOption} */ +const cli = { + name: "webpack-cli", + package: "webpack-cli", + binName: "webpack-cli", + installed: isInstalled("webpack-cli"), + url: "https://github.com/webpack/webpack-cli" +}; + +if (!cli.installed) { + const path = require("path"); + const fs = require("graceful-fs"); + const readLine = require("readline"); + + const notify = `CLI for webpack must be installed.\n ${cli.name} (${cli.url})\n`; + + console.error(notify); + + /** @type {string | undefined} */ + let packageManager; + + if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) { + packageManager = "yarn"; + } else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) { + packageManager = "pnpm"; + } else { + packageManager = "npm"; + } + + const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"]; + + console.error( + `We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join( + " " + )} ${cli.package}".` + ); + + const question = "Do you want to install 'webpack-cli' (yes/no): "; + + const questionInterface = readLine.createInterface({ + input: process.stdin, + output: process.stderr + }); + + // In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be + // executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback + // function is responsible for clearing the exit code if the user wishes to install webpack-cli. + process.exitCode = 1; + questionInterface.question(question, (answer) => { + questionInterface.close(); + + const normalizedAnswer = answer.toLowerCase().startsWith("y"); + + if (!normalizedAnswer) { + console.error( + "You need to install 'webpack-cli' to use webpack via CLI.\n" + + "You can also install the CLI manually." + ); + + return; + } + process.exitCode = 0; + + console.log( + `Installing '${ + cli.package + }' (running '${packageManager} ${installOptions.join(" ")} ${ + cli.package + }')...` + ); + + runCommand( + /** @type {string} */ + (packageManager), + [...installOptions, cli.package] + ) + .then(() => { + runCli(cli); + }) + .catch((err) => { + console.error(err); + process.exitCode = 1; + }); + }); +} else { + runCli(cli); +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/dev-server.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/dev-server.js new file mode 100644 index 0000000000000000000000000000000000000000..4812864a1286d77add33fe73322e6707dfc0514e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/dev-server.js @@ -0,0 +1,75 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/* globals __webpack_hash__ */ +if (module.hot) { + /** @type {undefined|string} */ + var lastHash; + var upToDate = function upToDate() { + return /** @type {string} */ (lastHash).indexOf(__webpack_hash__) >= 0; + }; + var log = require("./log"); + var check = function check() { + module.hot + .check(true) + .then(function (updatedModules) { + if (!updatedModules) { + log( + "warning", + "[HMR] Cannot find update. " + + (typeof window !== "undefined" + ? "Need to do a full reload!" + : "Please reload manually!") + ); + log( + "warning", + "[HMR] (Probably because of restarting the webpack-dev-server)" + ); + if (typeof window !== "undefined") { + window.location.reload(); + } + return; + } + + if (!upToDate()) { + check(); + } + + require("./log-apply-result")(updatedModules, updatedModules); + + if (upToDate()) { + log("info", "[HMR] App is up to date."); + } + }) + .catch(function (err) { + var status = module.hot.status(); + if (["abort", "fail"].indexOf(status) >= 0) { + log( + "warning", + "[HMR] Cannot apply update. " + + (typeof window !== "undefined" + ? "Need to do a full reload!" + : "Please reload manually!") + ); + log("warning", "[HMR] " + log.formatError(err)); + if (typeof window !== "undefined") { + window.location.reload(); + } + } else { + log("warning", "[HMR] Update failed: " + log.formatError(err)); + } + }); + }; + var hotEmitter = require("./emitter"); + hotEmitter.on("webpackHotUpdate", function (currentHash) { + lastHash = currentHash; + if (!upToDate() && module.hot.status() === "idle") { + log("info", "[HMR] Checking for updates on the server..."); + check(); + } + }); + log("info", "[HMR] Waiting for update signal from WDS..."); +} else { + throw new Error("[HMR] Hot Module Replacement is disabled."); +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/emitter.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/emitter.js new file mode 100644 index 0000000000000000000000000000000000000000..05e0fbe09946573a2927bfdac7ebf48c4c0d2818 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/emitter.js @@ -0,0 +1,2 @@ +var EventEmitter = require("events"); +module.exports = new EventEmitter(); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/lazy-compilation-node.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/lazy-compilation-node.js new file mode 100644 index 0000000000000000000000000000000000000000..da4058583b11e1a560519a68cff832052bbb63e1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/lazy-compilation-node.js @@ -0,0 +1,50 @@ +/* global __resourceQuery */ + +"use strict"; + +var urlBase = decodeURIComponent(__resourceQuery.slice(1)); + +/** + * @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options + * @returns {() => void} function to destroy response + */ +exports.keepAlive = function (options) { + var data = options.data; + var onError = options.onError; + var active = options.active; + var module = options.module; + /** @type {import("http").IncomingMessage} */ + var response; + var request = ( + urlBase.startsWith("https") ? require("https") : require("http") + ).request( + urlBase + data, + { + agent: false, + headers: { accept: "text/event-stream" } + }, + function (res) { + response = res; + response.on("error", errorHandler); + if (!active && !module.hot) { + console.log( + "Hot Module Replacement is not enabled. Waiting for process restart..." + ); + } + } + ); + + /** + * @param {Error} err error + */ + function errorHandler(err) { + err.message = + "Problem communicating active modules to the server: " + err.message; + onError(err); + } + request.on("error", errorHandler); + request.end(); + return function () { + response.destroy(); + }; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/lazy-compilation-web.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/lazy-compilation-web.js new file mode 100644 index 0000000000000000000000000000000000000000..ec8253f0a3cac0da8e84c16b6b64acb5f8402499 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/lazy-compilation-web.js @@ -0,0 +1,83 @@ +/* global __resourceQuery */ + +"use strict"; + +if (typeof EventSource !== "function") { + throw new Error( + "Environment doesn't support lazy compilation (requires EventSource)" + ); +} + +var urlBase = decodeURIComponent(__resourceQuery.slice(1)); +/** @type {EventSource | undefined} */ +var activeEventSource; +var activeKeys = new Map(); +var errorHandlers = new Set(); + +var updateEventSource = function updateEventSource() { + if (activeEventSource) activeEventSource.close(); + if (activeKeys.size) { + activeEventSource = new EventSource( + urlBase + Array.from(activeKeys.keys()).join("@") + ); + /** + * @this {EventSource} + * @param {Event & { message?: string, filename?: string, lineno?: number, colno?: number, error?: Error }} event event + */ + activeEventSource.onerror = function (event) { + errorHandlers.forEach(function (onError) { + onError( + new Error( + "Problem communicating active modules to the server: " + + event.message + + " " + + event.filename + + ":" + + event.lineno + + ":" + + event.colno + + " " + + event.error + ) + ); + }); + }; + } else { + activeEventSource = undefined; + } +}; + +/** + * @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options + * @returns {() => void} function to destroy response + */ +exports.keepAlive = function (options) { + var data = options.data; + var onError = options.onError; + var active = options.active; + var module = options.module; + errorHandlers.add(onError); + var value = activeKeys.get(data) || 0; + activeKeys.set(data, value + 1); + if (value === 0) { + updateEventSource(); + } + if (!active && !module.hot) { + console.log( + "Hot Module Replacement is not enabled. Waiting for process restart..." + ); + } + + return function () { + errorHandlers.delete(onError); + setTimeout(function () { + var value = activeKeys.get(data); + if (value === 1) { + activeKeys.delete(data); + updateEventSource(); + } else { + activeKeys.set(data, value - 1); + } + }, 1000); + }; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/log-apply-result.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/log-apply-result.js new file mode 100644 index 0000000000000000000000000000000000000000..cb46366dd443fd3d065b60c4c53f16eb268eb908 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/log-apply-result.js @@ -0,0 +1,49 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +/** + * @param {(string | number)[]} updatedModules updated modules + * @param {(string | number)[] | null} renewedModules renewed modules + */ +module.exports = function (updatedModules, renewedModules) { + var unacceptedModules = updatedModules.filter(function (moduleId) { + return renewedModules && renewedModules.indexOf(moduleId) < 0; + }); + var log = require("./log"); + + if (unacceptedModules.length > 0) { + log( + "warning", + "[HMR] The following modules couldn't be hot updated: (They would need a full reload!)" + ); + unacceptedModules.forEach(function (moduleId) { + log("warning", "[HMR] - " + moduleId); + }); + } + + if (!renewedModules || renewedModules.length === 0) { + log("info", "[HMR] Nothing hot updated."); + } else { + log("info", "[HMR] Updated modules:"); + renewedModules.forEach(function (moduleId) { + if (typeof moduleId === "string" && moduleId.indexOf("!") !== -1) { + var parts = moduleId.split("!"); + log.groupCollapsed("info", "[HMR] - " + parts.pop()); + log("info", "[HMR] - " + moduleId); + log.groupEnd("info"); + } else { + log("info", "[HMR] - " + moduleId); + } + }); + var numberIds = renewedModules.every(function (moduleId) { + return typeof moduleId === "number"; + }); + if (numberIds) + log( + "info", + '[HMR] Consider using the optimization.moduleIds: "named" for module names.' + ); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/log.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/log.js new file mode 100644 index 0000000000000000000000000000000000000000..d3e46e1bf86c0e875afc9d37cfd1cfbd49bf8925 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/log.js @@ -0,0 +1,78 @@ +/** @typedef {"info" | "warning" | "error"} LogLevel */ + +/** @type {LogLevel} */ +var logLevel = "info"; + +function dummy() {} + +/** + * @param {LogLevel} level log level + * @returns {boolean} true, if should log + */ +function shouldLog(level) { + var shouldLog = + (logLevel === "info" && level === "info") || + (["info", "warning"].indexOf(logLevel) >= 0 && level === "warning") || + (["info", "warning", "error"].indexOf(logLevel) >= 0 && level === "error"); + return shouldLog; +} + +/** + * @param {(msg?: string) => void} logFn log function + * @returns {(level: LogLevel, msg?: string) => void} function that logs when log level is sufficient + */ +function logGroup(logFn) { + return function (level, msg) { + if (shouldLog(level)) { + logFn(msg); + } + }; +} + +/** + * @param {LogLevel} level log level + * @param {string|Error} msg message + */ +module.exports = function (level, msg) { + if (shouldLog(level)) { + if (level === "info") { + console.log(msg); + } else if (level === "warning") { + console.warn(msg); + } else if (level === "error") { + console.error(msg); + } + } +}; + +/** + * @param {Error} err error + * @returns {string} formatted error + */ +module.exports.formatError = function (err) { + var message = err.message; + var stack = err.stack; + if (!stack) { + return message; + } else if (stack.indexOf(message) < 0) { + return message + "\n" + stack; + } + return stack; +}; + +var group = console.group || dummy; +var groupCollapsed = console.groupCollapsed || dummy; +var groupEnd = console.groupEnd || dummy; + +module.exports.group = logGroup(group); + +module.exports.groupCollapsed = logGroup(groupCollapsed); + +module.exports.groupEnd = logGroup(groupEnd); + +/** + * @param {LogLevel} level log level + */ +module.exports.setLogLevel = function (level) { + logLevel = level; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/only-dev-server.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/only-dev-server.js new file mode 100644 index 0000000000000000000000000000000000000000..5979ab543533024a2e2b0e26cf584c815336280b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/only-dev-server.js @@ -0,0 +1,103 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/* globals __webpack_hash__ */ +if (module.hot) { + /** @type {undefined|string} */ + var lastHash; + var upToDate = function upToDate() { + return /** @type {string} */ (lastHash).indexOf(__webpack_hash__) >= 0; + }; + var log = require("./log"); + var check = function check() { + module.hot + .check() + .then(function (updatedModules) { + if (!updatedModules) { + log("warning", "[HMR] Cannot find update. Need to do a full reload!"); + log( + "warning", + "[HMR] (Probably because of restarting the webpack-dev-server)" + ); + return; + } + + return module.hot + .apply({ + ignoreUnaccepted: true, + ignoreDeclined: true, + ignoreErrored: true, + onUnaccepted: function (data) { + log( + "warning", + "Ignored an update to unaccepted module " + + data.chain.join(" -> ") + ); + }, + onDeclined: function (data) { + log( + "warning", + "Ignored an update to declined module " + + data.chain.join(" -> ") + ); + }, + onErrored: function (data) { + log("error", data.error); + log( + "warning", + "Ignored an error while updating module " + + data.moduleId + + " (" + + data.type + + ")" + ); + } + }) + .then(function (renewedModules) { + if (!upToDate()) { + check(); + } + + require("./log-apply-result")(updatedModules, renewedModules); + + if (upToDate()) { + log("info", "[HMR] App is up to date."); + } + }); + }) + .catch(function (err) { + var status = module.hot.status(); + if (["abort", "fail"].indexOf(status) >= 0) { + log( + "warning", + "[HMR] Cannot check for update. Need to do a full reload!" + ); + log("warning", "[HMR] " + log.formatError(err)); + } else { + log("warning", "[HMR] Update check failed: " + log.formatError(err)); + } + }); + }; + var hotEmitter = require("./emitter"); + hotEmitter.on("webpackHotUpdate", function (currentHash) { + lastHash = currentHash; + if (!upToDate()) { + var status = module.hot.status(); + if (status === "idle") { + log("info", "[HMR] Checking for updates on the server..."); + check(); + } else if (["abort", "fail"].indexOf(status) >= 0) { + log( + "warning", + "[HMR] Cannot apply update as a previous update " + + status + + "ed. Need to do a full reload!" + ); + } + } + }); + log("info", "[HMR] Waiting for update signal from WDS..."); +} else { + throw new Error("[HMR] Hot Module Replacement is disabled."); +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/poll.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/poll.js new file mode 100644 index 0000000000000000000000000000000000000000..a35693cfa6f50234443a62271db738905b9c3a08 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/poll.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/* globals __resourceQuery */ +if (module.hot) { + // eslint-disable-next-line no-implicit-coercion + var hotPollInterval = +__resourceQuery.slice(1) || 10 * 60 * 1000; + var log = require("./log"); + + /** + * @param {boolean=} fromUpdate true when called from update + */ + var checkForUpdate = function checkForUpdate(fromUpdate) { + if (module.hot.status() === "idle") { + module.hot + .check(true) + .then(function (updatedModules) { + if (!updatedModules) { + if (fromUpdate) log("info", "[HMR] Update applied."); + return; + } + require("./log-apply-result")(updatedModules, updatedModules); + checkForUpdate(true); + }) + .catch(function (err) { + var status = module.hot.status(); + if (["abort", "fail"].indexOf(status) >= 0) { + log("warning", "[HMR] Cannot apply update."); + log("warning", "[HMR] " + log.formatError(err)); + log("warning", "[HMR] You need to restart the application!"); + } else { + log("warning", "[HMR] Update failed: " + log.formatError(err)); + } + }); + } + }; + setInterval(checkForUpdate, hotPollInterval); +} else { + throw new Error("[HMR] Hot Module Replacement is disabled."); +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/signal.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/signal.js new file mode 100644 index 0000000000000000000000000000000000000000..36a0cbe38c7ed85050508b82e28c2b9577b61afb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/hot/signal.js @@ -0,0 +1,66 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/* globals __resourceQuery */ +if (module.hot) { + var log = require("./log"); + + /** + * @param {boolean=} fromUpdate true when called from update + */ + var checkForUpdate = function checkForUpdate(fromUpdate) { + module.hot + .check() + .then(function (updatedModules) { + if (!updatedModules) { + if (fromUpdate) log("info", "[HMR] Update applied."); + else log("warning", "[HMR] Cannot find update."); + return; + } + + return module.hot + .apply({ + ignoreUnaccepted: true, + onUnaccepted: function (data) { + log( + "warning", + "Ignored an update to unaccepted module " + + data.chain.join(" -> ") + ); + } + }) + .then(function (renewedModules) { + require("./log-apply-result")(updatedModules, renewedModules); + + checkForUpdate(true); + return null; + }); + }) + .catch(function (err) { + var status = module.hot.status(); + if (["abort", "fail"].indexOf(status) >= 0) { + log("warning", "[HMR] Cannot apply update."); + log("warning", "[HMR] " + log.formatError(err)); + log("warning", "[HMR] You need to restart the application!"); + } else { + log("warning", "[HMR] Update failed: " + (err.stack || err.message)); + } + }); + }; + + process.on(__resourceQuery.slice(1) || "SIGUSR2", function () { + if (module.hot.status() !== "idle") { + log( + "warning", + "[HMR] Got signal but currently in " + module.hot.status() + " state." + ); + log("warning", "[HMR] Need to be in idle state to start hot update."); + return; + } + + checkForUpdate(); + }); +} else { + throw new Error("[HMR] Hot Module Replacement is disabled."); +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/APIPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/APIPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..56dcf63e0be29da2ef0a62e9685117cb0186813a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/APIPlugin.js @@ -0,0 +1,322 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const InitFragment = require("./InitFragment"); +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const WebpackError = require("./WebpackError"); +const ConstDependency = require("./dependencies/ConstDependency"); +const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression"); +const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); +const { + evaluateToString, + toConstantDependency +} = require("./javascript/JavascriptParserHelpers"); +const ChunkNameRuntimeModule = require("./runtime/ChunkNameRuntimeModule"); +const GetFullHashRuntimeModule = require("./runtime/GetFullHashRuntimeModule"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ + +/** + * @param {boolean | undefined} module true if ES module + * @param {string} importMetaName `import.meta` name + * @returns {Record} replacements + */ +function getReplacements(module, importMetaName) { + return { + __webpack_require__: { + expr: RuntimeGlobals.require, + req: [RuntimeGlobals.require], + type: "function", + assign: false + }, + __webpack_public_path__: { + expr: RuntimeGlobals.publicPath, + req: [RuntimeGlobals.publicPath], + type: "string", + assign: true + }, + __webpack_base_uri__: { + expr: RuntimeGlobals.baseURI, + req: [RuntimeGlobals.baseURI], + type: "string", + assign: true + }, + __webpack_modules__: { + expr: RuntimeGlobals.moduleFactories, + req: [RuntimeGlobals.moduleFactories], + type: "object", + assign: false + }, + __webpack_chunk_load__: { + expr: RuntimeGlobals.ensureChunk, + req: [RuntimeGlobals.ensureChunk], + type: "function", + assign: true + }, + __non_webpack_require__: { + expr: module + ? `__WEBPACK_EXTERNAL_createRequire(${importMetaName}.url)` + : "require", + req: null, + type: undefined, // type is not known, depends on environment + assign: true + }, + __webpack_nonce__: { + expr: RuntimeGlobals.scriptNonce, + req: [RuntimeGlobals.scriptNonce], + type: "string", + assign: true + }, + __webpack_hash__: { + expr: `${RuntimeGlobals.getFullHash}()`, + req: [RuntimeGlobals.getFullHash], + type: "string", + assign: false + }, + __webpack_chunkname__: { + expr: RuntimeGlobals.chunkName, + req: [RuntimeGlobals.chunkName], + type: "string", + assign: false + }, + __webpack_get_script_filename__: { + expr: RuntimeGlobals.getChunkScriptFilename, + req: [RuntimeGlobals.getChunkScriptFilename], + type: "function", + assign: true + }, + __webpack_runtime_id__: { + expr: RuntimeGlobals.runtimeId, + req: [RuntimeGlobals.runtimeId], + assign: false + }, + "require.onError": { + expr: RuntimeGlobals.uncaughtErrorHandler, + req: [RuntimeGlobals.uncaughtErrorHandler], + type: undefined, // type is not known, could be function or undefined + assign: true // is never a pattern + }, + __system_context__: { + expr: RuntimeGlobals.systemContext, + req: [RuntimeGlobals.systemContext], + type: "object", + assign: false + }, + __webpack_share_scopes__: { + expr: RuntimeGlobals.shareScopeMap, + req: [RuntimeGlobals.shareScopeMap], + type: "object", + assign: false + }, + __webpack_init_sharing__: { + expr: RuntimeGlobals.initializeSharing, + req: [RuntimeGlobals.initializeSharing], + type: "function", + assign: true + } + }; +} + +const PLUGIN_NAME = "APIPlugin"; + +/** + * @typedef {object} APIPluginOptions + * @property {boolean=} module the output filename + */ + +class APIPlugin { + /** + * @param {APIPluginOptions=} options options + */ + constructor(options = {}) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + const importMetaName = /** @type {string} */ ( + compilation.outputOptions.importMetaName + ); + const REPLACEMENTS = getReplacements( + this.options.module, + importMetaName + ); + + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.chunkName) + .tap(PLUGIN_NAME, (chunk) => { + compilation.addRuntimeModule( + chunk, + new ChunkNameRuntimeModule(/** @type {string} */ (chunk.name)) + ); + return true; + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getFullHash) + .tap(PLUGIN_NAME, (chunk, _set) => { + compilation.addRuntimeModule(chunk, new GetFullHashRuntimeModule()); + return true; + }); + + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + + hooks.renderModuleContent.tap( + PLUGIN_NAME, + (source, module, renderContext) => { + if (/** @type {BuildInfo} */ (module.buildInfo).needCreateRequire) { + const chunkInitFragments = [ + new InitFragment( + `import { createRequire as __WEBPACK_EXTERNAL_createRequire } from ${renderContext.runtimeTemplate.renderNodePrefixForCoreModule( + "module" + )};\n`, + InitFragment.STAGE_HARMONY_IMPORTS, + 0, + "external module node-commonjs" + ) + ]; + + renderContext.chunkInitFragments.push(...chunkInitFragments); + } + + return source; + } + ); + + /** + * @param {JavascriptParser} parser the parser + */ + const handler = (parser) => { + for (const key of Object.keys(REPLACEMENTS)) { + const info = REPLACEMENTS[key]; + parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expression) => { + const dep = toConstantDependency(parser, info.expr, info.req); + + if (key === "__non_webpack_require__" && this.options.module) { + /** @type {BuildInfo} */ + (parser.state.module.buildInfo).needCreateRequire = true; + } + + return dep(expression); + }); + if (info.assign === false) { + parser.hooks.assign.for(key).tap(PLUGIN_NAME, (expr) => { + const err = new WebpackError(`${key} must not be assigned`); + err.loc = /** @type {DependencyLocation} */ (expr.loc); + throw err; + }); + } + if (info.type) { + parser.hooks.evaluateTypeof + .for(key) + .tap(PLUGIN_NAME, evaluateToString(info.type)); + } + } + + parser.hooks.expression + .for("__webpack_layer__") + .tap(PLUGIN_NAME, (expr) => { + const dep = new ConstDependency( + JSON.stringify(parser.state.module.layer), + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluateIdentifier + .for("__webpack_layer__") + .tap(PLUGIN_NAME, (expr) => + (parser.state.module.layer === null + ? new BasicEvaluatedExpression().setNull() + : new BasicEvaluatedExpression().setString( + parser.state.module.layer + ) + ).setRange(/** @type {Range} */ (expr.range)) + ); + parser.hooks.evaluateTypeof + .for("__webpack_layer__") + .tap(PLUGIN_NAME, (expr) => + new BasicEvaluatedExpression() + .setString( + parser.state.module.layer === null ? "object" : "string" + ) + .setRange(/** @type {Range} */ (expr.range)) + ); + + parser.hooks.expression + .for("__webpack_module__.id") + .tap(PLUGIN_NAME, (expr) => { + /** @type {BuildInfo} */ + (parser.state.module.buildInfo).moduleConcatenationBailout = + "__webpack_module__.id"; + const dep = new ConstDependency( + `${parser.state.module.moduleArgument}.id`, + /** @type {Range} */ (expr.range), + [RuntimeGlobals.moduleId] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + parser.hooks.expression + .for("__webpack_module__") + .tap(PLUGIN_NAME, (expr) => { + /** @type {BuildInfo} */ + (parser.state.module.buildInfo).moduleConcatenationBailout = + "__webpack_module__"; + const dep = new ConstDependency( + parser.state.module.moduleArgument, + /** @type {Range} */ (expr.range), + [RuntimeGlobals.module] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("__webpack_module__") + .tap(PLUGIN_NAME, evaluateToString("object")); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = APIPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AbstractMethodError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AbstractMethodError.js new file mode 100644 index 0000000000000000000000000000000000000000..527d224a473a43858b1242896850f6fb2240cd5d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AbstractMethodError.js @@ -0,0 +1,55 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; + +/** + * @param {string=} method method name + * @returns {string} message + */ +function createMessage(method) { + return `Abstract method${method ? ` ${method}` : ""}. Must be overridden.`; +} + +/** + * @constructor + */ +function Message() { + /** @type {string | undefined} */ + this.stack = undefined; + Error.captureStackTrace(this); + /** @type {RegExpMatchArray | null} */ + const match = + /** @type {string} */ + (/** @type {unknown} */ (this.stack)) + .split("\n")[3] + .match(CURRENT_METHOD_REGEXP); + + this.message = match && match[1] ? createMessage(match[1]) : createMessage(); +} + +/** + * Error for abstract method + * @example + * ```js + * class FooClass { + * abstractMethod() { + * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overridden. + * } + * } + * ``` + */ +class AbstractMethodError extends WebpackError { + constructor() { + super(new Message().message); + this.name = "AbstractMethodError"; + } +} + +module.exports = AbstractMethodError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AsyncDependenciesBlock.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AsyncDependenciesBlock.js new file mode 100644 index 0000000000000000000000000000000000000000..2b66dc29a0808b3fa9aa6f2803ac5451ccdcf8d9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AsyncDependenciesBlock.js @@ -0,0 +1,116 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DependenciesBlock = require("./DependenciesBlock"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ + +/** @typedef {(ChunkGroupOptions & { entryOptions?: EntryOptions }) | string} GroupOptions */ + +class AsyncDependenciesBlock extends DependenciesBlock { + /** + * @param {GroupOptions | null} groupOptions options for the group + * @param {(DependencyLocation | null)=} loc the line of code + * @param {(string | null)=} request the request + */ + constructor(groupOptions, loc, request) { + super(); + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } else if (!groupOptions) { + groupOptions = { name: undefined }; + } + this.groupOptions = groupOptions; + this.loc = loc; + this.request = request; + this._stringifiedGroupOptions = undefined; + } + + /** + * @returns {string | null | undefined} The name of the chunk + */ + get chunkName() { + return this.groupOptions.name; + } + + /** + * @param {string | undefined} value The new chunk name + * @returns {void} + */ + set chunkName(value) { + if (this.groupOptions.name !== value) { + this.groupOptions.name = value; + this._stringifiedGroupOptions = undefined; + } + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const { chunkGraph } = context; + if (this._stringifiedGroupOptions === undefined) { + this._stringifiedGroupOptions = JSON.stringify(this.groupOptions); + } + const chunkGroup = chunkGraph.getBlockChunkGroup(this); + hash.update( + `${this._stringifiedGroupOptions}${chunkGroup ? chunkGroup.id : ""}` + ); + super.updateHash(hash, context); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.groupOptions); + write(this.loc); + write(this.request); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.groupOptions = read(); + this.loc = read(); + this.request = read(); + super.deserialize(context); + } +} + +makeSerializable(AsyncDependenciesBlock, "webpack/lib/AsyncDependenciesBlock"); + +Object.defineProperty(AsyncDependenciesBlock.prototype, "module", { + get() { + throw new Error( + "module property was removed from AsyncDependenciesBlock (it's not needed)" + ); + }, + set() { + throw new Error( + "module property was removed from AsyncDependenciesBlock (it's not needed)" + ); + } +}); + +module.exports = AsyncDependenciesBlock; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AsyncDependencyToInitialChunkError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AsyncDependencyToInitialChunkError.js new file mode 100644 index 0000000000000000000000000000000000000000..75888f869a3c00acdba58d21600d749e7e103cd9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AsyncDependencyToInitialChunkError.js @@ -0,0 +1,31 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ + +class AsyncDependencyToInitialChunkError extends WebpackError { + /** + * Creates an instance of AsyncDependencyToInitialChunkError. + * @param {string} chunkName Name of Chunk + * @param {Module} module module tied to dependency + * @param {DependencyLocation} loc location of dependency + */ + constructor(chunkName, module, loc) { + super( + `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.` + ); + + this.name = "AsyncDependencyToInitialChunkError"; + this.module = module; + this.loc = loc; + } +} + +module.exports = AsyncDependencyToInitialChunkError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AutomaticPrefetchPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AutomaticPrefetchPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..1295f8245efd4d78edf10c37c63f1af71567c323 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/AutomaticPrefetchPlugin.js @@ -0,0 +1,66 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const asyncLib = require("neo-async"); +const NormalModule = require("./NormalModule"); +const PrefetchDependency = require("./dependencies/PrefetchDependency"); + +/** @typedef {import("./Compiler")} Compiler */ + +const PLUGIN_NAME = "AutomaticPrefetchPlugin"; + +class AutomaticPrefetchPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory + ); + } + ); + /** @type {{context: string | null, request: string}[] | null} */ + let lastModules = null; + compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => { + lastModules = []; + + for (const m of compilation.modules) { + if (m instanceof NormalModule) { + lastModules.push({ + context: m.context, + request: m.request + }); + } + } + }); + compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { + if (!lastModules) return callback(); + asyncLib.each( + lastModules, + (m, callback) => { + compilation.addModuleChain( + m.context || compiler.context, + new PrefetchDependency(`!!${m.request}`), + callback + ); + }, + (err) => { + lastModules = null; + callback(err); + } + ); + }); + } +} + +module.exports = AutomaticPrefetchPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/BannerPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/BannerPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b45256e4fada4d9fdb0590c9c44b3597bcbb1cf2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/BannerPlugin.js @@ -0,0 +1,135 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const Compilation = require("./Compilation"); +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); +const Template = require("./Template"); +const createSchemaValidation = require("./util/create-schema-validation"); + +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerFunction} BannerFunction */ +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ +/** @typedef {import("./Compilation").PathData} PathData */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */ + +const validate = createSchemaValidation( + /** @type {((value: typeof import("../schemas/plugins/BannerPlugin.json")) => boolean)} */ + (require("../schemas/plugins/BannerPlugin.check")), + () => require("../schemas/plugins/BannerPlugin.json"), + { + name: "Banner Plugin", + baseDataPath: "options" + } +); + +/** + * @param {string} str string to wrap + * @returns {string} wrapped string + */ +const wrapComment = (str) => { + if (!str.includes("\n")) { + return Template.toComment(str); + } + return `/*!\n * ${str + .replace(/\*\//g, "* /") + .split("\n") + .join("\n * ") + .replace(/\s+\n/g, "\n") + .trimEnd()}\n */`; +}; + +const PLUGIN_NAME = "BannerPlugin"; + +class BannerPlugin { + /** + * @param {BannerPluginArgument} options options object + */ + constructor(options) { + if (typeof options === "string" || typeof options === "function") { + options = { + banner: options + }; + } + + validate(options); + + this.options = options; + + const bannerOption = options.banner; + if (typeof bannerOption === "function") { + const getBanner = bannerOption; + /** @type {BannerFunction} */ + this.banner = this.options.raw + ? getBanner + : /** @type {BannerFunction} */ (data) => wrapComment(getBanner(data)); + } else { + const banner = this.options.raw + ? bannerOption + : wrapComment(bannerOption); + /** @type {BannerFunction} */ + this.banner = () => banner; + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + const banner = this.banner; + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); + const cache = new WeakMap(); + const stage = + this.options.stage || Compilation.PROCESS_ASSETS_STAGE_ADDITIONS; + + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage }, () => { + for (const chunk of compilation.chunks) { + if (options.entryOnly && !chunk.canBeInitial()) { + continue; + } + + for (const file of chunk.files) { + if (!matchObject(file)) { + continue; + } + + /** @type {PathData} */ + const data = { chunk, filename: file }; + + const comment = compilation.getPath( + /** @type {TemplatePath} */ + (banner), + data + ); + + compilation.updateAsset(file, (old) => { + const cached = cache.get(old); + if (!cached || cached.comment !== comment) { + const source = options.footer + ? new ConcatSource(old, "\n", comment) + : new ConcatSource(comment, "\n", old); + cache.set(old, { source, comment }); + return source; + } + return cached.source; + }); + } + } + }); + }); + } +} + +module.exports = BannerPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Cache.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Cache.js new file mode 100644 index 0000000000000000000000000000000000000000..f807055e956153fcfb6c0b3f35a606125efe9af0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Cache.js @@ -0,0 +1,167 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { AsyncParallelHook, AsyncSeriesBailHook, SyncHook } = require("tapable"); +const { + makeWebpackError, + makeWebpackErrorCallback +} = require("./HookWebpackError"); + +/** @typedef {import("./WebpackError")} WebpackError */ + +/** + * @typedef {object} Etag + * @property {() => string} toString + */ + +/** + * @template T + * @callback CallbackCache + * @param {WebpackError | null} err + * @param {T=} result + * @returns {void} + */ + +/** @typedef {EXPECTED_ANY} Data */ + +/** + * @callback GotHandler + * @param {TODO} result + * @param {(err?: Error) => void} callback + * @returns {void} + */ + +/** + * @param {number} times times + * @param {(err?: Error) => void} callback callback + * @returns {(err?: Error) => void} callback + */ +const needCalls = (times, callback) => (err) => { + if (--times === 0) { + return callback(err); + } + if (err && times > 0) { + times = 0; + return callback(err); + } +}; + +class Cache { + constructor() { + this.hooks = { + /** @type {AsyncSeriesBailHook<[string, Etag | null, GotHandler[]], Data>} */ + get: new AsyncSeriesBailHook(["identifier", "etag", "gotHandlers"]), + /** @type {AsyncParallelHook<[string, Etag | null, Data]>} */ + store: new AsyncParallelHook(["identifier", "etag", "data"]), + /** @type {AsyncParallelHook<[Iterable]>} */ + storeBuildDependencies: new AsyncParallelHook(["dependencies"]), + /** @type {SyncHook<[]>} */ + beginIdle: new SyncHook([]), + /** @type {AsyncParallelHook<[]>} */ + endIdle: new AsyncParallelHook([]), + /** @type {AsyncParallelHook<[]>} */ + shutdown: new AsyncParallelHook([]) + }; + } + + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} + */ + get(identifier, etag, callback) { + /** @type {GotHandler[]} */ + const gotHandlers = []; + this.hooks.get.callAsync(identifier, etag, gotHandlers, (err, result) => { + if (err) { + callback(makeWebpackError(err, "Cache.hooks.get")); + return; + } + if (result === null) { + result = undefined; + } + if (gotHandlers.length > 1) { + const innerCallback = needCalls(gotHandlers.length, () => + callback(null, result) + ); + for (const gotHandler of gotHandlers) { + gotHandler(result, innerCallback); + } + } else if (gotHandlers.length === 1) { + gotHandlers[0](result, () => callback(null, result)); + } else { + callback(null, result); + } + }); + } + + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} + */ + store(identifier, etag, data, callback) { + this.hooks.store.callAsync( + identifier, + etag, + data, + makeWebpackErrorCallback(callback, "Cache.hooks.store") + ); + } + + /** + * After this method has succeeded the cache can only be restored when build dependencies are + * @param {Iterable} dependencies list of all build dependencies + * @param {CallbackCache} callback signals when the dependencies are stored + * @returns {void} + */ + storeBuildDependencies(dependencies, callback) { + this.hooks.storeBuildDependencies.callAsync( + dependencies, + makeWebpackErrorCallback(callback, "Cache.hooks.storeBuildDependencies") + ); + } + + /** + * @returns {void} + */ + beginIdle() { + this.hooks.beginIdle.call(); + } + + /** + * @param {CallbackCache} callback signals when the call finishes + * @returns {void} + */ + endIdle(callback) { + this.hooks.endIdle.callAsync( + makeWebpackErrorCallback(callback, "Cache.hooks.endIdle") + ); + } + + /** + * @param {CallbackCache} callback signals when the call finishes + * @returns {void} + */ + shutdown(callback) { + this.hooks.shutdown.callAsync( + makeWebpackErrorCallback(callback, "Cache.hooks.shutdown") + ); + } +} + +Cache.STAGE_MEMORY = -10; +Cache.STAGE_DEFAULT = 0; +Cache.STAGE_DISK = 10; +Cache.STAGE_NETWORK = 20; + +module.exports = Cache; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CacheFacade.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CacheFacade.js new file mode 100644 index 0000000000000000000000000000000000000000..8887d3d955ea21a6e704051338c11cc1fdcae965 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CacheFacade.js @@ -0,0 +1,350 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { forEachBail } = require("enhanced-resolve"); +const asyncLib = require("neo-async"); +const getLazyHashedEtag = require("./cache/getLazyHashedEtag"); +const mergeEtags = require("./cache/mergeEtags"); + +/** @typedef {import("./Cache")} Cache */ +/** @typedef {import("./Cache").Etag} Etag */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./cache/getLazyHashedEtag").HashableObject} HashableObject */ +/** @typedef {typeof import("./util/Hash")} HashConstructor */ + +/** + * @template T + * @callback CallbackCache + * @param {(Error | null)=} err + * @param {(T | null)=} result + * @returns {void} + */ + +/** + * @template T + * @callback CallbackNormalErrorCache + * @param {(Error | null)=} err + * @param {T=} result + * @returns {void} + */ + +class MultiItemCache { + /** + * @param {ItemCacheFacade[]} items item caches + */ + constructor(items) { + this._items = items; + // @ts-expect-error expected - returns the single ItemCacheFacade when passed an array of length 1 + // eslint-disable-next-line no-constructor-return + if (items.length === 1) return /** @type {ItemCacheFacade} */ (items[0]); + } + + /** + * @template T + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} + */ + get(callback) { + forEachBail(this._items, (item, callback) => item.get(callback), callback); + } + + /** + * @template T + * @returns {Promise} promise with the data + */ + getPromise() { + /** + * @param {number} i index + * @returns {Promise} promise with the data + */ + const next = (i) => + this._items[i].getPromise().then((result) => { + if (result !== undefined) return result; + if (++i < this._items.length) return next(i); + }); + return next(0); + } + + /** + * @template T + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} + */ + store(data, callback) { + asyncLib.each( + this._items, + (item, callback) => item.store(data, callback), + callback + ); + } + + /** + * @template T + * @param {T} data the value to store + * @returns {Promise} promise signals when the value is stored + */ + storePromise(data) { + return Promise.all(this._items.map((item) => item.storePromise(data))).then( + () => {} + ); + } +} + +class ItemCacheFacade { + /** + * @param {Cache} cache the root cache + * @param {string} name the child cache item name + * @param {Etag | null} etag the etag + */ + constructor(cache, name, etag) { + this._cache = cache; + this._name = name; + this._etag = etag; + } + + /** + * @template T + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} + */ + get(callback) { + this._cache.get(this._name, this._etag, callback); + } + + /** + * @template T + * @returns {Promise} promise with the data + */ + getPromise() { + return new Promise((resolve, reject) => { + this._cache.get(this._name, this._etag, (err, data) => { + if (err) { + reject(err); + } else { + resolve(data); + } + }); + }); + } + + /** + * @template T + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} + */ + store(data, callback) { + this._cache.store(this._name, this._etag, data, callback); + } + + /** + * @template T + * @param {T} data the value to store + * @returns {Promise} promise signals when the value is stored + */ + storePromise(data) { + return new Promise((resolve, reject) => { + this._cache.store(this._name, this._etag, data, (err) => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); + } + + /** + * @template T + * @param {(callback: CallbackNormalErrorCache) => void} computer function to compute the value if not cached + * @param {CallbackNormalErrorCache} callback signals when the value is retrieved + * @returns {void} + */ + provide(computer, callback) { + this.get((err, cacheEntry) => { + if (err) return callback(err); + if (cacheEntry !== undefined) return cacheEntry; + computer((err, result) => { + if (err) return callback(err); + this.store(result, (err) => { + if (err) return callback(err); + callback(null, result); + }); + }); + }); + } + + /** + * @template T + * @param {() => Promise | T} computer function to compute the value if not cached + * @returns {Promise} promise with the data + */ + async providePromise(computer) { + const cacheEntry = await this.getPromise(); + if (cacheEntry !== undefined) return cacheEntry; + const result = await computer(); + await this.storePromise(result); + return result; + } +} + +class CacheFacade { + /** + * @param {Cache} cache the root cache + * @param {string} name the child cache name + * @param {(string | HashConstructor)=} hashFunction the hash function to use + */ + constructor(cache, name, hashFunction) { + this._cache = cache; + this._name = name; + this._hashFunction = hashFunction; + } + + /** + * @param {string} name the child cache name# + * @returns {CacheFacade} child cache + */ + getChildCache(name) { + return new CacheFacade( + this._cache, + `${this._name}|${name}`, + this._hashFunction + ); + } + + /** + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @returns {ItemCacheFacade} item cache + */ + getItemCache(identifier, etag) { + return new ItemCacheFacade( + this._cache, + `${this._name}|${identifier}`, + etag + ); + } + + /** + * @param {HashableObject} obj an hashable object + * @returns {Etag} an etag that is lazy hashed + */ + getLazyHashedEtag(obj) { + return getLazyHashedEtag(obj, this._hashFunction); + } + + /** + * @param {Etag} a an etag + * @param {Etag} b another etag + * @returns {Etag} an etag that represents both + */ + mergeEtags(a, b) { + return mergeEtags(a, b); + } + + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} + */ + get(identifier, etag, callback) { + this._cache.get(`${this._name}|${identifier}`, etag, callback); + } + + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @returns {Promise} promise with the data + */ + getPromise(identifier, etag) { + return new Promise((resolve, reject) => { + this._cache.get(`${this._name}|${identifier}`, etag, (err, data) => { + if (err) { + reject(err); + } else { + resolve(data); + } + }); + }); + } + + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} + */ + store(identifier, etag, data, callback) { + this._cache.store(`${this._name}|${identifier}`, etag, data, callback); + } + + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {T} data the value to store + * @returns {Promise} promise signals when the value is stored + */ + storePromise(identifier, etag, data) { + return new Promise((resolve, reject) => { + this._cache.store(`${this._name}|${identifier}`, etag, data, (err) => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); + } + + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {(callback: CallbackNormalErrorCache) => void} computer function to compute the value if not cached + * @param {CallbackNormalErrorCache} callback signals when the value is retrieved + * @returns {void} + */ + provide(identifier, etag, computer, callback) { + this.get(identifier, etag, (err, cacheEntry) => { + if (err) return callback(err); + if (cacheEntry !== undefined) return cacheEntry; + computer((err, result) => { + if (err) return callback(err); + this.store(identifier, etag, result, (err) => { + if (err) return callback(err); + callback(null, result); + }); + }); + }); + } + + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {() => Promise | T} computer function to compute the value if not cached + * @returns {Promise} promise with the data + */ + async providePromise(identifier, etag, computer) { + const cacheEntry = await this.getPromise(identifier, etag); + if (cacheEntry !== undefined) return cacheEntry; + const result = await computer(); + await this.storePromise(identifier, etag, result); + return result; + } +} + +module.exports = CacheFacade; +module.exports.ItemCacheFacade = ItemCacheFacade; +module.exports.MultiItemCache = MultiItemCache; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CaseSensitiveModulesWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CaseSensitiveModulesWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..0ee17aa56c6bb2d229887d55b715ebd797fa3260 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CaseSensitiveModulesWarning.js @@ -0,0 +1,71 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ + +/** + * @param {Module[]} modules the modules to be sorted + * @returns {Module[]} sorted version of original modules + */ +const sortModules = (modules) => + modules.sort((a, b) => { + const aIdent = a.identifier(); + const bIdent = b.identifier(); + /* istanbul ignore next */ + if (aIdent < bIdent) return -1; + /* istanbul ignore next */ + if (aIdent > bIdent) return 1; + /* istanbul ignore next */ + return 0; + }); + +/** + * @param {Module[]} modules each module from throw + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string} each message from provided modules + */ +const createModulesListMessage = (modules, moduleGraph) => + modules + .map((m) => { + let message = `* ${m.identifier()}`; + const validReasons = [ + ...moduleGraph.getIncomingConnectionsByOriginModule(m).keys() + ].filter(Boolean); + + if (validReasons.length > 0) { + message += `\n Used by ${validReasons.length} module(s), i. e.`; + message += `\n ${ + /** @type {Module[]} */ (validReasons)[0].identifier() + }`; + } + return message; + }) + .join("\n"); + +class CaseSensitiveModulesWarning extends WebpackError { + /** + * Creates an instance of CaseSensitiveModulesWarning. + * @param {Iterable} modules modules that were detected + * @param {ModuleGraph} moduleGraph the module graph + */ + constructor(modules, moduleGraph) { + const sortedModules = sortModules([...modules]); + const modulesList = createModulesListMessage(sortedModules, moduleGraph); + super(`There are multiple modules with names that only differ in casing. +This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. +Use equal casing. Compare these module identifiers: +${modulesList}`); + + this.name = "CaseSensitiveModulesWarning"; + this.module = sortedModules[0]; + } +} + +module.exports = CaseSensitiveModulesWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Chunk.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Chunk.js new file mode 100644 index 0000000000000000000000000000000000000000..21fdaba9be722fb82773bbba5662c255a4357ff7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Chunk.js @@ -0,0 +1,877 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ChunkGraph = require("./ChunkGraph"); +const Entrypoint = require("./Entrypoint"); +const { intersect } = require("./util/SetHelpers"); +const SortableSet = require("./util/SortableSet"); +const StringXor = require("./util/StringXor"); +const { + compareChunkGroupsByIndex, + compareModulesById, + compareModulesByIdentifier +} = require("./util/comparators"); +const { createArrayToSetDeprecationSet } = require("./util/deprecation"); +const { mergeRuntime } = require("./util/runtime"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./ChunkGraph").ChunkFilterPredicate} ChunkFilterPredicate */ +/** @typedef {import("./ChunkGraph").ChunkSizeOptions} ChunkSizeOptions */ +/** @typedef {import("./ChunkGraph").ModuleFilterPredicate} ModuleFilterPredicate */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** @typedef {string | null} ChunkName */ +/** @typedef {number | string} ChunkId */ +/** @typedef {SortableSet} IdNameHints */ + +const ChunkFilesSet = createArrayToSetDeprecationSet("chunk.files"); + +/** + * @typedef {object} WithId an object who has an id property * + * @property {string | number} id the id of the object + */ + +/** + * @deprecated + * @typedef {object} ChunkMaps + * @property {Record} hash + * @property {Record>} contentHash + * @property {Record} name + */ + +/** + * @deprecated + * @typedef {object} ChunkModuleMaps + * @property {Record} id + * @property {Record} hash + */ + +let debugId = 1000; + +/** + * A Chunk is a unit of encapsulation for Modules. + * Chunks are "rendered" into bundles that get emitted when the build completes. + */ +class Chunk { + /** + * @param {ChunkName=} name of chunk being created, is optional (for subclasses) + * @param {boolean} backCompat enable backward-compatibility + */ + constructor(name, backCompat = true) { + /** @type {ChunkId | null} */ + this.id = null; + /** @type {ChunkId[] | null} */ + this.ids = null; + /** @type {number} */ + this.debugId = debugId++; + /** @type {ChunkName | undefined} */ + this.name = name; + /** @type {IdNameHints} */ + this.idNameHints = new SortableSet(); + /** @type {boolean} */ + this.preventIntegration = false; + /** @type {TemplatePath | undefined} */ + this.filenameTemplate = undefined; + /** @type {TemplatePath | undefined} */ + this.cssFilenameTemplate = undefined; + /** + * @private + * @type {SortableSet} + */ + this._groups = new SortableSet(undefined, compareChunkGroupsByIndex); + /** @type {RuntimeSpec} */ + this.runtime = undefined; + /** @type {Set} */ + this.files = backCompat ? new ChunkFilesSet() : new Set(); + /** @type {Set} */ + this.auxiliaryFiles = new Set(); + /** @type {boolean} */ + this.rendered = false; + /** @type {string=} */ + this.hash = undefined; + /** @type {Record} */ + this.contentHash = Object.create(null); + /** @type {string=} */ + this.renderedHash = undefined; + /** @type {string=} */ + this.chunkReason = undefined; + /** @type {boolean} */ + this.extraAsync = false; + } + + // TODO remove in webpack 6 + // BACKWARD-COMPAT START + get entryModule() { + const entryModules = [ + ...ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.entryModule", + "DEP_WEBPACK_CHUNK_ENTRY_MODULE" + ).getChunkEntryModulesIterable(this) + ]; + if (entryModules.length === 0) { + return undefined; + } else if (entryModules.length === 1) { + return entryModules[0]; + } + + throw new Error( + "Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API)" + ); + } + + /** + * @returns {boolean} true, if the chunk contains an entry module + */ + hasEntryModule() { + return ( + ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.hasEntryModule", + "DEP_WEBPACK_CHUNK_HAS_ENTRY_MODULE" + ).getNumberOfEntryModules(this) > 0 + ); + } + + /** + * @param {Module} module the module + * @returns {boolean} true, if the chunk could be added + */ + addModule(module) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.addModule", + "DEP_WEBPACK_CHUNK_ADD_MODULE" + ); + if (chunkGraph.isModuleInChunk(module, this)) return false; + chunkGraph.connectChunkAndModule(this, module); + return true; + } + + /** + * @param {Module} module the module + * @returns {void} + */ + removeModule(module) { + ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.removeModule", + "DEP_WEBPACK_CHUNK_REMOVE_MODULE" + ).disconnectChunkAndModule(this, module); + } + + /** + * @returns {number} the number of module which are contained in this chunk + */ + getNumberOfModules() { + return ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.getNumberOfModules", + "DEP_WEBPACK_CHUNK_GET_NUMBER_OF_MODULES" + ).getNumberOfChunkModules(this); + } + + get modulesIterable() { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.modulesIterable", + "DEP_WEBPACK_CHUNK_MODULES_ITERABLE" + ); + return chunkGraph.getOrderedChunkModulesIterable( + this, + compareModulesByIdentifier + ); + } + + /** + * @param {Chunk} otherChunk the chunk to compare with + * @returns {-1|0|1} the comparison result + */ + compareTo(otherChunk) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.compareTo", + "DEP_WEBPACK_CHUNK_COMPARE_TO" + ); + return chunkGraph.compareChunks(this, otherChunk); + } + + /** + * @param {Module} module the module + * @returns {boolean} true, if the chunk contains the module + */ + containsModule(module) { + return ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.containsModule", + "DEP_WEBPACK_CHUNK_CONTAINS_MODULE" + ).isModuleInChunk(module, this); + } + + /** + * @returns {Module[]} the modules for this chunk + */ + getModules() { + return ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.getModules", + "DEP_WEBPACK_CHUNK_GET_MODULES" + ).getChunkModules(this); + } + + /** + * @returns {void} + */ + remove() { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.remove", + "DEP_WEBPACK_CHUNK_REMOVE" + ); + chunkGraph.disconnectChunk(this); + this.disconnectFromGroups(); + } + + /** + * @param {Module} module the module + * @param {Chunk} otherChunk the target chunk + * @returns {void} + */ + moveModule(module, otherChunk) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.moveModule", + "DEP_WEBPACK_CHUNK_MOVE_MODULE" + ); + chunkGraph.disconnectChunkAndModule(this, module); + chunkGraph.connectChunkAndModule(otherChunk, module); + } + + /** + * @param {Chunk} otherChunk the other chunk + * @returns {boolean} true, if the specified chunk has been integrated + */ + integrate(otherChunk) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.integrate", + "DEP_WEBPACK_CHUNK_INTEGRATE" + ); + if (chunkGraph.canChunksBeIntegrated(this, otherChunk)) { + chunkGraph.integrateChunks(this, otherChunk); + return true; + } + + return false; + } + + /** + * @param {Chunk} otherChunk the other chunk + * @returns {boolean} true, if chunks could be integrated + */ + canBeIntegrated(otherChunk) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.canBeIntegrated", + "DEP_WEBPACK_CHUNK_CAN_BE_INTEGRATED" + ); + return chunkGraph.canChunksBeIntegrated(this, otherChunk); + } + + /** + * @returns {boolean} true, if this chunk contains no module + */ + isEmpty() { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.isEmpty", + "DEP_WEBPACK_CHUNK_IS_EMPTY" + ); + return chunkGraph.getNumberOfChunkModules(this) === 0; + } + + /** + * @returns {number} total size of all modules in this chunk + */ + modulesSize() { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.modulesSize", + "DEP_WEBPACK_CHUNK_MODULES_SIZE" + ); + return chunkGraph.getChunkModulesSize(this); + } + + /** + * @param {ChunkSizeOptions} options options object + * @returns {number} total size of this chunk + */ + size(options = {}) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.size", + "DEP_WEBPACK_CHUNK_SIZE" + ); + return chunkGraph.getChunkSize(this, options); + } + + /** + * @param {Chunk} otherChunk the other chunk + * @param {ChunkSizeOptions} options options object + * @returns {number} total size of the chunk or false if the chunk can't be integrated + */ + integratedSize(otherChunk, options) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.integratedSize", + "DEP_WEBPACK_CHUNK_INTEGRATED_SIZE" + ); + return chunkGraph.getIntegratedChunksSize(this, otherChunk, options); + } + + /** + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @returns {ChunkModuleMaps} module map information + */ + getChunkModuleMaps(filterFn) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.getChunkModuleMaps", + "DEP_WEBPACK_CHUNK_GET_CHUNK_MODULE_MAPS" + ); + /** @type {Record} */ + const chunkModuleIdMap = Object.create(null); + /** @type {Record} */ + const chunkModuleHashMap = Object.create(null); + + for (const asyncChunk of this.getAllAsyncChunks()) { + /** @type {ChunkId[] | undefined} */ + let array; + for (const module of chunkGraph.getOrderedChunkModulesIterable( + asyncChunk, + compareModulesById(chunkGraph) + )) { + if (filterFn(module)) { + if (array === undefined) { + array = []; + chunkModuleIdMap[/** @type {ChunkId} */ (asyncChunk.id)] = array; + } + const moduleId = + /** @type {ModuleId} */ + (chunkGraph.getModuleId(module)); + array.push(moduleId); + chunkModuleHashMap[moduleId] = chunkGraph.getRenderedModuleHash( + module, + undefined + ); + } + } + } + + return { + id: chunkModuleIdMap, + hash: chunkModuleHashMap + }; + } + + /** + * @param {ModuleFilterPredicate} filterFn predicate function used to filter modules + * @param {ChunkFilterPredicate=} filterChunkFn predicate function used to filter chunks + * @returns {boolean} return true if module exists in graph + */ + hasModuleInGraph(filterFn, filterChunkFn) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.hasModuleInGraph", + "DEP_WEBPACK_CHUNK_HAS_MODULE_IN_GRAPH" + ); + return chunkGraph.hasModuleInGraph(this, filterFn, filterChunkFn); + } + + /** + * @deprecated + * @param {boolean} realHash whether the full hash or the rendered hash is to be used + * @returns {ChunkMaps} the chunk map information + */ + getChunkMaps(realHash) { + /** @type {Record} */ + const chunkHashMap = Object.create(null); + /** @type {Record>} */ + const chunkContentHashMap = Object.create(null); + /** @type {Record} */ + const chunkNameMap = Object.create(null); + + for (const chunk of this.getAllAsyncChunks()) { + const id = /** @type {ChunkId} */ (chunk.id); + chunkHashMap[id] = + /** @type {string} */ + (realHash ? chunk.hash : chunk.renderedHash); + for (const key of Object.keys(chunk.contentHash)) { + if (!chunkContentHashMap[key]) { + chunkContentHashMap[key] = Object.create(null); + } + chunkContentHashMap[key][id] = chunk.contentHash[key]; + } + if (chunk.name) { + chunkNameMap[id] = chunk.name; + } + } + + return { + hash: chunkHashMap, + contentHash: chunkContentHashMap, + name: chunkNameMap + }; + } + // BACKWARD-COMPAT END + + /** + * @returns {boolean} whether or not the Chunk will have a runtime + */ + hasRuntime() { + for (const chunkGroup of this._groups) { + if ( + chunkGroup instanceof Entrypoint && + chunkGroup.getRuntimeChunk() === this + ) { + return true; + } + } + return false; + } + + /** + * @returns {boolean} whether or not this chunk can be an initial chunk + */ + canBeInitial() { + for (const chunkGroup of this._groups) { + if (chunkGroup.isInitial()) return true; + } + return false; + } + + /** + * @returns {boolean} whether this chunk can only be an initial chunk + */ + isOnlyInitial() { + if (this._groups.size <= 0) return false; + for (const chunkGroup of this._groups) { + if (!chunkGroup.isInitial()) return false; + } + return true; + } + + /** + * @returns {EntryOptions | undefined} the entry options for this chunk + */ + getEntryOptions() { + for (const chunkGroup of this._groups) { + if (chunkGroup instanceof Entrypoint) { + return chunkGroup.options; + } + } + return undefined; + } + + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added + * @returns {void} + */ + addGroup(chunkGroup) { + this._groups.add(chunkGroup); + } + + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from + * @returns {void} + */ + removeGroup(chunkGroup) { + this._groups.delete(chunkGroup); + } + + /** + * @param {ChunkGroup} chunkGroup the chunkGroup to check + * @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup + */ + isInGroup(chunkGroup) { + return this._groups.has(chunkGroup); + } + + /** + * @returns {number} the amount of groups that the said chunk is in + */ + getNumberOfGroups() { + return this._groups.size; + } + + /** + * @returns {SortableSet} the chunkGroups that the said chunk is referenced in + */ + get groupsIterable() { + this._groups.sort(); + return this._groups; + } + + /** + * @returns {void} + */ + disconnectFromGroups() { + for (const chunkGroup of this._groups) { + chunkGroup.removeChunk(this); + } + } + + /** + * @param {Chunk} newChunk the new chunk that will be split out of + * @returns {void} + */ + split(newChunk) { + for (const chunkGroup of this._groups) { + chunkGroup.insertChunk(newChunk, this); + newChunk.addGroup(chunkGroup); + } + for (const idHint of this.idNameHints) { + newChunk.idNameHints.add(idHint); + } + newChunk.runtime = mergeRuntime(newChunk.runtime, this.runtime); + } + + /** + * @param {Hash} hash hash (will be modified) + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + updateHash(hash, chunkGraph) { + hash.update( + `${this.id} ${this.ids ? this.ids.join() : ""} ${this.name || ""} ` + ); + const xor = new StringXor(); + for (const m of chunkGraph.getChunkModulesIterable(this)) { + xor.add(chunkGraph.getModuleHash(m, this.runtime)); + } + xor.updateHash(hash); + const entryModules = + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(this); + for (const [m, chunkGroup] of entryModules) { + hash.update( + `entry${chunkGraph.getModuleId(m)}${ + /** @type {ChunkGroup} */ (chunkGroup).id + }` + ); + } + } + + /** + * @returns {Set} a set of all the async chunks + */ + getAllAsyncChunks() { + const queue = new Set(); + const chunks = new Set(); + + const initialChunks = intersect( + Array.from(this.groupsIterable, (g) => new Set(g.chunks)) + ); + + const initialQueue = new Set(this.groupsIterable); + + for (const chunkGroup of initialQueue) { + for (const child of chunkGroup.childrenIterable) { + if (child instanceof Entrypoint) { + initialQueue.add(child); + } else { + queue.add(child); + } + } + } + + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + if (!initialChunks.has(chunk)) { + chunks.add(chunk); + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + + return chunks; + } + + /** + * @returns {Set} a set of all the initial chunks (including itself) + */ + getAllInitialChunks() { + const chunks = new Set(); + const queue = new Set(this.groupsIterable); + for (const group of queue) { + if (group.isInitial()) { + for (const c of group.chunks) chunks.add(c); + for (const g of group.childrenIterable) queue.add(g); + } + } + return chunks; + } + + /** + * @returns {Set} a set of all the referenced chunks (including itself) + */ + getAllReferencedChunks() { + const queue = new Set(this.groupsIterable); + const chunks = new Set(); + + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + chunks.add(chunk); + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + + return chunks; + } + + /** + * @returns {Set} a set of all the referenced entrypoints + */ + getAllReferencedAsyncEntrypoints() { + const queue = new Set(this.groupsIterable); + const entrypoints = new Set(); + + for (const chunkGroup of queue) { + for (const entrypoint of chunkGroup.asyncEntrypointsIterable) { + entrypoints.add(entrypoint); + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + + return entrypoints; + } + + /** + * @returns {boolean} true, if the chunk references async chunks + */ + hasAsyncChunks() { + const queue = new Set(); + + const initialChunks = intersect( + Array.from(this.groupsIterable, (g) => new Set(g.chunks)) + ); + + for (const chunkGroup of this.groupsIterable) { + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + if (!initialChunks.has(chunk)) { + return true; + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + + return false; + } + + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {ChunkFilterPredicate=} filterFn function used to filter chunks + * @returns {Record} a record object of names to lists of child ids(?) + */ + getChildIdsByOrders(chunkGraph, filterFn) { + /** @type {Map} */ + const lists = new Map(); + for (const group of this.groupsIterable) { + if (group.chunks[group.chunks.length - 1] === this) { + for (const childGroup of group.childrenIterable) { + for (const key of Object.keys(childGroup.options)) { + if (key.endsWith("Order")) { + const name = key.slice(0, key.length - "Order".length); + let list = lists.get(name); + if (list === undefined) { + list = []; + lists.set(name, list); + } + list.push({ + order: + /** @type {number} */ + ( + childGroup.options[ + /** @type {keyof ChunkGroupOptions} */ + (key) + ] + ), + group: childGroup + }); + } + } + } + } + } + /** @type {Record} */ + const result = Object.create(null); + for (const [name, list] of lists) { + list.sort((a, b) => { + const cmp = b.order - a.order; + if (cmp !== 0) return cmp; + return a.group.compareTo(chunkGraph, b.group); + }); + /** @type {Set} */ + const chunkIdSet = new Set(); + for (const item of list) { + for (const chunk of item.group.chunks) { + if (filterFn && !filterFn(chunk, chunkGraph)) continue; + chunkIdSet.add(/** @type {ChunkId} */ (chunk.id)); + } + } + if (chunkIdSet.size > 0) { + result[name] = [...chunkIdSet]; + } + } + return result; + } + + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} type option name + * @returns {{ onChunks: Chunk[], chunks: Set }[] | undefined} referenced chunks for a specific type + */ + getChildrenOfTypeInOrder(chunkGraph, type) { + const list = []; + for (const group of this.groupsIterable) { + for (const childGroup of group.childrenIterable) { + const order = + childGroup.options[/** @type {keyof ChunkGroupOptions} */ (type)]; + if (order === undefined) continue; + list.push({ + order, + group, + childGroup + }); + } + } + if (list.length === 0) return; + list.sort((a, b) => { + const cmp = + /** @type {number} */ (b.order) - /** @type {number} */ (a.order); + if (cmp !== 0) return cmp; + return a.group.compareTo(chunkGraph, b.group); + }); + const result = []; + let lastEntry; + for (const { group, childGroup } of list) { + if (lastEntry && lastEntry.onChunks === group.chunks) { + for (const chunk of childGroup.chunks) { + lastEntry.chunks.add(chunk); + } + } else { + result.push( + (lastEntry = { + onChunks: group.chunks, + chunks: new Set(childGroup.chunks) + }) + ); + } + } + return result; + } + + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {boolean=} includeDirectChildren include direct children (by default only children of async children are included) + * @param {ChunkFilterPredicate=} filterFn function used to filter chunks + * @returns {Record>} a record object of names to lists of child ids(?) by chunk id + */ + getChildIdsByOrdersMap(chunkGraph, includeDirectChildren, filterFn) { + /** @type {Record>} */ + const chunkMaps = Object.create(null); + + /** + * @param {Chunk} chunk a chunk + * @returns {void} + */ + const addChildIdsByOrdersToMap = (chunk) => { + const data = chunk.getChildIdsByOrders(chunkGraph, filterFn); + for (const key of Object.keys(data)) { + let chunkMap = chunkMaps[key]; + if (chunkMap === undefined) { + chunkMaps[key] = chunkMap = Object.create(null); + } + chunkMap[/** @type {ChunkId} */ (chunk.id)] = data[key]; + } + }; + + if (includeDirectChildren) { + /** @type {Set} */ + const chunks = new Set(); + for (const chunkGroup of this.groupsIterable) { + for (const chunk of chunkGroup.chunks) { + chunks.add(chunk); + } + } + for (const chunk of chunks) { + addChildIdsByOrdersToMap(chunk); + } + } + + for (const chunk of this.getAllAsyncChunks()) { + addChildIdsByOrdersToMap(chunk); + } + + return chunkMaps; + } + + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} type option name + * @param {boolean=} includeDirectChildren include direct children (by default only children of async children are included) + * @param {ChunkFilterPredicate=} filterFn function used to filter chunks + * @returns {boolean} true when the child is of type order, otherwise false + */ + hasChildByOrder(chunkGraph, type, includeDirectChildren, filterFn) { + if (includeDirectChildren) { + /** @type {Set} */ + const chunks = new Set(); + for (const chunkGroup of this.groupsIterable) { + for (const chunk of chunkGroup.chunks) { + chunks.add(chunk); + } + } + for (const chunk of chunks) { + const data = chunk.getChildIdsByOrders(chunkGraph, filterFn); + if (data[type] !== undefined) return true; + } + } + + for (const chunk of this.getAllAsyncChunks()) { + const data = chunk.getChildIdsByOrders(chunkGraph, filterFn); + if (data[type] !== undefined) return true; + } + + return false; + } +} + +module.exports = Chunk; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkGraph.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkGraph.js new file mode 100644 index 0000000000000000000000000000000000000000..bab0c5fedb1e768f7f39e3214f3e502f4a1307b9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkGraph.js @@ -0,0 +1,1935 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const Entrypoint = require("./Entrypoint"); +const ModuleGraphConnection = require("./ModuleGraphConnection"); +const { DEFAULTS } = require("./config/defaults"); +const { first } = require("./util/SetHelpers"); +const SortableSet = require("./util/SortableSet"); +const { + compareIds, + compareIterables, + compareModulesById, + compareModulesByIdentifier, + compareSelect, + concatComparators +} = require("./util/comparators"); +const createHash = require("./util/createHash"); +const findGraphRoots = require("./util/findGraphRoots"); +const { + RuntimeSpecMap, + RuntimeSpecSet, + forEachRuntime, + mergeRuntime, + runtimeToString +} = require("./util/runtime"); + +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Chunk").ChunkId} ChunkId */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Generator").SourceTypes} SourceTypes */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ +/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {typeof import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** @type {ReadonlySet} */ +const EMPTY_SET = new Set(); + +const ZERO_BIG_INT = BigInt(0); + +const compareModuleIterables = compareIterables(compareModulesByIdentifier); + +/** @typedef {(c: Chunk, chunkGraph: ChunkGraph) => boolean} ChunkFilterPredicate */ +/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ +/** @typedef {[Module, Entrypoint | undefined]} EntryModuleWithChunkGroup */ + +/** + * @typedef {object} ChunkSizeOptions + * @property {number=} chunkOverhead constant overhead for a chunk + * @property {number=} entryChunkMultiplicator multiplicator for initial chunks + */ + +class ModuleHashInfo { + /** + * @param {string} hash hash + * @param {string} renderedHash rendered hash + */ + constructor(hash, renderedHash) { + this.hash = hash; + this.renderedHash = renderedHash; + } +} + +/** + * @template T + * @param {SortableSet} set the set + * @returns {T[]} set as array + */ +const getArray = (set) => [...set]; + +/** + * @param {SortableSet} chunks the chunks + * @returns {RuntimeSpecSet} runtimes + */ +const getModuleRuntimes = (chunks) => { + const runtimes = new RuntimeSpecSet(); + for (const chunk of chunks) { + runtimes.add(chunk.runtime); + } + return runtimes; +}; + +/** + * @param {WeakMap> | undefined} sourceTypesByModule sourceTypesByModule + * @returns {(set: SortableSet) => Map>} modules by source type + */ +const modulesBySourceType = (sourceTypesByModule) => (set) => { + /** @type {Map>} */ + const map = new Map(); + for (const module of set) { + const sourceTypes = + (sourceTypesByModule && sourceTypesByModule.get(module)) || + module.getSourceTypes(); + for (const sourceType of sourceTypes) { + let innerSet = map.get(sourceType); + if (innerSet === undefined) { + innerSet = new SortableSet(); + map.set(sourceType, innerSet); + } + innerSet.add(module); + } + } + for (const [key, innerSet] of map) { + // When all modules have the source type, we reuse the original SortableSet + // to benefit from the shared cache (especially for sorting) + if (innerSet.size === set.size) { + map.set(key, set); + } + } + return map; +}; +const defaultModulesBySourceType = modulesBySourceType(undefined); + +/** + * @typedef {(set: SortableSet) => Module[]} ModuleSetToArrayFunction + */ + +/** + * @template T + * @type {WeakMap} + */ +const createOrderedArrayFunctionMap = new WeakMap(); + +/** + * @template T + * @param {ModuleComparator} comparator comparator function + * @returns {ModuleSetToArrayFunction} set as ordered array + */ +const createOrderedArrayFunction = (comparator) => { + let fn = createOrderedArrayFunctionMap.get(comparator); + if (fn !== undefined) return fn; + fn = (set) => { + set.sortWith(comparator); + return [...set]; + }; + createOrderedArrayFunctionMap.set(comparator, fn); + return fn; +}; + +/** + * @param {Iterable} modules the modules to get the count/size of + * @returns {number} the size of the modules + */ +const getModulesSize = (modules) => { + let size = 0; + for (const module of modules) { + for (const type of module.getSourceTypes()) { + size += module.size(type); + } + } + return size; +}; + +/** + * @param {Iterable} modules the sortable Set to get the size of + * @returns {Record} the sizes of the modules + */ +const getModulesSizes = (modules) => { + const sizes = Object.create(null); + for (const module of modules) { + for (const type of module.getSourceTypes()) { + sizes[type] = (sizes[type] || 0) + module.size(type); + } + } + return sizes; +}; + +/** + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {boolean} true, if a is always a parent of b + */ +const isAvailableChunk = (a, b) => { + const queue = new Set(b.groupsIterable); + for (const chunkGroup of queue) { + if (a.isInGroup(chunkGroup)) continue; + if (chunkGroup.isInitial()) return false; + for (const parent of chunkGroup.parentsIterable) { + queue.add(parent); + } + } + return true; +}; + +/** @typedef {Set} EntryInChunks */ +/** @typedef {Set} RuntimeInChunks */ +/** @typedef {string | number} ModuleId */ + +class ChunkGraphModule { + constructor() { + /** @type {SortableSet} */ + this.chunks = new SortableSet(); + /** @type {EntryInChunks | undefined} */ + this.entryInChunks = undefined; + /** @type {RuntimeInChunks | undefined} */ + this.runtimeInChunks = undefined; + /** @type {RuntimeSpecMap | undefined} */ + this.hashes = undefined; + /** @type {ModuleId | null} */ + this.id = null; + /** @type {RuntimeSpecMap, RuntimeRequirements> | undefined} */ + this.runtimeRequirements = undefined; + /** @type {RuntimeSpecMap | undefined} */ + this.graphHashes = undefined; + /** @type {RuntimeSpecMap | undefined} */ + this.graphHashesWithConnections = undefined; + } +} + +class ChunkGraphChunk { + constructor() { + /** @type {SortableSet} */ + this.modules = new SortableSet(); + /** @type {WeakMap> | undefined} */ + this.sourceTypesByModule = undefined; + /** @type {Map} */ + this.entryModules = new Map(); + /** @type {SortableSet} */ + this.runtimeModules = new SortableSet(); + /** @type {Set | undefined} */ + this.fullHashModules = undefined; + /** @type {Set | undefined} */ + this.dependentHashModules = undefined; + /** @type {Set | undefined} */ + this.runtimeRequirements = undefined; + /** @type {Set} */ + this.runtimeRequirementsInTree = new Set(); + + this._modulesBySourceType = defaultModulesBySourceType; + } +} + +/** @typedef {(a: Module, b: Module) => -1 | 0 | 1} ModuleComparator */ + +class ChunkGraph { + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {string | Hash} hashFunction the hash function to use + */ + constructor(moduleGraph, hashFunction = DEFAULTS.HASH_FUNCTION) { + /** + * @private + * @type {WeakMap} + */ + this._modules = new WeakMap(); + /** + * @private + * @type {WeakMap} + */ + this._chunks = new WeakMap(); + /** + * @private + * @type {WeakMap} + */ + this._blockChunkGroups = new WeakMap(); + /** + * @private + * @type {Map} + */ + this._runtimeIds = new Map(); + /** @type {ModuleGraph} */ + this.moduleGraph = moduleGraph; + + this._hashFunction = hashFunction; + + this._getGraphRoots = this._getGraphRoots.bind(this); + } + + /** + * @private + * @param {Module} module the module + * @returns {ChunkGraphModule} internal module + */ + _getChunkGraphModule(module) { + let cgm = this._modules.get(module); + if (cgm === undefined) { + cgm = new ChunkGraphModule(); + this._modules.set(module, cgm); + } + return cgm; + } + + /** + * @private + * @param {Chunk} chunk the chunk + * @returns {ChunkGraphChunk} internal chunk + */ + _getChunkGraphChunk(chunk) { + let cgc = this._chunks.get(chunk); + if (cgc === undefined) { + cgc = new ChunkGraphChunk(); + this._chunks.set(chunk, cgc); + } + return cgc; + } + + /** + * @param {SortableSet} set the sortable Set to get the roots of + * @returns {Module[]} the graph roots + */ + _getGraphRoots(set) { + const { moduleGraph } = this; + return [ + ...findGraphRoots(set, (module) => { + /** @type {Set} */ + const set = new Set(); + /** + * @param {Module} module module + */ + const addDependencies = (module) => { + for (const connection of moduleGraph.getOutgoingConnections(module)) { + if (!connection.module) continue; + const activeState = connection.getActiveState(undefined); + if (activeState === false) continue; + if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) { + addDependencies(connection.module); + continue; + } + set.add(connection.module); + } + }; + addDependencies(module); + return set; + }) + ].sort(compareModulesByIdentifier); + } + + /** + * @param {Chunk} chunk the new chunk + * @param {Module} module the module + * @returns {void} + */ + connectChunkAndModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgm.chunks.add(chunk); + cgc.modules.add(module); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Module} module the module + * @returns {void} + */ + disconnectChunkAndModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgc.modules.delete(module); + // No need to invalidate cgc._modulesBySourceType because we modified cgc.modules anyway + if (cgc.sourceTypesByModule) cgc.sourceTypesByModule.delete(module); + cgm.chunks.delete(chunk); + } + + /** + * @param {Chunk} chunk the chunk which will be disconnected + * @returns {void} + */ + disconnectChunk(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of cgc.modules) { + const cgm = this._getChunkGraphModule(module); + cgm.chunks.delete(chunk); + } + cgc.modules.clear(); + chunk.disconnectFromGroups(); + ChunkGraph.clearChunkGraphForChunk(chunk); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the modules + * @returns {void} + */ + attachModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of modules) { + cgc.modules.add(module); + } + } + + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the runtime modules + * @returns {void} + */ + attachRuntimeModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of modules) { + cgc.runtimeModules.add(module); + } + } + + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the modules that require a full hash + * @returns {void} + */ + attachFullHashModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); + for (const module of modules) { + cgc.fullHashModules.add(module); + } + } + + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the modules that require a full hash + * @returns {void} + */ + attachDependentHashModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.dependentHashModules === undefined) { + cgc.dependentHashModules = new Set(); + } + for (const module of modules) { + cgc.dependentHashModules.add(module); + } + } + + /** + * @param {Module} oldModule the replaced module + * @param {Module} newModule the replacing module + * @returns {void} + */ + replaceModule(oldModule, newModule) { + const oldCgm = this._getChunkGraphModule(oldModule); + const newCgm = this._getChunkGraphModule(newModule); + + for (const chunk of oldCgm.chunks) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.modules.delete(oldModule); + cgc.modules.add(newModule); + newCgm.chunks.add(chunk); + } + oldCgm.chunks.clear(); + + if (oldCgm.entryInChunks !== undefined) { + if (newCgm.entryInChunks === undefined) { + newCgm.entryInChunks = new Set(); + } + for (const chunk of oldCgm.entryInChunks) { + const cgc = this._getChunkGraphChunk(chunk); + const old = /** @type {Entrypoint} */ (cgc.entryModules.get(oldModule)); + /** @type {Map} */ + const newEntryModules = new Map(); + for (const [m, cg] of cgc.entryModules) { + if (m === oldModule) { + newEntryModules.set(newModule, old); + } else { + newEntryModules.set(m, cg); + } + } + cgc.entryModules = newEntryModules; + newCgm.entryInChunks.add(chunk); + } + oldCgm.entryInChunks = undefined; + } + + if (oldCgm.runtimeInChunks !== undefined) { + if (newCgm.runtimeInChunks === undefined) { + newCgm.runtimeInChunks = new Set(); + } + for (const chunk of oldCgm.runtimeInChunks) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.runtimeModules.delete(/** @type {RuntimeModule} */ (oldModule)); + cgc.runtimeModules.add(/** @type {RuntimeModule} */ (newModule)); + newCgm.runtimeInChunks.add(chunk); + if ( + cgc.fullHashModules !== undefined && + cgc.fullHashModules.has(/** @type {RuntimeModule} */ (oldModule)) + ) { + cgc.fullHashModules.delete(/** @type {RuntimeModule} */ (oldModule)); + cgc.fullHashModules.add(/** @type {RuntimeModule} */ (newModule)); + } + if ( + cgc.dependentHashModules !== undefined && + cgc.dependentHashModules.has(/** @type {RuntimeModule} */ (oldModule)) + ) { + cgc.dependentHashModules.delete( + /** @type {RuntimeModule} */ (oldModule) + ); + cgc.dependentHashModules.add( + /** @type {RuntimeModule} */ (newModule) + ); + } + } + oldCgm.runtimeInChunks = undefined; + } + } + + /** + * @param {Module} module the checked module + * @param {Chunk} chunk the checked chunk + * @returns {boolean} true, if the chunk contains the module + */ + isModuleInChunk(module, chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.has(module); + } + + /** + * @param {Module} module the checked module + * @param {ChunkGroup} chunkGroup the checked chunk group + * @returns {boolean} true, if the chunk contains the module + */ + isModuleInChunkGroup(module, chunkGroup) { + for (const chunk of chunkGroup.chunks) { + if (this.isModuleInChunk(module, chunk)) return true; + } + return false; + } + + /** + * @param {Module} module the checked module + * @returns {boolean} true, if the module is entry of any chunk + */ + isEntryModule(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.entryInChunks !== undefined; + } + + /** + * @param {Module} module the module + * @returns {Iterable} iterable of chunks (do not modify) + */ + getModuleChunksIterable(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks; + } + + /** + * @param {Module} module the module + * @param {(a: Chunk, b: Chunk) => -1 | 0 | 1} sortFn sort function + * @returns {Iterable} iterable of chunks (do not modify) + */ + getOrderedModuleChunksIterable(module, sortFn) { + const cgm = this._getChunkGraphModule(module); + cgm.chunks.sortWith(sortFn); + return cgm.chunks; + } + + /** + * @param {Module} module the module + * @returns {Chunk[]} array of chunks (cached, do not modify) + */ + getModuleChunks(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks.getFromCache(getArray); + } + + /** + * @param {Module} module the module + * @returns {number} the number of chunk which contain the module + */ + getNumberOfModuleChunks(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks.size; + } + + /** + * @param {Module} module the module + * @returns {RuntimeSpecSet} runtimes + */ + getModuleRuntimes(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks.getFromUnorderedCache(getModuleRuntimes); + } + + /** + * @param {Chunk} chunk the chunk + * @returns {number} the number of modules which are contained in this chunk + */ + getNumberOfChunkModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.size; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {number} the number of full hash modules which are contained in this chunk + */ + getNumberOfChunkFullHashModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.fullHashModules === undefined ? 0 : cgc.fullHashModules.size; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} return the modules for this chunk + */ + getChunkModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules; + } + + /** + * @param {Chunk} chunk the chunk + * @param {string} sourceType source type + * @returns {Iterable | undefined} return the modules for this chunk + */ + getChunkModulesIterableBySourceType(chunk, sourceType) { + const cgc = this._getChunkGraphChunk(chunk); + const modulesWithSourceType = cgc.modules + .getFromUnorderedCache(cgc._modulesBySourceType) + .get(sourceType); + return modulesWithSourceType; + } + + /** + * @param {Chunk} chunk chunk + * @param {Module} module chunk module + * @param {Set} sourceTypes source types + */ + setChunkModuleSourceTypes(chunk, module, sourceTypes) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.sourceTypesByModule === undefined) { + cgc.sourceTypesByModule = new WeakMap(); + } + cgc.sourceTypesByModule.set(module, sourceTypes); + // Update cgc._modulesBySourceType to invalidate the cache + cgc._modulesBySourceType = modulesBySourceType(cgc.sourceTypesByModule); + } + + /** + * @param {Chunk} chunk chunk + * @param {Module} module chunk module + * @returns {SourceTypes} source types + */ + getChunkModuleSourceTypes(chunk, module) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.sourceTypesByModule === undefined) { + return module.getSourceTypes(); + } + return cgc.sourceTypesByModule.get(module) || module.getSourceTypes(); + } + + /** + * @param {Module} module module + * @returns {SourceTypes} source types + */ + getModuleSourceTypes(module) { + return ( + this._getOverwrittenModuleSourceTypes(module) || module.getSourceTypes() + ); + } + + /** + * @param {Module} module module + * @returns {Set | undefined} source types + */ + _getOverwrittenModuleSourceTypes(module) { + let newSet = false; + let sourceTypes; + for (const chunk of this.getModuleChunksIterable(module)) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.sourceTypesByModule === undefined) return; + const st = cgc.sourceTypesByModule.get(module); + if (st === undefined) return; + if (!sourceTypes) { + sourceTypes = st; + } else if (!newSet) { + for (const type of st) { + if (!newSet) { + if (!sourceTypes.has(type)) { + newSet = true; + sourceTypes = new Set(sourceTypes); + sourceTypes.add(type); + } + } else { + sourceTypes.add(type); + } + } + } else { + for (const type of st) sourceTypes.add(type); + } + } + + return sourceTypes; + } + + /** + * @param {Chunk} chunk the chunk + * @param {ModuleComparator} comparator comparator function + * @returns {Iterable} return the modules for this chunk + */ + getOrderedChunkModulesIterable(chunk, comparator) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.modules.sortWith(comparator); + return cgc.modules; + } + + /** + * @param {Chunk} chunk the chunk + * @param {string} sourceType source type + * @param {ModuleComparator} comparator comparator function + * @returns {Iterable | undefined} return the modules for this chunk + */ + getOrderedChunkModulesIterableBySourceType(chunk, sourceType, comparator) { + const cgc = this._getChunkGraphChunk(chunk); + const modulesWithSourceType = cgc.modules + .getFromUnorderedCache(cgc._modulesBySourceType) + .get(sourceType); + if (modulesWithSourceType === undefined) return; + modulesWithSourceType.sortWith(comparator); + return modulesWithSourceType; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Module[]} return the modules for this chunk (cached, do not modify) + */ + getChunkModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(getArray); + } + + /** + * @param {Chunk} chunk the chunk + * @param {ModuleComparator} comparator comparator function + * @returns {Module[]} return the modules for this chunk (cached, do not modify) + */ + getOrderedChunkModules(chunk, comparator) { + const cgc = this._getChunkGraphChunk(chunk); + const arrayFunction = createOrderedArrayFunction(comparator); + return cgc.modules.getFromUnorderedCache(arrayFunction); + } + + /** + * @param {Chunk} chunk the chunk + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @param {boolean} includeAllChunks all chunks or only async chunks + * @returns {Record} chunk to module ids object + */ + getChunkModuleIdMap(chunk, filterFn, includeAllChunks = false) { + /** @type {Record} */ + const chunkModuleIdMap = Object.create(null); + + for (const asyncChunk of includeAllChunks + ? chunk.getAllReferencedChunks() + : chunk.getAllAsyncChunks()) { + /** @type {(string | number)[] | undefined} */ + let array; + for (const module of this.getOrderedChunkModulesIterable( + asyncChunk, + compareModulesById(this) + )) { + if (filterFn(module)) { + if (array === undefined) { + array = []; + chunkModuleIdMap[/** @type {ChunkId} */ (asyncChunk.id)] = array; + } + const moduleId = /** @type {ModuleId} */ (this.getModuleId(module)); + array.push(moduleId); + } + } + } + + return chunkModuleIdMap; + } + + /** + * @param {Chunk} chunk the chunk + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @param {number} hashLength length of the hash + * @param {boolean} includeAllChunks all chunks or only async chunks + * @returns {Record>} chunk to module id to module hash object + */ + getChunkModuleRenderedHashMap( + chunk, + filterFn, + hashLength = 0, + includeAllChunks = false + ) { + /** @type {Record>} */ + const chunkModuleHashMap = Object.create(null); + + /** @typedef {Record} IdToHashMap */ + + for (const asyncChunk of includeAllChunks + ? chunk.getAllReferencedChunks() + : chunk.getAllAsyncChunks()) { + /** @type {IdToHashMap | undefined} */ + let idToHashMap; + for (const module of this.getOrderedChunkModulesIterable( + asyncChunk, + compareModulesById(this) + )) { + if (filterFn(module)) { + if (idToHashMap === undefined) { + idToHashMap = Object.create(null); + chunkModuleHashMap[/** @type {ChunkId} */ (asyncChunk.id)] = + /** @type {IdToHashMap} */ (idToHashMap); + } + const moduleId = this.getModuleId(module); + const hash = this.getRenderedModuleHash(module, asyncChunk.runtime); + /** @type {IdToHashMap} */ + (idToHashMap)[/** @type {ModuleId} */ (moduleId)] = hashLength + ? hash.slice(0, hashLength) + : hash; + } + } + } + + return chunkModuleHashMap; + } + + /** + * @param {Chunk} chunk the chunk + * @param {ChunkFilterPredicate} filterFn function used to filter chunks + * @returns {Record} chunk map + */ + getChunkConditionMap(chunk, filterFn) { + const map = Object.create(null); + for (const c of chunk.getAllReferencedChunks()) { + map[/** @type {ChunkId} */ (c.id)] = filterFn(c, this); + } + return map; + } + + /** + * @param {Chunk} chunk the chunk + * @param {ModuleFilterPredicate} filterFn predicate function used to filter modules + * @param {ChunkFilterPredicate=} filterChunkFn predicate function used to filter chunks + * @returns {boolean} return true if module exists in graph + */ + hasModuleInGraph(chunk, filterFn, filterChunkFn) { + const queue = new Set(chunk.groupsIterable); + const chunksProcessed = new Set(); + + for (const chunkGroup of queue) { + for (const innerChunk of chunkGroup.chunks) { + if (!chunksProcessed.has(innerChunk)) { + chunksProcessed.add(innerChunk); + if (!filterChunkFn || filterChunkFn(innerChunk, this)) { + for (const module of this.getChunkModulesIterable(innerChunk)) { + if (filterFn(module)) { + return true; + } + } + } + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + return false; + } + + /** + * @param {Chunk} chunkA first chunk + * @param {Chunk} chunkB second chunk + * @returns {-1|0|1} this is a comparator function like sort and returns -1, 0, or 1 based on sort order + */ + compareChunks(chunkA, chunkB) { + const cgcA = this._getChunkGraphChunk(chunkA); + const cgcB = this._getChunkGraphChunk(chunkB); + if (cgcA.modules.size > cgcB.modules.size) return -1; + if (cgcA.modules.size < cgcB.modules.size) return 1; + cgcA.modules.sortWith(compareModulesByIdentifier); + cgcB.modules.sortWith(compareModulesByIdentifier); + return compareModuleIterables(cgcA.modules, cgcB.modules); + } + + /** + * @param {Chunk} chunk the chunk + * @returns {number} total size of all modules in the chunk + */ + getChunkModulesSize(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(getModulesSize); + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Record} total sizes of all modules in the chunk by source type + */ + getChunkModulesSizes(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(getModulesSizes); + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Module[]} root modules of the chunks (ordered by identifier) + */ + getChunkRootModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(this._getGraphRoots); + } + + /** + * @param {Chunk} chunk the chunk + * @param {ChunkSizeOptions} options options object + * @returns {number} total size of the chunk + */ + getChunkSize(chunk, options = {}) { + const cgc = this._getChunkGraphChunk(chunk); + const modulesSize = cgc.modules.getFromUnorderedCache(getModulesSize); + const chunkOverhead = + typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; + const entryChunkMultiplicator = + typeof options.entryChunkMultiplicator === "number" + ? options.entryChunkMultiplicator + : 10; + return ( + chunkOverhead + + modulesSize * (chunk.canBeInitial() ? entryChunkMultiplicator : 1) + ); + } + + /** + * @param {Chunk} chunkA chunk + * @param {Chunk} chunkB chunk + * @param {ChunkSizeOptions} options options object + * @returns {number} total size of the chunk or false if chunks can't be integrated + */ + getIntegratedChunksSize(chunkA, chunkB, options = {}) { + const cgcA = this._getChunkGraphChunk(chunkA); + const cgcB = this._getChunkGraphChunk(chunkB); + const allModules = new Set(cgcA.modules); + for (const m of cgcB.modules) allModules.add(m); + const modulesSize = getModulesSize(allModules); + const chunkOverhead = + typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; + const entryChunkMultiplicator = + typeof options.entryChunkMultiplicator === "number" + ? options.entryChunkMultiplicator + : 10; + return ( + chunkOverhead + + modulesSize * + (chunkA.canBeInitial() || chunkB.canBeInitial() + ? entryChunkMultiplicator + : 1) + ); + } + + /** + * @param {Chunk} chunkA chunk + * @param {Chunk} chunkB chunk + * @returns {boolean} true, if chunks could be integrated + */ + canChunksBeIntegrated(chunkA, chunkB) { + if (chunkA.preventIntegration || chunkB.preventIntegration) { + return false; + } + + const hasRuntimeA = chunkA.hasRuntime(); + const hasRuntimeB = chunkB.hasRuntime(); + + if (hasRuntimeA !== hasRuntimeB) { + if (hasRuntimeA) { + return isAvailableChunk(chunkA, chunkB); + } else if (hasRuntimeB) { + return isAvailableChunk(chunkB, chunkA); + } + + return false; + } + + if ( + this.getNumberOfEntryModules(chunkA) > 0 || + this.getNumberOfEntryModules(chunkB) > 0 + ) { + return false; + } + + return true; + } + + /** + * @param {Chunk} chunkA the target chunk + * @param {Chunk} chunkB the chunk to integrate + * @returns {void} + */ + integrateChunks(chunkA, chunkB) { + // Decide for one name (deterministic) + if (chunkA.name && chunkB.name) { + if ( + this.getNumberOfEntryModules(chunkA) > 0 === + this.getNumberOfEntryModules(chunkB) > 0 + ) { + // When both chunks have entry modules or none have one, use + // shortest name + if (chunkA.name.length !== chunkB.name.length) { + chunkA.name = + chunkA.name.length < chunkB.name.length ? chunkA.name : chunkB.name; + } else { + chunkA.name = chunkA.name < chunkB.name ? chunkA.name : chunkB.name; + } + } else if (this.getNumberOfEntryModules(chunkB) > 0) { + // Pick the name of the chunk with the entry module + chunkA.name = chunkB.name; + } + } else if (chunkB.name) { + chunkA.name = chunkB.name; + } + + // Merge id name hints + for (const hint of chunkB.idNameHints) { + chunkA.idNameHints.add(hint); + } + + // Merge runtime + chunkA.runtime = mergeRuntime(chunkA.runtime, chunkB.runtime); + + // getChunkModules is used here to create a clone, because disconnectChunkAndModule modifies + for (const module of this.getChunkModules(chunkB)) { + this.disconnectChunkAndModule(chunkB, module); + this.connectChunkAndModule(chunkA, module); + } + + for (const [ + module, + chunkGroup + ] of this.getChunkEntryModulesWithChunkGroupIterable(chunkB)) { + this.disconnectChunkAndEntryModule(chunkB, module); + this.connectChunkAndEntryModule( + chunkA, + module, + /** @type {Entrypoint} */ + (chunkGroup) + ); + } + + for (const chunkGroup of chunkB.groupsIterable) { + chunkGroup.replaceChunk(chunkB, chunkA); + chunkA.addGroup(chunkGroup); + chunkB.removeGroup(chunkGroup); + } + ChunkGraph.clearChunkGraphForChunk(chunkB); + } + + /** + * @param {Chunk} chunk the chunk to upgrade + * @returns {void} + */ + upgradeDependentToFullHashModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.dependentHashModules === undefined) return; + if (cgc.fullHashModules === undefined) { + cgc.fullHashModules = cgc.dependentHashModules; + } else { + for (const m of cgc.dependentHashModules) { + cgc.fullHashModules.add(m); + } + cgc.dependentHashModules = undefined; + } + } + + /** + * @param {Module} module the checked module + * @param {Chunk} chunk the checked chunk + * @returns {boolean} true, if the chunk contains the module as entry + */ + isEntryModuleInChunk(module, chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules.has(module); + } + + /** + * @param {Chunk} chunk the new chunk + * @param {Module} module the entry module + * @param {Entrypoint} entrypoint the chunk group which must be loaded before the module is executed + * @returns {void} + */ + connectChunkAndEntryModule(chunk, module, entrypoint) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + if (cgm.entryInChunks === undefined) { + cgm.entryInChunks = new Set(); + } + cgm.entryInChunks.add(chunk); + cgc.entryModules.set(module, entrypoint); + } + + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the runtime module + * @returns {void} + */ + connectChunkAndRuntimeModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + if (cgm.runtimeInChunks === undefined) { + cgm.runtimeInChunks = new Set(); + } + cgm.runtimeInChunks.add(chunk); + cgc.runtimeModules.add(module); + } + + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the module that require a full hash + * @returns {void} + */ + addFullHashModuleToChunk(chunk, module) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); + cgc.fullHashModules.add(module); + } + + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the module that require a full hash + * @returns {void} + */ + addDependentHashModuleToChunk(chunk, module) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.dependentHashModules === undefined) { + cgc.dependentHashModules = new Set(); + } + cgc.dependentHashModules.add(module); + } + + /** + * @param {Chunk} chunk the new chunk + * @param {Module} module the entry module + * @returns {void} + */ + disconnectChunkAndEntryModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + /** @type {EntryInChunks} */ + (cgm.entryInChunks).delete(chunk); + if (/** @type {EntryInChunks} */ (cgm.entryInChunks).size === 0) { + cgm.entryInChunks = undefined; + } + cgc.entryModules.delete(module); + } + + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the runtime module + * @returns {void} + */ + disconnectChunkAndRuntimeModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + /** @type {RuntimeInChunks} */ + (cgm.runtimeInChunks).delete(chunk); + if (/** @type {RuntimeInChunks} */ (cgm.runtimeInChunks).size === 0) { + cgm.runtimeInChunks = undefined; + } + cgc.runtimeModules.delete(module); + } + + /** + * @param {Module} module the entry module, it will no longer be entry + * @returns {void} + */ + disconnectEntryModule(module) { + const cgm = this._getChunkGraphModule(module); + for (const chunk of /** @type {EntryInChunks} */ (cgm.entryInChunks)) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.entryModules.delete(module); + } + cgm.entryInChunks = undefined; + } + + /** + * @param {Chunk} chunk the chunk, for which all entries will be removed + * @returns {void} + */ + disconnectEntries(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of cgc.entryModules.keys()) { + const cgm = this._getChunkGraphModule(module); + /** @type {EntryInChunks} */ + (cgm.entryInChunks).delete(chunk); + if (/** @type {EntryInChunks} */ (cgm.entryInChunks).size === 0) { + cgm.entryInChunks = undefined; + } + } + cgc.entryModules.clear(); + } + + /** + * @param {Chunk} chunk the chunk + * @returns {number} the amount of entry modules in chunk + */ + getNumberOfEntryModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules.size; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {number} the amount of entry modules in chunk + */ + getNumberOfRuntimeModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.runtimeModules.size; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of modules (do not modify) + */ + getChunkEntryModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules.keys(); + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of chunks + */ + getChunkEntryDependentChunksIterable(chunk) { + /** @type {Set} */ + const set = new Set(); + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup instanceof Entrypoint) { + const entrypointChunk = chunkGroup.getEntrypointChunk(); + const cgc = this._getChunkGraphChunk(entrypointChunk); + for (const chunkGroup of cgc.entryModules.values()) { + for (const c of chunkGroup.chunks) { + if (c !== chunk && c !== entrypointChunk && !c.hasRuntime()) { + set.add(c); + } + } + } + } + } + + return set; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of chunks and include chunks from children entrypoints + */ + getRuntimeChunkDependentChunksIterable(chunk) { + /** @type {Set} */ + const set = new Set(); + + /** @type {Set} */ + const entrypoints = new Set(); + + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup instanceof Entrypoint) { + const queue = [chunkGroup]; + while (queue.length > 0) { + const current = queue.shift(); + if (current) { + entrypoints.add(current); + + let hasChildrenEntrypoint = false; + for (const child of current.childrenIterable) { + if (child instanceof Entrypoint && child.dependOn(current)) { + hasChildrenEntrypoint = true; + queue.push(/** @type {Entrypoint} */ (child)); + } + } + // entryChunkB: hasChildrenEntrypoint = true + // entryChunkA: dependOn = entryChunkB + if (hasChildrenEntrypoint) { + const entrypointChunk = current.getEntrypointChunk(); + if (entrypointChunk !== chunk && !entrypointChunk.hasRuntime()) { + // add entryChunkB to set + set.add(entrypointChunk); + } + } + } + } + } + } + + for (const entrypoint of entrypoints) { + const entrypointChunk = entrypoint.getEntrypointChunk(); + const cgc = this._getChunkGraphChunk(entrypointChunk); + for (const chunkGroup of cgc.entryModules.values()) { + for (const c of chunkGroup.chunks) { + if (c !== chunk && c !== entrypointChunk && !c.hasRuntime()) { + set.add(c); + } + } + } + } + return set; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {boolean} true, when it has dependent chunks + */ + hasChunkEntryDependentChunks(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + for (const chunkGroup of cgc.entryModules.values()) { + for (const c of chunkGroup.chunks) { + if (c !== chunk) { + return true; + } + } + } + return false; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of modules (do not modify) + */ + getChunkRuntimeModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.runtimeModules; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {RuntimeModule[]} array of modules in order of execution + */ + getChunkRuntimeModulesInOrder(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + const array = [...cgc.runtimeModules]; + array.sort( + concatComparators( + compareSelect( + (r) => /** @type {RuntimeModule} */ (r).stage, + compareIds + ), + compareModulesByIdentifier + ) + ); + return array; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable | undefined} iterable of modules (do not modify) + */ + getChunkFullHashModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.fullHashModules; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {ReadonlySet | undefined} set of modules (do not modify) + */ + getChunkFullHashModulesSet(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.fullHashModules; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable | undefined} iterable of modules (do not modify) + */ + getChunkDependentHashModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.dependentHashModules; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of modules (do not modify) + */ + getChunkEntryModulesWithChunkGroupIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules; + } + + /** + * @param {AsyncDependenciesBlock} depBlock the async block + * @returns {ChunkGroup | undefined} the chunk group + */ + getBlockChunkGroup(depBlock) { + return this._blockChunkGroups.get(depBlock); + } + + /** + * @param {AsyncDependenciesBlock} depBlock the async block + * @param {ChunkGroup} chunkGroup the chunk group + * @returns {void} + */ + connectBlockAndChunkGroup(depBlock, chunkGroup) { + this._blockChunkGroups.set(depBlock, chunkGroup); + chunkGroup.addBlock(depBlock); + } + + /** + * @param {ChunkGroup} chunkGroup the chunk group + * @returns {void} + */ + disconnectChunkGroup(chunkGroup) { + for (const block of chunkGroup.blocksIterable) { + this._blockChunkGroups.delete(block); + } + // TODO refactor by moving blocks list into ChunkGraph + chunkGroup._blocks.clear(); + } + + /** + * @param {Module} module the module + * @returns {ModuleId | null} the id of the module + */ + getModuleId(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.id; + } + + /** + * @param {Module} module the module + * @param {ModuleId} id the id of the module + * @returns {void} + */ + setModuleId(module, id) { + const cgm = this._getChunkGraphModule(module); + cgm.id = id; + } + + /** + * @param {string} runtime runtime + * @returns {string | number} the id of the runtime + */ + getRuntimeId(runtime) { + return /** @type {string | number} */ (this._runtimeIds.get(runtime)); + } + + /** + * @param {string} runtime runtime + * @param {string | number} id the id of the runtime + * @returns {void} + */ + setRuntimeId(runtime, id) { + this._runtimeIds.set(runtime, id); + } + + /** + * @template T + * @param {Module} module the module + * @param {RuntimeSpecMap} hashes hashes data + * @param {RuntimeSpec} runtime the runtime + * @returns {T} hash + */ + _getModuleHashInfo(module, hashes, runtime) { + if (!hashes) { + throw new Error( + `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( + runtime + )} (hashes not set at all)` + ); + } else if (runtime === undefined) { + const hashInfoItems = new Set(hashes.values()); + if (hashInfoItems.size !== 1) { + throw new Error( + `No unique hash info entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from( + hashes.keys(), + (r) => runtimeToString(r) + ).join(", ")}). +Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").` + ); + } + return /** @type {T} */ (first(hashInfoItems)); + } else { + const hashInfo = hashes.get(runtime); + if (!hashInfo) { + throw new Error( + `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( + runtime + )} (available runtimes ${Array.from( + hashes.keys(), + runtimeToString + ).join(", ")})` + ); + } + return hashInfo; + } + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, if the module has hashes for this runtime + */ + hasModuleHashes(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const hashes = /** @type {RuntimeSpecMap} */ (cgm.hashes); + return hashes && hashes.has(runtime); + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {string} hash + */ + getModuleHash(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const hashes = /** @type {RuntimeSpecMap} */ (cgm.hashes); + return this._getModuleHashInfo(module, hashes, runtime).hash; + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {string} hash + */ + getRenderedModuleHash(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const hashes = /** @type {RuntimeSpecMap} */ (cgm.hashes); + return this._getModuleHashInfo(module, hashes, runtime).renderedHash; + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {string} hash the full hash + * @param {string} renderedHash the shortened hash for rendering + * @returns {void} + */ + setModuleHashes(module, runtime, hash, renderedHash) { + const cgm = this._getChunkGraphModule(module); + if (cgm.hashes === undefined) { + cgm.hashes = new RuntimeSpecMap(); + } + cgm.hashes.set(runtime, new ModuleHashInfo(hash, renderedHash)); + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph when transferOwnership not false) + * @param {boolean} transferOwnership true: transfer ownership of the items object, false: items is immutable and shared and won't be modified + * @returns {void} + */ + addModuleRuntimeRequirements( + module, + runtime, + items, + transferOwnership = true + ) { + const cgm = this._getChunkGraphModule(module); + const runtimeRequirementsMap = cgm.runtimeRequirements; + if (runtimeRequirementsMap === undefined) { + const map = new RuntimeSpecMap(); + // TODO avoid cloning item and track ownership instead + map.set(runtime, transferOwnership ? items : new Set(items)); + cgm.runtimeRequirements = map; + return; + } + runtimeRequirementsMap.update(runtime, (runtimeRequirements) => { + if (runtimeRequirements === undefined) { + return transferOwnership ? items : new Set(items); + } else if (!transferOwnership || runtimeRequirements.size >= items.size) { + for (const item of items) runtimeRequirements.add(item); + return runtimeRequirements; + } + + for (const item of runtimeRequirements) items.add(item); + return items; + }); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph) + * @returns {void} + */ + addChunkRuntimeRequirements(chunk, items) { + const cgc = this._getChunkGraphChunk(chunk); + const runtimeRequirements = cgc.runtimeRequirements; + if (runtimeRequirements === undefined) { + cgc.runtimeRequirements = items; + } else if (runtimeRequirements.size >= items.size) { + for (const item of items) runtimeRequirements.add(item); + } else { + for (const item of runtimeRequirements) items.add(item); + cgc.runtimeRequirements = items; + } + } + + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} items runtime requirements to be added + * @returns {void} + */ + addTreeRuntimeRequirements(chunk, items) { + const cgc = this._getChunkGraphChunk(chunk); + const runtimeRequirements = cgc.runtimeRequirementsInTree; + for (const item of items) runtimeRequirements.add(item); + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {ReadOnlyRuntimeRequirements} runtime requirements + */ + getModuleRuntimeRequirements(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const runtimeRequirements = + cgm.runtimeRequirements && cgm.runtimeRequirements.get(runtime); + return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {ReadOnlyRuntimeRequirements} runtime requirements + */ + getChunkRuntimeRequirements(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + const runtimeRequirements = cgc.runtimeRequirements; + return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {boolean} withConnections include connections + * @returns {string} hash + */ + getModuleGraphHash(module, runtime, withConnections = true) { + const cgm = this._getChunkGraphModule(module); + return withConnections + ? this._getModuleGraphHashWithConnections(cgm, module, runtime) + : this._getModuleGraphHashBigInt(cgm, module, runtime).toString(16); + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {boolean} withConnections include connections + * @returns {bigint} hash + */ + getModuleGraphHashBigInt(module, runtime, withConnections = true) { + const cgm = this._getChunkGraphModule(module); + return withConnections + ? BigInt( + `0x${this._getModuleGraphHashWithConnections(cgm, module, runtime)}` + ) + : this._getModuleGraphHashBigInt(cgm, module, runtime); + } + + /** + * @param {ChunkGraphModule} cgm the ChunkGraphModule + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {bigint} hash as big int + */ + _getModuleGraphHashBigInt(cgm, module, runtime) { + if (cgm.graphHashes === undefined) { + cgm.graphHashes = new RuntimeSpecMap(); + } + const graphHash = cgm.graphHashes.provide(runtime, () => { + const hash = createHash(this._hashFunction); + hash.update(`${cgm.id}${this.moduleGraph.isAsync(module)}`); + const sourceTypes = this._getOverwrittenModuleSourceTypes(module); + if (sourceTypes !== undefined) { + for (const type of sourceTypes) hash.update(type); + } + this.moduleGraph.getExportsInfo(module).updateHash(hash, runtime); + return BigInt(`0x${/** @type {string} */ (hash.digest("hex"))}`); + }); + return graphHash; + } + + /** + * @param {ChunkGraphModule} cgm the ChunkGraphModule + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {string} hash + */ + _getModuleGraphHashWithConnections(cgm, module, runtime) { + if (cgm.graphHashesWithConnections === undefined) { + cgm.graphHashesWithConnections = new RuntimeSpecMap(); + } + + /** + * @param {ConnectionState} state state + * @returns {"F" | "T" | "O"} result + */ + const activeStateToString = (state) => { + if (state === false) return "F"; + if (state === true) return "T"; + if (state === ModuleGraphConnection.TRANSITIVE_ONLY) return "O"; + throw new Error("Not implemented active state"); + }; + const strict = module.buildMeta && module.buildMeta.strictHarmonyModule; + return cgm.graphHashesWithConnections.provide(runtime, () => { + const graphHash = this._getModuleGraphHashBigInt( + cgm, + module, + runtime + ).toString(16); + const connections = this.moduleGraph.getOutgoingConnections(module); + /** @type {Set} */ + const activeNamespaceModules = new Set(); + /** @type {Map>} */ + const connectedModules = new Map(); + /** + * @param {ModuleGraphConnection} connection connection + * @param {string} stateInfo state info + */ + const processConnection = (connection, stateInfo) => { + const module = connection.module; + stateInfo += module.getExportsType(this.moduleGraph, strict); + // cspell:word Tnamespace + if (stateInfo === "Tnamespace") { + activeNamespaceModules.add(module); + } else { + const oldModule = connectedModules.get(stateInfo); + if (oldModule === undefined) { + connectedModules.set(stateInfo, module); + } else if (oldModule instanceof Set) { + oldModule.add(module); + } else if (oldModule !== module) { + connectedModules.set(stateInfo, new Set([oldModule, module])); + } + } + }; + if (runtime === undefined || typeof runtime === "string") { + for (const connection of connections) { + const state = connection.getActiveState(runtime); + if (state === false) continue; + processConnection(connection, state === true ? "T" : "O"); + } + } else { + // cspell:word Tnamespace + for (const connection of connections) { + const states = new Set(); + let stateInfo = ""; + forEachRuntime( + runtime, + (runtime) => { + const state = connection.getActiveState(runtime); + states.add(state); + stateInfo += activeStateToString(state) + runtime; + }, + true + ); + if (states.size === 1) { + const state = first(states); + if (state === false) continue; + stateInfo = activeStateToString(state); + } + processConnection(connection, stateInfo); + } + } + // cspell:word Tnamespace + if (activeNamespaceModules.size === 0 && connectedModules.size === 0) { + return graphHash; + } + const connectedModulesInOrder = + connectedModules.size > 1 + ? [...connectedModules].sort(([a], [b]) => (a < b ? -1 : 1)) + : connectedModules; + const hash = createHash(this._hashFunction); + /** + * @param {Module} module module + */ + const addModuleToHash = (module) => { + hash.update( + this._getModuleGraphHashBigInt( + this._getChunkGraphModule(module), + module, + runtime + ).toString(16) + ); + }; + /** + * @param {Set} modules modules + */ + const addModulesToHash = (modules) => { + let xor = ZERO_BIG_INT; + for (const m of modules) { + xor ^= this._getModuleGraphHashBigInt( + this._getChunkGraphModule(m), + m, + runtime + ); + } + hash.update(xor.toString(16)); + }; + if (activeNamespaceModules.size === 1) { + addModuleToHash( + /** @type {Module} */ (activeNamespaceModules.values().next().value) + ); + } else if (activeNamespaceModules.size > 1) { + addModulesToHash(activeNamespaceModules); + } + for (const [stateInfo, modules] of connectedModulesInOrder) { + hash.update(stateInfo); + if (modules instanceof Set) { + addModulesToHash(modules); + } else { + addModuleToHash(modules); + } + } + hash.update(graphHash); + return /** @type {string} */ (hash.digest("hex")); + }); + } + + /** + * @param {Chunk} chunk the chunk + * @returns {ReadOnlyRuntimeRequirements} runtime requirements + */ + getTreeRuntimeRequirements(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.runtimeRequirementsInTree; + } + + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @param {string} deprecateMessage message for the deprecation message + * @param {string} deprecationCode code for the deprecation + * @returns {ChunkGraph} the chunk graph + */ + static getChunkGraphForModule(module, deprecateMessage, deprecationCode) { + const fn = deprecateGetChunkGraphForModuleMap.get(deprecateMessage); + if (fn) return fn(module); + const newFn = util.deprecate( + /** + * @param {Module} module the module + * @returns {ChunkGraph} the chunk graph + */ + (module) => { + const chunkGraph = chunkGraphForModuleMap.get(module); + if (!chunkGraph) { + throw new Error( + `${ + deprecateMessage + }: There was no ChunkGraph assigned to the Module for backward-compat (Use the new API)` + ); + } + return chunkGraph; + }, + `${deprecateMessage}: Use new ChunkGraph API`, + deprecationCode + ); + deprecateGetChunkGraphForModuleMap.set(deprecateMessage, newFn); + return newFn(module); + } + + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + static setChunkGraphForModule(module, chunkGraph) { + chunkGraphForModuleMap.set(module, chunkGraph); + } + + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @returns {void} + */ + static clearChunkGraphForModule(module) { + chunkGraphForModuleMap.delete(module); + } + + // TODO remove in webpack 6 + /** + * @param {Chunk} chunk the chunk + * @param {string} deprecateMessage message for the deprecation message + * @param {string} deprecationCode code for the deprecation + * @returns {ChunkGraph} the chunk graph + */ + static getChunkGraphForChunk(chunk, deprecateMessage, deprecationCode) { + const fn = deprecateGetChunkGraphForChunkMap.get(deprecateMessage); + if (fn) return fn(chunk); + const newFn = util.deprecate( + /** + * @param {Chunk} chunk the chunk + * @returns {ChunkGraph} the chunk graph + */ + (chunk) => { + const chunkGraph = chunkGraphForChunkMap.get(chunk); + if (!chunkGraph) { + throw new Error( + `${ + deprecateMessage + }There was no ChunkGraph assigned to the Chunk for backward-compat (Use the new API)` + ); + } + return chunkGraph; + }, + `${deprecateMessage}: Use new ChunkGraph API`, + deprecationCode + ); + deprecateGetChunkGraphForChunkMap.set(deprecateMessage, newFn); + return newFn(chunk); + } + + // TODO remove in webpack 6 + /** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + static setChunkGraphForChunk(chunk, chunkGraph) { + chunkGraphForChunkMap.set(chunk, chunkGraph); + } + + // TODO remove in webpack 6 + /** + * @param {Chunk} chunk the chunk + * @returns {void} + */ + static clearChunkGraphForChunk(chunk) { + chunkGraphForChunkMap.delete(chunk); + } +} + +// TODO remove in webpack 6 +/** @type {WeakMap} */ +const chunkGraphForModuleMap = new WeakMap(); + +// TODO remove in webpack 6 +/** @type {WeakMap} */ +const chunkGraphForChunkMap = new WeakMap(); + +// TODO remove in webpack 6 +/** @type {Map ChunkGraph>} */ +const deprecateGetChunkGraphForModuleMap = new Map(); + +// TODO remove in webpack 6 +/** @type {Map ChunkGraph>} */ +const deprecateGetChunkGraphForChunkMap = new Map(); + +module.exports = ChunkGraph; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkGroup.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkGroup.js new file mode 100644 index 0000000000000000000000000000000000000000..36d7389d2feff73c49a059a51968259211a2e8fa --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkGroup.js @@ -0,0 +1,611 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const SortableSet = require("./util/SortableSet"); +const { + compareChunks, + compareIterables, + compareLocations +} = require("./util/comparators"); + +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Entrypoint")} Entrypoint */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ + +/** @typedef {{id: number}} HasId */ +/** @typedef {{module: Module | null, loc: DependencyLocation, request: string}} OriginRecord */ + +/** + * @typedef {object} RawChunkGroupOptions + * @property {number=} preloadOrder + * @property {number=} prefetchOrder + * @property {("low" | "high" | "auto")=} fetchPriority + */ + +/** @typedef {RawChunkGroupOptions & { name?: string | null }} ChunkGroupOptions */ + +let debugId = 5000; + +/** + * @template T + * @param {SortableSet} set set to convert to array. + * @returns {T[]} the array format of existing set + */ +const getArray = (set) => [...set]; + +/** + * A convenience method used to sort chunks based on their id's + * @param {ChunkGroup} a first sorting comparator + * @param {ChunkGroup} b second sorting comparator + * @returns {1|0|-1} a sorting index to determine order + */ +const sortById = (a, b) => { + if (a.id < b.id) return -1; + if (b.id < a.id) return 1; + return 0; +}; + +/** + * @param {OriginRecord} a the first comparator in sort + * @param {OriginRecord} b the second comparator in sort + * @returns {1|-1|0} returns sorting order as index + */ +const sortOrigin = (a, b) => { + const aIdent = a.module ? a.module.identifier() : ""; + const bIdent = b.module ? b.module.identifier() : ""; + if (aIdent < bIdent) return -1; + if (aIdent > bIdent) return 1; + return compareLocations(a.loc, b.loc); +}; + +class ChunkGroup { + /** + * Creates an instance of ChunkGroup. + * @param {string | ChunkGroupOptions=} options chunk group options passed to chunkGroup + */ + constructor(options) { + if (typeof options === "string") { + options = { name: options }; + } else if (!options) { + options = { name: undefined }; + } + /** @type {number} */ + this.groupDebugId = debugId++; + this.options = /** @type {ChunkGroupOptions} */ (options); + /** @type {SortableSet} */ + this._children = new SortableSet(undefined, sortById); + /** @type {SortableSet} */ + this._parents = new SortableSet(undefined, sortById); + /** @type {SortableSet} */ + this._asyncEntrypoints = new SortableSet(undefined, sortById); + this._blocks = new SortableSet(); + /** @type {Chunk[]} */ + this.chunks = []; + /** @type {OriginRecord[]} */ + this.origins = []; + /** Indices in top-down order */ + /** + * @private + * @type {Map} + */ + this._modulePreOrderIndices = new Map(); + /** Indices in bottom-up order */ + /** + * @private + * @type {Map} + */ + this._modulePostOrderIndices = new Map(); + /** @type {number | undefined} */ + this.index = undefined; + } + + /** + * when a new chunk is added to a chunkGroup, addingOptions will occur. + * @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions + * @returns {void} + */ + addOptions(options) { + for (const _key of Object.keys(options)) { + const key = + /** @type {keyof ChunkGroupOptions} */ + (_key); + if (this.options[key] === undefined) { + /** @type {EXPECTED_ANY} */ + (this.options)[key] = options[key]; + } else if (this.options[key] !== options[key]) { + if (key.endsWith("Order")) { + const orderKey = + /** @type {Exclude} */ + (key); + + this.options[orderKey] = Math.max( + /** @type {number} */ + (this.options[orderKey]), + /** @type {number} */ + (options[orderKey]) + ); + } else { + throw new Error( + `ChunkGroup.addOptions: No option merge strategy for ${key}` + ); + } + } + } + } + + /** + * returns the name of current ChunkGroup + * @returns {string | null | undefined} returns the ChunkGroup name + */ + get name() { + return this.options.name; + } + + /** + * sets a new name for current ChunkGroup + * @param {string | undefined} value the new name for ChunkGroup + * @returns {void} + */ + set name(value) { + this.options.name = value; + } + + /* istanbul ignore next */ + /** + * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's + * @returns {string} a unique concatenation of chunk debugId's + */ + get debugId() { + return Array.from(this.chunks, (x) => x.debugId).join("+"); + } + + /** + * get a unique id for ChunkGroup, made up of its member Chunk id's + * @returns {string} a unique concatenation of chunk ids + */ + get id() { + return Array.from(this.chunks, (x) => x.id).join("+"); + } + + /** + * Performs an unshift of a specific chunk + * @param {Chunk} chunk chunk being unshifted + * @returns {boolean} returns true if attempted chunk shift is accepted + */ + unshiftChunk(chunk) { + const oldIdx = this.chunks.indexOf(chunk); + if (oldIdx > 0) { + this.chunks.splice(oldIdx, 1); + this.chunks.unshift(chunk); + } else if (oldIdx < 0) { + this.chunks.unshift(chunk); + return true; + } + return false; + } + + /** + * inserts a chunk before another existing chunk in group + * @param {Chunk} chunk Chunk being inserted + * @param {Chunk} before Placeholder/target chunk marking new chunk insertion point + * @returns {boolean} return true if insertion was successful + */ + insertChunk(chunk, before) { + const oldIdx = this.chunks.indexOf(chunk); + const idx = this.chunks.indexOf(before); + if (idx < 0) { + throw new Error("before chunk not found"); + } + if (oldIdx >= 0 && oldIdx > idx) { + this.chunks.splice(oldIdx, 1); + this.chunks.splice(idx, 0, chunk); + } else if (oldIdx < 0) { + this.chunks.splice(idx, 0, chunk); + return true; + } + return false; + } + + /** + * add a chunk into ChunkGroup. Is pushed on or prepended + * @param {Chunk} chunk chunk being pushed into ChunkGroupS + * @returns {boolean} returns true if chunk addition was successful. + */ + pushChunk(chunk) { + const oldIdx = this.chunks.indexOf(chunk); + if (oldIdx >= 0) { + return false; + } + this.chunks.push(chunk); + return true; + } + + /** + * @param {Chunk} oldChunk chunk to be replaced + * @param {Chunk} newChunk New chunk that will be replaced with + * @returns {boolean | undefined} returns true if the replacement was successful + */ + replaceChunk(oldChunk, newChunk) { + const oldIdx = this.chunks.indexOf(oldChunk); + if (oldIdx < 0) return false; + const newIdx = this.chunks.indexOf(newChunk); + if (newIdx < 0) { + this.chunks[oldIdx] = newChunk; + return true; + } + if (newIdx < oldIdx) { + this.chunks.splice(oldIdx, 1); + return true; + } else if (newIdx !== oldIdx) { + this.chunks[oldIdx] = newChunk; + this.chunks.splice(newIdx, 1); + return true; + } + } + + /** + * @param {Chunk} chunk chunk to remove + * @returns {boolean} returns true if chunk was removed + */ + removeChunk(chunk) { + const idx = this.chunks.indexOf(chunk); + if (idx >= 0) { + this.chunks.splice(idx, 1); + return true; + } + return false; + } + + /** + * @returns {boolean} true, when this chunk group will be loaded on initial page load + */ + isInitial() { + return false; + } + + /** + * @param {ChunkGroup} group chunk group to add + * @returns {boolean} returns true if chunk group was added + */ + addChild(group) { + const size = this._children.size; + this._children.add(group); + return size !== this._children.size; + } + + /** + * @returns {ChunkGroup[]} returns the children of this group + */ + getChildren() { + return this._children.getFromCache(getArray); + } + + getNumberOfChildren() { + return this._children.size; + } + + get childrenIterable() { + return this._children; + } + + /** + * @param {ChunkGroup} group the chunk group to remove + * @returns {boolean} returns true if the chunk group was removed + */ + removeChild(group) { + if (!this._children.has(group)) { + return false; + } + + this._children.delete(group); + group.removeParent(this); + return true; + } + + /** + * @param {ChunkGroup} parentChunk the parent group to be added into + * @returns {boolean} returns true if this chunk group was added to the parent group + */ + addParent(parentChunk) { + if (!this._parents.has(parentChunk)) { + this._parents.add(parentChunk); + return true; + } + return false; + } + + /** + * @returns {ChunkGroup[]} returns the parents of this group + */ + getParents() { + return this._parents.getFromCache(getArray); + } + + getNumberOfParents() { + return this._parents.size; + } + + /** + * @param {ChunkGroup} parent the parent group + * @returns {boolean} returns true if the parent group contains this group + */ + hasParent(parent) { + return this._parents.has(parent); + } + + get parentsIterable() { + return this._parents; + } + + /** + * @param {ChunkGroup} chunkGroup the parent group + * @returns {boolean} returns true if this group has been removed from the parent + */ + removeParent(chunkGroup) { + if (this._parents.delete(chunkGroup)) { + chunkGroup.removeChild(this); + return true; + } + return false; + } + + /** + * @param {Entrypoint} entrypoint entrypoint to add + * @returns {boolean} returns true if entrypoint was added + */ + addAsyncEntrypoint(entrypoint) { + const size = this._asyncEntrypoints.size; + this._asyncEntrypoints.add(entrypoint); + return size !== this._asyncEntrypoints.size; + } + + get asyncEntrypointsIterable() { + return this._asyncEntrypoints; + } + + /** + * @returns {Array} an array containing the blocks + */ + getBlocks() { + return this._blocks.getFromCache(getArray); + } + + getNumberOfBlocks() { + return this._blocks.size; + } + + /** + * @param {AsyncDependenciesBlock} block block + * @returns {boolean} true, if block exists + */ + hasBlock(block) { + return this._blocks.has(block); + } + + /** + * @returns {Iterable} blocks + */ + get blocksIterable() { + return this._blocks; + } + + /** + * @param {AsyncDependenciesBlock} block a block + * @returns {boolean} false, if block was already added + */ + addBlock(block) { + if (!this._blocks.has(block)) { + this._blocks.add(block); + return true; + } + return false; + } + + /** + * @param {Module | null} module origin module + * @param {DependencyLocation} loc location of the reference in the origin module + * @param {string} request request name of the reference + * @returns {void} + */ + addOrigin(module, loc, request) { + this.origins.push({ + module, + loc, + request + }); + } + + /** + * @returns {string[]} the files contained this chunk group + */ + getFiles() { + const files = new Set(); + + for (const chunk of this.chunks) { + for (const file of chunk.files) { + files.add(file); + } + } + + return [...files]; + } + + /** + * @returns {void} + */ + remove() { + // cleanup parents + for (const parentChunkGroup of this._parents) { + // remove this chunk from its parents + parentChunkGroup._children.delete(this); + + // cleanup "sub chunks" + for (const chunkGroup of this._children) { + /** + * remove this chunk as "intermediary" and connect + * it "sub chunks" and parents directly + */ + // add parent to each "sub chunk" + chunkGroup.addParent(parentChunkGroup); + // add "sub chunk" to parent + parentChunkGroup.addChild(chunkGroup); + } + } + + /** + * we need to iterate again over the children + * to remove this from the child's parents. + * This can not be done in the above loop + * as it is not guaranteed that `this._parents` contains anything. + */ + for (const chunkGroup of this._children) { + // remove this as parent of every "sub chunk" + chunkGroup._parents.delete(this); + } + + // remove chunks + for (const chunk of this.chunks) { + chunk.removeGroup(this); + } + } + + sortItems() { + this.origins.sort(sortOrigin); + } + + /** + * Sorting predicate which allows current ChunkGroup to be compared against another. + * Sorting values are based off of number of chunks in ChunkGroup. + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {ChunkGroup} otherGroup the chunkGroup to compare this against + * @returns {-1|0|1} sort position for comparison + */ + compareTo(chunkGraph, otherGroup) { + if (this.chunks.length > otherGroup.chunks.length) return -1; + if (this.chunks.length < otherGroup.chunks.length) return 1; + return compareIterables(compareChunks(chunkGraph))( + this.chunks, + otherGroup.chunks + ); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {Record} mapping from children type to ordered list of ChunkGroups + */ + getChildrenByOrders(moduleGraph, chunkGraph) { + /** @type {Map} */ + const lists = new Map(); + for (const childGroup of this._children) { + for (const key of Object.keys(childGroup.options)) { + if (key.endsWith("Order")) { + const name = key.slice(0, key.length - "Order".length); + let list = lists.get(name); + if (list === undefined) { + lists.set(name, (list = [])); + } + list.push({ + order: + /** @type {number} */ + ( + childGroup.options[/** @type {keyof ChunkGroupOptions} */ (key)] + ), + group: childGroup + }); + } + } + } + /** @type {Record} */ + const result = Object.create(null); + for (const [name, list] of lists) { + list.sort((a, b) => { + const cmp = b.order - a.order; + if (cmp !== 0) return cmp; + return a.group.compareTo(chunkGraph, b.group); + }); + result[name] = list.map((i) => i.group); + } + return result; + } + + /** + * Sets the top-down index of a module in this ChunkGroup + * @param {Module} module module for which the index should be set + * @param {number} index the index of the module + * @returns {void} + */ + setModulePreOrderIndex(module, index) { + this._modulePreOrderIndices.set(module, index); + } + + /** + * Gets the top-down index of a module in this ChunkGroup + * @param {Module} module the module + * @returns {number | undefined} index + */ + getModulePreOrderIndex(module) { + return this._modulePreOrderIndices.get(module); + } + + /** + * Sets the bottom-up index of a module in this ChunkGroup + * @param {Module} module module for which the index should be set + * @param {number} index the index of the module + * @returns {void} + */ + setModulePostOrderIndex(module, index) { + this._modulePostOrderIndices.set(module, index); + } + + /** + * Gets the bottom-up index of a module in this ChunkGroup + * @param {Module} module the module + * @returns {number | undefined} index + */ + getModulePostOrderIndex(module) { + return this._modulePostOrderIndices.get(module); + } + + /* istanbul ignore next */ + checkConstraints() { + const chunk = this; + for (const child of chunk._children) { + if (!child._parents.has(chunk)) { + throw new Error( + `checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}` + ); + } + } + for (const parentChunk of chunk._parents) { + if (!parentChunk._children.has(chunk)) { + throw new Error( + `checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}` + ); + } + } + } +} + +ChunkGroup.prototype.getModuleIndex = util.deprecate( + ChunkGroup.prototype.getModulePreOrderIndex, + "ChunkGroup.getModuleIndex was renamed to getModulePreOrderIndex", + "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX" +); + +ChunkGroup.prototype.getModuleIndex2 = util.deprecate( + ChunkGroup.prototype.getModulePostOrderIndex, + "ChunkGroup.getModuleIndex2 was renamed to getModulePostOrderIndex", + "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX_2" +); + +module.exports = ChunkGroup; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkRenderError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkRenderError.js new file mode 100644 index 0000000000000000000000000000000000000000..fce913f171ac4a46b34a51afc05bcf3fa73ec2b7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkRenderError.js @@ -0,0 +1,31 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Chunk")} Chunk */ + +class ChunkRenderError extends WebpackError { + /** + * Create a new ChunkRenderError + * @param {Chunk} chunk A chunk + * @param {string} file Related file + * @param {Error} error Original error + */ + constructor(chunk, file, error) { + super(); + + this.name = "ChunkRenderError"; + this.error = error; + this.message = error.message; + this.details = error.stack; + this.file = file; + this.chunk = chunk; + } +} + +module.exports = ChunkRenderError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkTemplate.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkTemplate.js new file mode 100644 index 0000000000000000000000000000000000000000..fa81ad078911cef909e3efc444a9830db9aa1326 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ChunkTemplate.js @@ -0,0 +1,181 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const memoize = require("./util/memoize"); + +/** @typedef {import("tapable").Tap} Tap */ +/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("./Compilation").Hash} Hash */ +/** @typedef {import("./Compilation").RenderManifestEntry} RenderManifestEntry */ +/** @typedef {import("./Compilation").RenderManifestOptions} RenderManifestOptions */ +/** @typedef {import("./Compilation").Source} Source */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** + * @template T + * @typedef {import("tapable").IfSet} IfSet + */ + +const getJavascriptModulesPlugin = memoize(() => + require("./javascript/JavascriptModulesPlugin") +); + +// TODO webpack 6 remove this class +class ChunkTemplate { + /** + * @param {OutputOptions} outputOptions output options + * @param {Compilation} compilation the compilation + */ + constructor(outputOptions, compilation) { + this._outputOptions = outputOptions || {}; + this.hooks = Object.freeze({ + renderManifest: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(renderManifestEntries: RenderManifestEntry[], renderManifestOptions: RenderManifestOptions) => RenderManifestEntry[]} fn function + */ + (options, fn) => { + compilation.hooks.renderManifest.tap( + options, + (entries, options) => { + if (options.chunk.hasRuntime()) return entries; + return fn(entries, options); + } + ); + }, + "ChunkTemplate.hooks.renderManifest is deprecated (use Compilation.hooks.renderManifest instead)", + "DEP_WEBPACK_CHUNK_TEMPLATE_RENDER_MANIFEST" + ) + }, + modules: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(source: Source, moduleTemplate: ModuleTemplate, renderContext: RenderContext) => Source} fn function + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .renderChunk.tap(options, (source, renderContext) => + fn( + source, + compilation.moduleTemplates.javascript, + renderContext + ) + ); + }, + "ChunkTemplate.hooks.modules is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderChunk instead)", + "DEP_WEBPACK_CHUNK_TEMPLATE_MODULES" + ) + }, + render: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(source: Source, moduleTemplate: ModuleTemplate, renderContext: RenderContext) => Source} fn function + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .renderChunk.tap(options, (source, renderContext) => + fn( + source, + compilation.moduleTemplates.javascript, + renderContext + ) + ); + }, + "ChunkTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderChunk instead)", + "DEP_WEBPACK_CHUNK_TEMPLATE_RENDER" + ) + }, + renderWithEntry: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(source: Source, chunk: Chunk) => Source} fn function + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .render.tap(options, (source, renderContext) => { + if ( + renderContext.chunkGraph.getNumberOfEntryModules( + renderContext.chunk + ) === 0 || + renderContext.chunk.hasRuntime() + ) { + return source; + } + return fn(source, renderContext.chunk); + }); + }, + "ChunkTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)", + "DEP_WEBPACK_CHUNK_TEMPLATE_RENDER_WITH_ENTRY" + ) + }, + hash: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(hash: Hash) => void} fn function + */ + (options, fn) => { + compilation.hooks.fullHash.tap(options, fn); + }, + "ChunkTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)", + "DEP_WEBPACK_CHUNK_TEMPLATE_HASH" + ) + }, + hashForChunk: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(hash: Hash, chunk: Chunk, chunkHashContext: ChunkHashContext) => void} fn function + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .chunkHash.tap(options, (chunk, hash, context) => { + if (chunk.hasRuntime()) return; + fn(hash, chunk, context); + }); + }, + "ChunkTemplate.hooks.hashForChunk is deprecated (use JavascriptModulesPlugin.getCompilationHooks().chunkHash instead)", + "DEP_WEBPACK_CHUNK_TEMPLATE_HASH_FOR_CHUNK" + ) + } + }); + } +} + +Object.defineProperty(ChunkTemplate.prototype, "outputOptions", { + get: util.deprecate( + /** + * @this {ChunkTemplate} + * @returns {OutputOptions} output options + */ + function outputOptions() { + return this._outputOptions; + }, + "ChunkTemplate.outputOptions is deprecated (use Compilation.outputOptions instead)", + "DEP_WEBPACK_CHUNK_TEMPLATE_OUTPUT_OPTIONS" + ) +}); + +module.exports = ChunkTemplate; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CleanPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CleanPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..5a43a7dc32ffc84d6bbe8009f43f0af9651ff284 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CleanPlugin.js @@ -0,0 +1,488 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + +"use strict"; + +const path = require("path"); +const asyncLib = require("neo-async"); +const { SyncBailHook } = require("tapable"); +const Compilation = require("./Compilation"); +const createSchemaValidation = require("./util/create-schema-validation"); +const { join } = require("./util/fs"); +const processAsyncTree = require("./util/processAsyncTree"); + +/** @typedef {import("../declarations/WebpackOptions").CleanOptions} CleanOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./util/fs").IStats} IStats */ +/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ +/** @typedef {import("./util/fs").StatsCallback} StatsCallback */ + +/** @typedef {Map} Assets */ + +/** + * @typedef {object} CleanPluginCompilationHooks + * @property {SyncBailHook<[string], boolean | void>} keep when returning true the file/directory will be kept during cleaning, returning false will clean it and ignore the following plugins and config + */ + +/** + * @callback KeepFn + * @param {string} path path + * @returns {boolean | void} true, if the path should be kept + */ + +const validate = createSchemaValidation( + undefined, + () => { + const { definitions } = require("../schemas/WebpackOptions.json"); + + return { + definitions, + oneOf: [{ $ref: "#/definitions/CleanOptions" }] + }; + }, + { + name: "Clean Plugin", + baseDataPath: "options" + } +); +const _10sec = 10 * 1000; + +/** + * merge assets map 2 into map 1 + * @param {Assets} as1 assets + * @param {Assets} as2 assets + * @returns {void} + */ +const mergeAssets = (as1, as2) => { + for (const [key, value1] of as2) { + const value2 = as1.get(key); + if (!value2 || value1 > value2) as1.set(key, value1); + } +}; + +/** + * @param {Map} assets current assets + * @returns {Set} Set of directory paths + */ +function getDirectories(assets) { + const directories = new Set(); + /** + * @param {string} filename asset filename + */ + const addDirectory = (filename) => { + directories.add(path.dirname(filename)); + }; + + // get directories of assets + for (const [asset] of assets) { + addDirectory(asset); + } + // and all parent directories + for (const directory of directories) { + addDirectory(directory); + } + return directories; +} + +/** @typedef {Set} Diff */ + +/** + * @param {OutputFileSystem} fs filesystem + * @param {string} outputPath output path + * @param {Map} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator) + * @param {(err?: Error | null, set?: Diff) => void} callback returns the filenames of the assets that shouldn't be there + * @returns {void} + */ +const getDiffToFs = (fs, outputPath, currentAssets, callback) => { + const directories = getDirectories(currentAssets); + const diff = new Set(); + asyncLib.forEachLimit( + directories, + 10, + (directory, callback) => { + /** @type {NonNullable} */ + (fs.readdir)(join(fs, outputPath, directory), (err, entries) => { + if (err) { + if (err.code === "ENOENT") return callback(); + if (err.code === "ENOTDIR") { + diff.add(directory); + return callback(); + } + return callback(err); + } + for (const entry of /** @type {string[]} */ (entries)) { + const file = entry; + // Since path.normalize("./file") === path.normalize("file"), + // return file directly when directory === "." + const filename = + directory && directory !== "." ? `${directory}/${file}` : file; + if (!directories.has(filename) && !currentAssets.has(filename)) { + diff.add(filename); + } + } + callback(); + }); + }, + (err) => { + if (err) return callback(err); + + callback(null, diff); + } + ); +}; + +/** + * @param {Assets} currentAssets assets list + * @param {Assets} oldAssets old assets list + * @returns {Diff} diff + */ +const getDiffToOldAssets = (currentAssets, oldAssets) => { + const diff = new Set(); + const now = Date.now(); + for (const [asset, ts] of oldAssets) { + if (ts >= now) continue; + if (!currentAssets.has(asset)) diff.add(asset); + } + return diff; +}; + +/** + * @param {OutputFileSystem} fs filesystem + * @param {string} filename path to file + * @param {StatsCallback} callback callback for provided filename + * @returns {void} + */ +const doStat = (fs, filename, callback) => { + if ("lstat" in fs) { + /** @type {NonNullable} */ + (fs.lstat)(filename, callback); + } else { + fs.stat(filename, callback); + } +}; + +/** + * @param {OutputFileSystem} fs filesystem + * @param {string} outputPath output path + * @param {boolean} dry only log instead of fs modification + * @param {Logger} logger logger + * @param {Diff} diff filenames of the assets that shouldn't be there + * @param {(path: string) => boolean | void} isKept check if the entry is ignored + * @param {(err?: Error, assets?: Assets) => void} callback callback + * @returns {void} + */ +const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => { + /** + * @param {string} msg message + */ + const log = (msg) => { + if (dry) { + logger.info(msg); + } else { + logger.log(msg); + } + }; + /** @typedef {{ type: "check" | "unlink" | "rmdir", filename: string, parent: { remaining: number, job: Job } | undefined }} Job */ + /** @type {Job[]} */ + const jobs = Array.from(diff.keys(), (filename) => ({ + type: "check", + filename, + parent: undefined + })); + /** @type {Assets} */ + const keptAssets = new Map(); + processAsyncTree( + jobs, + 10, + ({ type, filename, parent }, push, callback) => { + const path = join(fs, outputPath, filename); + /** + * @param {Error & { code?: string }} err error + * @returns {void} + */ + const handleError = (err) => { + const isAlreadyRemoved = () => + new Promise((resolve) => { + if (err.code === "ENOENT") { + resolve(true); + } else if (err.code === "EPERM") { + // https://github.com/isaacs/rimraf/blob/main/src/fix-eperm.ts#L37 + // fs.existsSync(path) === false https://github.com/webpack/webpack/actions/runs/15493412975/job/43624272783?pr=19586 + doStat(fs, path, (err) => { + if (err) { + resolve(err.code === "ENOENT"); + } else { + resolve(false); + } + }); + } else { + resolve(false); + } + }); + + isAlreadyRemoved().then((isRemoved) => { + if (isRemoved) { + log(`${filename} was removed during cleaning by something else`); + handleParent(); + return callback(); + } + return callback(err); + }); + }; + const handleParent = () => { + if (parent && --parent.remaining === 0) push(parent.job); + }; + switch (type) { + case "check": + if (isKept(filename)) { + keptAssets.set(filename, 0); + // do not decrement parent entry as we don't want to delete the parent + log(`${filename} will be kept`); + return process.nextTick(callback); + } + doStat(fs, path, (err, stats) => { + if (err) return handleError(err); + if (!(/** @type {IStats} */ (stats).isDirectory())) { + push({ + type: "unlink", + filename, + parent + }); + return callback(); + } + + /** @type {NonNullable} */ + (fs.readdir)(path, (err, _entries) => { + if (err) return handleError(err); + /** @type {Job} */ + const deleteJob = { + type: "rmdir", + filename, + parent + }; + const entries = /** @type {string[]} */ (_entries); + if (entries.length === 0) { + push(deleteJob); + } else { + const parentToken = { + remaining: entries.length, + job: deleteJob + }; + for (const entry of entries) { + const file = /** @type {string} */ (entry); + if (file.startsWith(".")) { + log( + `${filename} will be kept (dot-files will never be removed)` + ); + continue; + } + push({ + type: "check", + filename: `${filename}/${file}`, + parent: parentToken + }); + } + } + return callback(); + }); + }); + break; + case "rmdir": + log(`${filename} will be removed`); + if (dry) { + handleParent(); + return process.nextTick(callback); + } + if (!fs.rmdir) { + logger.warn( + `${filename} can't be removed because output file system doesn't support removing directories (rmdir)` + ); + return process.nextTick(callback); + } + fs.rmdir(path, (err) => { + if (err) return handleError(err); + handleParent(); + callback(); + }); + break; + case "unlink": + log(`${filename} will be removed`); + if (dry) { + handleParent(); + return process.nextTick(callback); + } + if (!fs.unlink) { + logger.warn( + `${filename} can't be removed because output file system doesn't support removing files (rmdir)` + ); + return process.nextTick(callback); + } + fs.unlink(path, (err) => { + if (err) return handleError(err); + handleParent(); + callback(); + }); + break; + } + }, + (err) => { + if (err) return callback(err); + callback(undefined, keptAssets); + } + ); +}; + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +const PLUGIN_NAME = "CleanPlugin"; + +class CleanPlugin { + /** + * @param {Compilation} compilation the compilation + * @returns {CleanPluginCompilationHooks} the attached hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + keep: new SyncBailHook(["ignore"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** @param {CleanOptions} options options */ + constructor(options = {}) { + validate(options); + this.options = { dry: false, ...options }; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { dry, keep } = this.options; + + /** @type {KeepFn} */ + const keepFn = + typeof keep === "function" + ? keep + : typeof keep === "string" + ? (path) => path.startsWith(keep) + : typeof keep === "object" && keep.test + ? (path) => keep.test(path) + : () => false; + + // We assume that no external modification happens while the compiler is active + // So we can store the old assets and only diff to them to avoid fs access on + // incremental builds + /** @type {undefined|Assets} */ + let oldAssets; + + compiler.hooks.emit.tapAsync( + { + name: PLUGIN_NAME, + stage: 100 + }, + (compilation, callback) => { + const hooks = CleanPlugin.getCompilationHooks(compilation); + const logger = compilation.getLogger(`webpack.${PLUGIN_NAME}`); + const fs = /** @type {OutputFileSystem} */ (compiler.outputFileSystem); + + if (!fs.readdir) { + return callback( + new Error( + `${PLUGIN_NAME}: Output filesystem doesn't support listing directories (readdir)` + ) + ); + } + + /** @type {Assets} */ + const currentAssets = new Map(); + const now = Date.now(); + for (const asset of Object.keys(compilation.assets)) { + if (/^[A-Za-z]:\\|^\/|^\\\\/.test(asset)) continue; + let normalizedAsset; + let newNormalizedAsset = asset.replace(/\\/g, "/"); + do { + normalizedAsset = newNormalizedAsset; + newNormalizedAsset = normalizedAsset.replace( + /(^|\/)(?!\.\.)[^/]+\/\.\.\//g, + "$1" + ); + } while (newNormalizedAsset !== normalizedAsset); + if (normalizedAsset.startsWith("../")) continue; + const assetInfo = compilation.assetsInfo.get(asset); + if (assetInfo && assetInfo.hotModuleReplacement) { + currentAssets.set(normalizedAsset, now + _10sec); + } else { + currentAssets.set(normalizedAsset, 0); + } + } + + const outputPath = compilation.getPath(compiler.outputPath, {}); + + /** + * @param {string} path path + * @returns {boolean | void} true, if needs to be kept + */ + const isKept = (path) => { + const result = hooks.keep.call(path); + if (result !== undefined) return result; + return keepFn(path); + }; + + /** + * @param {(Error | null)=} err err + * @param {Diff=} diff diff + */ + const diffCallback = (err, diff) => { + if (err) { + oldAssets = undefined; + callback(err); + return; + } + applyDiff( + fs, + outputPath, + dry, + logger, + /** @type {Diff} */ (diff), + isKept, + (err, keptAssets) => { + if (err) { + oldAssets = undefined; + } else { + if (oldAssets) mergeAssets(currentAssets, oldAssets); + oldAssets = currentAssets; + if (keptAssets) mergeAssets(oldAssets, keptAssets); + } + callback(err); + } + ); + }; + + if (oldAssets) { + diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets)); + } else { + getDiffToFs(fs, outputPath, currentAssets, diffCallback); + } + } + ); + } +} + +module.exports = CleanPlugin; +module.exports._getDirectories = getDirectories; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CodeGenerationError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CodeGenerationError.js new file mode 100644 index 0000000000000000000000000000000000000000..b1cf51d744e630a926bb8d3c3605d42f824cfc90 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CodeGenerationError.js @@ -0,0 +1,29 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Module")} Module */ + +class CodeGenerationError extends WebpackError { + /** + * Create a new CodeGenerationError + * @param {Module} module related module + * @param {Error} error Original error + */ + constructor(module, error) { + super(); + + this.name = "CodeGenerationError"; + this.error = error; + this.message = error.message; + this.details = error.stack; + this.module = module; + } +} + +module.exports = CodeGenerationError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CodeGenerationResults.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CodeGenerationResults.js new file mode 100644 index 0000000000000000000000000000000000000000..fe2097ea5d3468cf7daaafe337ed34b392776ed1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CodeGenerationResults.js @@ -0,0 +1,158 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { DEFAULTS } = require("./config/defaults"); +const { getOrInsert } = require("./util/MapHelpers"); +const { first } = require("./util/SetHelpers"); +const createHash = require("./util/createHash"); +const { RuntimeSpecMap, runtimeToString } = require("./util/runtime"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ +/** @typedef {typeof import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +class CodeGenerationResults { + /** + * @param {string | Hash} hashFunction the hash function to use + */ + constructor(hashFunction = DEFAULTS.HASH_FUNCTION) { + /** @type {Map>} */ + this.map = new Map(); + this._hashFunction = hashFunction; + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @returns {CodeGenerationResult} the CodeGenerationResult + */ + get(module, runtime) { + const entry = this.map.get(module); + if (entry === undefined) { + throw new Error( + `No code generation entry for ${module.identifier()} (existing entries: ${Array.from( + this.map.keys(), + (m) => m.identifier() + ).join(", ")})` + ); + } + if (runtime === undefined) { + if (entry.size > 1) { + const results = new Set(entry.values()); + if (results.size !== 1) { + throw new Error( + `No unique code generation entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from( + entry.keys(), + (r) => runtimeToString(r) + ).join(", ")}). +Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").` + ); + } + return /** @type {CodeGenerationResult} */ (first(results)); + } + return /** @type {CodeGenerationResult} */ (entry.values().next().value); + } + const result = entry.get(runtime); + if (result === undefined) { + throw new Error( + `No code generation entry for runtime ${runtimeToString( + runtime + )} for ${module.identifier()} (existing runtimes: ${Array.from( + entry.keys(), + (r) => runtimeToString(r) + ).join(", ")})` + ); + } + return result; + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @returns {boolean} true, when we have data for this + */ + has(module, runtime) { + const entry = this.map.get(module); + if (entry === undefined) { + return false; + } + if (runtime !== undefined) { + return entry.has(runtime); + } else if (entry.size > 1) { + const results = new Set(entry.values()); + return results.size === 1; + } + return entry.size === 1; + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @param {string} sourceType the source type + * @returns {Source} a source + */ + getSource(module, runtime, sourceType) { + return /** @type {Source} */ ( + this.get(module, runtime).sources.get(sourceType) + ); + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @returns {ReadOnlyRuntimeRequirements | null} runtime requirements + */ + getRuntimeRequirements(module, runtime) { + return this.get(module, runtime).runtimeRequirements; + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @param {string} key data key + * @returns {TODO | undefined} data generated by code generation + */ + getData(module, runtime, key) { + const data = this.get(module, runtime).data; + return data === undefined ? undefined : data.get(key); + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @returns {string} hash of the code generation + */ + getHash(module, runtime) { + const info = this.get(module, runtime); + if (info.hash !== undefined) return info.hash; + const hash = createHash(this._hashFunction); + for (const [type, source] of info.sources) { + hash.update(type); + source.updateHash(hash); + } + if (info.runtimeRequirements) { + for (const rr of info.runtimeRequirements) hash.update(rr); + } + return (info.hash = /** @type {string} */ (hash.digest("hex"))); + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @param {CodeGenerationResult} result result from module + * @returns {void} + */ + add(module, runtime, result) { + const map = getOrInsert(this.map, module, () => new RuntimeSpecMap()); + map.set(runtime, result); + } +} + +module.exports = CodeGenerationResults; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CommentCompilationWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CommentCompilationWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..99cd0fbdadab3a0a781e671b62aeea5b5d64de1f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CommentCompilationWarning.js @@ -0,0 +1,32 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + +class CommentCompilationWarning extends WebpackError { + /** + * @param {string} message warning message + * @param {DependencyLocation} loc affected lines of code + */ + constructor(message, loc) { + super(message); + + this.name = "CommentCompilationWarning"; + + this.loc = loc; + } +} + +makeSerializable( + CommentCompilationWarning, + "webpack/lib/CommentCompilationWarning" +); + +module.exports = CommentCompilationWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CompatibilityPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CompatibilityPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d5ce1872512a1d047b44e4ccf1bb0c56b46c2878 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CompatibilityPlugin.js @@ -0,0 +1,197 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const ConstDependency = require("./dependencies/ConstDependency"); + +/** @typedef {import("estree").CallExpression} CallExpression */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ +/** @typedef {import("./javascript/JavascriptParser").TagData} TagData */ + +const nestedWebpackIdentifierTag = Symbol("nested webpack identifier"); +const PLUGIN_NAME = "CompatibilityPlugin"; + +class CompatibilityPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, (parser, parserOptions) => { + if ( + parserOptions.browserify !== undefined && + !parserOptions.browserify + ) { + return; + } + + parser.hooks.call.for("require").tap( + PLUGIN_NAME, + /** + * @param {CallExpression} expr call expression + * @returns {boolean | void} true when need to handle + */ + (expr) => { + // support for browserify style require delegator: "require(o, !0)" + if (expr.arguments.length !== 2) return; + const second = parser.evaluateExpression(expr.arguments[1]); + if (!second.isBoolean()) return; + if (second.asBool() !== true) return; + const dep = new ConstDependency( + "require", + /** @type {Range} */ (expr.callee.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + if (parser.state.current.dependencies.length > 0) { + const last = + parser.state.current.dependencies[ + parser.state.current.dependencies.length - 1 + ]; + if ( + last.critical && + last.options && + last.options.request === "." && + last.userRequest === "." && + last.options.recursive + ) { + parser.state.current.dependencies.pop(); + } + } + parser.state.module.addPresentationalDependency(dep); + return true; + } + ); + }); + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const handler = (parser) => { + // Handle nested requires + parser.hooks.preStatement.tap(PLUGIN_NAME, (statement) => { + if ( + statement.type === "FunctionDeclaration" && + statement.id && + statement.id.name === RuntimeGlobals.require + ) { + const newName = `__nested_webpack_require_${ + /** @type {Range} */ (statement.range)[0] + }__`; + parser.tagVariable( + statement.id.name, + nestedWebpackIdentifierTag, + { + name: newName, + declaration: { + updated: false, + loc: statement.id.loc, + range: statement.id.range + } + } + ); + return true; + } + }); + parser.hooks.pattern + .for(RuntimeGlobals.require) + .tap(PLUGIN_NAME, (pattern) => { + const newName = `__nested_webpack_require_${ + /** @type {Range} */ (pattern.range)[0] + }__`; + parser.tagVariable(pattern.name, nestedWebpackIdentifierTag, { + name: newName, + declaration: { + updated: false, + loc: pattern.loc, + range: pattern.range + } + }); + return true; + }); + parser.hooks.pattern + .for(RuntimeGlobals.exports) + .tap(PLUGIN_NAME, (pattern) => { + parser.tagVariable(pattern.name, nestedWebpackIdentifierTag, { + name: "__nested_webpack_exports__", + declaration: { + updated: false, + loc: pattern.loc, + range: pattern.range + } + }); + return true; + }); + parser.hooks.expression + .for(nestedWebpackIdentifierTag) + .tap(PLUGIN_NAME, (expr) => { + const { name, declaration } = + /** @type {TagData} */ + (parser.currentTagData); + if (!declaration.updated) { + const dep = new ConstDependency(name, declaration.range); + dep.loc = declaration.loc; + parser.state.module.addPresentationalDependency(dep); + declaration.updated = true; + } + const dep = new ConstDependency( + name, + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + // Handle hashbang + parser.hooks.program.tap(PLUGIN_NAME, (program, comments) => { + if (comments.length === 0) return; + const c = comments[0]; + if (c.type === "Line" && /** @type {Range} */ (c.range)[0] === 0) { + if (parser.state.source.slice(0, 2).toString() !== "#!") return; + // this is a hashbang comment + const dep = new ConstDependency("//", 0); + dep.loc = /** @type {DependencyLocation} */ (c.loc); + parser.state.module.addPresentationalDependency(dep); + } + }); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = CompatibilityPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Compilation.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Compilation.js new file mode 100644 index 0000000000000000000000000000000000000000..2fe088d5b0e2679112ee8abbbfbe4069e5e88526 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Compilation.js @@ -0,0 +1,5776 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const asyncLib = require("neo-async"); +const { + AsyncParallelHook, + AsyncSeriesBailHook, + AsyncSeriesHook, + HookMap, + SyncBailHook, + SyncHook, + SyncWaterfallHook +} = require("tapable"); +const { CachedSource } = require("webpack-sources"); +const { MultiItemCache } = require("./CacheFacade"); +const Chunk = require("./Chunk"); +const ChunkGraph = require("./ChunkGraph"); +const ChunkGroup = require("./ChunkGroup"); +const ChunkRenderError = require("./ChunkRenderError"); +const ChunkTemplate = require("./ChunkTemplate"); +const CodeGenerationError = require("./CodeGenerationError"); +const CodeGenerationResults = require("./CodeGenerationResults"); +const Dependency = require("./Dependency"); +const DependencyTemplates = require("./DependencyTemplates"); +const Entrypoint = require("./Entrypoint"); +const ErrorHelpers = require("./ErrorHelpers"); +const FileSystemInfo = require("./FileSystemInfo"); +const { + connectChunkGroupAndChunk, + connectChunkGroupParentAndChild, + connectEntrypointAndDependOn +} = require("./GraphHelpers"); +const { + makeWebpackError, + tryRunOrWebpackError +} = require("./HookWebpackError"); +const MainTemplate = require("./MainTemplate"); +const Module = require("./Module"); +const ModuleDependencyError = require("./ModuleDependencyError"); +const ModuleDependencyWarning = require("./ModuleDependencyWarning"); +const ModuleGraph = require("./ModuleGraph"); +const ModuleHashingError = require("./ModuleHashingError"); +const ModuleNotFoundError = require("./ModuleNotFoundError"); +const ModuleProfile = require("./ModuleProfile"); +const ModuleRestoreError = require("./ModuleRestoreError"); +const ModuleStoreError = require("./ModuleStoreError"); +const ModuleTemplate = require("./ModuleTemplate"); +const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const RuntimeTemplate = require("./RuntimeTemplate"); +const Stats = require("./Stats"); +const WebpackError = require("./WebpackError"); +const buildChunkGraph = require("./buildChunkGraph"); +const BuildCycleError = require("./errors/BuildCycleError"); +const { LogType, Logger } = require("./logging/Logger"); +const StatsFactory = require("./stats/StatsFactory"); +const StatsPrinter = require("./stats/StatsPrinter"); +const { equals: arrayEquals } = require("./util/ArrayHelpers"); +const AsyncQueue = require("./util/AsyncQueue"); +const LazySet = require("./util/LazySet"); +const { getOrInsert } = require("./util/MapHelpers"); +const WeakTupleMap = require("./util/WeakTupleMap"); +const { cachedCleverMerge } = require("./util/cleverMerge"); +const { + compareIds, + compareLocations, + compareModulesByIdentifier, + compareSelect, + compareStringsNumeric, + concatComparators +} = require("./util/comparators"); +const createHash = require("./util/createHash"); +const { + arrayToSetDeprecation, + createFakeHook, + soonFrozenObjectDeprecation +} = require("./util/deprecation"); +const processAsyncTree = require("./util/processAsyncTree"); +const { getRuntimeKey } = require("./util/runtime"); +const { isSourceEqual } = require("./util/source"); + +/** @template T @typedef {import("tapable").AsArray} AsArray */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Cache")} Cache */ +/** @typedef {import("./CacheFacade")} CacheFacade */ +/** @typedef {import("./Chunk").ChunkName} ChunkName */ +/** @typedef {import("./Chunk").ChunkId} ChunkId */ +/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Compiler").CompilationParams} CompilationParams */ +/** @typedef {import("./Compiler").MemCache} MemCache */ +/** @typedef {import("./Compiler").WeakReferences} WeakReferences */ +/** @typedef {import("./Compiler").ModuleMemCachesItem} ModuleMemCachesItem */ +/** @typedef {import("./Compiler").Records} Records */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */ +/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */ +/** @typedef {import("./NormalModule").NormalModuleCompilationHooks} NormalModuleCompilationHooks */ +/** @typedef {import("./Module").FactoryMeta} FactoryMeta */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./ModuleFactory")} ModuleFactory */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./NormalModule").ParserOptions} ParserOptions */ +/** @typedef {import("./NormalModule").GeneratorOptions} GeneratorOptions */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */ +/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */ +/** + * @template T + * @typedef {import("./util/deprecation").FakeHook} FakeHook + */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** + * @callback Callback + * @param {(WebpackError | null)=} err + * @returns {void} + */ + +/** + * @callback ModuleCallback + * @param {(WebpackError | null)=} err + * @param {(Module | null)=} result + * @returns {void} + */ + +/** + * @callback ModuleFactoryResultCallback + * @param {(WebpackError | null)=} err + * @param {ModuleFactoryResult=} result + * @returns {void} + */ + +/** + * @callback ModuleOrFactoryResultCallback + * @param {(WebpackError | null)=} err + * @param {Module | ModuleFactoryResult=} result + * @returns {void} + */ + +/** + * @callback ExecuteModuleCallback + * @param {WebpackError | null} err + * @param {ExecuteModuleResult=} result + * @returns {void} + */ + +/** @typedef {new (...args: EXPECTED_ANY[]) => Dependency} DepConstructor */ + +/** @typedef {Record} CompilationAssets */ + +/** + * @typedef {object} AvailableModulesChunkGroupMapping + * @property {ChunkGroup} chunkGroup + * @property {Set} availableModules + * @property {boolean} needCopy + */ + +/** + * @typedef {object} DependenciesBlockLike + * @property {Dependency[]} dependencies + * @property {AsyncDependenciesBlock[]} blocks + */ + +/** + * @typedef {object} ChunkPathData + * @property {string | number} id + * @property {string=} name + * @property {string} hash + * @property {((length: number) => string)=} hashWithLength + * @property {(Record)=} contentHash + * @property {(Record string>)=} contentHashWithLength + */ + +/** + * @typedef {object} ChunkHashContext + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + */ + +/** + * @typedef {object} RuntimeRequirementsContext + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults the code generation results + */ + +/** + * @typedef {object} ExecuteModuleOptions + * @property {EntryOptions=} entryOptions + */ + +/** @typedef {EXPECTED_ANY} ExecuteModuleExports */ + +/** + * @typedef {object} ExecuteModuleResult + * @property {ExecuteModuleExports} exports + * @property {boolean} cacheable + * @property {Map} assets + * @property {LazySet} fileDependencies + * @property {LazySet} contextDependencies + * @property {LazySet} missingDependencies + * @property {LazySet} buildDependencies + */ + +/** + * @typedef {object} ExecuteModuleObject + * @property {string=} id module id + * @property {ExecuteModuleExports} exports exports + * @property {boolean} loaded is loaded + * @property {Error=} error error + */ + +/** + * @typedef {object} ExecuteModuleArgument + * @property {Module} module + * @property {ExecuteModuleObject=} moduleObject + * @property {TODO} preparedInfo + * @property {CodeGenerationResult} codeGenerationResult + */ + +/** @typedef {((id: string) => ExecuteModuleExports) & { i?: ((options: ExecuteOptions) => void)[], c?: Record }} WebpackRequire */ + +/** + * @typedef {object} ExecuteOptions + * @property {string=} id module id + * @property {ExecuteModuleObject} module module + * @property {WebpackRequire} require require function + */ + +/** + * @typedef {object} ExecuteModuleContext + * @property {Map} assets + * @property {Chunk} chunk + * @property {ChunkGraph} chunkGraph + * @property {WebpackRequire=} __webpack_require__ + */ + +/** + * @typedef {object} EntryData + * @property {Dependency[]} dependencies dependencies of the entrypoint that should be evaluated at startup + * @property {Dependency[]} includeDependencies dependencies of the entrypoint that should be included but not evaluated + * @property {EntryOptions} options options of the entrypoint + */ + +/** + * @typedef {object} LogEntry + * @property {string} type + * @property {EXPECTED_ANY[]=} args + * @property {number} time + * @property {string[]=} trace + */ + +/** + * @typedef {object} KnownAssetInfo + * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash) + * @property {boolean=} minimized whether the asset is minimized + * @property {string | string[]=} fullhash the value(s) of the full hash used for this asset + * @property {string | string[]=} chunkhash the value(s) of the chunk hash used for this asset + * @property {string | string[]=} modulehash the value(s) of the module hash used for this asset + * @property {string | string[]=} contenthash the value(s) of the content hash used for this asset + * @property {string=} sourceFilename when asset was created from a source file (potentially transformed), the original filename relative to compilation context + * @property {number=} size size in bytes, only set after asset has been emitted + * @property {boolean=} development true, when asset is only used for development and doesn't count towards user-facing assets + * @property {boolean=} hotModuleReplacement true, when asset ships data for updating an existing application (HMR) + * @property {boolean=} javascriptModule true, when asset is javascript and an ESM + * @property {Record=} related object of pointers to other assets, keyed by type of relation (only points from parent to child) + */ + +/** @typedef {KnownAssetInfo & Record} AssetInfo */ + +/** @typedef {{ path: string, info: AssetInfo }} InterpolatedPathAndAssetInfo */ + +/** + * @typedef {object} Asset + * @property {string} name the filename of the asset + * @property {Source} source source of the asset + * @property {AssetInfo} info info about the asset + */ + +/** + * @typedef {object} ModulePathData + * @property {string | number} id + * @property {string} hash + * @property {((length: number) => string)=} hashWithLength + */ + +/** + * @typedef {object} PathData + * @property {ChunkGraph=} chunkGraph + * @property {string=} hash + * @property {((length: number) => string)=} hashWithLength + * @property {(Chunk | ChunkPathData)=} chunk + * @property {(Module | ModulePathData)=} module + * @property {RuntimeSpec=} runtime + * @property {string=} filename + * @property {string=} basename + * @property {string=} query + * @property {string=} contentHashType + * @property {string=} contentHash + * @property {((length: number) => string)=} contentHashWithLength + * @property {boolean=} noChunkHash + * @property {string=} url + */ + +/** @typedef {"module" | "chunk" | "root-of-chunk" | "nested"} ExcludeModulesType */ + +/** + * @typedef {object} KnownNormalizedStatsOptions + * @property {string} context + * @property {RequestShortener} requestShortener + * @property {string | false} chunksSort + * @property {string | false} modulesSort + * @property {string | false} chunkModulesSort + * @property {string | false} nestedModulesSort + * @property {string | false} assetsSort + * @property {boolean} ids + * @property {boolean} cachedAssets + * @property {boolean} groupAssetsByEmitStatus + * @property {boolean} groupAssetsByPath + * @property {boolean} groupAssetsByExtension + * @property {number} assetsSpace + * @property {((value: string, asset: StatsAsset) => boolean)[]} excludeAssets + * @property {((name: string, module: StatsModule, type: ExcludeModulesType) => boolean)[]} excludeModules + * @property {((warning: StatsError, textValue: string) => boolean)[]} warningsFilter + * @property {boolean} cachedModules + * @property {boolean} orphanModules + * @property {boolean} dependentModules + * @property {boolean} runtimeModules + * @property {boolean} groupModulesByCacheStatus + * @property {boolean} groupModulesByLayer + * @property {boolean} groupModulesByAttributes + * @property {boolean} groupModulesByPath + * @property {boolean} groupModulesByExtension + * @property {boolean} groupModulesByType + * @property {boolean | "auto"} entrypoints + * @property {boolean} chunkGroups + * @property {boolean} chunkGroupAuxiliary + * @property {boolean} chunkGroupChildren + * @property {number} chunkGroupMaxAssets + * @property {number} modulesSpace + * @property {number} chunkModulesSpace + * @property {number} nestedModulesSpace + * @property {false | "none" | "error" | "warn" | "info" | "log" | "verbose"} logging + * @property {((value: string) => boolean)[]} loggingDebug + * @property {boolean} loggingTrace + * @property {EXPECTED_ANY} _env + */ + +/** @typedef {KnownNormalizedStatsOptions & Omit & Record} NormalizedStatsOptions */ + +/** + * @typedef {object} KnownCreateStatsOptionsContext + * @property {boolean=} forToString + */ + +/** @typedef {KnownCreateStatsOptionsContext & Record} CreateStatsOptionsContext */ + +/** @typedef {{ module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}} CodeGenerationJob */ + +/** @typedef {CodeGenerationJob[]} CodeGenerationJobs */ + +/** @typedef {{javascript: ModuleTemplate}} ModuleTemplates */ + +/** @typedef {Set} NotCodeGeneratedModules */ + +/** @type {AssetInfo} */ +const EMPTY_ASSET_INFO = Object.freeze({}); + +const esmDependencyCategory = "esm"; + +// TODO webpack 6: remove +const deprecatedNormalModuleLoaderHook = util.deprecate( + /** + * @param {Compilation} compilation compilation + * @returns {NormalModuleCompilationHooks["loader"]} hooks + */ + (compilation) => + require("./NormalModule").getCompilationHooks(compilation).loader, + "Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader", + "DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK" +); + +// TODO webpack 6: remove +/** + * @param {ModuleTemplates | undefined} moduleTemplates module templates + */ +const defineRemovedModuleTemplates = (moduleTemplates) => { + Object.defineProperties(moduleTemplates, { + asset: { + enumerable: false, + configurable: false, + get: () => { + throw new WebpackError( + "Compilation.moduleTemplates.asset has been removed" + ); + } + }, + webassembly: { + enumerable: false, + configurable: false, + get: () => { + throw new WebpackError( + "Compilation.moduleTemplates.webassembly has been removed" + ); + } + } + }); + moduleTemplates = undefined; +}; + +const byId = compareSelect((c) => c.id, compareIds); + +const byNameOrHash = concatComparators( + compareSelect((c) => c.name, compareIds), + compareSelect((c) => c.fullHash, compareIds) +); + +const byMessage = compareSelect( + (err) => `${err.message}`, + compareStringsNumeric +); + +const byModule = compareSelect( + (err) => (err.module && err.module.identifier()) || "", + compareStringsNumeric +); + +const byLocation = compareSelect((err) => err.loc, compareLocations); + +const compareErrors = concatComparators(byModule, byLocation, byMessage); + +/** + * @typedef {object} KnownUnsafeCacheData + * @property {FactoryMeta=} factoryMeta factory meta + * @property {ResolveOptions=} resolveOptions resolve options + * @property {ParserOptions=} parserOptions + * @property {GeneratorOptions=} generatorOptions + */ + +/** @typedef {KnownUnsafeCacheData & Record} UnsafeCacheData */ + +/** + * @typedef {Module & { restoreFromUnsafeCache?: (unsafeCacheData: UnsafeCacheData, moduleFactory: ModuleFactory, compilationParams: CompilationParams) => void }} ModuleWithRestoreFromUnsafeCache + */ + +/** @type {WeakMap} */ +const unsafeCacheDependencies = new WeakMap(); + +/** @type {WeakMap} */ +const unsafeCacheData = new WeakMap(); + +/** @typedef {{ id: ModuleId, modules?: Map, blocks?: (string | number | null)[] }} References */ +/** @typedef {Map>} ModuleMemCaches */ + +class Compilation { + /** + * Creates an instance of Compilation. + * @param {Compiler} compiler the compiler which created the compilation + * @param {CompilationParams} params the compilation parameters + */ + constructor(compiler, params) { + this._backCompat = compiler._backCompat; + + const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this); + /** @typedef {{ additionalAssets?: true | TODO }} ProcessAssetsAdditionalOptions */ + /** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */ + const processAssetsHook = new AsyncSeriesHook(["assets"]); + + let savedAssets = new Set(); + /** + * @param {CompilationAssets} assets assets + * @returns {CompilationAssets} new assets + */ + const popNewAssets = (assets) => { + let newAssets; + for (const file of Object.keys(assets)) { + if (savedAssets.has(file)) continue; + if (newAssets === undefined) { + newAssets = Object.create(null); + } + newAssets[file] = assets[file]; + savedAssets.add(file); + } + return newAssets; + }; + processAssetsHook.intercept({ + name: "Compilation", + call: () => { + savedAssets = new Set(Object.keys(this.assets)); + }, + register: (tap) => { + const { type, name } = tap; + const { fn, additionalAssets, ...remainingTap } = tap; + const additionalAssetsFn = + additionalAssets === true ? fn : additionalAssets; + /** @typedef {WeakSet} ProcessedAssets */ + + /** @type {ProcessedAssets | undefined} */ + const processedAssets = additionalAssetsFn ? new WeakSet() : undefined; + /** + * @param {CompilationAssets} assets to be processed by additionalAssetsFn + * @returns {CompilationAssets} available assets + */ + const getAvailableAssets = (assets) => { + /** @type {CompilationAssets} */ + const availableAssets = {}; + for (const file of Object.keys(assets)) { + // https://github.com/webpack-contrib/compression-webpack-plugin/issues/390 + if (this.assets[file]) { + availableAssets[file] = assets[file]; + } + } + return availableAssets; + }; + switch (type) { + case "sync": + if (additionalAssetsFn) { + this.hooks.processAdditionalAssets.tap(name, (assets) => { + if ( + /** @type {ProcessedAssets} */ + (processedAssets).has(this.assets) + ) { + additionalAssetsFn(getAvailableAssets(assets)); + } + }); + } + return { + ...remainingTap, + type: "async", + /** + * @param {CompilationAssets} assets assets + * @param {(err?: Error | null, result?: void) => void} callback callback + * @returns {void} + */ + fn: (assets, callback) => { + try { + fn(assets); + } catch (err) { + return callback(/** @type {Error} */ (err)); + } + if (processedAssets !== undefined) { + processedAssets.add(this.assets); + } + const newAssets = popNewAssets(assets); + if (newAssets !== undefined) { + this.hooks.processAdditionalAssets.callAsync( + newAssets, + callback + ); + return; + } + callback(); + } + }; + case "async": + if (additionalAssetsFn) { + this.hooks.processAdditionalAssets.tapAsync( + name, + (assets, callback) => { + if ( + /** @type {ProcessedAssets} */ + (processedAssets).has(this.assets) + ) { + return additionalAssetsFn( + getAvailableAssets(assets), + callback + ); + } + callback(); + } + ); + } + return { + ...remainingTap, + /** + * @param {CompilationAssets} assets assets + * @param {(err?: Error | null, result?: void) => void} callback callback + * @returns {void} + */ + fn: (assets, callback) => { + fn( + assets, + /** + * @param {Error} err err + * @returns {void} + */ + (err) => { + if (err) return callback(err); + if (processedAssets !== undefined) { + processedAssets.add(this.assets); + } + const newAssets = popNewAssets(assets); + if (newAssets !== undefined) { + this.hooks.processAdditionalAssets.callAsync( + newAssets, + callback + ); + return; + } + callback(); + } + ); + } + }; + case "promise": + if (additionalAssetsFn) { + this.hooks.processAdditionalAssets.tapPromise(name, (assets) => { + if ( + /** @type {ProcessedAssets} */ + (processedAssets).has(this.assets) + ) { + return additionalAssetsFn(getAvailableAssets(assets)); + } + return Promise.resolve(); + }); + } + return { + ...remainingTap, + /** + * @param {CompilationAssets} assets assets + * @returns {Promise} result + */ + fn: (assets) => { + const p = fn(assets); + if (!p || !p.then) return p; + return p.then(() => { + if (processedAssets !== undefined) { + processedAssets.add(this.assets); + } + const newAssets = popNewAssets(assets); + if (newAssets !== undefined) { + return this.hooks.processAdditionalAssets.promise( + newAssets + ); + } + }); + } + }; + } + } + }); + + /** @type {SyncHook<[CompilationAssets]>} */ + const afterProcessAssetsHook = new SyncHook(["assets"]); + + /** + * @template T + * @param {string} name name of the hook + * @param {number} stage new stage + * @param {() => AsArray} getArgs get old hook function args + * @param {string=} code deprecation code (not deprecated when unset) + * @returns {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">> | undefined} fake hook which redirects + */ + const createProcessAssetsHook = (name, stage, getArgs, code) => { + if (!this._backCompat && code) return; + /** + * @param {string} reason reason + * @returns {string} error message + */ + const errorMessage = ( + reason + ) => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}. +BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`; + /** + * @param {string | (import("tapable").TapOptions & { name: string; } & ProcessAssetsAdditionalOptions)} options hook options + * @returns {import("tapable").TapOptions & { name: string; } & ProcessAssetsAdditionalOptions} modified options + */ + const getOptions = (options) => { + if (typeof options === "string") options = { name: options }; + if (options.stage) { + throw new Error(errorMessage("it's using the 'stage' option")); + } + return { ...options, stage }; + }; + return createFakeHook( + { + name, + /** @type {AsyncSeriesHook["intercept"]} */ + intercept(_interceptor) { + throw new Error(errorMessage("it's using 'intercept'")); + }, + /** @type {AsyncSeriesHook["tap"]} */ + tap: (options, fn) => { + processAssetsHook.tap(getOptions(options), () => fn(...getArgs())); + }, + /** @type {AsyncSeriesHook["tapAsync"]} */ + tapAsync: (options, fn) => { + processAssetsHook.tapAsync( + getOptions(options), + (assets, callback) => + /** @type {TODO} */ (fn)(...getArgs(), callback) + ); + }, + /** @type {AsyncSeriesHook["tapPromise"]} */ + tapPromise: (options, fn) => { + processAssetsHook.tapPromise(getOptions(options), () => + fn(...getArgs()) + ); + } + }, + `${name} is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)`, + code + ); + }; + this.hooks = Object.freeze({ + /** @type {SyncHook<[Module]>} */ + buildModule: new SyncHook(["module"]), + /** @type {SyncHook<[Module]>} */ + rebuildModule: new SyncHook(["module"]), + /** @type {SyncHook<[Module, WebpackError]>} */ + failedModule: new SyncHook(["module", "error"]), + /** @type {SyncHook<[Module]>} */ + succeedModule: new SyncHook(["module"]), + /** @type {SyncHook<[Module]>} */ + stillValidModule: new SyncHook(["module"]), + + /** @type {SyncHook<[Dependency, EntryOptions]>} */ + addEntry: new SyncHook(["entry", "options"]), + /** @type {SyncHook<[Dependency, EntryOptions, Error]>} */ + failedEntry: new SyncHook(["entry", "options", "error"]), + /** @type {SyncHook<[Dependency, EntryOptions, Module]>} */ + succeedEntry: new SyncHook(["entry", "options", "module"]), + + /** @type {SyncWaterfallHook<[(string[] | ReferencedExport)[], Dependency, RuntimeSpec]>} */ + dependencyReferencedExports: new SyncWaterfallHook([ + "referencedExports", + "dependency", + "runtime" + ]), + + /** @type {SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ + executeModule: new SyncHook(["options", "context"]), + /** @type {AsyncParallelHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ + prepareModuleExecution: new AsyncParallelHook(["options", "context"]), + + /** @type {AsyncSeriesHook<[Iterable]>} */ + finishModules: new AsyncSeriesHook(["modules"]), + /** @type {AsyncSeriesHook<[Module]>} */ + finishRebuildingModule: new AsyncSeriesHook(["module"]), + /** @type {SyncHook<[]>} */ + unseal: new SyncHook([]), + /** @type {SyncHook<[]>} */ + seal: new SyncHook([]), + + /** @type {SyncHook<[]>} */ + beforeChunks: new SyncHook([]), + /** + * The `afterChunks` hook is called directly after the chunks and module graph have + * been created and before the chunks and modules have been optimized. This hook is useful to + * inspect, analyze, and/or modify the chunk graph. + * @type {SyncHook<[Iterable]>} + */ + afterChunks: new SyncHook(["chunks"]), + + /** @type {SyncBailHook<[Iterable], boolean | void>} */ + optimizeDependencies: new SyncBailHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeDependencies: new SyncHook(["modules"]), + + /** @type {SyncHook<[]>} */ + optimize: new SyncHook([]), + /** @type {SyncBailHook<[Iterable], boolean | void>} */ + optimizeModules: new SyncBailHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeModules: new SyncHook(["modules"]), + + /** @type {SyncBailHook<[Iterable, ChunkGroup[]], boolean | void>} */ + optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncHook<[Iterable, ChunkGroup[]]>} */ + afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), + + /** @type {AsyncSeriesHook<[Iterable, Iterable]>} */ + optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), + /** @type {SyncHook<[Iterable, Iterable]>} */ + afterOptimizeTree: new SyncHook(["chunks", "modules"]), + + /** @type {AsyncSeriesBailHook<[Iterable, Iterable], void>} */ + optimizeChunkModules: new AsyncSeriesBailHook(["chunks", "modules"]), + /** @type {SyncHook<[Iterable, Iterable]>} */ + afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), + /** @type {SyncBailHook<[], boolean | void>} */ + shouldRecord: new SyncBailHook([]), + + /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ + additionalChunkRuntimeRequirements: new SyncHook([ + "chunk", + "runtimeRequirements", + "context" + ]), + /** @type {HookMap, RuntimeRequirementsContext], void>>} */ + runtimeRequirementInChunk: new HookMap( + () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) + ), + /** @type {SyncHook<[Module, Set, RuntimeRequirementsContext]>} */ + additionalModuleRuntimeRequirements: new SyncHook([ + "module", + "runtimeRequirements", + "context" + ]), + /** @type {HookMap, RuntimeRequirementsContext], void>>} */ + runtimeRequirementInModule: new HookMap( + () => new SyncBailHook(["module", "runtimeRequirements", "context"]) + ), + /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ + additionalTreeRuntimeRequirements: new SyncHook([ + "chunk", + "runtimeRequirements", + "context" + ]), + /** @type {HookMap, RuntimeRequirementsContext], void>>} */ + runtimeRequirementInTree: new HookMap( + () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) + ), + + /** @type {SyncHook<[RuntimeModule, Chunk]>} */ + runtimeModule: new SyncHook(["module", "chunk"]), + + /** @type {SyncHook<[Iterable, Records]>} */ + reviveModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook<[Iterable]>} */ + beforeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + moduleIds: new SyncHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + optimizeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeModuleIds: new SyncHook(["modules"]), + + /** @type {SyncHook<[Iterable, Records]>} */ + reviveChunks: new SyncHook(["chunks", "records"]), + /** @type {SyncHook<[Iterable]>} */ + beforeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<[Iterable]>} */ + chunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<[Iterable]>} */ + optimizeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeChunkIds: new SyncHook(["chunks"]), + + /** @type {SyncHook<[Iterable, Records]>} */ + recordModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook<[Iterable, Records]>} */ + recordChunks: new SyncHook(["chunks", "records"]), + + /** @type {SyncHook<[Iterable]>} */ + optimizeCodeGeneration: new SyncHook(["modules"]), + + /** @type {SyncHook<[]>} */ + beforeModuleHash: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterModuleHash: new SyncHook([]), + + /** @type {SyncHook<[]>} */ + beforeCodeGeneration: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterCodeGeneration: new SyncHook([]), + + /** @type {SyncHook<[]>} */ + beforeRuntimeRequirements: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterRuntimeRequirements: new SyncHook([]), + + /** @type {SyncHook<[]>} */ + beforeHash: new SyncHook([]), + /** @type {SyncHook<[Chunk]>} */ + contentHash: new SyncHook(["chunk"]), + /** @type {SyncHook<[]>} */ + afterHash: new SyncHook([]), + /** @type {SyncHook<[Records]>} */ + recordHash: new SyncHook(["records"]), + /** @type {SyncHook<[Compilation, Records]>} */ + record: new SyncHook(["compilation", "records"]), + + /** @type {SyncHook<[]>} */ + beforeModuleAssets: new SyncHook([]), + /** @type {SyncBailHook<[], boolean | void>} */ + shouldGenerateChunkAssets: new SyncBailHook([]), + /** @type {SyncHook<[]>} */ + beforeChunkAssets: new SyncHook([]), + // TODO webpack 6 remove + /** @deprecated */ + additionalChunkAssets: + /** @type {FakeHook]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */ + ( + createProcessAssetsHook( + "additionalChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS" + ) + ), + + // TODO webpack 6 deprecate + /** @deprecated */ + additionalAssets: + /** @type {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">>} */ + ( + createProcessAssetsHook( + "additionalAssets", + Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, + () => [] + ) + ), + // TODO webpack 6 remove + /** @deprecated */ + optimizeChunkAssets: + /** @type {FakeHook]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */ + ( + createProcessAssetsHook( + "optimizeChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS" + ) + ), + // TODO webpack 6 remove + /** @deprecated */ + afterOptimizeChunkAssets: + /** @type {FakeHook]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */ + ( + createProcessAssetsHook( + "afterOptimizeChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS" + ) + ), + // TODO webpack 6 deprecate + /** @deprecated */ + optimizeAssets: processAssetsHook, + // TODO webpack 6 deprecate + /** @deprecated */ + afterOptimizeAssets: afterProcessAssetsHook, + + processAssets: processAssetsHook, + afterProcessAssets: afterProcessAssetsHook, + /** @type {AsyncSeriesHook<[CompilationAssets]>} */ + processAdditionalAssets: new AsyncSeriesHook(["assets"]), + + /** @type {SyncBailHook<[], boolean | void>} */ + needAdditionalSeal: new SyncBailHook([]), + /** @type {AsyncSeriesHook<[]>} */ + afterSeal: new AsyncSeriesHook([]), + + /** @type {SyncWaterfallHook<[RenderManifestEntry[], RenderManifestOptions]>} */ + renderManifest: new SyncWaterfallHook(["result", "options"]), + + /** @type {SyncHook<[Hash]>} */ + fullHash: new SyncHook(["hash"]), + /** @type {SyncHook<[Chunk, Hash, ChunkHashContext]>} */ + chunkHash: new SyncHook(["chunk", "chunkHash", "ChunkHashContext"]), + + /** @type {SyncHook<[Module, string]>} */ + moduleAsset: new SyncHook(["module", "filename"]), + /** @type {SyncHook<[Chunk, string]>} */ + chunkAsset: new SyncHook(["chunk", "filename"]), + + /** @type {SyncWaterfallHook<[string, PathData, AssetInfo | undefined]>} */ + assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]), + + /** @type {SyncBailHook<[], boolean | void>} */ + needAdditionalPass: new SyncBailHook([]), + + /** @type {SyncHook<[Compiler, string, number]>} */ + childCompiler: new SyncHook([ + "childCompiler", + "compilerName", + "compilerIndex" + ]), + + /** @type {SyncBailHook<[string, LogEntry], boolean | void>} */ + log: new SyncBailHook(["origin", "logEntry"]), + + /** @type {SyncWaterfallHook<[Error[]]>} */ + processWarnings: new SyncWaterfallHook(["warnings"]), + /** @type {SyncWaterfallHook<[Error[]]>} */ + processErrors: new SyncWaterfallHook(["errors"]), + + /** @type {HookMap, CreateStatsOptionsContext]>>} */ + statsPreset: new HookMap(() => new SyncHook(["options", "context"])), + /** @type {SyncHook<[Partial, CreateStatsOptionsContext]>} */ + statsNormalize: new SyncHook(["options", "context"]), + /** @type {SyncHook<[StatsFactory, NormalizedStatsOptions]>} */ + statsFactory: new SyncHook(["statsFactory", "options"]), + /** @type {SyncHook<[StatsPrinter, NormalizedStatsOptions]>} */ + statsPrinter: new SyncHook(["statsPrinter", "options"]), + + get normalModuleLoader() { + return getNormalModuleLoader(); + } + }); + /** @type {string=} */ + this.name = undefined; + /** @type {number | undefined} */ + this.startTime = undefined; + /** @type {number | undefined} */ + this.endTime = undefined; + /** @type {Compiler} */ + this.compiler = compiler; + this.resolverFactory = compiler.resolverFactory; + /** @type {InputFileSystem} */ + this.inputFileSystem = + /** @type {InputFileSystem} */ + (compiler.inputFileSystem); + this.fileSystemInfo = new FileSystemInfo(this.inputFileSystem, { + unmanagedPaths: compiler.unmanagedPaths, + managedPaths: compiler.managedPaths, + immutablePaths: compiler.immutablePaths, + logger: this.getLogger("webpack.FileSystemInfo"), + hashFunction: compiler.options.output.hashFunction + }); + if (compiler.fileTimestamps) { + this.fileSystemInfo.addFileTimestamps(compiler.fileTimestamps, true); + } + if (compiler.contextTimestamps) { + this.fileSystemInfo.addContextTimestamps( + compiler.contextTimestamps, + true + ); + } + /** @type {ValueCacheVersions} */ + this.valueCacheVersions = new Map(); + this.requestShortener = compiler.requestShortener; + this.compilerPath = compiler.compilerPath; + + this.logger = this.getLogger("webpack.Compilation"); + + const options = /** @type {WebpackOptions} */ (compiler.options); + this.options = options; + this.outputOptions = options && options.output; + /** @type {boolean} */ + this.bail = (options && options.bail) || false; + /** @type {boolean} */ + this.profile = (options && options.profile) || false; + + this.params = params; + this.mainTemplate = new MainTemplate(this.outputOptions, this); + this.chunkTemplate = new ChunkTemplate(this.outputOptions, this); + this.runtimeTemplate = new RuntimeTemplate( + this, + this.outputOptions, + this.requestShortener + ); + /** @type {ModuleTemplates} */ + this.moduleTemplates = { + javascript: new ModuleTemplate(this.runtimeTemplate, this) + }; + defineRemovedModuleTemplates(this.moduleTemplates); + + // We need to think how implement types here + /** @type {ModuleMemCaches | undefined} */ + this.moduleMemCaches = undefined; + /** @type {ModuleMemCaches | undefined} */ + this.moduleMemCaches2 = undefined; + this.moduleGraph = new ModuleGraph(); + /** @type {ChunkGraph} */ + this.chunkGraph = /** @type {TODO} */ (undefined); + /** @type {CodeGenerationResults} */ + this.codeGenerationResults = /** @type {TODO} */ (undefined); + + /** @type {AsyncQueue} */ + this.processDependenciesQueue = new AsyncQueue({ + name: "processDependencies", + parallelism: options.parallelism || 100, + processor: this._processModuleDependencies.bind(this) + }); + /** @type {AsyncQueue} */ + this.addModuleQueue = new AsyncQueue({ + name: "addModule", + parent: this.processDependenciesQueue, + getKey: (module) => module.identifier(), + processor: this._addModule.bind(this) + }); + /** @type {AsyncQueue} */ + this.factorizeQueue = new AsyncQueue({ + name: "factorize", + parent: this.addModuleQueue, + processor: this._factorizeModule.bind(this) + }); + /** @type {AsyncQueue} */ + this.buildQueue = new AsyncQueue({ + name: "build", + parent: this.factorizeQueue, + processor: this._buildModule.bind(this) + }); + /** @type {AsyncQueue} */ + this.rebuildQueue = new AsyncQueue({ + name: "rebuild", + parallelism: options.parallelism || 100, + processor: this._rebuildModule.bind(this) + }); + + /** + * Modules in value are building during the build of Module in key. + * Means value blocking key from finishing. + * Needed to detect build cycles. + * @type {WeakMap>} + */ + this.creatingModuleDuringBuild = new WeakMap(); + + /** @type {Map, EntryData>} */ + this.entries = new Map(); + /** @type {EntryData} */ + this.globalEntry = { + dependencies: [], + includeDependencies: [], + options: { + name: undefined + } + }; + /** @type {Map} */ + this.entrypoints = new Map(); + /** @type {Entrypoint[]} */ + this.asyncEntrypoints = []; + /** @type {Set} */ + this.chunks = new Set(); + /** @type {ChunkGroup[]} */ + this.chunkGroups = []; + /** @type {Map} */ + this.namedChunkGroups = new Map(); + /** @type {Map} */ + this.namedChunks = new Map(); + /** @type {Set} */ + this.modules = new Set(); + if (this._backCompat) { + arrayToSetDeprecation(this.chunks, "Compilation.chunks"); + arrayToSetDeprecation(this.modules, "Compilation.modules"); + } + /** + * @private + * @type {Map} + */ + this._modules = new Map(); + /** @type {Records | null} */ + this.records = null; + /** @type {string[]} */ + this.additionalChunkAssets = []; + /** @type {CompilationAssets} */ + this.assets = {}; + /** @type {Map} */ + this.assetsInfo = new Map(); + /** @type {Map>>} */ + this._assetsRelatedIn = new Map(); + /** @type {Error[]} */ + this.errors = []; + /** @type {Error[]} */ + this.warnings = []; + /** @type {Compilation[]} */ + this.children = []; + /** @type {Map} */ + this.logging = new Map(); + /** @type {Map} */ + this.dependencyFactories = new Map(); + /** @type {DependencyTemplates} */ + this.dependencyTemplates = new DependencyTemplates( + this.outputOptions.hashFunction + ); + /** @type {Record} */ + this.childrenCounters = {}; + /** @type {Set | null} */ + this.usedChunkIds = null; + /** @type {Set | null} */ + this.usedModuleIds = null; + /** @type {boolean} */ + this.needAdditionalPass = false; + /** @type {Set} */ + this._restoredUnsafeCacheModuleEntries = new Set(); + /** @type {Map} */ + this._restoredUnsafeCacheEntries = new Map(); + /** @type {WeakSet} */ + this.builtModules = new WeakSet(); + /** @type {WeakSet} */ + this.codeGeneratedModules = new WeakSet(); + /** @type {WeakSet} */ + this.buildTimeExecutedModules = new WeakSet(); + /** @type {Set} */ + this.emittedAssets = new Set(); + /** @type {Set} */ + this.comparedForEmitAssets = new Set(); + /** @type {LazySet} */ + this.fileDependencies = new LazySet(); + /** @type {LazySet} */ + this.contextDependencies = new LazySet(); + /** @type {LazySet} */ + this.missingDependencies = new LazySet(); + /** @type {LazySet} */ + this.buildDependencies = new LazySet(); + // TODO webpack 6 remove + this.compilationDependencies = { + add: util.deprecate( + /** + * @param {string} item item + * @returns {LazySet} file dependencies + */ + (item) => this.fileDependencies.add(item), + "Compilation.compilationDependencies is deprecated (used Compilation.fileDependencies instead)", + "DEP_WEBPACK_COMPILATION_COMPILATION_DEPENDENCIES" + ) + }; + + this._modulesCache = this.getCache("Compilation/modules"); + this._assetsCache = this.getCache("Compilation/assets"); + this._codeGenerationCache = this.getCache("Compilation/codeGeneration"); + + const unsafeCache = options.module.unsafeCache; + this._unsafeCache = Boolean(unsafeCache); + this._unsafeCachePredicate = + typeof unsafeCache === "function" ? unsafeCache : () => true; + } + + getStats() { + return new Stats(this); + } + + /** + * @param {string | boolean | StatsOptions | undefined} optionsOrPreset stats option value + * @param {CreateStatsOptionsContext=} context context + * @returns {NormalizedStatsOptions} normalized options + */ + createStatsOptions(optionsOrPreset, context = {}) { + if (typeof optionsOrPreset === "boolean") { + optionsOrPreset = { + preset: optionsOrPreset === false ? "none" : "normal" + }; + } else if (typeof optionsOrPreset === "string") { + optionsOrPreset = { preset: optionsOrPreset }; + } + if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) { + // We use this method of shallow cloning this object to include + // properties in the prototype chain + /** @type {Partial} */ + const options = {}; + for (const key in optionsOrPreset) { + options[key] = optionsOrPreset[/** @type {keyof StatsOptions} */ (key)]; + } + if (options.preset !== undefined) { + this.hooks.statsPreset.for(options.preset).call(options, context); + } + this.hooks.statsNormalize.call(options, context); + return /** @type {NormalizedStatsOptions} */ (options); + } + /** @type {Partial} */ + const options = {}; + this.hooks.statsNormalize.call(options, context); + return /** @type {NormalizedStatsOptions} */ (options); + } + + /** + * @param {NormalizedStatsOptions} options options + * @returns {StatsFactory} the stats factory + */ + createStatsFactory(options) { + const statsFactory = new StatsFactory(); + this.hooks.statsFactory.call(statsFactory, options); + return statsFactory; + } + + /** + * @param {NormalizedStatsOptions} options options + * @returns {StatsPrinter} the stats printer + */ + createStatsPrinter(options) { + const statsPrinter = new StatsPrinter(); + this.hooks.statsPrinter.call(statsPrinter, options); + return statsPrinter; + } + + /** + * @param {string} name cache name + * @returns {CacheFacade} the cache facade instance + */ + getCache(name) { + return this.compiler.getCache(name); + } + + /** + * @param {string | (() => string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name + */ + getLogger(name) { + if (!name) { + throw new TypeError("Compilation.getLogger(name) called without a name"); + } + /** @type {LogEntry[] | undefined} */ + let logEntries; + return new Logger( + (type, args) => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); + } + } + let trace; + switch (type) { + case LogType.warn: + case LogType.error: + case LogType.trace: + trace = ErrorHelpers.cutOffLoaderExecution( + /** @type {string} */ (new Error("Trace").stack) + ) + .split("\n") + .slice(3); + break; + } + /** @type {LogEntry} */ + const logEntry = { + time: Date.now(), + type, + args, + trace + }; + /* eslint-disable no-console */ + if (this.hooks.log.call(name, logEntry) === undefined) { + if ( + logEntry.type === LogType.profileEnd && + typeof console.profileEnd === "function" + ) { + console.profileEnd( + `[${name}] ${/** @type {NonNullable} */ (logEntry.args)[0]}` + ); + } + if (logEntries === undefined) { + logEntries = this.logging.get(name); + if (logEntries === undefined) { + logEntries = []; + this.logging.set(name, logEntries); + } + } + logEntries.push(logEntry); + if ( + logEntry.type === LogType.profile && + typeof console.profile === "function" + ) { + console.profile( + `[${name}] ${ + /** @type {NonNullable} */ + (logEntry.args)[0] + }` + ); + } + /* eslint-enable no-console */ + } + }, + (childName) => { + if (typeof name === "function") { + if (typeof childName === "function") { + return this.getLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); + } + } + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + return this.getLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + if (typeof childName === "function") { + return this.getLogger(() => { + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + return this.getLogger(`${name}/${childName}`); + } + ); + } + + /** + * @param {Module} module module to be added that was created + * @param {ModuleCallback} callback returns the module in the compilation, + * it could be the passed one (if new), or an already existing in the compilation + * @returns {void} + */ + addModule(module, callback) { + this.addModuleQueue.add(module, callback); + } + + /** + * @param {Module} module module to be added that was created + * @param {ModuleCallback} callback returns the module in the compilation, + * it could be the passed one (if new), or an already existing in the compilation + * @returns {void} + */ + _addModule(module, callback) { + const identifier = module.identifier(); + const alreadyAddedModule = this._modules.get(identifier); + if (alreadyAddedModule) { + return callback(null, alreadyAddedModule); + } + + const currentProfile = this.profile + ? this.moduleGraph.getProfile(module) + : undefined; + if (currentProfile !== undefined) { + currentProfile.markRestoringStart(); + } + + this._modulesCache.get(identifier, null, (err, cacheModule) => { + if (err) return callback(new ModuleRestoreError(module, err)); + + if (currentProfile !== undefined) { + currentProfile.markRestoringEnd(); + currentProfile.markIntegrationStart(); + } + + if (cacheModule) { + cacheModule.updateCacheModule(module); + + module = cacheModule; + } + this._modules.set(identifier, module); + this.modules.add(module); + if (this._backCompat) { + ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); + } + if (currentProfile !== undefined) { + currentProfile.markIntegrationEnd(); + } + callback(null, module); + }); + } + + /** + * Fetches a module from a compilation by its identifier + * @param {Module} module the module provided + * @returns {Module} the module requested + */ + getModule(module) { + const identifier = module.identifier(); + return /** @type {Module} */ (this._modules.get(identifier)); + } + + /** + * Attempts to search for a module by its identifier + * @param {string} identifier identifier (usually path) for module + * @returns {Module|undefined} attempt to search for module and return it, else undefined + */ + findModule(identifier) { + return this._modules.get(identifier); + } + + /** + * Schedules a build of the module object + * @param {Module} module module to be built + * @param {ModuleCallback} callback the callback + * @returns {void} + */ + buildModule(module, callback) { + this.buildQueue.add(module, callback); + } + + /** + * Builds the module object + * @param {Module} module module to be built + * @param {ModuleCallback} callback the callback + * @returns {void} + */ + _buildModule(module, callback) { + const currentProfile = this.profile + ? this.moduleGraph.getProfile(module) + : undefined; + if (currentProfile !== undefined) { + currentProfile.markBuildingStart(); + } + + module.needBuild( + { + compilation: this, + fileSystemInfo: this.fileSystemInfo, + valueCacheVersions: this.valueCacheVersions + }, + (err, needBuild) => { + if (err) return callback(err); + + if (!needBuild) { + if (currentProfile !== undefined) { + currentProfile.markBuildingEnd(); + } + this.hooks.stillValidModule.call(module); + return callback(); + } + + this.hooks.buildModule.call(module); + this.builtModules.add(module); + module.build( + this.options, + this, + this.resolverFactory.get("normal", module.resolveOptions), + /** @type {InputFileSystem} */ + (this.inputFileSystem), + (err) => { + if (currentProfile !== undefined) { + currentProfile.markBuildingEnd(); + } + if (err) { + this.hooks.failedModule.call(module, err); + return callback(err); + } + if (currentProfile !== undefined) { + currentProfile.markStoringStart(); + } + this._modulesCache.store( + module.identifier(), + null, + module, + (err) => { + if (currentProfile !== undefined) { + currentProfile.markStoringEnd(); + } + if (err) { + this.hooks.failedModule.call( + module, + /** @type {WebpackError} */ (err) + ); + return callback(new ModuleStoreError(module, err)); + } + this.hooks.succeedModule.call(module); + return callback(); + } + ); + } + ); + } + ); + } + + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + processModuleDependencies(module, callback) { + this.processDependenciesQueue.add(module, callback); + } + + /** + * @param {Module} module to be processed for deps + * @returns {void} + */ + processModuleDependenciesNonRecursive(module) { + /** + * @param {DependenciesBlock} block block + */ + const processDependenciesBlock = (block) => { + if (block.dependencies) { + let i = 0; + for (const dep of block.dependencies) { + this.moduleGraph.setParents(dep, block, module, i++); + } + } + if (block.blocks) { + for (const b of block.blocks) processDependenciesBlock(b); + } + }; + + processDependenciesBlock(module); + } + + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + _processModuleDependencies(module, callback) { + /** @type {Array<{factory: ModuleFactory, dependencies: Dependency[], context: string|undefined, originModule: Module|null}>} */ + const sortedDependencies = []; + + /** @type {DependenciesBlock} */ + let currentBlock; + + /** @type {Map>} */ + let dependencies; + /** @type {DepConstructor} */ + let factoryCacheKey; + /** @type {ModuleFactory} */ + let factoryCacheKey2; + /** @typedef {Map} FactoryCacheValue */ + /** @type {FactoryCacheValue | undefined} */ + let factoryCacheValue; + /** @type {string} */ + let listCacheKey1; + /** @type {string} */ + let listCacheKey2; + /** @type {Dependency[]} */ + let listCacheValue; + + let inProgressSorting = 1; + let inProgressTransitive = 1; + + /** + * @param {WebpackError=} err error + * @returns {void} + */ + const onDependenciesSorted = (err) => { + if (err) return callback(err); + + // early exit without changing parallelism back and forth + if (sortedDependencies.length === 0 && inProgressTransitive === 1) { + return callback(); + } + + // This is nested so we need to allow one additional task + this.processDependenciesQueue.increaseParallelism(); + + for (const item of sortedDependencies) { + inProgressTransitive++; + // eslint-disable-next-line no-loop-func + this.handleModuleCreation(item, (err) => { + // In V8, the Error objects keep a reference to the functions on the stack. These warnings & + // errors are created inside closures that keep a reference to the Compilation, so errors are + // leaking the Compilation object. + if (err && this.bail) { + if (inProgressTransitive <= 0) return; + inProgressTransitive = -1; + // eslint-disable-next-line no-self-assign + err.stack = err.stack; + onTransitiveTasksFinished(err); + return; + } + if (--inProgressTransitive === 0) onTransitiveTasksFinished(); + }); + } + if (--inProgressTransitive === 0) onTransitiveTasksFinished(); + }; + + /** + * @param {WebpackError=} err error + * @returns {void} + */ + const onTransitiveTasksFinished = (err) => { + if (err) return callback(err); + this.processDependenciesQueue.decreaseParallelism(); + + return callback(); + }; + + /** + * @param {Dependency} dep dependency + * @param {number} index index in block + * @returns {void} + */ + const processDependency = (dep, index) => { + this.moduleGraph.setParents(dep, currentBlock, module, index); + if (this._unsafeCache) { + try { + const unsafeCachedModule = unsafeCacheDependencies.get(dep); + if (unsafeCachedModule === null) return; + if (unsafeCachedModule !== undefined) { + if ( + this._restoredUnsafeCacheModuleEntries.has(unsafeCachedModule) + ) { + this._handleExistingModuleFromUnsafeCache( + module, + dep, + unsafeCachedModule + ); + return; + } + const identifier = unsafeCachedModule.identifier(); + const cachedModule = + this._restoredUnsafeCacheEntries.get(identifier); + if (cachedModule !== undefined) { + // update unsafe cache to new module + unsafeCacheDependencies.set(dep, cachedModule); + this._handleExistingModuleFromUnsafeCache( + module, + dep, + cachedModule + ); + return; + } + inProgressSorting++; + this._modulesCache.get(identifier, null, (err, cachedModule) => { + if (err) { + if (inProgressSorting <= 0) return; + inProgressSorting = -1; + onDependenciesSorted(/** @type {WebpackError} */ (err)); + return; + } + try { + if (!this._restoredUnsafeCacheEntries.has(identifier)) { + const data = unsafeCacheData.get(cachedModule); + if (data === undefined) { + processDependencyForResolving(dep); + if (--inProgressSorting === 0) onDependenciesSorted(); + return; + } + if (cachedModule !== unsafeCachedModule) { + unsafeCacheDependencies.set(dep, cachedModule); + } + cachedModule.restoreFromUnsafeCache( + data, + this.params.normalModuleFactory, + this.params + ); + this._restoredUnsafeCacheEntries.set( + identifier, + cachedModule + ); + this._restoredUnsafeCacheModuleEntries.add(cachedModule); + if (!this.modules.has(cachedModule)) { + inProgressTransitive++; + this._handleNewModuleFromUnsafeCache( + module, + dep, + cachedModule, + (err) => { + if (err) { + if (inProgressTransitive <= 0) return; + inProgressTransitive = -1; + onTransitiveTasksFinished(err); + } + if (--inProgressTransitive === 0) { + return onTransitiveTasksFinished(); + } + } + ); + if (--inProgressSorting === 0) onDependenciesSorted(); + return; + } + } + if (unsafeCachedModule !== cachedModule) { + unsafeCacheDependencies.set(dep, cachedModule); + } + this._handleExistingModuleFromUnsafeCache( + module, + dep, + cachedModule + ); // a3 + } catch (err) { + if (inProgressSorting <= 0) return; + inProgressSorting = -1; + onDependenciesSorted(/** @type {WebpackError} */ (err)); + return; + } + if (--inProgressSorting === 0) onDependenciesSorted(); + }); + return; + } + } catch (err) { + // eslint-disable-next-line no-console + console.error(err); + } + } + processDependencyForResolving(dep); + }; + + /** + * @param {Dependency} dep dependency + * @returns {void} + */ + const processDependencyForResolving = (dep) => { + const resourceIdent = dep.getResourceIdentifier(); + if (resourceIdent !== undefined && resourceIdent !== null) { + const category = dep.category; + const constructor = /** @type {DepConstructor} */ (dep.constructor); + if (factoryCacheKey === constructor) { + // Fast path 1: same constructor as prev item + if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { + // Super fast path 1: also same resource + listCacheValue.push(dep); + return; + } + } else { + const factory = this.dependencyFactories.get(constructor); + if (factory === undefined) { + throw new Error( + `No module factory available for dependency type: ${constructor.name}` + ); + } + if (factoryCacheKey2 === factory) { + // Fast path 2: same factory as prev item + factoryCacheKey = constructor; + if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { + // Super fast path 2: also same resource + listCacheValue.push(dep); + return; + } + } else { + // Slow path + if (factoryCacheKey2 !== undefined) { + // Archive last cache entry + if (dependencies === undefined) dependencies = new Map(); + dependencies.set( + factoryCacheKey2, + /** @type {FactoryCacheValue} */ (factoryCacheValue) + ); + factoryCacheValue = dependencies.get(factory); + if (factoryCacheValue === undefined) { + factoryCacheValue = new Map(); + } + } else { + factoryCacheValue = new Map(); + } + factoryCacheKey = constructor; + factoryCacheKey2 = factory; + } + } + // Here webpack is using heuristic that assumes + // mostly esm dependencies would be used + // so we don't allocate extra string for them + const cacheKey = + category === esmDependencyCategory + ? resourceIdent + : `${category}${resourceIdent}`; + let list = /** @type {FactoryCacheValue} */ (factoryCacheValue).get( + cacheKey + ); + if (list === undefined) { + /** @type {FactoryCacheValue} */ + (factoryCacheValue).set(cacheKey, (list = [])); + sortedDependencies.push({ + factory: factoryCacheKey2, + dependencies: list, + context: dep.getContext(), + originModule: module + }); + } + list.push(dep); + listCacheKey1 = category; + listCacheKey2 = resourceIdent; + listCacheValue = list; + } + }; + + try { + /** @type {DependenciesBlock[]} */ + const queue = [module]; + do { + const block = /** @type {DependenciesBlock} */ (queue.pop()); + if (block.dependencies) { + currentBlock = block; + let i = 0; + for (const dep of block.dependencies) processDependency(dep, i++); + } + if (block.blocks) { + for (const b of block.blocks) queue.push(b); + } + } while (queue.length !== 0); + } catch (err) { + return callback(/** @type {WebpackError} */ (err)); + } + + if (--inProgressSorting === 0) onDependenciesSorted(); + } + + /** + * @private + * @param {Module} originModule original module + * @param {Dependency} dependency dependency + * @param {Module} module cached module + * @param {Callback} callback callback + */ + _handleNewModuleFromUnsafeCache(originModule, dependency, module, callback) { + const moduleGraph = this.moduleGraph; + + moduleGraph.setResolvedModule(originModule, dependency, module); + + moduleGraph.setIssuerIfUnset( + module, + originModule !== undefined ? originModule : null + ); + + this._modules.set(module.identifier(), module); + this.modules.add(module); + if (this._backCompat) { + ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); + } + + this._handleModuleBuildAndDependencies( + originModule, + module, + true, + false, + callback + ); + } + + /** + * @private + * @param {Module} originModule original modules + * @param {Dependency} dependency dependency + * @param {Module} module cached module + */ + _handleExistingModuleFromUnsafeCache(originModule, dependency, module) { + const moduleGraph = this.moduleGraph; + + moduleGraph.setResolvedModule(originModule, dependency, module); + } + + /** + * @typedef {object} HandleModuleCreationOptions + * @property {ModuleFactory} factory + * @property {Dependency[]} dependencies + * @property {Module | null} originModule + * @property {Partial=} contextInfo + * @property {string=} context + * @property {boolean=} recursive recurse into dependencies of the created module + * @property {boolean=} connectOrigin connect the resolved module with the origin module + * @property {boolean=} checkCycle check the cycle dependencies of the created module + */ + + /** + * @param {HandleModuleCreationOptions} options options object + * @param {ModuleCallback} callback callback + * @returns {void} + */ + handleModuleCreation( + { + factory, + dependencies, + originModule, + contextInfo, + context, + recursive = true, + connectOrigin = recursive, + checkCycle = !recursive + }, + callback + ) { + const moduleGraph = this.moduleGraph; + + const currentProfile = this.profile ? new ModuleProfile() : undefined; + + this.factorizeModule( + { + currentProfile, + factory, + dependencies, + factoryResult: true, + originModule, + contextInfo, + context + }, + (err, factoryResult) => { + const applyFactoryResultDependencies = () => { + const { fileDependencies, contextDependencies, missingDependencies } = + /** @type {ModuleFactoryResult} */ (factoryResult); + if (fileDependencies) { + this.fileDependencies.addAll(fileDependencies); + } + if (contextDependencies) { + this.contextDependencies.addAll(contextDependencies); + } + if (missingDependencies) { + this.missingDependencies.addAll(missingDependencies); + } + }; + if (err) { + if (factoryResult) applyFactoryResultDependencies(); + if (dependencies.every((d) => d.optional)) { + this.warnings.push(err); + return callback(); + } + this.errors.push(err); + return callback(err); + } + + const newModule = + /** @type {ModuleFactoryResult} */ + (factoryResult).module; + + if (!newModule) { + applyFactoryResultDependencies(); + return callback(); + } + + if (currentProfile !== undefined) { + moduleGraph.setProfile(newModule, currentProfile); + } + + this.addModule(newModule, (err, _module) => { + if (err) { + applyFactoryResultDependencies(); + if (!err.module) { + err.module = _module; + } + this.errors.push(err); + + return callback(err); + } + + const module = + /** @type {ModuleWithRestoreFromUnsafeCache} */ + (_module); + + if ( + this._unsafeCache && + /** @type {ModuleFactoryResult} */ + (factoryResult).cacheable !== false && + module.restoreFromUnsafeCache && + this._unsafeCachePredicate(module) + ) { + const unsafeCacheableModule = + /** @type {ModuleWithRestoreFromUnsafeCache} */ + (module); + for (const dependency of dependencies) { + moduleGraph.setResolvedModule( + connectOrigin ? originModule : null, + dependency, + unsafeCacheableModule + ); + unsafeCacheDependencies.set(dependency, unsafeCacheableModule); + } + if (!unsafeCacheData.has(unsafeCacheableModule)) { + unsafeCacheData.set( + unsafeCacheableModule, + unsafeCacheableModule.getUnsafeCacheData() + ); + } + } else { + applyFactoryResultDependencies(); + for (const dependency of dependencies) { + moduleGraph.setResolvedModule( + connectOrigin ? originModule : null, + dependency, + module + ); + } + } + + moduleGraph.setIssuerIfUnset( + module, + originModule !== undefined ? originModule : null + ); + if (module !== newModule && currentProfile !== undefined) { + const otherProfile = moduleGraph.getProfile(module); + if (otherProfile !== undefined) { + currentProfile.mergeInto(otherProfile); + } else { + moduleGraph.setProfile(module, currentProfile); + } + } + + this._handleModuleBuildAndDependencies( + originModule, + module, + recursive, + checkCycle, + callback + ); + }); + } + ); + } + + /** + * @private + * @param {Module | null} originModule original module + * @param {Module} module module + * @param {boolean} recursive true if make it recursive, otherwise false + * @param {boolean} checkCycle true if need to check cycle, otherwise false + * @param {ModuleCallback} callback callback + * @returns {void} + */ + _handleModuleBuildAndDependencies( + originModule, + module, + recursive, + checkCycle, + callback + ) { + // Check for cycles when build is trigger inside another build + /** @type {Set | undefined} */ + let creatingModuleDuringBuildSet; + if ( + checkCycle && + this.buildQueue.isProcessing(/** @type {Module} */ (originModule)) + ) { + // Track build dependency + creatingModuleDuringBuildSet = this.creatingModuleDuringBuild.get( + /** @type {Module} */ + (originModule) + ); + if (creatingModuleDuringBuildSet === undefined) { + creatingModuleDuringBuildSet = new Set(); + this.creatingModuleDuringBuild.set( + /** @type {Module} */ + (originModule), + creatingModuleDuringBuildSet + ); + } + creatingModuleDuringBuildSet.add(module); + + // When building is blocked by another module + // search for a cycle, cancel the cycle by throwing + // an error (otherwise this would deadlock) + const blockReasons = this.creatingModuleDuringBuild.get(module); + if (blockReasons !== undefined) { + const set = new Set(blockReasons); + for (const item of set) { + const blockReasons = this.creatingModuleDuringBuild.get(item); + if (blockReasons !== undefined) { + for (const m of blockReasons) { + if (m === module) { + return callback(new BuildCycleError(module)); + } + set.add(m); + } + } + } + } + } + + this.buildModule(module, (err) => { + if (creatingModuleDuringBuildSet !== undefined) { + creatingModuleDuringBuildSet.delete(module); + } + if (err) { + if (!err.module) { + err.module = module; + } + this.errors.push(err); + + return callback(err); + } + + if (!recursive) { + this.processModuleDependenciesNonRecursive(module); + callback(null, module); + return; + } + + // This avoids deadlocks for circular dependencies + if (this.processDependenciesQueue.isProcessing(module)) { + return callback(null, module); + } + + this.processModuleDependencies(module, (err) => { + if (err) { + return callback(err); + } + callback(null, module); + }); + }); + } + + /** + * @param {FactorizeModuleOptions} options options object + * @param {ModuleOrFactoryResultCallback} callback callback + * @returns {void} + */ + _factorizeModule( + { + currentProfile, + factory, + dependencies, + originModule, + factoryResult, + contextInfo, + context + }, + callback + ) { + if (currentProfile !== undefined) { + currentProfile.markFactoryStart(); + } + factory.create( + { + contextInfo: { + issuer: originModule + ? /** @type {string} */ (originModule.nameForCondition()) + : "", + issuerLayer: originModule ? originModule.layer : null, + compiler: /** @type {string} */ (this.compiler.name), + ...contextInfo + }, + resolveOptions: originModule ? originModule.resolveOptions : undefined, + context: + context || + (originModule + ? /** @type {string} */ (originModule.context) + : /** @type {string} */ (this.compiler.context)), + dependencies + }, + (err, result) => { + if (result) { + // TODO webpack 6: remove + // For backward-compat + if (result.module === undefined && result instanceof Module) { + result = { + module: result + }; + } + if (!factoryResult) { + const { + fileDependencies, + contextDependencies, + missingDependencies + } = result; + if (fileDependencies) { + this.fileDependencies.addAll(fileDependencies); + } + if (contextDependencies) { + this.contextDependencies.addAll(contextDependencies); + } + if (missingDependencies) { + this.missingDependencies.addAll(missingDependencies); + } + } + } + if (err) { + const notFoundError = new ModuleNotFoundError( + originModule, + err, + /** @type {DependencyLocation} */ + (dependencies.map((d) => d.loc).find(Boolean)) + ); + return callback(notFoundError, factoryResult ? result : undefined); + } + if (!result) { + return callback(); + } + + if (currentProfile !== undefined) { + currentProfile.markFactoryEnd(); + } + + callback(null, factoryResult ? result : result.module); + } + ); + } + + /** + * @param {string} context context string path + * @param {Dependency} dependency dependency used to create Module chain + * @param {ModuleCallback} callback callback for when module chain is complete + * @returns {void} will throw if dependency instance is not a valid Dependency + */ + addModuleChain(context, dependency, callback) { + return this.addModuleTree({ context, dependency }, callback); + } + + /** + * @param {object} options options + * @param {string} options.context context string path + * @param {Dependency} options.dependency dependency used to create Module chain + * @param {Partial=} options.contextInfo additional context info for the root module + * @param {ModuleCallback} callback callback for when module chain is complete + * @returns {void} will throw if dependency instance is not a valid Dependency + */ + addModuleTree({ context, dependency, contextInfo }, callback) { + if ( + typeof dependency !== "object" || + dependency === null || + !dependency.constructor + ) { + return callback( + new WebpackError("Parameter 'dependency' must be a Dependency") + ); + } + const Dep = /** @type {DepConstructor} */ (dependency.constructor); + const moduleFactory = this.dependencyFactories.get(Dep); + if (!moduleFactory) { + return callback( + new WebpackError( + `No dependency factory available for this dependency type: ${dependency.constructor.name}` + ) + ); + } + + this.handleModuleCreation( + { + factory: moduleFactory, + dependencies: [dependency], + originModule: null, + contextInfo, + context + }, + (err, result) => { + if (err && this.bail) { + callback(err); + this.buildQueue.stop(); + this.rebuildQueue.stop(); + this.processDependenciesQueue.stop(); + this.factorizeQueue.stop(); + } else if (!err && result) { + callback(null, result); + } else { + callback(); + } + } + ); + } + + /** + * @param {string} context context path for entry + * @param {Dependency} entry entry dependency that should be followed + * @param {string | EntryOptions} optionsOrName options or deprecated name of entry + * @param {ModuleCallback} callback callback function + * @returns {void} returns + */ + addEntry(context, entry, optionsOrName, callback) { + // TODO webpack 6 remove + const options = + typeof optionsOrName === "object" + ? optionsOrName + : { name: optionsOrName }; + + this._addEntryItem(context, entry, "dependencies", options, callback); + } + + /** + * @param {string} context context path for entry + * @param {Dependency} dependency dependency that should be followed + * @param {EntryOptions} options options + * @param {ModuleCallback} callback callback function + * @returns {void} returns + */ + addInclude(context, dependency, options, callback) { + this._addEntryItem( + context, + dependency, + "includeDependencies", + options, + callback + ); + } + + /** + * @param {string} context context path for entry + * @param {Dependency} entry entry dependency that should be followed + * @param {"dependencies" | "includeDependencies"} target type of entry + * @param {EntryOptions} options options + * @param {ModuleCallback} callback callback function + * @returns {void} returns + */ + _addEntryItem(context, entry, target, options, callback) { + const { name } = options; + /** @type {EntryData | undefined} */ + let entryData = + name !== undefined ? this.entries.get(name) : this.globalEntry; + if (entryData === undefined) { + entryData = { + dependencies: [], + includeDependencies: [], + options: { + name: undefined, + ...options + } + }; + entryData[target].push(entry); + this.entries.set( + /** @type {NonNullable} */ + (name), + entryData + ); + } else { + entryData[target].push(entry); + for (const _key of Object.keys(options)) { + const key = /** @type {keyof EntryOptions} */ (_key); + if (options[key] === undefined) continue; + if (entryData.options[key] === options[key]) continue; + if ( + Array.isArray(entryData.options[key]) && + Array.isArray(options[key]) && + arrayEquals(entryData.options[key], options[key]) + ) { + continue; + } + if (entryData.options[key] === undefined) { + /** @type {TODO} */ + (entryData.options)[key] = + /** @type {NonNullable} */ + (options[key]); + } else { + return callback( + new WebpackError( + `Conflicting entry option ${key} = ${entryData.options[key]} vs ${options[key]}` + ) + ); + } + } + } + + this.hooks.addEntry.call(entry, options); + + this.addModuleTree( + { + context, + dependency: entry, + contextInfo: entryData.options.layer + ? { issuerLayer: entryData.options.layer } + : undefined + }, + (err, module) => { + if (err) { + this.hooks.failedEntry.call(entry, options, err); + return callback(err); + } + this.hooks.succeedEntry.call( + entry, + options, + /** @type {Module} */ + (module) + ); + return callback(null, module); + } + ); + } + + /** + * @param {Module} module module to be rebuilt + * @param {ModuleCallback} callback callback when module finishes rebuilding + * @returns {void} + */ + rebuildModule(module, callback) { + this.rebuildQueue.add(module, callback); + } + + /** + * @param {Module} module module to be rebuilt + * @param {ModuleCallback} callback callback when module finishes rebuilding + * @returns {void} + */ + _rebuildModule(module, callback) { + this.hooks.rebuildModule.call(module); + const oldDependencies = [...module.dependencies]; + const oldBlocks = [...module.blocks]; + module.invalidateBuild(); + this.buildQueue.invalidate(module); + this.buildModule(module, (err) => { + if (err) { + return this.hooks.finishRebuildingModule.callAsync(module, (err2) => { + if (err2) { + callback( + makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") + ); + return; + } + callback(err); + }); + } + + this.processDependenciesQueue.invalidate(module); + this.moduleGraph.unfreeze(); + this.processModuleDependencies(module, (err) => { + if (err) return callback(err); + this.removeReasonsOfDependencyBlock(module, { + dependencies: oldDependencies, + blocks: oldBlocks + }); + this.hooks.finishRebuildingModule.callAsync(module, (err2) => { + if (err2) { + callback( + makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") + ); + return; + } + callback(null, module); + }); + }); + }); + } + + /** + * @private + * @param {Set} modules modules + */ + _computeAffectedModules(modules) { + const moduleMemCacheCache = this.compiler.moduleMemCaches; + if (!moduleMemCacheCache) return; + if (!this.moduleMemCaches) { + this.moduleMemCaches = new Map(); + this.moduleGraph.setModuleMemCaches(this.moduleMemCaches); + } + const { moduleGraph, moduleMemCaches } = this; + const affectedModules = new Set(); + const infectedModules = new Set(); + let statNew = 0; + let statChanged = 0; + let statUnchanged = 0; + let statReferencesChanged = 0; + let statWithoutBuild = 0; + + /** + * @param {Module} module module + * @returns {WeakReferences | undefined} references + */ + const computeReferences = (module) => { + /** @type {WeakReferences | undefined} */ + let references; + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const d = connection.dependency; + const m = connection.module; + if (!d || !m || unsafeCacheDependencies.has(d)) continue; + if (references === undefined) references = new WeakMap(); + references.set(d, m); + } + return references; + }; + + /** + * @param {Module} module the module + * @param {WeakReferences | undefined} references references + * @returns {boolean} true, when the references differ + */ + const compareReferences = (module, references) => { + if (references === undefined) return true; + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const d = connection.dependency; + if (!d) continue; + const entry = references.get(d); + if (entry === undefined) continue; + if (entry !== connection.module) return false; + } + return true; + }; + + const modulesWithoutCache = new Set(modules); + for (const [module, cachedMemCache] of moduleMemCacheCache) { + if (modulesWithoutCache.has(module)) { + const buildInfo = module.buildInfo; + if (buildInfo) { + if (cachedMemCache.buildInfo !== buildInfo) { + // use a new one + /** @type {MemCache} */ + const memCache = new WeakTupleMap(); + moduleMemCaches.set(module, memCache); + affectedModules.add(module); + cachedMemCache.buildInfo = buildInfo; + cachedMemCache.references = computeReferences(module); + cachedMemCache.memCache = memCache; + statChanged++; + } else if (!compareReferences(module, cachedMemCache.references)) { + // use a new one + /** @type {MemCache} */ + const memCache = new WeakTupleMap(); + moduleMemCaches.set(module, memCache); + affectedModules.add(module); + cachedMemCache.references = computeReferences(module); + cachedMemCache.memCache = memCache; + statReferencesChanged++; + } else { + // keep the old mem cache + moduleMemCaches.set(module, cachedMemCache.memCache); + statUnchanged++; + } + } else { + infectedModules.add(module); + moduleMemCacheCache.delete(module); + statWithoutBuild++; + } + modulesWithoutCache.delete(module); + } else { + moduleMemCacheCache.delete(module); + } + } + + for (const module of modulesWithoutCache) { + const buildInfo = module.buildInfo; + if (buildInfo) { + // create a new entry + const memCache = new WeakTupleMap(); + moduleMemCacheCache.set(module, { + buildInfo, + references: computeReferences(module), + memCache + }); + moduleMemCaches.set(module, memCache); + affectedModules.add(module); + statNew++; + } else { + infectedModules.add(module); + statWithoutBuild++; + } + } + + /** + * @param {readonly ModuleGraphConnection[]} connections connections + * @returns {symbol|boolean} result + */ + const reduceAffectType = (connections) => { + let affected = false; + for (const { dependency } of connections) { + if (!dependency) continue; + const type = dependency.couldAffectReferencingModule(); + if (type === Dependency.TRANSITIVE) return Dependency.TRANSITIVE; + if (type === false) continue; + affected = true; + } + return affected; + }; + const directOnlyInfectedModules = new Set(); + for (const module of infectedModules) { + for (const [ + referencingModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!referencingModule) continue; + if (infectedModules.has(referencingModule)) continue; + const type = reduceAffectType(connections); + if (!type) continue; + if (type === true) { + directOnlyInfectedModules.add(referencingModule); + } else { + infectedModules.add(referencingModule); + } + } + } + for (const module of directOnlyInfectedModules) infectedModules.add(module); + const directOnlyAffectModules = new Set(); + for (const module of affectedModules) { + for (const [ + referencingModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!referencingModule) continue; + if (infectedModules.has(referencingModule)) continue; + if (affectedModules.has(referencingModule)) continue; + const type = reduceAffectType(connections); + if (!type) continue; + if (type === true) { + directOnlyAffectModules.add(referencingModule); + } else { + affectedModules.add(referencingModule); + } + /** @type {MemCache} */ + const memCache = new WeakTupleMap(); + const cache = + /** @type {ModuleMemCachesItem} */ + (moduleMemCacheCache.get(referencingModule)); + cache.memCache = memCache; + moduleMemCaches.set(referencingModule, memCache); + } + } + for (const module of directOnlyAffectModules) affectedModules.add(module); + this.logger.log( + `${Math.round( + (100 * (affectedModules.size + infectedModules.size)) / + this.modules.size + )}% (${affectedModules.size} affected + ${ + infectedModules.size + } infected of ${ + this.modules.size + }) modules flagged as affected (${statNew} new modules, ${statChanged} changed, ${statReferencesChanged} references changed, ${statUnchanged} unchanged, ${statWithoutBuild} were not built)` + ); + } + + _computeAffectedModulesWithChunkGraph() { + const { moduleMemCaches } = this; + if (!moduleMemCaches) return; + const moduleMemCaches2 = (this.moduleMemCaches2 = new Map()); + const { moduleGraph, chunkGraph } = this; + const key = "memCache2"; + let statUnchanged = 0; + let statChanged = 0; + let statNew = 0; + /** + * @param {Module} module module + * @returns {References} references + */ + const computeReferences = (module) => { + const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module)); + /** @type {Map | undefined} */ + let modules; + /** @type {(string | number | null)[] | undefined} */ + let blocks; + const outgoing = moduleGraph.getOutgoingConnectionsByModule(module); + if (outgoing !== undefined) { + for (const m of outgoing.keys()) { + if (!m) continue; + if (modules === undefined) modules = new Map(); + modules.set(m, /** @type {ModuleId} */ (chunkGraph.getModuleId(m))); + } + } + if (module.blocks.length > 0) { + blocks = []; + const queue = [...module.blocks]; + for (const block of queue) { + const chunkGroup = chunkGraph.getBlockChunkGroup(block); + if (chunkGroup) { + for (const chunk of chunkGroup.chunks) { + blocks.push(chunk.id); + } + } else { + blocks.push(null); + } + // eslint-disable-next-line prefer-spread + queue.push.apply(queue, block.blocks); + } + } + return { id, modules, blocks }; + }; + /** + * @param {Module} module module + * @param {object} references references + * @param {string | number} references.id id + * @param {Map=} references.modules modules + * @param {(string | number | null)[]=} references.blocks blocks + * @returns {boolean} ok? + */ + const compareReferences = (module, { id, modules, blocks }) => { + if (id !== chunkGraph.getModuleId(module)) return false; + if (modules !== undefined) { + for (const [module, id] of modules) { + if (chunkGraph.getModuleId(module) !== id) return false; + } + } + if (blocks !== undefined) { + const queue = [...module.blocks]; + let i = 0; + for (const block of queue) { + const chunkGroup = chunkGraph.getBlockChunkGroup(block); + if (chunkGroup) { + for (const chunk of chunkGroup.chunks) { + if (i >= blocks.length || blocks[i++] !== chunk.id) return false; + } + } else if (i >= blocks.length || blocks[i++] !== null) { + return false; + } + // eslint-disable-next-line prefer-spread + queue.push.apply(queue, block.blocks); + } + if (i !== blocks.length) return false; + } + return true; + }; + + for (const [module, memCache] of moduleMemCaches) { + /** @type {{ references: References, memCache: MemCache } | undefined} */ + const cache = memCache.get(key); + if (cache === undefined) { + /** @type {WeakTupleMap | undefined} */ + const memCache2 = new WeakTupleMap(); + memCache.set(key, { + references: computeReferences(module), + memCache: memCache2 + }); + moduleMemCaches2.set(module, memCache2); + statNew++; + } else if (!compareReferences(module, cache.references)) { + /** @type {WeakTupleMap | undefined} */ + const memCache = new WeakTupleMap(); + cache.references = computeReferences(module); + cache.memCache = memCache; + moduleMemCaches2.set(module, memCache); + statChanged++; + } else { + moduleMemCaches2.set(module, cache.memCache); + statUnchanged++; + } + } + + this.logger.log( + `${Math.round( + (100 * statChanged) / (statNew + statChanged + statUnchanged) + )}% modules flagged as affected by chunk graph (${statNew} new modules, ${statChanged} changed, ${statUnchanged} unchanged)` + ); + } + + /** + * @param {Callback} callback callback + */ + finish(callback) { + this.factorizeQueue.clear(); + if (this.profile) { + this.logger.time("finish module profiles"); + + const ParallelismFactorCalculator = require("./util/ParallelismFactorCalculator"); + + const p = new ParallelismFactorCalculator(); + const moduleGraph = this.moduleGraph; + /** @type {Map} */ + const modulesWithProfiles = new Map(); + for (const module of this.modules) { + const profile = moduleGraph.getProfile(module); + if (!profile) continue; + modulesWithProfiles.set(module, profile); + p.range( + profile.buildingStartTime, + profile.buildingEndTime, + (f) => (profile.buildingParallelismFactor = f) + ); + p.range( + profile.factoryStartTime, + profile.factoryEndTime, + (f) => (profile.factoryParallelismFactor = f) + ); + p.range( + profile.integrationStartTime, + profile.integrationEndTime, + (f) => (profile.integrationParallelismFactor = f) + ); + p.range( + profile.storingStartTime, + profile.storingEndTime, + (f) => (profile.storingParallelismFactor = f) + ); + p.range( + profile.restoringStartTime, + profile.restoringEndTime, + (f) => (profile.restoringParallelismFactor = f) + ); + if (profile.additionalFactoryTimes) { + for (const { start, end } of profile.additionalFactoryTimes) { + const influence = (end - start) / profile.additionalFactories; + p.range( + start, + end, + (f) => + (profile.additionalFactoriesParallelismFactor += f * influence) + ); + } + } + } + p.calculate(); + + const logger = this.getLogger("webpack.Compilation.ModuleProfile"); + // Avoid coverage problems due indirect changes + /** + * @param {number} value value + * @param {string} msg message + */ + /* istanbul ignore next */ + const logByValue = (value, msg) => { + if (value > 1000) { + logger.error(msg); + } else if (value > 500) { + logger.warn(msg); + } else if (value > 200) { + logger.info(msg); + } else if (value > 30) { + logger.log(msg); + } else { + logger.debug(msg); + } + }; + /** + * @param {string} category a category + * @param {(profile: ModuleProfile) => number} getDuration get duration callback + * @param {(profile: ModuleProfile) => number} getParallelism get parallelism callback + */ + const logNormalSummary = (category, getDuration, getParallelism) => { + let sum = 0; + let max = 0; + for (const [module, profile] of modulesWithProfiles) { + const p = getParallelism(profile); + const d = getDuration(profile); + if (d === 0 || p === 0) continue; + const t = d / p; + sum += t; + if (t <= 10) continue; + logByValue( + t, + ` | ${Math.round(t)} ms${ + p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" + } ${category} > ${module.readableIdentifier(this.requestShortener)}` + ); + max = Math.max(max, t); + } + if (sum <= 10) return; + logByValue( + Math.max(sum / 10, max), + `${Math.round(sum)} ms ${category}` + ); + }; + /** + * @param {string} category a category + * @param {(profile: ModuleProfile) => number} getDuration get duration callback + * @param {(profile: ModuleProfile) => number} getParallelism get parallelism callback + */ + const logByLoadersSummary = (category, getDuration, getParallelism) => { + const map = new Map(); + for (const [module, profile] of modulesWithProfiles) { + const list = getOrInsert( + map, + `${module.type}!${module.identifier().replace(/(!|^)[^!]*$/, "")}`, + () => [] + ); + list.push({ module, profile }); + } + + let sum = 0; + let max = 0; + for (const [key, modules] of map) { + let innerSum = 0; + let innerMax = 0; + for (const { module, profile } of modules) { + const p = getParallelism(profile); + const d = getDuration(profile); + if (d === 0 || p === 0) continue; + const t = d / p; + innerSum += t; + if (t <= 10) continue; + logByValue( + t, + ` | | ${Math.round(t)} ms${ + p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" + } ${category} > ${module.readableIdentifier( + this.requestShortener + )}` + ); + innerMax = Math.max(innerMax, t); + } + sum += innerSum; + if (innerSum <= 10) continue; + const idx = key.indexOf("!"); + const loaders = key.slice(idx + 1); + const moduleType = key.slice(0, idx); + const t = Math.max(innerSum / 10, innerMax); + logByValue( + t, + ` | ${Math.round(innerSum)} ms ${category} > ${ + loaders + ? `${ + modules.length + } x ${moduleType} with ${this.requestShortener.shorten( + loaders + )}` + : `${modules.length} x ${moduleType}` + }` + ); + max = Math.max(max, t); + } + if (sum <= 10) return; + logByValue( + Math.max(sum / 10, max), + `${Math.round(sum)} ms ${category}` + ); + }; + logNormalSummary( + "resolve to new modules", + (p) => p.factory, + (p) => p.factoryParallelismFactor + ); + logNormalSummary( + "resolve to existing modules", + (p) => p.additionalFactories, + (p) => p.additionalFactoriesParallelismFactor + ); + logNormalSummary( + "integrate modules", + (p) => p.restoring, + (p) => p.restoringParallelismFactor + ); + logByLoadersSummary( + "build modules", + (p) => p.building, + (p) => p.buildingParallelismFactor + ); + logNormalSummary( + "store modules", + (p) => p.storing, + (p) => p.storingParallelismFactor + ); + logNormalSummary( + "restore modules", + (p) => p.restoring, + (p) => p.restoringParallelismFactor + ); + this.logger.timeEnd("finish module profiles"); + } + this.logger.time("compute affected modules"); + this._computeAffectedModules(this.modules); + this.logger.timeEnd("compute affected modules"); + this.logger.time("finish modules"); + const { modules, moduleMemCaches } = this; + this.hooks.finishModules.callAsync(modules, (err) => { + this.logger.timeEnd("finish modules"); + if (err) return callback(/** @type {WebpackError} */ (err)); + + // extract warnings and errors from modules + this.moduleGraph.freeze("dependency errors"); + // TODO keep a cacheToken (= {}) for each module in the graph + // create a new one per compilation and flag all updated files + // and parents with it + this.logger.time("report dependency errors and warnings"); + for (const module of modules) { + // TODO only run for modules with changed cacheToken + // global WeakMap> to keep modules without errors/warnings + const memCache = moduleMemCaches && moduleMemCaches.get(module); + if (memCache && memCache.get("noWarningsOrErrors")) continue; + let hasProblems = this.reportDependencyErrorsAndWarnings(module, [ + module + ]); + const errors = module.getErrors(); + if (errors !== undefined) { + for (const error of errors) { + if (!error.module) { + error.module = module; + } + this.errors.push(error); + hasProblems = true; + } + } + const warnings = module.getWarnings(); + if (warnings !== undefined) { + for (const warning of warnings) { + if (!warning.module) { + warning.module = module; + } + this.warnings.push(warning); + hasProblems = true; + } + } + if (!hasProblems && memCache) memCache.set("noWarningsOrErrors", true); + } + this.moduleGraph.unfreeze(); + this.logger.timeEnd("report dependency errors and warnings"); + + callback(); + }); + } + + unseal() { + this.hooks.unseal.call(); + this.chunks.clear(); + this.chunkGroups.length = 0; + this.namedChunks.clear(); + this.namedChunkGroups.clear(); + this.entrypoints.clear(); + this.additionalChunkAssets.length = 0; + this.assets = {}; + this.assetsInfo.clear(); + this.moduleGraph.removeAllModuleAttributes(); + this.moduleGraph.unfreeze(); + this.moduleMemCaches2 = undefined; + } + + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + seal(callback) { + /** + * @param {WebpackError=} err err + * @returns {void} + */ + const finalCallback = (err) => { + this.factorizeQueue.clear(); + this.buildQueue.clear(); + this.rebuildQueue.clear(); + this.processDependenciesQueue.clear(); + this.addModuleQueue.clear(); + return callback(err); + }; + const chunkGraph = new ChunkGraph( + this.moduleGraph, + this.outputOptions.hashFunction + ); + this.chunkGraph = chunkGraph; + + if (this._backCompat) { + for (const module of this.modules) { + ChunkGraph.setChunkGraphForModule(module, chunkGraph); + } + } + + this.hooks.seal.call(); + + this.logger.time("optimize dependencies"); + while (this.hooks.optimizeDependencies.call(this.modules)) { + /* empty */ + } + this.hooks.afterOptimizeDependencies.call(this.modules); + this.logger.timeEnd("optimize dependencies"); + + this.logger.time("create chunks"); + this.hooks.beforeChunks.call(); + this.moduleGraph.freeze("seal"); + /** @type {Map} */ + const chunkGraphInit = new Map(); + for (const [name, { dependencies, includeDependencies, options }] of this + .entries) { + const chunk = this.addChunk(name); + if (options.filename) { + chunk.filenameTemplate = options.filename; + } + const entrypoint = new Entrypoint(options); + if (!options.dependOn && !options.runtime) { + entrypoint.setRuntimeChunk(chunk); + } + entrypoint.setEntrypointChunk(chunk); + this.namedChunkGroups.set(name, entrypoint); + this.entrypoints.set(name, entrypoint); + this.chunkGroups.push(entrypoint); + connectChunkGroupAndChunk(entrypoint, chunk); + + const entryModules = new Set(); + for (const dep of [...this.globalEntry.dependencies, ...dependencies]) { + entrypoint.addOrigin( + null, + { name }, + /** @type {Dependency & { request: string }} */ + (dep).request + ); + + const module = this.moduleGraph.getModule(dep); + if (module) { + chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); + entryModules.add(module); + const modulesList = chunkGraphInit.get(entrypoint); + if (modulesList === undefined) { + chunkGraphInit.set(entrypoint, [module]); + } else { + modulesList.push(module); + } + } + } + + this.assignDepths(entryModules); + + /** + * @param {Dependency[]} deps deps + * @returns {Module[]} sorted deps + */ + const mapAndSort = (deps) => + /** @type {Module[]} */ + ( + deps.map((dep) => this.moduleGraph.getModule(dep)).filter(Boolean) + ).sort(compareModulesByIdentifier); + const includedModules = [ + ...mapAndSort(this.globalEntry.includeDependencies), + ...mapAndSort(includeDependencies) + ]; + + let modulesList = chunkGraphInit.get(entrypoint); + if (modulesList === undefined) { + chunkGraphInit.set(entrypoint, (modulesList = [])); + } + for (const module of includedModules) { + this.assignDepth(module); + modulesList.push(module); + } + } + const runtimeChunks = new Set(); + outer: for (const [ + name, + { + options: { dependOn, runtime } + } + ] of this.entries) { + if (dependOn && runtime) { + const err = + new WebpackError(`Entrypoint '${name}' has 'dependOn' and 'runtime' specified. This is not valid. +Entrypoints that depend on other entrypoints do not have their own runtime. +They will use the runtime(s) from referenced entrypoints instead. +Remove the 'runtime' option from the entrypoint.`); + const entry = /** @type {Entrypoint} */ (this.entrypoints.get(name)); + err.chunk = entry.getEntrypointChunk(); + this.errors.push(err); + } + if (dependOn) { + const entry = /** @type {Entrypoint} */ (this.entrypoints.get(name)); + const referencedChunks = entry + .getEntrypointChunk() + .getAllReferencedChunks(); + for (const dep of dependOn) { + const dependency = this.entrypoints.get(dep); + if (!dependency) { + throw new Error( + `Entry ${name} depends on ${dep}, but this entry was not found` + ); + } + if (referencedChunks.has(dependency.getEntrypointChunk())) { + const err = new WebpackError( + `Entrypoints '${name}' and '${dep}' use 'dependOn' to depend on each other in a circular way.` + ); + const entryChunk = entry.getEntrypointChunk(); + err.chunk = entryChunk; + this.errors.push(err); + entry.setRuntimeChunk(entryChunk); + continue outer; + } + connectEntrypointAndDependOn(entry, dependency); + connectChunkGroupParentAndChild(dependency, entry); + } + } else if (runtime) { + const entry = /** @type {Entrypoint} */ (this.entrypoints.get(name)); + let chunk = this.namedChunks.get(runtime); + if (chunk) { + if (!runtimeChunks.has(chunk)) { + const err = + new WebpackError(`Entrypoint '${name}' has a 'runtime' option which points to another entrypoint named '${runtime}'. +It's not valid to use other entrypoints as runtime chunk. +Did you mean to use 'dependOn: ${JSON.stringify( + runtime + )}' instead to allow using entrypoint '${name}' within the runtime of entrypoint '${runtime}'? For this '${runtime}' must always be loaded when '${name}' is used. +Or do you want to use the entrypoints '${name}' and '${runtime}' independently on the same page with a shared runtime? In this case give them both the same value for the 'runtime' option. It must be a name not already used by an entrypoint.`); + const entryChunk = + /** @type {Chunk} */ + (entry.getEntrypointChunk()); + err.chunk = entryChunk; + this.errors.push(err); + entry.setRuntimeChunk(entryChunk); + continue; + } + } else { + chunk = this.addChunk(runtime); + chunk.preventIntegration = true; + runtimeChunks.add(chunk); + } + entry.unshiftChunk(chunk); + chunk.addGroup(entry); + entry.setRuntimeChunk(chunk); + } + } + + buildChunkGraph(this, chunkGraphInit); + this.hooks.afterChunks.call(this.chunks); + this.logger.timeEnd("create chunks"); + + this.logger.time("optimize"); + this.hooks.optimize.call(); + + while (this.hooks.optimizeModules.call(this.modules)) { + /* empty */ + } + this.hooks.afterOptimizeModules.call(this.modules); + + while (this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups)) { + /* empty */ + } + this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); + + this.hooks.optimizeTree.callAsync(this.chunks, this.modules, (err) => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.optimizeTree") + ); + } + + this.hooks.afterOptimizeTree.call(this.chunks, this.modules); + + this.hooks.optimizeChunkModules.callAsync( + this.chunks, + this.modules, + (err) => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.optimizeChunkModules") + ); + } + + this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); + + const shouldRecord = this.hooks.shouldRecord.call() !== false; + + this.hooks.reviveModules.call( + this.modules, + /** @type {Records} */ + (this.records) + ); + this.hooks.beforeModuleIds.call(this.modules); + this.hooks.moduleIds.call(this.modules); + this.hooks.optimizeModuleIds.call(this.modules); + this.hooks.afterOptimizeModuleIds.call(this.modules); + + this.hooks.reviveChunks.call( + this.chunks, + /** @type {Records} */ + (this.records) + ); + this.hooks.beforeChunkIds.call(this.chunks); + this.hooks.chunkIds.call(this.chunks); + this.hooks.optimizeChunkIds.call(this.chunks); + this.hooks.afterOptimizeChunkIds.call(this.chunks); + + this.assignRuntimeIds(); + + this.logger.time("compute affected modules with chunk graph"); + this._computeAffectedModulesWithChunkGraph(); + this.logger.timeEnd("compute affected modules with chunk graph"); + + this.sortItemsWithChunkIds(); + + if (shouldRecord) { + this.hooks.recordModules.call( + this.modules, + /** @type {Records} */ + (this.records) + ); + this.hooks.recordChunks.call( + this.chunks, + /** @type {Records} */ + (this.records) + ); + } + + this.hooks.optimizeCodeGeneration.call(this.modules); + this.logger.timeEnd("optimize"); + + this.logger.time("module hashing"); + this.hooks.beforeModuleHash.call(); + this.createModuleHashes(); + this.hooks.afterModuleHash.call(); + this.logger.timeEnd("module hashing"); + + this.logger.time("code generation"); + this.hooks.beforeCodeGeneration.call(); + this.codeGeneration((err) => { + if (err) { + return finalCallback(err); + } + this.hooks.afterCodeGeneration.call(); + this.logger.timeEnd("code generation"); + + this.logger.time("runtime requirements"); + this.hooks.beforeRuntimeRequirements.call(); + this.processRuntimeRequirements(); + this.hooks.afterRuntimeRequirements.call(); + this.logger.timeEnd("runtime requirements"); + + this.logger.time("hashing"); + this.hooks.beforeHash.call(); + const codeGenerationJobs = this.createHash(); + this.hooks.afterHash.call(); + this.logger.timeEnd("hashing"); + + this._runCodeGenerationJobs(codeGenerationJobs, (err) => { + if (err) { + return finalCallback(err); + } + + if (shouldRecord) { + this.logger.time("record hash"); + this.hooks.recordHash.call( + /** @type {Records} */ + (this.records) + ); + this.logger.timeEnd("record hash"); + } + + this.logger.time("module assets"); + this.clearAssets(); + + this.hooks.beforeModuleAssets.call(); + this.createModuleAssets(); + this.logger.timeEnd("module assets"); + + const cont = () => { + this.logger.time("process assets"); + this.hooks.processAssets.callAsync(this.assets, (err) => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.processAssets") + ); + } + this.hooks.afterProcessAssets.call(this.assets); + this.logger.timeEnd("process assets"); + this.assets = + /** @type {CompilationAssets} */ + ( + this._backCompat + ? soonFrozenObjectDeprecation( + this.assets, + "Compilation.assets", + "DEP_WEBPACK_COMPILATION_ASSETS", + `BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation. + Do changes to assets earlier, e. g. in Compilation.hooks.processAssets. + Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.` + ) + : Object.freeze(this.assets) + ); + + this.summarizeDependencies(); + if (shouldRecord) { + this.hooks.record.call( + this, + /** @type {Records} */ + (this.records) + ); + } + + if (this.hooks.needAdditionalSeal.call()) { + this.unseal(); + return this.seal(callback); + } + return this.hooks.afterSeal.callAsync((err) => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.afterSeal") + ); + } + this.fileSystemInfo.logStatistics(); + finalCallback(); + }); + }); + }; + + this.logger.time("create chunk assets"); + if (this.hooks.shouldGenerateChunkAssets.call() !== false) { + this.hooks.beforeChunkAssets.call(); + this.createChunkAssets((err) => { + this.logger.timeEnd("create chunk assets"); + if (err) { + return finalCallback(err); + } + cont(); + }); + } else { + this.logger.timeEnd("create chunk assets"); + cont(); + } + }); + }); + } + ); + }); + } + + /** + * @param {Module} module module to report from + * @param {DependenciesBlock[]} blocks blocks to report from + * @returns {boolean} true, when it has warnings or errors + */ + reportDependencyErrorsAndWarnings(module, blocks) { + let hasProblems = false; + for (const block of blocks) { + const dependencies = block.dependencies; + + for (const d of dependencies) { + const warnings = d.getWarnings(this.moduleGraph); + if (warnings) { + for (const w of warnings) { + const warning = new ModuleDependencyWarning(module, w, d.loc); + this.warnings.push(warning); + hasProblems = true; + } + } + const errors = d.getErrors(this.moduleGraph); + if (errors) { + for (const e of errors) { + const error = new ModuleDependencyError(module, e, d.loc); + this.errors.push(error); + hasProblems = true; + } + } + } + + if (this.reportDependencyErrorsAndWarnings(module, block.blocks)) { + hasProblems = true; + } + } + return hasProblems; + } + + /** + * @param {Callback} callback callback + */ + codeGeneration(callback) { + const { chunkGraph } = this; + this.codeGenerationResults = new CodeGenerationResults( + this.outputOptions.hashFunction + ); + /** @type {CodeGenerationJobs} */ + const jobs = []; + for (const module of this.modules) { + const runtimes = chunkGraph.getModuleRuntimes(module); + if (runtimes.size === 1) { + for (const runtime of runtimes) { + const hash = chunkGraph.getModuleHash(module, runtime); + jobs.push({ module, hash, runtime, runtimes: [runtime] }); + } + } else if (runtimes.size > 1) { + /** @type {Map} */ + const map = new Map(); + for (const runtime of runtimes) { + const hash = chunkGraph.getModuleHash(module, runtime); + const job = map.get(hash); + if (job === undefined) { + const newJob = { module, hash, runtime, runtimes: [runtime] }; + jobs.push(newJob); + map.set(hash, newJob); + } else { + job.runtimes.push(runtime); + } + } + } + } + + this._runCodeGenerationJobs(jobs, callback); + } + + /** + * @private + * @param {CodeGenerationJobs} jobs code generation jobs + * @param {Callback} callback callback + * @returns {void} + */ + _runCodeGenerationJobs(jobs, callback) { + if (jobs.length === 0) { + return callback(); + } + let statModulesFromCache = 0; + let statModulesGenerated = 0; + const { chunkGraph, moduleGraph, dependencyTemplates, runtimeTemplate } = + this; + const results = this.codeGenerationResults; + /** @type {WebpackError[]} */ + const errors = []; + /** @type {NotCodeGeneratedModules | undefined} */ + let notCodeGeneratedModules; + const runIteration = () => { + /** @type {CodeGenerationJobs} */ + let delayedJobs = []; + let delayedModules = new Set(); + asyncLib.eachLimit( + jobs, + /** @type {number} */ + (this.options.parallelism), + (job, callback) => { + const { module } = job; + const { codeGenerationDependencies } = module; + if ( + codeGenerationDependencies !== undefined && + (notCodeGeneratedModules === undefined || + codeGenerationDependencies.some((dep) => { + const referencedModule = /** @type {Module} */ ( + moduleGraph.getModule(dep) + ); + return /** @type {NotCodeGeneratedModules} */ ( + notCodeGeneratedModules + ).has(referencedModule); + })) + ) { + delayedJobs.push(job); + delayedModules.add(module); + return callback(); + } + const { hash, runtime, runtimes } = job; + this._codeGenerationModule( + module, + runtime, + runtimes, + hash, + dependencyTemplates, + chunkGraph, + moduleGraph, + runtimeTemplate, + errors, + results, + (err, codeGenerated) => { + if (codeGenerated) statModulesGenerated++; + else statModulesFromCache++; + callback(err); + } + ); + }, + (err) => { + if (err) return callback(err); + if (delayedJobs.length > 0) { + if (delayedJobs.length === jobs.length) { + return callback( + /** @type {WebpackError} */ ( + new Error( + `Unable to make progress during code generation because of circular code generation dependency: ${Array.from( + delayedModules, + (m) => m.identifier() + ).join(", ")}` + ) + ) + ); + } + jobs = delayedJobs; + delayedJobs = []; + notCodeGeneratedModules = delayedModules; + delayedModules = new Set(); + return runIteration(); + } + if (errors.length > 0) { + errors.sort( + compareSelect((err) => err.module, compareModulesByIdentifier) + ); + for (const error of errors) { + this.errors.push(error); + } + } + this.logger.log( + `${Math.round( + (100 * statModulesGenerated) / + (statModulesGenerated + statModulesFromCache) + )}% code generated (${statModulesGenerated} generated, ${statModulesFromCache} from cache)` + ); + callback(); + } + ); + }; + runIteration(); + } + + /** + * @param {Module} module module + * @param {RuntimeSpec} runtime runtime + * @param {RuntimeSpec[]} runtimes runtimes + * @param {string} hash hash + * @param {DependencyTemplates} dependencyTemplates dependencyTemplates + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate + * @param {WebpackError[]} errors errors + * @param {CodeGenerationResults} results results + * @param {(err?: WebpackError | null, result?: boolean) => void} callback callback + */ + _codeGenerationModule( + module, + runtime, + runtimes, + hash, + dependencyTemplates, + chunkGraph, + moduleGraph, + runtimeTemplate, + errors, + results, + callback + ) { + let codeGenerated = false; + const cache = new MultiItemCache( + runtimes.map((runtime) => + this._codeGenerationCache.getItemCache( + `${module.identifier()}|${getRuntimeKey(runtime)}`, + `${hash}|${dependencyTemplates.getHash()}` + ) + ) + ); + cache.get((err, cachedResult) => { + if (err) return callback(/** @type {WebpackError} */ (err)); + let result; + if (!cachedResult) { + try { + codeGenerated = true; + this.codeGeneratedModules.add(module); + result = module.codeGeneration({ + chunkGraph, + moduleGraph, + dependencyTemplates, + runtimeTemplate, + runtime, + codeGenerationResults: results, + compilation: this + }); + } catch (err) { + errors.push( + new CodeGenerationError(module, /** @type {Error} */ (err)) + ); + result = cachedResult = { + sources: new Map(), + runtimeRequirements: null + }; + } + } else { + result = cachedResult; + } + for (const runtime of runtimes) { + results.add(module, runtime, result); + } + if (!cachedResult) { + cache.store(result, (err) => + callback(/** @type {WebpackError} */ (err), codeGenerated) + ); + } else { + callback(null, codeGenerated); + } + }); + } + + _getChunkGraphEntries() { + /** @type {Set} */ + const treeEntries = new Set(); + for (const ep of this.entrypoints.values()) { + const chunk = ep.getRuntimeChunk(); + if (chunk) treeEntries.add(chunk); + } + for (const ep of this.asyncEntrypoints) { + const chunk = ep.getRuntimeChunk(); + if (chunk) treeEntries.add(chunk); + } + return treeEntries; + } + + /** + * @param {object} options options + * @param {ChunkGraph=} options.chunkGraph the chunk graph + * @param {Iterable=} options.modules modules + * @param {Iterable=} options.chunks chunks + * @param {CodeGenerationResults=} options.codeGenerationResults codeGenerationResults + * @param {Iterable=} options.chunkGraphEntries chunkGraphEntries + * @returns {void} + */ + processRuntimeRequirements({ + chunkGraph = this.chunkGraph, + modules = this.modules, + chunks = this.chunks, + codeGenerationResults = this.codeGenerationResults, + chunkGraphEntries = this._getChunkGraphEntries() + } = {}) { + const context = { chunkGraph, codeGenerationResults }; + const { moduleMemCaches2 } = this; + this.logger.time("runtime requirements.modules"); + const additionalModuleRuntimeRequirements = + this.hooks.additionalModuleRuntimeRequirements; + const runtimeRequirementInModule = this.hooks.runtimeRequirementInModule; + for (const module of modules) { + if (chunkGraph.getNumberOfModuleChunks(module) > 0) { + const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); + for (const runtime of chunkGraph.getModuleRuntimes(module)) { + if (memCache) { + const cached = memCache.get( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}` + ); + if (cached !== undefined) { + if (cached !== null) { + chunkGraph.addModuleRuntimeRequirements( + module, + runtime, + /** @type {RuntimeRequirements} */ + (cached), + false + ); + } + continue; + } + } + let set; + const runtimeRequirements = + codeGenerationResults.getRuntimeRequirements(module, runtime); + if (runtimeRequirements && runtimeRequirements.size > 0) { + set = new Set(runtimeRequirements); + } else if (additionalModuleRuntimeRequirements.isUsed()) { + set = new Set(); + } else { + if (memCache) { + memCache.set( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, + null + ); + } + continue; + } + additionalModuleRuntimeRequirements.call(module, set, context); + + for (const r of set) { + const hook = runtimeRequirementInModule.get(r); + if (hook !== undefined) hook.call(module, set, context); + } + if (set.size === 0) { + if (memCache) { + memCache.set( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, + null + ); + } + } else if (memCache) { + memCache.set( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, + set + ); + chunkGraph.addModuleRuntimeRequirements( + module, + runtime, + set, + false + ); + } else { + chunkGraph.addModuleRuntimeRequirements(module, runtime, set); + } + } + } + } + this.logger.timeEnd("runtime requirements.modules"); + + this.logger.time("runtime requirements.chunks"); + for (const chunk of chunks) { + const set = new Set(); + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( + module, + chunk.runtime + ); + for (const r of runtimeRequirements) set.add(r); + } + this.hooks.additionalChunkRuntimeRequirements.call(chunk, set, context); + + for (const r of set) { + this.hooks.runtimeRequirementInChunk.for(r).call(chunk, set, context); + } + + chunkGraph.addChunkRuntimeRequirements(chunk, set); + } + this.logger.timeEnd("runtime requirements.chunks"); + + this.logger.time("runtime requirements.entries"); + for (const treeEntry of chunkGraphEntries) { + const set = new Set(); + for (const chunk of treeEntry.getAllReferencedChunks()) { + const runtimeRequirements = + chunkGraph.getChunkRuntimeRequirements(chunk); + for (const r of runtimeRequirements) set.add(r); + } + + this.hooks.additionalTreeRuntimeRequirements.call( + treeEntry, + set, + context + ); + + for (const r of set) { + this.hooks.runtimeRequirementInTree + .for(r) + .call(treeEntry, set, context); + } + + chunkGraph.addTreeRuntimeRequirements(treeEntry, set); + } + this.logger.timeEnd("runtime requirements.entries"); + } + + // TODO webpack 6 make chunkGraph argument non-optional + /** + * @param {Chunk} chunk target chunk + * @param {RuntimeModule} module runtime module + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + addRuntimeModule(chunk, module, chunkGraph = this.chunkGraph) { + // Deprecated ModuleGraph association + if (this._backCompat) { + ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); + } + + // add it to the list + this.modules.add(module); + this._modules.set(module.identifier(), module); + + // connect to the chunk graph + chunkGraph.connectChunkAndModule(chunk, module); + chunkGraph.connectChunkAndRuntimeModule(chunk, module); + if (module.fullHash) { + chunkGraph.addFullHashModuleToChunk(chunk, module); + } else if (module.dependentHash) { + chunkGraph.addDependentHashModuleToChunk(chunk, module); + } + + // attach runtime module + module.attach(this, chunk, chunkGraph); + + // Setup internals + const exportsInfo = this.moduleGraph.getExportsInfo(module); + exportsInfo.setHasProvideInfo(); + if (typeof chunk.runtime === "string") { + exportsInfo.setUsedForSideEffectsOnly(chunk.runtime); + } else if (chunk.runtime === undefined) { + exportsInfo.setUsedForSideEffectsOnly(undefined); + } else { + for (const runtime of chunk.runtime) { + exportsInfo.setUsedForSideEffectsOnly(runtime); + } + } + chunkGraph.addModuleRuntimeRequirements( + module, + chunk.runtime, + new Set([RuntimeGlobals.requireScope]) + ); + + // runtime modules don't need ids + chunkGraph.setModuleId(module, ""); + + // Call hook + this.hooks.runtimeModule.call(module, chunk); + } + + /** + * If `module` is passed, `loc` and `request` must also be passed. + * @param {string | ChunkGroupOptions} groupOptions options for the chunk group + * @param {Module=} module the module the references the chunk group + * @param {DependencyLocation=} loc the location from with the chunk group is referenced (inside of module) + * @param {string=} request the request from which the the chunk group is referenced + * @returns {ChunkGroup} the new or existing chunk group + */ + addChunkInGroup(groupOptions, module, loc, request) { + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } + const name = groupOptions.name; + if (name) { + const chunkGroup = this.namedChunkGroups.get(name); + if (chunkGroup !== undefined) { + if (module) { + chunkGroup.addOrigin( + module, + /** @type {DependencyLocation} */ + (loc), + /** @type {string} */ + (request) + ); + } + return chunkGroup; + } + } + const chunkGroup = new ChunkGroup(groupOptions); + if (module) { + chunkGroup.addOrigin( + module, + /** @type {DependencyLocation} */ + (loc), + /** @type {string} */ + (request) + ); + } + const chunk = this.addChunk(name); + + connectChunkGroupAndChunk(chunkGroup, chunk); + + this.chunkGroups.push(chunkGroup); + if (name) { + this.namedChunkGroups.set(name, chunkGroup); + } + return chunkGroup; + } + + /** + * @param {EntryOptions} options options for the entrypoint + * @param {Module} module the module the references the chunk group + * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) + * @param {string} request the request from which the the chunk group is referenced + * @returns {Entrypoint} the new or existing entrypoint + */ + addAsyncEntrypoint(options, module, loc, request) { + const name = options.name; + if (name) { + const entrypoint = this.namedChunkGroups.get(name); + if (entrypoint instanceof Entrypoint) { + if (entrypoint !== undefined) { + if (module) { + entrypoint.addOrigin(module, loc, request); + } + return entrypoint; + } + } else if (entrypoint) { + throw new Error( + `Cannot add an async entrypoint with the name '${name}', because there is already an chunk group with this name` + ); + } + } + const chunk = this.addChunk(name); + if (options.filename) { + chunk.filenameTemplate = options.filename; + } + const entrypoint = new Entrypoint(options, false); + entrypoint.setRuntimeChunk(chunk); + entrypoint.setEntrypointChunk(chunk); + if (name) { + this.namedChunkGroups.set(name, entrypoint); + } + this.chunkGroups.push(entrypoint); + this.asyncEntrypoints.push(entrypoint); + connectChunkGroupAndChunk(entrypoint, chunk); + if (module) { + entrypoint.addOrigin(module, loc, request); + } + return entrypoint; + } + + /** + * This method first looks to see if a name is provided for a new chunk, + * and first looks to see if any named chunks already exist and reuse that chunk instead. + * @param {ChunkName=} name optional chunk name to be provided + * @returns {Chunk} create a chunk (invoked during seal event) + */ + addChunk(name) { + if (name) { + const chunk = this.namedChunks.get(name); + if (chunk !== undefined) { + return chunk; + } + } + const chunk = new Chunk(name, this._backCompat); + this.chunks.add(chunk); + if (this._backCompat) { + ChunkGraph.setChunkGraphForChunk(chunk, this.chunkGraph); + } + if (name) { + this.namedChunks.set(name, chunk); + } + return chunk; + } + + /** + * @deprecated + * @param {Module} module module to assign depth + * @returns {void} + */ + assignDepth(module) { + const moduleGraph = this.moduleGraph; + + const queue = new Set([module]); + /** @type {number} */ + let depth; + + moduleGraph.setDepth(module, 0); + + /** + * @param {Module} module module for processing + * @returns {void} + */ + const processModule = (module) => { + if (!moduleGraph.setDepthIfLower(module, depth)) return; + queue.add(module); + }; + + for (module of queue) { + queue.delete(module); + depth = /** @type {number} */ (moduleGraph.getDepth(module)) + 1; + + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const refModule = connection.module; + if (refModule) { + processModule(refModule); + } + } + } + } + + /** + * @param {Set} modules module to assign depth + * @returns {void} + */ + assignDepths(modules) { + const moduleGraph = this.moduleGraph; + + /** @type {Set} */ + const queue = new Set(modules); + // Track these in local variables so that queue only has one data type + let nextDepthAt = queue.size; + let depth = 0; + + let i = 0; + for (const module of queue) { + moduleGraph.setDepth(module, depth); + // Some of these results come from cache, which speeds this up + const connections = moduleGraph.getOutgoingConnectionsByModule(module); + // connections will be undefined if there are no outgoing connections + if (connections) { + for (const refModule of connections.keys()) { + if (refModule) queue.add(refModule); + } + } + i++; + // Since this is a breadth-first search, all modules added to the queue + // while at depth N will be depth N+1 + if (i >= nextDepthAt) { + depth++; + nextDepthAt = queue.size; + } + } + } + + /** + * @param {Dependency} dependency the dependency + * @param {RuntimeSpec} runtime the runtime + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getDependencyReferencedExports(dependency, runtime) { + const referencedExports = dependency.getReferencedExports( + this.moduleGraph, + runtime + ); + return this.hooks.dependencyReferencedExports.call( + referencedExports, + dependency, + runtime + ); + } + + /** + * @param {Module} module module relationship for removal + * @param {DependenciesBlockLike} block dependencies block + * @returns {void} + */ + removeReasonsOfDependencyBlock(module, block) { + if (block.blocks) { + for (const b of block.blocks) { + this.removeReasonsOfDependencyBlock(module, b); + } + } + + if (block.dependencies) { + for (const dep of block.dependencies) { + const originalModule = this.moduleGraph.getModule(dep); + if (originalModule) { + this.moduleGraph.removeConnection(dep); + + if (this.chunkGraph) { + for (const chunk of this.chunkGraph.getModuleChunks( + originalModule + )) { + this.patchChunksAfterReasonRemoval(originalModule, chunk); + } + } + } + } + } + } + + /** + * @param {Module} module module to patch tie + * @param {Chunk} chunk chunk to patch tie + * @returns {void} + */ + patchChunksAfterReasonRemoval(module, chunk) { + if (!module.hasReasons(this.moduleGraph, chunk.runtime)) { + this.removeReasonsOfDependencyBlock(module, module); + } + if ( + !module.hasReasonForChunk(chunk, this.moduleGraph, this.chunkGraph) && + this.chunkGraph.isModuleInChunk(module, chunk) + ) { + this.chunkGraph.disconnectChunkAndModule(chunk, module); + this.removeChunkFromDependencies(module, chunk); + } + } + + /** + * @param {DependenciesBlock} block block tie for Chunk + * @param {Chunk} chunk chunk to remove from dep + * @returns {void} + */ + removeChunkFromDependencies(block, chunk) { + /** + * @param {Dependency} d dependency to (maybe) patch up + */ + const iteratorDependency = (d) => { + const depModule = this.moduleGraph.getModule(d); + if (!depModule) { + return; + } + this.patchChunksAfterReasonRemoval(depModule, chunk); + }; + + const blocks = block.blocks; + for (const asyncBlock of blocks) { + const chunkGroup = + /** @type {ChunkGroup} */ + (this.chunkGraph.getBlockChunkGroup(asyncBlock)); + // Grab all chunks from the first Block's AsyncDepBlock + const chunks = chunkGroup.chunks; + // For each chunk in chunkGroup + for (const iteratedChunk of chunks) { + chunkGroup.removeChunk(iteratedChunk); + // Recurse + this.removeChunkFromDependencies(block, iteratedChunk); + } + } + + if (block.dependencies) { + for (const dep of block.dependencies) iteratorDependency(dep); + } + } + + assignRuntimeIds() { + const { chunkGraph } = this; + /** + * @param {Entrypoint} ep an entrypoint + */ + const processEntrypoint = (ep) => { + const runtime = /** @type {string} */ (ep.options.runtime || ep.name); + const chunk = /** @type {Chunk} */ (ep.getRuntimeChunk()); + chunkGraph.setRuntimeId(runtime, /** @type {ChunkId} */ (chunk.id)); + }; + for (const ep of this.entrypoints.values()) { + processEntrypoint(ep); + } + for (const ep of this.asyncEntrypoints) { + processEntrypoint(ep); + } + } + + sortItemsWithChunkIds() { + for (const chunkGroup of this.chunkGroups) { + chunkGroup.sortItems(); + } + + this.errors.sort(compareErrors); + this.warnings.sort(compareErrors); + this.children.sort(byNameOrHash); + } + + summarizeDependencies() { + for (const child of this.children) { + this.fileDependencies.addAll(child.fileDependencies); + this.contextDependencies.addAll(child.contextDependencies); + this.missingDependencies.addAll(child.missingDependencies); + this.buildDependencies.addAll(child.buildDependencies); + } + + for (const module of this.modules) { + module.addCacheDependencies( + this.fileDependencies, + this.contextDependencies, + this.missingDependencies, + this.buildDependencies + ); + } + } + + createModuleHashes() { + let statModulesHashed = 0; + let statModulesFromCache = 0; + const { chunkGraph, runtimeTemplate, moduleMemCaches2 } = this; + const { hashFunction, hashDigest, hashDigestLength } = this.outputOptions; + /** @type {WebpackError[]} */ + const errors = []; + for (const module of this.modules) { + const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); + for (const runtime of chunkGraph.getModuleRuntimes(module)) { + if (memCache) { + const digest = + /** @type {string} */ + (memCache.get(`moduleHash-${getRuntimeKey(runtime)}`)); + if (digest !== undefined) { + chunkGraph.setModuleHashes( + module, + runtime, + digest, + digest.slice(0, hashDigestLength) + ); + statModulesFromCache++; + continue; + } + } + statModulesHashed++; + const digest = this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength, + errors + ); + if (memCache) { + memCache.set(`moduleHash-${getRuntimeKey(runtime)}`, digest); + } + } + } + if (errors.length > 0) { + errors.sort( + compareSelect((err) => err.module, compareModulesByIdentifier) + ); + for (const error of errors) { + this.errors.push(error); + } + } + this.logger.log( + `${statModulesHashed} modules hashed, ${statModulesFromCache} from cache (${ + Math.round( + (100 * (statModulesHashed + statModulesFromCache)) / this.modules.size + ) / 100 + } variants per module in average)` + ); + } + + /** + * @private + * @param {Module} module module + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {RuntimeSpec} runtime runtime + * @param {OutputOptions["hashFunction"]} hashFunction hash function + * @param {RuntimeTemplate} runtimeTemplate runtime template + * @param {OutputOptions["hashDigest"]} hashDigest hash digest + * @param {OutputOptions["hashDigestLength"]} hashDigestLength hash digest length + * @param {WebpackError[]} errors errors + * @returns {string} module hash digest + */ + _createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength, + errors + ) { + let moduleHashDigest; + try { + const moduleHash = createHash(/** @type {HashFunction} */ (hashFunction)); + module.updateHash(moduleHash, { + chunkGraph, + runtime, + runtimeTemplate + }); + moduleHashDigest = /** @type {string} */ (moduleHash.digest(hashDigest)); + } catch (err) { + errors.push(new ModuleHashingError(module, /** @type {Error} */ (err))); + moduleHashDigest = "XXXXXX"; + } + chunkGraph.setModuleHashes( + module, + runtime, + moduleHashDigest, + moduleHashDigest.slice(0, hashDigestLength) + ); + return moduleHashDigest; + } + + createHash() { + this.logger.time("hashing: initialize hash"); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const runtimeTemplate = this.runtimeTemplate; + const outputOptions = this.outputOptions; + const hashFunction = outputOptions.hashFunction; + const hashDigest = outputOptions.hashDigest; + const hashDigestLength = outputOptions.hashDigestLength; + const hash = createHash(/** @type {HashFunction} */ (hashFunction)); + if (outputOptions.hashSalt) { + hash.update(outputOptions.hashSalt); + } + this.logger.timeEnd("hashing: initialize hash"); + if (this.children.length > 0) { + this.logger.time("hashing: hash child compilations"); + for (const child of this.children) { + hash.update(/** @type {string} */ (child.hash)); + } + this.logger.timeEnd("hashing: hash child compilations"); + } + if (this.warnings.length > 0) { + this.logger.time("hashing: hash warnings"); + for (const warning of this.warnings) { + hash.update(`${warning.message}`); + } + this.logger.timeEnd("hashing: hash warnings"); + } + if (this.errors.length > 0) { + this.logger.time("hashing: hash errors"); + for (const error of this.errors) { + hash.update(`${error.message}`); + } + this.logger.timeEnd("hashing: hash errors"); + } + + this.logger.time("hashing: sort chunks"); + /* + * all non-runtime chunks need to be hashes first, + * since runtime chunk might use their hashes. + * runtime chunks need to be hashed in the correct order + * since they may depend on each other (for async entrypoints). + * So we put all non-runtime chunks first and hash them in any order. + * And order runtime chunks according to referenced between each other. + * Chunks need to be in deterministic order since we add hashes to full chunk + * during these hashing. + */ + /** @type {Chunk[]} */ + const unorderedRuntimeChunks = []; + /** @type {Chunk[]} */ + const initialChunks = []; + /** @type {Chunk[]} */ + const asyncChunks = []; + for (const c of this.chunks) { + if (c.hasRuntime()) { + unorderedRuntimeChunks.push(c); + } else if (c.canBeInitial()) { + initialChunks.push(c); + } else { + asyncChunks.push(c); + } + } + unorderedRuntimeChunks.sort(byId); + initialChunks.sort(byId); + asyncChunks.sort(byId); + + /** @typedef {{ chunk: Chunk, referencedBy: RuntimeChunkInfo[], remaining: number }} RuntimeChunkInfo */ + /** @type {Map} */ + const runtimeChunksMap = new Map(); + for (const chunk of unorderedRuntimeChunks) { + runtimeChunksMap.set(chunk, { + chunk, + referencedBy: [], + remaining: 0 + }); + } + let remaining = 0; + for (const info of runtimeChunksMap.values()) { + for (const other of new Set( + [...info.chunk.getAllReferencedAsyncEntrypoints()].map( + (e) => e.chunks[e.chunks.length - 1] + ) + )) { + const otherInfo = + /** @type {RuntimeChunkInfo} */ + (runtimeChunksMap.get(other)); + otherInfo.referencedBy.push(info); + info.remaining++; + remaining++; + } + } + /** @type {Chunk[]} */ + const runtimeChunks = []; + for (const info of runtimeChunksMap.values()) { + if (info.remaining === 0) { + runtimeChunks.push(info.chunk); + } + } + // If there are any references between chunks + // make sure to follow these chains + if (remaining > 0) { + const readyChunks = []; + for (const chunk of runtimeChunks) { + const hasFullHashModules = + chunkGraph.getNumberOfChunkFullHashModules(chunk) !== 0; + const info = + /** @type {RuntimeChunkInfo} */ + (runtimeChunksMap.get(chunk)); + for (const otherInfo of info.referencedBy) { + if (hasFullHashModules) { + chunkGraph.upgradeDependentToFullHashModules(otherInfo.chunk); + } + remaining--; + if (--otherInfo.remaining === 0) { + readyChunks.push(otherInfo.chunk); + } + } + if (readyChunks.length > 0) { + // This ensures deterministic ordering, since referencedBy is non-deterministic + readyChunks.sort(byId); + for (const c of readyChunks) runtimeChunks.push(c); + readyChunks.length = 0; + } + } + } + // If there are still remaining references we have cycles and want to create a warning + if (remaining > 0) { + const circularRuntimeChunkInfo = []; + for (const info of runtimeChunksMap.values()) { + if (info.remaining !== 0) { + circularRuntimeChunkInfo.push(info); + } + } + circularRuntimeChunkInfo.sort(compareSelect((i) => i.chunk, byId)); + const err = + new WebpackError(`Circular dependency between chunks with runtime (${Array.from( + circularRuntimeChunkInfo, + (c) => c.chunk.name || c.chunk.id + ).join(", ")}) +This prevents using hashes of each other and should be avoided.`); + err.chunk = circularRuntimeChunkInfo[0].chunk; + this.warnings.push(err); + for (const i of circularRuntimeChunkInfo) runtimeChunks.push(i.chunk); + } + this.logger.timeEnd("hashing: sort chunks"); + + const fullHashChunks = new Set(); + /** @type {CodeGenerationJobs} */ + const codeGenerationJobs = []; + /** @type {Map>} */ + const codeGenerationJobsMap = new Map(); + /** @type {WebpackError[]} */ + const errors = []; + + /** + * @param {Chunk} chunk chunk + */ + const processChunk = (chunk) => { + // Last minute module hash generation for modules that depend on chunk hashes + this.logger.time("hashing: hash runtime modules"); + const runtime = chunk.runtime; + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!chunkGraph.hasModuleHashes(module, runtime)) { + const hash = this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength, + errors + ); + let hashMap = codeGenerationJobsMap.get(hash); + if (hashMap) { + const moduleJob = hashMap.get(module); + if (moduleJob) { + moduleJob.runtimes.push(runtime); + continue; + } + } else { + hashMap = new Map(); + codeGenerationJobsMap.set(hash, hashMap); + } + const job = { + module, + hash, + runtime, + runtimes: [runtime] + }; + hashMap.set(module, job); + codeGenerationJobs.push(job); + } + } + this.logger.timeAggregate("hashing: hash runtime modules"); + try { + this.logger.time("hashing: hash chunks"); + const chunkHash = createHash( + /** @type {HashFunction} */ (hashFunction) + ); + if (outputOptions.hashSalt) { + chunkHash.update(outputOptions.hashSalt); + } + chunk.updateHash(chunkHash, chunkGraph); + this.hooks.chunkHash.call(chunk, chunkHash, { + chunkGraph, + codeGenerationResults: this.codeGenerationResults, + moduleGraph: this.moduleGraph, + runtimeTemplate: this.runtimeTemplate + }); + const chunkHashDigest = /** @type {string} */ ( + chunkHash.digest(hashDigest) + ); + hash.update(chunkHashDigest); + chunk.hash = chunkHashDigest; + chunk.renderedHash = chunk.hash.slice(0, hashDigestLength); + const fullHashModules = + chunkGraph.getChunkFullHashModulesIterable(chunk); + if (fullHashModules) { + fullHashChunks.add(chunk); + } else { + this.hooks.contentHash.call(chunk); + } + } catch (err) { + this.errors.push( + new ChunkRenderError(chunk, "", /** @type {Error} */ (err)) + ); + } + this.logger.timeAggregate("hashing: hash chunks"); + }; + for (const chunk of asyncChunks) processChunk(chunk); + for (const chunk of runtimeChunks) processChunk(chunk); + for (const chunk of initialChunks) processChunk(chunk); + if (errors.length > 0) { + errors.sort( + compareSelect((err) => err.module, compareModulesByIdentifier) + ); + for (const error of errors) { + this.errors.push(error); + } + } + + this.logger.timeAggregateEnd("hashing: hash runtime modules"); + this.logger.timeAggregateEnd("hashing: hash chunks"); + this.logger.time("hashing: hash digest"); + this.hooks.fullHash.call(hash); + this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); + this.hash = this.fullHash.slice(0, hashDigestLength); + this.logger.timeEnd("hashing: hash digest"); + + this.logger.time("hashing: process full hash modules"); + for (const chunk of fullHashChunks) { + for (const module of /** @type {Iterable} */ ( + chunkGraph.getChunkFullHashModulesIterable(chunk) + )) { + const moduleHash = createHash( + /** @type {HashFunction} */ (hashFunction) + ); + module.updateHash(moduleHash, { + chunkGraph, + runtime: chunk.runtime, + runtimeTemplate + }); + const moduleHashDigest = /** @type {string} */ ( + moduleHash.digest(hashDigest) + ); + const oldHash = chunkGraph.getModuleHash(module, chunk.runtime); + chunkGraph.setModuleHashes( + module, + chunk.runtime, + moduleHashDigest, + moduleHashDigest.slice(0, hashDigestLength) + ); + /** @type {CodeGenerationJob} */ + ( + /** @type {Map} */ + (codeGenerationJobsMap.get(oldHash)).get(module) + ).hash = moduleHashDigest; + } + const chunkHash = createHash(/** @type {HashFunction} */ (hashFunction)); + chunkHash.update(chunk.hash); + chunkHash.update(this.hash); + const chunkHashDigest = + /** @type {string} */ + (chunkHash.digest(hashDigest)); + chunk.hash = chunkHashDigest; + chunk.renderedHash = chunk.hash.slice(0, hashDigestLength); + this.hooks.contentHash.call(chunk); + } + this.logger.timeEnd("hashing: process full hash modules"); + return codeGenerationJobs; + } + + /** + * @param {string} file file name + * @param {Source} source asset source + * @param {AssetInfo} assetInfo extra asset information + * @returns {void} + */ + emitAsset(file, source, assetInfo = {}) { + if (this.assets[file]) { + if (!isSourceEqual(this.assets[file], source)) { + this.errors.push( + new WebpackError( + `Conflict: Multiple assets emit different content to the same filename ${file}${ + assetInfo.sourceFilename + ? `. Original source ${assetInfo.sourceFilename}` + : "" + }` + ) + ); + this.assets[file] = source; + this._setAssetInfo(file, assetInfo); + return; + } + const oldInfo = this.assetsInfo.get(file); + const newInfo = { ...oldInfo, ...assetInfo }; + this._setAssetInfo(file, newInfo, oldInfo); + return; + } + this.assets[file] = source; + this._setAssetInfo(file, assetInfo, undefined); + } + + /** + * @private + * @param {string} file file name + * @param {AssetInfo=} newInfo new asset information + * @param {AssetInfo=} oldInfo old asset information + */ + _setAssetInfo(file, newInfo, oldInfo = this.assetsInfo.get(file)) { + if (newInfo === undefined) { + this.assetsInfo.delete(file); + } else { + this.assetsInfo.set(file, newInfo); + } + const oldRelated = oldInfo && oldInfo.related; + const newRelated = newInfo && newInfo.related; + if (oldRelated) { + for (const key of Object.keys(oldRelated)) { + /** + * @param {string} name name + */ + const remove = (name) => { + const relatedIn = this._assetsRelatedIn.get(name); + if (relatedIn === undefined) return; + const entry = relatedIn.get(key); + if (entry === undefined) return; + entry.delete(file); + if (entry.size !== 0) return; + relatedIn.delete(key); + if (relatedIn.size === 0) this._assetsRelatedIn.delete(name); + }; + const entry = oldRelated[key]; + if (Array.isArray(entry)) { + for (const name of entry) { + remove(name); + } + } else if (entry) { + remove(entry); + } + } + } + if (newRelated) { + for (const key of Object.keys(newRelated)) { + /** + * @param {string} name name + */ + const add = (name) => { + let relatedIn = this._assetsRelatedIn.get(name); + if (relatedIn === undefined) { + this._assetsRelatedIn.set(name, (relatedIn = new Map())); + } + let entry = relatedIn.get(key); + if (entry === undefined) { + relatedIn.set(key, (entry = new Set())); + } + entry.add(file); + }; + const entry = newRelated[key]; + if (Array.isArray(entry)) { + for (const name of entry) { + add(name); + } + } else if (entry) { + add(entry); + } + } + } + } + + /** + * @param {string} file file name + * @param {Source | ((source: Source) => Source)} newSourceOrFunction new asset source or function converting old to new + * @param {(AssetInfo | ((assetInfo?: AssetInfo) => AssetInfo | undefined)) | undefined} assetInfoUpdateOrFunction new asset info or function converting old to new + */ + updateAsset( + file, + newSourceOrFunction, + assetInfoUpdateOrFunction = undefined + ) { + if (!this.assets[file]) { + throw new Error( + `Called Compilation.updateAsset for not existing filename ${file}` + ); + } + this.assets[file] = + typeof newSourceOrFunction === "function" + ? newSourceOrFunction(this.assets[file]) + : newSourceOrFunction; + if (assetInfoUpdateOrFunction !== undefined) { + const oldInfo = this.assetsInfo.get(file) || EMPTY_ASSET_INFO; + if (typeof assetInfoUpdateOrFunction === "function") { + this._setAssetInfo(file, assetInfoUpdateOrFunction(oldInfo), oldInfo); + } else { + this._setAssetInfo( + file, + cachedCleverMerge(oldInfo, assetInfoUpdateOrFunction), + oldInfo + ); + } + } + } + + /** + * @param {string} file file name + * @param {string} newFile the new name of file + */ + renameAsset(file, newFile) { + const source = this.assets[file]; + if (!source) { + throw new Error( + `Called Compilation.renameAsset for not existing filename ${file}` + ); + } + if (this.assets[newFile] && !isSourceEqual(this.assets[file], source)) { + this.errors.push( + new WebpackError( + `Conflict: Called Compilation.renameAsset for already existing filename ${newFile} with different content` + ) + ); + } + const assetInfo = this.assetsInfo.get(file); + // Update related in all other assets + const relatedInInfo = this._assetsRelatedIn.get(file); + if (relatedInInfo) { + for (const [key, assets] of relatedInInfo) { + for (const name of assets) { + const info = this.assetsInfo.get(name); + if (!info) continue; + const related = info.related; + if (!related) continue; + const entry = related[key]; + let newEntry; + if (Array.isArray(entry)) { + newEntry = entry.map((x) => (x === file ? newFile : x)); + } else if (entry === file) { + newEntry = newFile; + } else { + continue; + } + this.assetsInfo.set(name, { + ...info, + related: { + ...related, + [key]: newEntry + } + }); + } + } + } + this._setAssetInfo(file, undefined, assetInfo); + this._setAssetInfo(newFile, assetInfo); + delete this.assets[file]; + this.assets[newFile] = source; + for (const chunk of this.chunks) { + { + const size = chunk.files.size; + chunk.files.delete(file); + if (size !== chunk.files.size) { + chunk.files.add(newFile); + } + } + { + const size = chunk.auxiliaryFiles.size; + chunk.auxiliaryFiles.delete(file); + if (size !== chunk.auxiliaryFiles.size) { + chunk.auxiliaryFiles.add(newFile); + } + } + } + } + + /** + * @param {string} file file name + */ + deleteAsset(file) { + if (!this.assets[file]) { + return; + } + delete this.assets[file]; + const assetInfo = this.assetsInfo.get(file); + this._setAssetInfo(file, undefined, assetInfo); + const related = assetInfo && assetInfo.related; + if (related) { + for (const key of Object.keys(related)) { + /** + * @param {string} file file + */ + const checkUsedAndDelete = (file) => { + if (!this._assetsRelatedIn.has(file)) { + this.deleteAsset(file); + } + }; + const items = related[key]; + if (Array.isArray(items)) { + for (const file of items) { + checkUsedAndDelete(file); + } + } else if (items) { + checkUsedAndDelete(items); + } + } + } + // TODO If this becomes a performance problem + // store a reverse mapping from asset to chunk + for (const chunk of this.chunks) { + chunk.files.delete(file); + chunk.auxiliaryFiles.delete(file); + } + } + + getAssets() { + /** @type {Readonly[]} */ + const array = []; + for (const assetName of Object.keys(this.assets)) { + if (Object.prototype.hasOwnProperty.call(this.assets, assetName)) { + array.push({ + name: assetName, + source: this.assets[assetName], + info: this.assetsInfo.get(assetName) || EMPTY_ASSET_INFO + }); + } + } + return array; + } + + /** + * @param {string} name the name of the asset + * @returns {Readonly | undefined} the asset or undefined when not found + */ + getAsset(name) { + if (!Object.prototype.hasOwnProperty.call(this.assets, name)) return; + return { + name, + source: this.assets[name], + info: this.assetsInfo.get(name) || EMPTY_ASSET_INFO + }; + } + + clearAssets() { + for (const chunk of this.chunks) { + chunk.files.clear(); + chunk.auxiliaryFiles.clear(); + } + } + + createModuleAssets() { + const { chunkGraph } = this; + for (const module of this.modules) { + const buildInfo = /** @type {BuildInfo} */ (module.buildInfo); + if (buildInfo.assets) { + const assetsInfo = buildInfo.assetsInfo; + for (const assetName of Object.keys(buildInfo.assets)) { + const fileName = this.getPath(assetName, { + chunkGraph: this.chunkGraph, + module + }); + for (const chunk of chunkGraph.getModuleChunksIterable(module)) { + chunk.auxiliaryFiles.add(fileName); + } + this.emitAsset( + fileName, + buildInfo.assets[assetName], + assetsInfo ? assetsInfo.get(assetName) : undefined + ); + this.hooks.moduleAsset.call(module, fileName); + } + } + } + } + + /** + * @param {RenderManifestOptions} options options object + * @returns {RenderManifestEntry[]} manifest entries + */ + getRenderManifest(options) { + return this.hooks.renderManifest.call([], options); + } + + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + createChunkAssets(callback) { + const outputOptions = this.outputOptions; + const cachedSourceMap = new WeakMap(); + /** @type {Map} */ + const alreadyWrittenFiles = new Map(); + + asyncLib.forEachLimit( + this.chunks, + 15, + (chunk, callback) => { + /** @type {RenderManifestEntry[]} */ + let manifest; + try { + manifest = this.getRenderManifest({ + chunk, + hash: /** @type {string} */ (this.hash), + fullHash: /** @type {string} */ (this.fullHash), + outputOptions, + codeGenerationResults: this.codeGenerationResults, + moduleTemplates: this.moduleTemplates, + dependencyTemplates: this.dependencyTemplates, + chunkGraph: this.chunkGraph, + moduleGraph: this.moduleGraph, + runtimeTemplate: this.runtimeTemplate + }); + } catch (err) { + this.errors.push( + new ChunkRenderError(chunk, "", /** @type {Error} */ (err)) + ); + return callback(); + } + asyncLib.each( + manifest, + (fileManifest, callback) => { + const ident = fileManifest.identifier; + const usedHash = /** @type {string} */ (fileManifest.hash); + + const assetCacheItem = this._assetsCache.getItemCache( + ident, + usedHash + ); + + assetCacheItem.get((err, sourceFromCache) => { + /** @type {TemplatePath} */ + let filenameTemplate; + /** @type {string} */ + let file; + /** @type {AssetInfo} */ + let assetInfo; + + let inTry = true; + /** + * @param {Error} err error + * @returns {void} + */ + const errorAndCallback = (err) => { + const filename = + file || + (typeof file === "string" + ? file + : typeof filenameTemplate === "string" + ? filenameTemplate + : ""); + + this.errors.push(new ChunkRenderError(chunk, filename, err)); + inTry = false; + return callback(); + }; + + try { + if ("filename" in fileManifest) { + file = fileManifest.filename; + assetInfo = fileManifest.info; + } else { + filenameTemplate = fileManifest.filenameTemplate; + const pathAndInfo = this.getPathWithInfo( + filenameTemplate, + fileManifest.pathOptions + ); + file = pathAndInfo.path; + assetInfo = fileManifest.info + ? { + ...pathAndInfo.info, + ...fileManifest.info + } + : pathAndInfo.info; + } + + if (err) { + return errorAndCallback(err); + } + + let source = sourceFromCache; + + // check if the same filename was already written by another chunk + const alreadyWritten = alreadyWrittenFiles.get(file); + if (alreadyWritten !== undefined) { + if (alreadyWritten.hash !== usedHash) { + inTry = false; + return callback( + new WebpackError( + `Conflict: Multiple chunks emit assets to the same filename ${file}` + + ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` + ) + ); + } + source = alreadyWritten.source; + } else if (!source) { + // render the asset + source = fileManifest.render(); + + // Ensure that source is a cached source to avoid additional cost because of repeated access + if (!(source instanceof CachedSource)) { + const cacheEntry = cachedSourceMap.get(source); + if (cacheEntry) { + source = cacheEntry; + } else { + const cachedSource = new CachedSource(source); + cachedSourceMap.set(source, cachedSource); + source = cachedSource; + } + } + } + this.emitAsset(file, source, assetInfo); + if (fileManifest.auxiliary) { + chunk.auxiliaryFiles.add(file); + } else { + chunk.files.add(file); + } + this.hooks.chunkAsset.call(chunk, file); + alreadyWrittenFiles.set(file, { + hash: usedHash, + source, + chunk + }); + if (source !== sourceFromCache) { + assetCacheItem.store(source, (err) => { + if (err) return errorAndCallback(err); + inTry = false; + return callback(); + }); + } else { + inTry = false; + callback(); + } + } catch (err) { + if (!inTry) throw err; + errorAndCallback(/** @type {Error} */ (err)); + } + }); + }, + callback + ); + }, + callback + ); + } + + /** + * @param {TemplatePath} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {string} interpolated path + */ + getPath(filename, data = {}) { + if (!data.hash) { + data = { + hash: this.hash, + ...data + }; + } + return this.getAssetPath(filename, data); + } + + /** + * @param {TemplatePath} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info + */ + getPathWithInfo(filename, data = {}) { + if (!data.hash) { + data = { + hash: this.hash, + ...data + }; + } + return this.getAssetPathWithInfo(filename, data); + } + + /** + * @param {TemplatePath} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {string} interpolated path + */ + getAssetPath(filename, data) { + return this.hooks.assetPath.call( + typeof filename === "function" ? filename(data) : filename, + data, + undefined + ); + } + + /** + * @param {TemplatePath} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info + */ + getAssetPathWithInfo(filename, data) { + const assetInfo = {}; + // TODO webpack 5: refactor assetPath hook to receive { path, info } object + const newPath = this.hooks.assetPath.call( + typeof filename === "function" ? filename(data, assetInfo) : filename, + data, + assetInfo + ); + return { path: newPath, info: assetInfo }; + } + + getWarnings() { + return this.hooks.processWarnings.call(this.warnings); + } + + getErrors() { + return this.hooks.processErrors.call(this.errors); + } + + /** + * This function allows you to run another instance of webpack inside of webpack however as + * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins + * from parent (or top level compiler) and creates a child Compilation + * @param {string} name name of the child compiler + * @param {Partial=} outputOptions // Need to convert config schema to types for this + * @param {Array=} plugins webpack plugins that will be applied + * @returns {Compiler} creates a child Compiler instance + */ + createChildCompiler(name, outputOptions, plugins) { + const idx = this.childrenCounters[name] || 0; + this.childrenCounters[name] = idx + 1; + return this.compiler.createChildCompiler( + this, + name, + idx, + outputOptions, + plugins + ); + } + + /** + * @param {Module} module the module + * @param {ExecuteModuleOptions} options options + * @param {ExecuteModuleCallback} callback callback + */ + executeModule(module, options, callback) { + // Aggregate all referenced modules and ensure they are ready + const modules = new Set([module]); + processAsyncTree( + modules, + 10, + (module, push, callback) => { + this.buildQueue.waitFor(module, (err) => { + if (err) return callback(err); + this.processDependenciesQueue.waitFor(module, (err) => { + if (err) return callback(err); + for (const { module: m } of this.moduleGraph.getOutgoingConnections( + module + )) { + const size = modules.size; + modules.add(m); + if (modules.size !== size) push(m); + } + callback(); + }); + }); + }, + (err) => { + if (err) return callback(/** @type {WebpackError} */ (err)); + + // Create new chunk graph, chunk and entrypoint for the build time execution + const chunkGraph = new ChunkGraph( + this.moduleGraph, + this.outputOptions.hashFunction + ); + const runtime = "build time"; + const { hashFunction, hashDigest, hashDigestLength } = + this.outputOptions; + const runtimeTemplate = this.runtimeTemplate; + + const chunk = new Chunk("build time chunk", this._backCompat); + chunk.id = /** @type {ChunkId} */ (chunk.name); + chunk.ids = [chunk.id]; + chunk.runtime = runtime; + + const entrypoint = new Entrypoint({ + runtime, + chunkLoading: false, + ...options.entryOptions + }); + chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); + connectChunkGroupAndChunk(entrypoint, chunk); + entrypoint.setRuntimeChunk(chunk); + entrypoint.setEntrypointChunk(chunk); + + const chunks = new Set([chunk]); + + // Assign ids to modules and modules to the chunk + for (const module of modules) { + const id = module.identifier(); + chunkGraph.setModuleId(module, id); + chunkGraph.connectChunkAndModule(chunk, module); + } + + /** @type {WebpackError[]} */ + const errors = []; + + // Hash modules + for (const module of modules) { + this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength, + errors + ); + } + + const codeGenerationResults = new CodeGenerationResults( + this.outputOptions.hashFunction + ); + /** + * @param {Module} module the module + * @param {Callback} callback callback + * @returns {void} + */ + const codeGen = (module, callback) => { + this._codeGenerationModule( + module, + runtime, + [runtime], + chunkGraph.getModuleHash(module, runtime), + this.dependencyTemplates, + chunkGraph, + this.moduleGraph, + runtimeTemplate, + errors, + codeGenerationResults, + (err, _codeGenerated) => { + callback(err); + } + ); + }; + + const reportErrors = () => { + if (errors.length > 0) { + errors.sort( + compareSelect((err) => err.module, compareModulesByIdentifier) + ); + for (const error of errors) { + this.errors.push(error); + } + errors.length = 0; + } + }; + + // Generate code for all aggregated modules + asyncLib.eachLimit(modules, 10, codeGen, (err) => { + if (err) return callback(err); + reportErrors(); + + // for backward-compat temporary set the chunk graph + // TODO webpack 6 + const old = this.chunkGraph; + this.chunkGraph = chunkGraph; + this.processRuntimeRequirements({ + chunkGraph, + modules, + chunks, + codeGenerationResults, + chunkGraphEntries: chunks + }); + this.chunkGraph = old; + + const runtimeModules = + chunkGraph.getChunkRuntimeModulesIterable(chunk); + + // Hash runtime modules + for (const module of runtimeModules) { + modules.add(module); + this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength, + errors + ); + } + + // Generate code for all runtime modules + asyncLib.eachLimit(runtimeModules, 10, codeGen, (err) => { + if (err) return callback(err); + reportErrors(); + + /** @type {Map} */ + const moduleArgumentsMap = new Map(); + /** @type {Map} */ + const moduleArgumentsById = new Map(); + + /** @type {ExecuteModuleResult["fileDependencies"]} */ + const fileDependencies = new LazySet(); + /** @type {ExecuteModuleResult["contextDependencies"]} */ + const contextDependencies = new LazySet(); + /** @type {ExecuteModuleResult["missingDependencies"]} */ + const missingDependencies = new LazySet(); + /** @type {ExecuteModuleResult["buildDependencies"]} */ + const buildDependencies = new LazySet(); + + /** @type {ExecuteModuleResult["assets"]} */ + const assets = new Map(); + + let cacheable = true; + + /** @type {ExecuteModuleContext} */ + const context = { + assets, + __webpack_require__: undefined, + chunk, + chunkGraph + }; + + // Prepare execution + asyncLib.eachLimit( + modules, + 10, + (module, callback) => { + const codeGenerationResult = codeGenerationResults.get( + module, + runtime + ); + /** @type {ExecuteModuleArgument} */ + const moduleArgument = { + module, + codeGenerationResult, + preparedInfo: undefined, + moduleObject: undefined + }; + moduleArgumentsMap.set(module, moduleArgument); + moduleArgumentsById.set(module.identifier(), moduleArgument); + module.addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ); + if ( + /** @type {BuildInfo} */ (module.buildInfo).cacheable === + false + ) { + cacheable = false; + } + if (module.buildInfo && module.buildInfo.assets) { + const { assets: moduleAssets, assetsInfo } = module.buildInfo; + for (const assetName of Object.keys(moduleAssets)) { + assets.set(assetName, { + source: moduleAssets[assetName], + info: assetsInfo ? assetsInfo.get(assetName) : undefined + }); + } + } + this.hooks.prepareModuleExecution.callAsync( + moduleArgument, + context, + callback + ); + }, + (err) => { + if (err) return callback(err); + + /** @type {ExecuteModuleExports | undefined} */ + let exports; + try { + const { + strictModuleErrorHandling, + strictModuleExceptionHandling + } = this.outputOptions; + + /** @type {WebpackRequire} */ + const __webpack_require__ = (id) => { + const cached = moduleCache[id]; + if (cached !== undefined) { + if (cached.error) throw cached.error; + return cached.exports; + } + const moduleArgument = moduleArgumentsById.get(id); + return __webpack_require_module__( + /** @type {ExecuteModuleArgument} */ + (moduleArgument), + id + ); + }; + const interceptModuleExecution = (__webpack_require__[ + /** @type {"i"} */ + ( + RuntimeGlobals.interceptModuleExecution.replace( + `${RuntimeGlobals.require}.`, + "" + ) + ) + ] = /** @type {NonNullable} */ ([])); + const moduleCache = (__webpack_require__[ + /** @type {"c"} */ ( + RuntimeGlobals.moduleCache.replace( + `${RuntimeGlobals.require}.`, + "" + ) + ) + ] = /** @type {NonNullable} */ ({})); + + context.__webpack_require__ = __webpack_require__; + + /** + * @param {ExecuteModuleArgument} moduleArgument the module argument + * @param {string=} id id + * @returns {ExecuteModuleExports} exports + */ + const __webpack_require_module__ = (moduleArgument, id) => { + /** @type {ExecuteOptions} */ + const execOptions = { + id, + module: { + id, + exports: {}, + loaded: false, + error: undefined + }, + require: __webpack_require__ + }; + for (const handler of interceptModuleExecution) { + handler(execOptions); + } + const module = moduleArgument.module; + this.buildTimeExecutedModules.add(module); + const moduleObject = execOptions.module; + moduleArgument.moduleObject = moduleObject; + try { + if (id) moduleCache[id] = moduleObject; + + tryRunOrWebpackError( + () => + this.hooks.executeModule.call( + moduleArgument, + context + ), + "Compilation.hooks.executeModule" + ); + moduleObject.loaded = true; + return moduleObject.exports; + } catch (execErr) { + if (strictModuleExceptionHandling) { + if (id) delete moduleCache[id]; + } else if (strictModuleErrorHandling) { + moduleObject.error = + /** @type {WebpackError} */ + (execErr); + } + if (!(/** @type {WebpackError} */ (execErr).module)) { + /** @type {WebpackError} */ + (execErr).module = module; + } + throw execErr; + } + }; + + for (const runtimeModule of chunkGraph.getChunkRuntimeModulesInOrder( + chunk + )) { + __webpack_require_module__( + /** @type {ExecuteModuleArgument} */ + (moduleArgumentsMap.get(runtimeModule)) + ); + } + + exports = __webpack_require__(module.identifier()); + } catch (execErr) { + const { message, stack, module } = + /** @type {WebpackError} */ + (execErr); + const err = new WebpackError( + `Execution of module code from module graph (${ + /** @type {Module} */ + (module).readableIdentifier(this.requestShortener) + }) failed: ${message}`, + { cause: execErr } + ); + err.stack = stack; + err.module = module; + return callback(err); + } + + callback(null, { + exports, + assets, + cacheable, + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + }); + } + ); + }); + }); + } + ); + } + + checkConstraints() { + const chunkGraph = this.chunkGraph; + + /** @type {Set} */ + const usedIds = new Set(); + + for (const module of this.modules) { + if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) continue; + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) continue; + if (usedIds.has(moduleId)) { + throw new Error(`checkConstraints: duplicate module id ${moduleId}`); + } + usedIds.add(moduleId); + } + + for (const chunk of this.chunks) { + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!this.modules.has(module)) { + throw new Error( + "checkConstraints: module in chunk but not in compilation " + + ` ${chunk.debugId} ${module.debugId}` + ); + } + } + for (const module of chunkGraph.getChunkEntryModulesIterable(chunk)) { + if (!this.modules.has(module)) { + throw new Error( + "checkConstraints: entry module in chunk but not in compilation " + + ` ${chunk.debugId} ${module.debugId}` + ); + } + } + } + + for (const chunkGroup of this.chunkGroups) { + chunkGroup.checkConstraints(); + } + } +} + +/** + * @typedef {object} FactorizeModuleOptions + * @property {ModuleProfile=} currentProfile + * @property {ModuleFactory} factory + * @property {Dependency[]} dependencies + * @property {boolean=} factoryResult return full ModuleFactoryResult instead of only module + * @property {Module | null} originModule + * @property {Partial=} contextInfo + * @property {string=} context + */ + +/** + * @param {FactorizeModuleOptions} options options object + * @param {ModuleCallback | ModuleFactoryResultCallback} callback callback + * @returns {void} + */ + +// Workaround for typescript as it doesn't support function overloading in jsdoc within a class +/* eslint-disable jsdoc/require-asterisk-prefix */ +Compilation.prototype.factorizeModule = /** + @type {{ + (options: FactorizeModuleOptions & { factoryResult?: false }, callback: ModuleCallback): void; + (options: FactorizeModuleOptions & { factoryResult: true }, callback: ModuleFactoryResultCallback): void; +}} */ ( + function factorizeModule(options, callback) { + this.factorizeQueue.add(options, /** @type {TODO} */ (callback)); + } +); +/* eslint-enable jsdoc/require-asterisk-prefix */ + +// Hide from typescript +const compilationPrototype = Compilation.prototype; + +// TODO webpack 6 remove +Object.defineProperty(compilationPrototype, "modifyHash", { + writable: false, + enumerable: false, + configurable: false, + value: () => { + throw new Error( + "Compilation.modifyHash was removed in favor of Compilation.hooks.fullHash" + ); + } +}); + +// TODO webpack 6 remove +Object.defineProperty(compilationPrototype, "cache", { + enumerable: false, + configurable: false, + get: util.deprecate( + /** + * @this {Compilation} the compilation + * @returns {Cache} the cache + */ + function cache() { + return this.compiler.cache; + }, + "Compilation.cache was removed in favor of Compilation.getCache()", + "DEP_WEBPACK_COMPILATION_CACHE" + ), + set: util.deprecate( + /** + * @param {EXPECTED_ANY} _v value + */ + (_v) => {}, + "Compilation.cache was removed in favor of Compilation.getCache()", + "DEP_WEBPACK_COMPILATION_CACHE" + ) +}); + +/** + * Add additional assets to the compilation. + */ +Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL = -2000; + +/** + * Basic preprocessing of assets. + */ +Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS = -1000; + +/** + * Derive new assets from existing assets. + * Existing assets should not be treated as complete. + */ +Compilation.PROCESS_ASSETS_STAGE_DERIVED = -200; + +/** + * Add additional sections to existing assets, like a banner or initialization code. + */ +Compilation.PROCESS_ASSETS_STAGE_ADDITIONS = -100; + +/** + * Optimize existing assets in a general way. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE = 100; + +/** + * Optimize the count of existing assets, e. g. by merging them. + * Only assets of the same type should be merged. + * For assets of different types see PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT = 200; + +/** + * Optimize the compatibility of existing assets, e. g. add polyfills or vendor-prefixes. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY = 300; + +/** + * Optimize the size of existing assets, e. g. by minimizing or omitting whitespace. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE = 400; + +/** + * Add development tooling to assets, e. g. by extracting a SourceMap. + */ +Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING = 500; + +/** + * Optimize the count of existing assets, e. g. by inlining assets of into other assets. + * Only assets of different types should be inlined. + * For assets of the same type see PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE = 700; + +/** + * Summarize the list of existing assets + * e. g. creating an assets manifest of Service Workers. + */ +Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE = 1000; + +/** + * Optimize the hashes of the assets, e. g. by generating real hashes of the asset content. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH = 2500; + +/** + * Optimize the transfer of existing assets, e. g. by preparing a compressed (gzip) file as separate asset. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER = 3000; + +/** + * Analyse existing assets. + */ +Compilation.PROCESS_ASSETS_STAGE_ANALYSE = 4000; + +/** + * Creating assets for reporting purposes. + */ +Compilation.PROCESS_ASSETS_STAGE_REPORT = 5000; + +module.exports = Compilation; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Compiler.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Compiler.js new file mode 100644 index 0000000000000000000000000000000000000000..f87921e8139a6e3c60cb693c754a1fbe5bafd3ca --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Compiler.js @@ -0,0 +1,1411 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const parseJson = require("json-parse-even-better-errors"); +const asyncLib = require("neo-async"); +const { + AsyncParallelHook, + AsyncSeriesHook, + SyncBailHook, + SyncHook +} = require("tapable"); +const { SizeOnlySource } = require("webpack-sources"); +const Cache = require("./Cache"); +const CacheFacade = require("./CacheFacade"); +const ChunkGraph = require("./ChunkGraph"); +const Compilation = require("./Compilation"); +const ConcurrentCompilationError = require("./ConcurrentCompilationError"); +const ContextModuleFactory = require("./ContextModuleFactory"); +const ModuleGraph = require("./ModuleGraph"); +const NormalModuleFactory = require("./NormalModuleFactory"); +const RequestShortener = require("./RequestShortener"); +const ResolverFactory = require("./ResolverFactory"); +const Stats = require("./Stats"); +const Watching = require("./Watching"); +const WebpackError = require("./WebpackError"); +const { Logger } = require("./logging/Logger"); +const { dirname, join, mkdirp } = require("./util/fs"); +const { makePathsRelative } = require("./util/identifier"); +const { isSourceEqual } = require("./util/source"); +const webpack = require("."); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./HotModuleReplacementPlugin").ChunkHashes} ChunkHashes */ +/** @typedef {import("./HotModuleReplacementPlugin").ChunkModuleHashes} ChunkModuleHashes */ +/** @typedef {import("./HotModuleReplacementPlugin").ChunkModuleIds} ChunkModuleIds */ +/** @typedef {import("./HotModuleReplacementPlugin").ChunkRuntime} ChunkRuntime */ +/** @typedef {import("./HotModuleReplacementPlugin").FullHashChunkModuleHashes} FullHashChunkModuleHashes */ +/** @typedef {import("./HotModuleReplacementPlugin").HotIndex} HotIndex */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./RecordIdsPlugin").RecordsChunks} RecordsChunks */ +/** @typedef {import("./RecordIdsPlugin").RecordsModules} RecordsModules */ +/** @typedef {import("./config/target").PlatformTargetProperties} PlatformTargetProperties */ +/** @typedef {import("./logging/createConsoleLogger").LoggingFunction} LoggingFunction */ +/** @typedef {import("./optimize/AggressiveSplittingPlugin").SplitData} SplitData */ +/** @typedef {import("./util/fs").IStats} IStats */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ +/** @typedef {import("./util/fs").TimeInfoEntries} TimeInfoEntries */ +/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ + +/** + * @typedef {object} CompilationParams + * @property {NormalModuleFactory} normalModuleFactory + * @property {ContextModuleFactory} contextModuleFactory + */ + +/** + * @template T + * @callback RunCallback + * @param {Error | null} err + * @param {T=} result + */ + +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result + */ + +/** + * @callback RunAsChildCallback + * @param {Error | null} err + * @param {Chunk[]=} entries + * @param {Compilation=} compilation + */ + +/** + * @typedef {object} KnownRecords + * @property {SplitData[]=} aggressiveSplits + * @property {RecordsChunks=} chunks + * @property {RecordsModules=} modules + * @property {string=} hash + * @property {HotIndex=} hotIndex + * @property {FullHashChunkModuleHashes=} fullHashChunkModuleHashes + * @property {ChunkModuleHashes=} chunkModuleHashes + * @property {ChunkHashes=} chunkHashes + * @property {ChunkRuntime=} chunkRuntime + * @property {ChunkModuleIds=} chunkModuleIds + */ + +/** @typedef {KnownRecords & Record & Record} Records */ + +/** + * @typedef {object} AssetEmittedInfo + * @property {Buffer} content + * @property {Source} source + * @property {Compilation} compilation + * @property {string} outputPath + * @property {string} targetPath + */ + +/** @typedef {{ sizeOnlySource: SizeOnlySource | undefined, writtenTo: Map }} CacheEntry */ +/** @typedef {{ path: string, source: Source, size: number | undefined, waiting: ({ cacheEntry: CacheEntry, file: string }[] | undefined) }} SimilarEntry */ + +/** @typedef {WeakMap} WeakReferences */ +/** @typedef {import("./util/WeakTupleMap")} MemCache */ +/** @typedef {{ buildInfo: BuildInfo, references: WeakReferences | undefined, memCache: MemCache }} ModuleMemCachesItem */ + +/** + * @param {string[]} array an array + * @returns {boolean} true, if the array is sorted + */ +const isSorted = (array) => { + for (let i = 1; i < array.length; i++) { + if (array[i - 1] > array[i]) return false; + } + return true; +}; + +/** + * @template {object} T + * @param {T} obj an object + * @param {(keyof T)[]} keys the keys of the object + * @returns {T} the object with properties sorted by property name + */ +const sortObject = (obj, keys) => { + const o = /** @type {T} */ ({}); + for (const k of keys.sort()) { + o[k] = obj[k]; + } + return o; +}; + +/** + * @param {string} filename filename + * @param {string | string[] | undefined} hashes list of hashes + * @returns {boolean} true, if the filename contains any hash + */ +const includesHash = (filename, hashes) => { + if (!hashes) return false; + if (Array.isArray(hashes)) { + return hashes.some((hash) => filename.includes(hash)); + } + return filename.includes(hashes); +}; + +class Compiler { + /** + * @param {string} context the compilation path + * @param {WebpackOptions} options options + */ + constructor(context, options = /** @type {WebpackOptions} */ ({})) { + this.hooks = Object.freeze({ + /** @type {SyncHook<[]>} */ + initialize: new SyncHook([]), + + /** @type {SyncBailHook<[Compilation], boolean | void>} */ + shouldEmit: new SyncBailHook(["compilation"]), + /** @type {AsyncSeriesHook<[Stats]>} */ + done: new AsyncSeriesHook(["stats"]), + /** @type {SyncHook<[Stats]>} */ + afterDone: new SyncHook(["stats"]), + /** @type {AsyncSeriesHook<[]>} */ + additionalPass: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook<[Compiler]>} */ + beforeRun: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook<[Compiler]>} */ + run: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook<[Compilation]>} */ + emit: new AsyncSeriesHook(["compilation"]), + /** @type {AsyncSeriesHook<[string, AssetEmittedInfo]>} */ + assetEmitted: new AsyncSeriesHook(["file", "info"]), + /** @type {AsyncSeriesHook<[Compilation]>} */ + afterEmit: new AsyncSeriesHook(["compilation"]), + + /** @type {SyncHook<[Compilation, CompilationParams]>} */ + thisCompilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook<[Compilation, CompilationParams]>} */ + compilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook<[NormalModuleFactory]>} */ + normalModuleFactory: new SyncHook(["normalModuleFactory"]), + /** @type {SyncHook<[ContextModuleFactory]>} */ + contextModuleFactory: new SyncHook(["contextModuleFactory"]), + + /** @type {AsyncSeriesHook<[CompilationParams]>} */ + beforeCompile: new AsyncSeriesHook(["params"]), + /** @type {SyncHook<[CompilationParams]>} */ + compile: new SyncHook(["params"]), + /** @type {AsyncParallelHook<[Compilation]>} */ + make: new AsyncParallelHook(["compilation"]), + /** @type {AsyncParallelHook<[Compilation]>} */ + finishMake: new AsyncSeriesHook(["compilation"]), + /** @type {AsyncSeriesHook<[Compilation]>} */ + afterCompile: new AsyncSeriesHook(["compilation"]), + + /** @type {AsyncSeriesHook<[]>} */ + readRecords: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook<[]>} */ + emitRecords: new AsyncSeriesHook([]), + + /** @type {AsyncSeriesHook<[Compiler]>} */ + watchRun: new AsyncSeriesHook(["compiler"]), + /** @type {SyncHook<[Error]>} */ + failed: new SyncHook(["error"]), + /** @type {SyncHook<[string | null, number]>} */ + invalid: new SyncHook(["filename", "changeTime"]), + /** @type {SyncHook<[]>} */ + watchClose: new SyncHook([]), + /** @type {AsyncSeriesHook<[]>} */ + shutdown: new AsyncSeriesHook([]), + + /** @type {SyncBailHook<[string, string, EXPECTED_ANY[] | undefined], true | void>} */ + infrastructureLog: new SyncBailHook(["origin", "type", "args"]), + + // TODO the following hooks are weirdly located here + // TODO move them for webpack 5 + /** @type {SyncHook<[]>} */ + environment: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterEnvironment: new SyncHook([]), + /** @type {SyncHook<[Compiler]>} */ + afterPlugins: new SyncHook(["compiler"]), + /** @type {SyncHook<[Compiler]>} */ + afterResolvers: new SyncHook(["compiler"]), + /** @type {SyncBailHook<[string, Entry], boolean | void>} */ + entryOption: new SyncBailHook(["context", "entry"]) + }); + + this.webpack = webpack; + + /** @type {string | undefined} */ + this.name = undefined; + /** @type {Compilation | undefined} */ + this.parentCompilation = undefined; + /** @type {Compiler} */ + this.root = this; + /** @type {string} */ + this.outputPath = ""; + /** @type {Watching | undefined} */ + this.watching = undefined; + + /** @type {OutputFileSystem | null} */ + this.outputFileSystem = null; + /** @type {IntermediateFileSystem | null} */ + this.intermediateFileSystem = null; + /** @type {InputFileSystem | null} */ + this.inputFileSystem = null; + /** @type {WatchFileSystem | null} */ + this.watchFileSystem = null; + + /** @type {string | null} */ + this.recordsInputPath = null; + /** @type {string | null} */ + this.recordsOutputPath = null; + /** @type {Records} */ + this.records = {}; + /** @type {Set} */ + this.managedPaths = new Set(); + /** @type {Set} */ + this.unmanagedPaths = new Set(); + /** @type {Set} */ + this.immutablePaths = new Set(); + + /** @type {ReadonlySet | undefined} */ + this.modifiedFiles = undefined; + /** @type {ReadonlySet | undefined} */ + this.removedFiles = undefined; + /** @type {TimeInfoEntries | undefined} */ + this.fileTimestamps = undefined; + /** @type {TimeInfoEntries | undefined} */ + this.contextTimestamps = undefined; + /** @type {number | undefined} */ + this.fsStartTime = undefined; + + /** @type {ResolverFactory} */ + this.resolverFactory = new ResolverFactory(); + + /** @type {LoggingFunction | undefined} */ + this.infrastructureLogger = undefined; + + /** @type {Readonly} */ + this.platform = { + web: null, + browser: null, + webworker: null, + node: null, + nwjs: null, + electron: null + }; + + this.options = options; + + this.context = context; + + this.requestShortener = new RequestShortener(context, this.root); + + this.cache = new Cache(); + + /** @type {Map | undefined} */ + this.moduleMemCaches = undefined; + + this.compilerPath = ""; + + /** @type {boolean} */ + this.running = false; + + /** @type {boolean} */ + this.idle = false; + + /** @type {boolean} */ + this.watchMode = false; + + this._backCompat = this.options.experiments.backCompat !== false; + + /** @type {Compilation | undefined} */ + this._lastCompilation = undefined; + /** @type {NormalModuleFactory | undefined} */ + this._lastNormalModuleFactory = undefined; + + /** + * @private + * @type {WeakMap} + */ + this._assetEmittingSourceCache = new WeakMap(); + /** + * @private + * @type {Map} + */ + this._assetEmittingWrittenFiles = new Map(); + /** + * @private + * @type {Set} + */ + this._assetEmittingPreviousFiles = new Set(); + } + + /** + * @param {string} name cache name + * @returns {CacheFacade} the cache facade instance + */ + getCache(name) { + return new CacheFacade( + this.cache, + `${this.compilerPath}${name}`, + this.options.output.hashFunction + ); + } + + /** + * @param {string | (() => string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name + */ + getInfrastructureLogger(name) { + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called without a name" + ); + } + return new Logger( + (type, args) => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + if ( + this.hooks.infrastructureLog.call(name, type, args) === undefined && + this.infrastructureLogger !== undefined + ) { + this.infrastructureLogger(name, type, args); + } + }, + (childName) => { + if (typeof name === "function") { + if (typeof childName === "function") { + return this.getInfrastructureLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + return this.getInfrastructureLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + if (typeof childName === "function") { + return this.getInfrastructureLogger(() => { + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + return this.getInfrastructureLogger(`${name}/${childName}`); + } + ); + } + + // TODO webpack 6: solve this in a better way + // e.g. move compilation specific info from Modules into ModuleGraph + _cleanupLastCompilation() { + if (this._lastCompilation !== undefined) { + for (const childCompilation of this._lastCompilation.children) { + for (const module of childCompilation.modules) { + ChunkGraph.clearChunkGraphForModule(module); + ModuleGraph.clearModuleGraphForModule(module); + module.cleanupForCache(); + } + for (const chunk of childCompilation.chunks) { + ChunkGraph.clearChunkGraphForChunk(chunk); + } + } + + for (const module of this._lastCompilation.modules) { + ChunkGraph.clearChunkGraphForModule(module); + ModuleGraph.clearModuleGraphForModule(module); + module.cleanupForCache(); + } + for (const chunk of this._lastCompilation.chunks) { + ChunkGraph.clearChunkGraphForChunk(chunk); + } + this._lastCompilation = undefined; + } + } + + // TODO webpack 6: solve this in a better way + _cleanupLastNormalModuleFactory() { + if (this._lastNormalModuleFactory !== undefined) { + this._lastNormalModuleFactory.cleanupForCache(); + this._lastNormalModuleFactory = undefined; + } + } + + /** + * @param {WatchOptions} watchOptions the watcher's options + * @param {RunCallback} handler signals when the call finishes + * @returns {Watching} a compiler watcher + */ + watch(watchOptions, handler) { + if (this.running) { + return handler(new ConcurrentCompilationError()); + } + + this.running = true; + this.watchMode = true; + this.watching = new Watching(this, watchOptions, handler); + return this.watching; + } + + /** + * @param {RunCallback} callback signals when the call finishes + * @returns {void} + */ + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); + } + + /** @type {Logger | undefined} */ + let logger; + + /** + * @param {Error | null} err error + * @param {Stats=} stats stats + */ + const finalCallback = (err, stats) => { + if (logger) logger.time("beginIdle"); + this.idle = true; + this.cache.beginIdle(); + this.idle = true; + if (logger) logger.timeEnd("beginIdle"); + this.running = false; + if (err) { + this.hooks.failed.call(err); + } + if (callback !== undefined) callback(err, stats); + this.hooks.afterDone.call(/** @type {Stats} */ (stats)); + }; + + const startTime = Date.now(); + + this.running = true; + + /** + * @param {Error | null} err error + * @param {Compilation=} _compilation compilation + * @returns {void} + */ + const onCompiled = (err, _compilation) => { + if (err) return finalCallback(err); + + const compilation = /** @type {Compilation} */ (_compilation); + + if (this.hooks.shouldEmit.call(compilation) === false) { + compilation.startTime = startTime; + compilation.endTime = Date.now(); + const stats = new Stats(compilation); + this.hooks.done.callAsync(stats, (err) => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + }); + return; + } + + process.nextTick(() => { + logger = compilation.getLogger("webpack.Compiler"); + logger.time("emitAssets"); + this.emitAssets(compilation, (err) => { + /** @type {Logger} */ + (logger).timeEnd("emitAssets"); + if (err) return finalCallback(err); + + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; + + compilation.startTime = startTime; + compilation.endTime = Date.now(); + /** @type {Logger} */ + (logger).time("done hook"); + const stats = new Stats(compilation); + this.hooks.done.callAsync(stats, (err) => { + /** @type {Logger} */ + (logger).timeEnd("done hook"); + if (err) return finalCallback(err); + + this.hooks.additionalPass.callAsync((err) => { + if (err) return finalCallback(err); + this.compile(onCompiled); + }); + }); + return; + } + + /** @type {Logger} */ + (logger).time("emitRecords"); + this.emitRecords((err) => { + /** @type {Logger} */ + (logger).timeEnd("emitRecords"); + if (err) return finalCallback(err); + + compilation.startTime = startTime; + compilation.endTime = Date.now(); + /** @type {Logger} */ + (logger).time("done hook"); + const stats = new Stats(compilation); + this.hooks.done.callAsync(stats, (err) => { + /** @type {Logger} */ + (logger).timeEnd("done hook"); + if (err) return finalCallback(err); + this.cache.storeBuildDependencies( + compilation.buildDependencies, + (err) => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + } + ); + }); + }); + }); + }); + }; + + const run = () => { + this.hooks.beforeRun.callAsync(this, (err) => { + if (err) return finalCallback(err); + + this.hooks.run.callAsync(this, (err) => { + if (err) return finalCallback(err); + + this.readRecords((err) => { + if (err) return finalCallback(err); + + this.compile(onCompiled); + }); + }); + }); + }; + + if (this.idle) { + this.cache.endIdle((err) => { + if (err) return finalCallback(err); + + this.idle = false; + run(); + }); + } else { + run(); + } + } + + /** + * @param {RunAsChildCallback} callback signals when the call finishes + * @returns {void} + */ + runAsChild(callback) { + const startTime = Date.now(); + + /** + * @param {Error | null} err error + * @param {Chunk[]=} entries entries + * @param {Compilation=} compilation compilation + */ + const finalCallback = (err, entries, compilation) => { + try { + callback(err, entries, compilation); + } catch (runAsChildErr) { + const err = new WebpackError( + `compiler.runAsChild callback error: ${runAsChildErr}`, + { cause: runAsChildErr } + ); + err.details = /** @type {Error} */ (runAsChildErr).stack; + /** @type {Compilation} */ + (this.parentCompilation).errors.push(err); + } + }; + + this.compile((err, _compilation) => { + if (err) return finalCallback(err); + + const compilation = /** @type {Compilation} */ (_compilation); + const parentCompilation = /** @type {Compilation} */ ( + this.parentCompilation + ); + + parentCompilation.children.push(compilation); + + for (const { name, source, info } of compilation.getAssets()) { + parentCompilation.emitAsset(name, source, info); + } + + /** @type {Chunk[]} */ + const entries = []; + + for (const ep of compilation.entrypoints.values()) { + entries.push(...ep.chunks); + } + + compilation.startTime = startTime; + compilation.endTime = Date.now(); + + return finalCallback(null, entries, compilation); + }); + } + + purgeInputFileSystem() { + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(); + } + } + + /** + * @param {Compilation} compilation the compilation + * @param {Callback} callback signals when the assets are emitted + * @returns {void} + */ + emitAssets(compilation, callback) { + /** @type {string} */ + let outputPath; + + /** + * @param {Error=} err error + * @returns {void} + */ + const emitFiles = (err) => { + if (err) return callback(err); + + const assets = compilation.getAssets(); + compilation.assets = { ...compilation.assets }; + /** @type {Map} */ + const caseInsensitiveMap = new Map(); + /** @type {Set} */ + const allTargetPaths = new Set(); + asyncLib.forEachLimit( + assets, + 15, + ({ name: file, source, info }, callback) => { + let targetFile = file; + let immutable = info.immutable; + const queryStringIdx = targetFile.indexOf("?"); + if (queryStringIdx >= 0) { + targetFile = targetFile.slice(0, queryStringIdx); + // We may remove the hash, which is in the query string + // So we recheck if the file is immutable + // This doesn't cover all cases, but immutable is only a performance optimization anyway + immutable = + immutable && + (includesHash(targetFile, info.contenthash) || + includesHash(targetFile, info.chunkhash) || + includesHash(targetFile, info.modulehash) || + includesHash(targetFile, info.fullhash)); + } + + /** + * @param {Error=} err error + * @returns {void} + */ + const writeOut = (err) => { + if (err) return callback(err); + const targetPath = join( + /** @type {OutputFileSystem} */ + (this.outputFileSystem), + outputPath, + targetFile + ); + allTargetPaths.add(targetPath); + + // check if the target file has already been written by this Compiler + const targetFileGeneration = + this._assetEmittingWrittenFiles.get(targetPath); + + // create an cache entry for this Source if not already existing + let cacheEntry = this._assetEmittingSourceCache.get(source); + if (cacheEntry === undefined) { + cacheEntry = { + sizeOnlySource: undefined, + writtenTo: new Map() + }; + this._assetEmittingSourceCache.set(source, cacheEntry); + } + + /** @type {SimilarEntry | undefined} */ + let similarEntry; + + const checkSimilarFile = () => { + const caseInsensitiveTargetPath = targetPath.toLowerCase(); + similarEntry = caseInsensitiveMap.get(caseInsensitiveTargetPath); + if (similarEntry !== undefined) { + const { path: other, source: otherSource } = similarEntry; + if (isSourceEqual(otherSource, source)) { + // Size may or may not be available at this point. + // If it's not available add to "waiting" list and it will be updated once available + if (similarEntry.size !== undefined) { + updateWithReplacementSource(similarEntry.size); + } else { + if (!similarEntry.waiting) similarEntry.waiting = []; + similarEntry.waiting.push({ file, cacheEntry }); + } + alreadyWritten(); + } else { + const err = + new WebpackError(`Prevent writing to file that only differs in casing or query string from already written file. +This will lead to a race-condition and corrupted files on case-insensitive file systems. +${targetPath} +${other}`); + err.file = file; + callback(err); + } + return true; + } + caseInsensitiveMap.set( + caseInsensitiveTargetPath, + (similarEntry = /** @type {SimilarEntry} */ ({ + path: targetPath, + source, + size: undefined, + waiting: undefined + })) + ); + return false; + }; + + /** + * get the binary (Buffer) content from the Source + * @returns {Buffer} content for the source + */ + const getContent = () => { + if (typeof source.buffer === "function") { + return source.buffer(); + } + const bufferOrString = source.source(); + if (Buffer.isBuffer(bufferOrString)) { + return bufferOrString; + } + return Buffer.from(bufferOrString, "utf8"); + }; + + const alreadyWritten = () => { + // cache the information that the Source has been already been written to that location + if (targetFileGeneration === undefined) { + const newGeneration = 1; + this._assetEmittingWrittenFiles.set(targetPath, newGeneration); + /** @type {CacheEntry} */ + (cacheEntry).writtenTo.set(targetPath, newGeneration); + } else { + /** @type {CacheEntry} */ + (cacheEntry).writtenTo.set(targetPath, targetFileGeneration); + } + callback(); + }; + + /** + * Write the file to output file system + * @param {Buffer} content content to be written + * @returns {void} + */ + const doWrite = (content) => { + /** @type {OutputFileSystem} */ + (this.outputFileSystem).writeFile(targetPath, content, (err) => { + if (err) return callback(err); + + // information marker that the asset has been emitted + compilation.emittedAssets.add(file); + + // cache the information that the Source has been written to that location + const newGeneration = + targetFileGeneration === undefined + ? 1 + : targetFileGeneration + 1; + /** @type {CacheEntry} */ + (cacheEntry).writtenTo.set(targetPath, newGeneration); + this._assetEmittingWrittenFiles.set(targetPath, newGeneration); + this.hooks.assetEmitted.callAsync( + file, + { + content, + source, + outputPath, + compilation, + targetPath + }, + callback + ); + }); + }; + + /** + * @param {number} size size + */ + const updateWithReplacementSource = (size) => { + updateFileWithReplacementSource( + file, + /** @type {CacheEntry} */ (cacheEntry), + size + ); + /** @type {SimilarEntry} */ + (similarEntry).size = size; + if ( + /** @type {SimilarEntry} */ (similarEntry).waiting !== undefined + ) { + for (const { file, cacheEntry } of /** @type {SimilarEntry} */ ( + similarEntry + ).waiting) { + updateFileWithReplacementSource(file, cacheEntry, size); + } + } + }; + + /** + * @param {string} file file + * @param {CacheEntry} cacheEntry cache entry + * @param {number} size size + */ + const updateFileWithReplacementSource = ( + file, + cacheEntry, + size + ) => { + // Create a replacement resource which only allows to ask for size + // This allows to GC all memory allocated by the Source + // (expect when the Source is stored in any other cache) + if (!cacheEntry.sizeOnlySource) { + cacheEntry.sizeOnlySource = new SizeOnlySource(size); + } + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size + }); + }; + + /** + * @param {IStats} stats stats + * @returns {void} + */ + const processExistingFile = (stats) => { + // skip emitting if it's already there and an immutable file + if (immutable) { + updateWithReplacementSource(/** @type {number} */ (stats.size)); + return alreadyWritten(); + } + + const content = getContent(); + + updateWithReplacementSource(content.length); + + // if it exists and content on disk matches content + // skip writing the same content again + // (to keep mtime and don't trigger watchers) + // for a fast negative match file size is compared first + if (content.length === stats.size) { + compilation.comparedForEmitAssets.add(file); + return /** @type {OutputFileSystem} */ ( + this.outputFileSystem + ).readFile(targetPath, (err, existingContent) => { + if ( + err || + !content.equals(/** @type {Buffer} */ (existingContent)) + ) { + return doWrite(content); + } + return alreadyWritten(); + }); + } + + return doWrite(content); + }; + + const processMissingFile = () => { + const content = getContent(); + + updateWithReplacementSource(content.length); + + return doWrite(content); + }; + + // if the target file has already been written + if (targetFileGeneration !== undefined) { + // check if the Source has been written to this target file + const writtenGeneration = /** @type {CacheEntry} */ ( + cacheEntry + ).writtenTo.get(targetPath); + if (writtenGeneration === targetFileGeneration) { + // if yes, we may skip writing the file + // if it's already there + // (we assume one doesn't modify files while the Compiler is running, other then removing them) + + if (this._assetEmittingPreviousFiles.has(targetPath)) { + const sizeOnlySource = /** @type {SizeOnlySource} */ ( + /** @type {CacheEntry} */ (cacheEntry).sizeOnlySource + ); + + // We assume that assets from the last compilation say intact on disk (they are not removed) + compilation.updateAsset(file, sizeOnlySource, { + size: sizeOnlySource.size() + }); + + return callback(); + } + // Settings immutable will make it accept file content without comparing when file exist + immutable = true; + } else if (!immutable) { + if (checkSimilarFile()) return; + // We wrote to this file before which has very likely a different content + // skip comparing and assume content is different for performance + // This case happens often during watch mode. + return processMissingFile(); + } + } + + if (checkSimilarFile()) return; + if (this.options.output.compareBeforeEmit) { + /** @type {OutputFileSystem} */ + (this.outputFileSystem).stat(targetPath, (err, stats) => { + const exists = !err && /** @type {IStats} */ (stats).isFile(); + + if (exists) { + processExistingFile(/** @type {IStats} */ (stats)); + } else { + processMissingFile(); + } + }); + } else { + processMissingFile(); + } + }; + + if (/\/|\\/.test(targetFile)) { + const fs = /** @type {OutputFileSystem} */ (this.outputFileSystem); + const dir = dirname(fs, join(fs, outputPath, targetFile)); + mkdirp(fs, dir, writeOut); + } else { + writeOut(); + } + }, + (err) => { + // Clear map to free up memory + caseInsensitiveMap.clear(); + if (err) { + this._assetEmittingPreviousFiles.clear(); + return callback(err); + } + + this._assetEmittingPreviousFiles = allTargetPaths; + + this.hooks.afterEmit.callAsync(compilation, (err) => { + if (err) return callback(err); + + return callback(); + }); + } + ); + }; + + this.hooks.emit.callAsync(compilation, (err) => { + if (err) return callback(err); + outputPath = compilation.getPath(this.outputPath, {}); + mkdirp( + /** @type {OutputFileSystem} */ (this.outputFileSystem), + outputPath, + emitFiles + ); + }); + } + + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + emitRecords(callback) { + if (this.hooks.emitRecords.isUsed()) { + if (this.recordsOutputPath) { + asyncLib.parallel( + [ + (cb) => this.hooks.emitRecords.callAsync(cb), + this._emitRecords.bind(this) + ], + (err) => callback(err) + ); + } else { + this.hooks.emitRecords.callAsync(callback); + } + } else if (this.recordsOutputPath) { + this._emitRecords(callback); + } else { + callback(); + } + } + + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + _emitRecords(callback) { + const writeFile = () => { + /** @type {OutputFileSystem} */ + (this.outputFileSystem).writeFile( + /** @type {string} */ (this.recordsOutputPath), + JSON.stringify( + this.records, + (n, value) => { + if ( + typeof value === "object" && + value !== null && + !Array.isArray(value) + ) { + const keys = Object.keys(value); + if (!isSorted(keys)) { + return sortObject(value, keys); + } + } + return value; + }, + 2 + ), + callback + ); + }; + + const recordsOutputPathDirectory = dirname( + /** @type {OutputFileSystem} */ + (this.outputFileSystem), + /** @type {string} */ + (this.recordsOutputPath) + ); + if (!recordsOutputPathDirectory) { + return writeFile(); + } + mkdirp( + /** @type {OutputFileSystem} */ (this.outputFileSystem), + recordsOutputPathDirectory, + (err) => { + if (err) return callback(err); + writeFile(); + } + ); + } + + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + readRecords(callback) { + if (this.hooks.readRecords.isUsed()) { + if (this.recordsInputPath) { + asyncLib.parallel( + [ + (cb) => this.hooks.readRecords.callAsync(cb), + this._readRecords.bind(this) + ], + (err) => callback(err) + ); + } else { + this.records = {}; + this.hooks.readRecords.callAsync(callback); + } + } else if (this.recordsInputPath) { + this._readRecords(callback); + } else { + this.records = {}; + callback(); + } + } + + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + _readRecords(callback) { + if (!this.recordsInputPath) { + this.records = {}; + return callback(); + } + /** @type {InputFileSystem} */ + (this.inputFileSystem).stat(this.recordsInputPath, (err) => { + // It doesn't exist + // We can ignore this. + if (err) return callback(); + + /** @type {InputFileSystem} */ + (this.inputFileSystem).readFile( + /** @type {string} */ (this.recordsInputPath), + (err, content) => { + if (err) return callback(err); + + try { + this.records = parseJson( + /** @type {Buffer} */ (content).toString("utf8") + ); + } catch (parseErr) { + return callback( + new Error( + `Cannot parse records: ${/** @type {Error} */ (parseErr).message}` + ) + ); + } + + return callback(); + } + ); + }); + } + + /** + * @param {Compilation} compilation the compilation + * @param {string} compilerName the compiler's name + * @param {number} compilerIndex the compiler's index + * @param {Partial=} outputOptions the output options + * @param {WebpackPluginInstance[]=} plugins the plugins to apply + * @returns {Compiler} a child compiler + */ + createChildCompiler( + compilation, + compilerName, + compilerIndex, + outputOptions, + plugins + ) { + const childCompiler = new Compiler(this.context, { + ...this.options, + output: { + ...this.options.output, + ...outputOptions + } + }); + childCompiler.name = compilerName; + childCompiler.outputPath = this.outputPath; + childCompiler.inputFileSystem = this.inputFileSystem; + childCompiler.outputFileSystem = null; + childCompiler.resolverFactory = this.resolverFactory; + childCompiler.modifiedFiles = this.modifiedFiles; + childCompiler.removedFiles = this.removedFiles; + childCompiler.fileTimestamps = this.fileTimestamps; + childCompiler.contextTimestamps = this.contextTimestamps; + childCompiler.fsStartTime = this.fsStartTime; + childCompiler.cache = this.cache; + childCompiler.compilerPath = `${this.compilerPath}${compilerName}|${compilerIndex}|`; + childCompiler._backCompat = this._backCompat; + + const relativeCompilerName = makePathsRelative( + this.context, + compilerName, + this.root + ); + if (!this.records[relativeCompilerName]) { + this.records[relativeCompilerName] = []; + } + if (this.records[relativeCompilerName][compilerIndex]) { + childCompiler.records = + /** @type {Records} */ + (this.records[relativeCompilerName][compilerIndex]); + } else { + this.records[relativeCompilerName].push((childCompiler.records = {})); + } + + childCompiler.parentCompilation = compilation; + childCompiler.root = this.root; + if (Array.isArray(plugins)) { + for (const plugin of plugins) { + if (plugin) { + plugin.apply(childCompiler); + } + } + } + for (const name in this.hooks) { + if ( + ![ + "make", + "compile", + "emit", + "afterEmit", + "invalid", + "done", + "thisCompilation" + ].includes(name) && + childCompiler.hooks[/** @type {keyof Compiler["hooks"]} */ (name)] + ) { + childCompiler.hooks[ + /** @type {keyof Compiler["hooks"]} */ + (name) + ].taps = [ + ...this.hooks[ + /** @type {keyof Compiler["hooks"]} */ + (name) + ].taps + ]; + } + } + + compilation.hooks.childCompiler.call( + childCompiler, + compilerName, + compilerIndex + ); + + return childCompiler; + } + + isChild() { + return Boolean(this.parentCompilation); + } + + /** + * @param {CompilationParams} params the compilation parameters + * @returns {Compilation} compilation + */ + createCompilation(params) { + this._cleanupLastCompilation(); + return (this._lastCompilation = new Compilation(this, params)); + } + + /** + * @param {CompilationParams} params the compilation parameters + * @returns {Compilation} the created compilation + */ + newCompilation(params) { + const compilation = this.createCompilation(params); + compilation.name = this.name; + compilation.records = this.records; + this.hooks.thisCompilation.call(compilation, params); + this.hooks.compilation.call(compilation, params); + return compilation; + } + + createNormalModuleFactory() { + this._cleanupLastNormalModuleFactory(); + const normalModuleFactory = new NormalModuleFactory({ + context: this.options.context, + fs: /** @type {InputFileSystem} */ (this.inputFileSystem), + resolverFactory: this.resolverFactory, + options: this.options.module, + associatedObjectForCache: this.root, + layers: this.options.experiments.layers + }); + this._lastNormalModuleFactory = normalModuleFactory; + this.hooks.normalModuleFactory.call(normalModuleFactory); + return normalModuleFactory; + } + + createContextModuleFactory() { + const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); + this.hooks.contextModuleFactory.call(contextModuleFactory); + return contextModuleFactory; + } + + newCompilationParams() { + const params = { + normalModuleFactory: this.createNormalModuleFactory(), + contextModuleFactory: this.createContextModuleFactory() + }; + return params; + } + + /** + * @param {RunCallback} callback signals when the compilation finishes + * @returns {void} + */ + compile(callback) { + const params = this.newCompilationParams(); + this.hooks.beforeCompile.callAsync(params, (err) => { + if (err) return callback(err); + + this.hooks.compile.call(params); + + const compilation = this.newCompilation(params); + + const logger = compilation.getLogger("webpack.Compiler"); + + logger.time("make hook"); + this.hooks.make.callAsync(compilation, (err) => { + logger.timeEnd("make hook"); + if (err) return callback(err); + + logger.time("finish make hook"); + this.hooks.finishMake.callAsync(compilation, (err) => { + logger.timeEnd("finish make hook"); + if (err) return callback(err); + + process.nextTick(() => { + logger.time("finish compilation"); + compilation.finish((err) => { + logger.timeEnd("finish compilation"); + if (err) return callback(err); + + logger.time("seal compilation"); + compilation.seal((err) => { + logger.timeEnd("seal compilation"); + if (err) return callback(err); + + logger.time("afterCompile hook"); + this.hooks.afterCompile.callAsync(compilation, (err) => { + logger.timeEnd("afterCompile hook"); + if (err) return callback(err); + + return callback(null, compilation); + }); + }); + }); + }); + }); + }); + }); + } + + /** + * @param {RunCallback} callback signals when the compiler closes + * @returns {void} + */ + close(callback) { + if (this.watching) { + // When there is still an active watching, close this first + this.watching.close((_err) => { + this.close(callback); + }); + return; + } + this.hooks.shutdown.callAsync((err) => { + if (err) return callback(err); + // Get rid of reference to last compilation to avoid leaking memory + // We can't run this._cleanupLastCompilation() as the Stats to this compilation + // might be still in use. We try to get rid of the reference to the cache instead. + this._lastCompilation = undefined; + this._lastNormalModuleFactory = undefined; + this.cache.shutdown(callback); + }); + } +} + +module.exports = Compiler; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConcatenationScope.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConcatenationScope.js new file mode 100644 index 0000000000000000000000000000000000000000..e14add3899fd144b8fd1e49de49a8e6e895f87f3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConcatenationScope.js @@ -0,0 +1,190 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + DEFAULT_EXPORT, + NAMESPACE_OBJECT_EXPORT +} = require("./util/concatenate"); + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */ +/** @typedef {import("./optimize/ConcatenatedModule").ModuleInfo} ModuleInfo */ + +const MODULE_REFERENCE_REGEXP = + /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(_deferredImport)?(?:_asiSafe(\d))?__$/; + +/** + * @typedef {object} ModuleReferenceOptions + * @property {string[]} ids the properties/exports of the module + * @property {boolean} call true, when this referenced export is called + * @property {boolean} directImport true, when this referenced export is directly imported (not via property access) + * @property {boolean} deferredImport true, when this referenced export is deferred + * @property {boolean | undefined} asiSafe if the position is ASI safe or unknown + */ + +class ConcatenationScope { + /** + * @param {ModuleInfo[] | Map} modulesMap all module info by module + * @param {ConcatenatedModuleInfo} currentModule the current module info + * @param {Set} usedNames all used names + */ + constructor(modulesMap, currentModule, usedNames) { + this._currentModule = currentModule; + if (Array.isArray(modulesMap)) { + const map = new Map(); + for (const info of modulesMap) { + map.set(info.module, info); + } + modulesMap = map; + } + this.usedNames = usedNames; + this._modulesMap = modulesMap; + } + + /** + * @param {Module} module the referenced module + * @returns {boolean} true, when it's in the scope + */ + isModuleInScope(module) { + return this._modulesMap.has(module); + } + + /** + * @param {string} exportName name of the export + * @param {string} symbol identifier of the export in source code + */ + registerExport(exportName, symbol) { + if (!this._currentModule.exportMap) { + this._currentModule.exportMap = new Map(); + } + if (!this._currentModule.exportMap.has(exportName)) { + this._currentModule.exportMap.set(exportName, symbol); + } + } + + /** + * @param {string} exportName name of the export + * @param {string} expression expression to be used + */ + registerRawExport(exportName, expression) { + if (!this._currentModule.rawExportMap) { + this._currentModule.rawExportMap = new Map(); + } + if (!this._currentModule.rawExportMap.has(exportName)) { + this._currentModule.rawExportMap.set(exportName, expression); + } + } + + /** + * @param {string} exportName name of the export + * @returns {string | undefined} the expression of the export + */ + getRawExport(exportName) { + if (!this._currentModule.rawExportMap) { + return undefined; + } + return this._currentModule.rawExportMap.get(exportName); + } + + /** + * @param {string} exportName name of the export + * @param {string} expression expression to be used + */ + setRawExportMap(exportName, expression) { + if (!this._currentModule.rawExportMap) { + this._currentModule.rawExportMap = new Map(); + } + if (this._currentModule.rawExportMap.has(exportName)) { + this._currentModule.rawExportMap.set(exportName, expression); + } + } + + /** + * @param {string} symbol identifier of the export in source code + */ + registerNamespaceExport(symbol) { + this._currentModule.namespaceExportSymbol = symbol; + } + + /** + * @param {string} symbol identifier of the export in source code + * @returns {boolean} registered success + */ + registerUsedName(symbol) { + if (this.usedNames.has(symbol)) { + return false; + } + this.usedNames.add(symbol); + return true; + } + + /** + * @param {Module} module the referenced module + * @param {Partial} options options + * @returns {string} the reference as identifier + */ + createModuleReference( + module, + { + ids = undefined, + call = false, + directImport = false, + deferredImport = false, + asiSafe = false + } + ) { + const info = /** @type {ModuleInfo} */ (this._modulesMap.get(module)); + const callFlag = call ? "_call" : ""; + const directImportFlag = directImport ? "_directImport" : ""; + const deferredImportFlag = deferredImport ? "_deferredImport" : ""; + const asiSafeFlag = asiSafe + ? "_asiSafe1" + : asiSafe === false + ? "_asiSafe0" + : ""; + const exportData = ids + ? Buffer.from(JSON.stringify(ids), "utf8").toString("hex") + : "ns"; + // a "._" is appended to allow "delete ...", which would cause a SyntaxError in strict mode + return `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${callFlag}${directImportFlag}${deferredImportFlag}${asiSafeFlag}__._`; + } + + /** + * @param {string} name the identifier + * @returns {boolean} true, when it's an module reference + */ + static isModuleReference(name) { + return MODULE_REFERENCE_REGEXP.test(name); + } + + /** + * @param {string} name the identifier + * @returns {ModuleReferenceOptions & { index: number } | null} parsed options and index + */ + static matchModuleReference(name) { + const match = MODULE_REFERENCE_REGEXP.exec(name); + if (!match) return null; + const index = Number(match[1]); + const asiSafe = match[6]; + return { + index, + ids: + match[2] === "ns" + ? [] + : JSON.parse(Buffer.from(match[2], "hex").toString("utf8")), + call: Boolean(match[3]), + directImport: Boolean(match[4]), + deferredImport: Boolean(match[5]), + asiSafe: asiSafe ? asiSafe === "1" : undefined + }; + } +} + +ConcatenationScope.DEFAULT_EXPORT = DEFAULT_EXPORT; +ConcatenationScope.NAMESPACE_OBJECT_EXPORT = NAMESPACE_OBJECT_EXPORT; + +module.exports = ConcatenationScope; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConcurrentCompilationError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConcurrentCompilationError.js new file mode 100644 index 0000000000000000000000000000000000000000..3643553f050e03b082b659fadb6d52545e25d520 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConcurrentCompilationError.js @@ -0,0 +1,18 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Maksim Nazarjev @acupofspirt +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +module.exports = class ConcurrentCompilationError extends WebpackError { + constructor() { + super(); + + this.name = "ConcurrentCompilationError"; + this.message = + "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time."; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConditionalInitFragment.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConditionalInitFragment.js new file mode 100644 index 0000000000000000000000000000000000000000..4386fee4dfaefec0f74ff3dc1e9b97737d62e8d7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConditionalInitFragment.js @@ -0,0 +1,120 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource, PrefixSource } = require("webpack-sources"); +const InitFragment = require("./InitFragment"); +const Template = require("./Template"); +const { mergeRuntime } = require("./util/runtime"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Generator").GenerateContext} GenerateContext */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @param {string} condition condition + * @param {string | Source} source source + * @returns {string | Source} wrapped source + */ +const wrapInCondition = (condition, source) => { + if (typeof source === "string") { + return Template.asString([ + `if (${condition}) {`, + Template.indent(source), + "}", + "" + ]); + } + return new ConcatSource( + `if (${condition}) {\n`, + new PrefixSource("\t", source), + "}\n" + ); +}; + +/** + * @extends {InitFragment} + */ +class ConditionalInitFragment extends InitFragment { + /** + * @param {string | Source | undefined} content the source code that will be included as initialization code + * @param {number} stage category of initialization code (contribute to order) + * @param {number} position position in the category (contribute to order) + * @param {string | undefined} key unique key to avoid emitting the same initialization code twice + * @param {RuntimeSpec | boolean} runtimeCondition in which runtime this fragment should be executed + * @param {string | Source=} endContent the source code that will be included at the end of the module + */ + constructor( + content, + stage, + position, + key, + runtimeCondition = true, + endContent = undefined + ) { + super(content, stage, position, key, endContent); + this.runtimeCondition = runtimeCondition; + } + + /** + * @param {GenerateContext} context context + * @returns {string | Source | undefined} the source code that will be included as initialization code + */ + getContent(context) { + if (this.runtimeCondition === false || !this.content) return ""; + if (this.runtimeCondition === true) return this.content; + const expr = context.runtimeTemplate.runtimeConditionExpression({ + chunkGraph: context.chunkGraph, + runtimeRequirements: context.runtimeRequirements, + runtime: context.runtime, + runtimeCondition: this.runtimeCondition + }); + if (expr === "true") return this.content; + return wrapInCondition(expr, this.content); + } + + /** + * @param {GenerateContext} context context + * @returns {string | Source=} the source code that will be included at the end of the module + */ + getEndContent(context) { + if (this.runtimeCondition === false || !this.endContent) return ""; + if (this.runtimeCondition === true) return this.endContent; + const expr = context.runtimeTemplate.runtimeConditionExpression({ + chunkGraph: context.chunkGraph, + runtimeRequirements: context.runtimeRequirements, + runtime: context.runtime, + runtimeCondition: this.runtimeCondition + }); + if (expr === "true") return this.endContent; + return wrapInCondition(expr, this.endContent); + } + + /** + * @param {ConditionalInitFragment} other fragment to merge with + * @returns {ConditionalInitFragment} merged fragment + */ + merge(other) { + if (this.runtimeCondition === true) return this; + if (other.runtimeCondition === true) return other; + if (this.runtimeCondition === false) return other; + if (other.runtimeCondition === false) return this; + const runtimeCondition = mergeRuntime( + this.runtimeCondition, + other.runtimeCondition + ); + return new ConditionalInitFragment( + this.content, + this.stage, + this.position, + this.key, + runtimeCondition, + this.endContent + ); + } +} + +module.exports = ConditionalInitFragment; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConstPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConstPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..5efb75a45e6daf58ca73bbb8337baa93f527f8ca --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ConstPlugin.js @@ -0,0 +1,566 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("./ModuleTypeConstants"); +const CachedConstDependency = require("./dependencies/CachedConstDependency"); +const ConstDependency = require("./dependencies/ConstDependency"); +const { evaluateToString } = require("./javascript/JavascriptParserHelpers"); +const { parseResource } = require("./util/identifier"); + +/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").Pattern} Pattern */ +/** @typedef {import("estree").SourceLocation} SourceLocation */ +/** @typedef {import("estree").Statement} Statement */ +/** @typedef {import("estree").Super} Super */ +/** @typedef {import("estree").VariableDeclaration} VariableDeclaration */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ + +/** + * @param {Set} declarations set of declarations + * @param {Identifier | Pattern} pattern pattern to collect declarations from + */ +const collectDeclaration = (declarations, pattern) => { + const stack = [pattern]; + while (stack.length > 0) { + const node = /** @type {Pattern} */ (stack.pop()); + switch (node.type) { + case "Identifier": + declarations.add(node.name); + break; + case "ArrayPattern": + for (const element of node.elements) { + if (element) { + stack.push(element); + } + } + break; + case "AssignmentPattern": + stack.push(node.left); + break; + case "ObjectPattern": + for (const property of node.properties) { + stack.push(/** @type {AssignmentProperty} */ (property).value); + } + break; + case "RestElement": + stack.push(node.argument); + break; + } + } +}; + +/** + * @param {Statement} branch branch to get hoisted declarations from + * @param {boolean} includeFunctionDeclarations whether to include function declarations + * @returns {Array} hoisted declarations + */ +const getHoistedDeclarations = (branch, includeFunctionDeclarations) => { + /** @type {Set} */ + const declarations = new Set(); + /** @type {Array} */ + const stack = [branch]; + while (stack.length > 0) { + const node = stack.pop(); + // Some node could be `null` or `undefined`. + if (!node) continue; + switch (node.type) { + // Walk through control statements to look for hoisted declarations. + // Some branches are skipped since they do not allow declarations. + case "BlockStatement": + for (const stmt of node.body) { + stack.push(stmt); + } + break; + case "IfStatement": + stack.push(node.consequent); + stack.push(node.alternate); + break; + case "ForStatement": + stack.push(/** @type {VariableDeclaration} */ (node.init)); + stack.push(node.body); + break; + case "ForInStatement": + case "ForOfStatement": + stack.push(/** @type {VariableDeclaration} */ (node.left)); + stack.push(node.body); + break; + case "DoWhileStatement": + case "WhileStatement": + case "LabeledStatement": + stack.push(node.body); + break; + case "SwitchStatement": + for (const cs of node.cases) { + for (const consequent of cs.consequent) { + stack.push(consequent); + } + } + break; + case "TryStatement": + stack.push(node.block); + if (node.handler) { + stack.push(node.handler.body); + } + stack.push(node.finalizer); + break; + case "FunctionDeclaration": + if (includeFunctionDeclarations) { + collectDeclaration(declarations, /** @type {Identifier} */ (node.id)); + } + break; + case "VariableDeclaration": + if (node.kind === "var") { + for (const decl of node.declarations) { + collectDeclaration(declarations, decl.id); + } + } + break; + } + } + return [...declarations]; +}; + +const PLUGIN_NAME = "ConstPlugin"; + +class ConstPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const cachedParseResource = parseResource.bindCache(compiler.root); + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + compilation.dependencyTemplates.set( + CachedConstDependency, + new CachedConstDependency.Template() + ); + + /** + * @param {JavascriptParser} parser the parser + */ + const handler = (parser) => { + parser.hooks.terminate.tap(PLUGIN_NAME, (_statement) => true); + parser.hooks.statementIf.tap(PLUGIN_NAME, (statement) => { + if (parser.scope.isAsmJs) return; + const param = parser.evaluateExpression(statement.test); + const bool = param.asBool(); + if (typeof bool === "boolean") { + if (!param.couldHaveSideEffects()) { + const dep = new ConstDependency( + `${bool}`, + /** @type {Range} */ (param.range) + ); + dep.loc = /** @type {SourceLocation} */ (statement.loc); + parser.state.module.addPresentationalDependency(dep); + } else { + parser.walkExpression(statement.test); + } + const branchToRemove = bool + ? statement.alternate + : statement.consequent; + if (branchToRemove) { + this.eliminateUnusedStatement(parser, branchToRemove, true); + } + return bool; + } + }); + parser.hooks.unusedStatement.tap(PLUGIN_NAME, (statement) => { + if ( + parser.scope.isAsmJs || + // Check top level scope here again + parser.scope.topLevelScope === true + ) { + return; + } + this.eliminateUnusedStatement(parser, statement, false); + return true; + }); + parser.hooks.expressionConditionalOperator.tap( + PLUGIN_NAME, + (expression) => { + if (parser.scope.isAsmJs) return; + const param = parser.evaluateExpression(expression.test); + const bool = param.asBool(); + if (typeof bool === "boolean") { + if (!param.couldHaveSideEffects()) { + const dep = new ConstDependency( + ` ${bool}`, + /** @type {Range} */ (param.range) + ); + dep.loc = /** @type {SourceLocation} */ (expression.loc); + parser.state.module.addPresentationalDependency(dep); + } else { + parser.walkExpression(expression.test); + } + // Expressions do not hoist. + // It is safe to remove the dead branch. + // + // Given the following code: + // + // false ? someExpression() : otherExpression(); + // + // the generated code is: + // + // false ? 0 : otherExpression(); + // + const branchToRemove = bool + ? expression.alternate + : expression.consequent; + const dep = new ConstDependency( + "0", + /** @type {Range} */ (branchToRemove.range) + ); + dep.loc = /** @type {SourceLocation} */ (branchToRemove.loc); + parser.state.module.addPresentationalDependency(dep); + return bool; + } + } + ); + parser.hooks.expressionLogicalOperator.tap( + PLUGIN_NAME, + (expression) => { + if (parser.scope.isAsmJs) return; + if ( + expression.operator === "&&" || + expression.operator === "||" + ) { + const param = parser.evaluateExpression(expression.left); + const bool = param.asBool(); + if (typeof bool === "boolean") { + // Expressions do not hoist. + // It is safe to remove the dead branch. + // + // ------------------------------------------ + // + // Given the following code: + // + // falsyExpression() && someExpression(); + // + // the generated code is: + // + // falsyExpression() && false; + // + // ------------------------------------------ + // + // Given the following code: + // + // truthyExpression() && someExpression(); + // + // the generated code is: + // + // true && someExpression(); + // + // ------------------------------------------ + // + // Given the following code: + // + // truthyExpression() || someExpression(); + // + // the generated code is: + // + // truthyExpression() || false; + // + // ------------------------------------------ + // + // Given the following code: + // + // falsyExpression() || someExpression(); + // + // the generated code is: + // + // false && someExpression(); + // + const keepRight = + (expression.operator === "&&" && bool) || + (expression.operator === "||" && !bool); + + if ( + !param.couldHaveSideEffects() && + (param.isBoolean() || keepRight) + ) { + // for case like + // + // return'development'===process.env.NODE_ENV&&'foo' + // + // we need a space before the bool to prevent result like + // + // returnfalse&&'foo' + // + const dep = new ConstDependency( + ` ${bool}`, + /** @type {Range} */ (param.range) + ); + dep.loc = /** @type {SourceLocation} */ (expression.loc); + parser.state.module.addPresentationalDependency(dep); + } else { + parser.walkExpression(expression.left); + } + if (!keepRight) { + const dep = new ConstDependency( + "0", + /** @type {Range} */ (expression.right.range) + ); + dep.loc = /** @type {SourceLocation} */ (expression.loc); + parser.state.module.addPresentationalDependency(dep); + } + return keepRight; + } + } else if (expression.operator === "??") { + const param = parser.evaluateExpression(expression.left); + const keepRight = param.asNullish(); + if (typeof keepRight === "boolean") { + // ------------------------------------------ + // + // Given the following code: + // + // nonNullish ?? someExpression(); + // + // the generated code is: + // + // nonNullish ?? 0; + // + // ------------------------------------------ + // + // Given the following code: + // + // nullish ?? someExpression(); + // + // the generated code is: + // + // null ?? someExpression(); + // + if (!param.couldHaveSideEffects() && keepRight) { + // cspell:word returnnull + // for case like + // + // return('development'===process.env.NODE_ENV&&null)??'foo' + // + // we need a space before the bool to prevent result like + // + // returnnull??'foo' + // + const dep = new ConstDependency( + " null", + /** @type {Range} */ (param.range) + ); + dep.loc = /** @type {SourceLocation} */ (expression.loc); + parser.state.module.addPresentationalDependency(dep); + } else { + const dep = new ConstDependency( + "0", + /** @type {Range} */ (expression.right.range) + ); + dep.loc = /** @type {SourceLocation} */ (expression.loc); + parser.state.module.addPresentationalDependency(dep); + parser.walkExpression(expression.left); + } + + return keepRight; + } + } + } + ); + parser.hooks.optionalChaining.tap(PLUGIN_NAME, (expr) => { + /** @type {Expression[]} */ + const optionalExpressionsStack = []; + /** @type {Expression | Super} */ + let next = expr.expression; + + while ( + next.type === "MemberExpression" || + next.type === "CallExpression" + ) { + if (next.type === "MemberExpression") { + if (next.optional) { + // SuperNode can not be optional + optionalExpressionsStack.push( + /** @type {Expression} */ (next.object) + ); + } + next = next.object; + } else { + if (next.optional) { + // SuperNode can not be optional + optionalExpressionsStack.push( + /** @type {Expression} */ (next.callee) + ); + } + next = next.callee; + } + } + + while (optionalExpressionsStack.length) { + const expression = optionalExpressionsStack.pop(); + const evaluated = parser.evaluateExpression( + /** @type {Expression} */ (expression) + ); + + if (evaluated.asNullish()) { + // ------------------------------------------ + // + // Given the following code: + // + // nullishMemberChain?.a.b(); + // + // the generated code is: + // + // undefined; + // + // ------------------------------------------ + // + const dep = new ConstDependency( + " undefined", + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {SourceLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + }); + parser.hooks.evaluateIdentifier + .for("__resourceQuery") + .tap(PLUGIN_NAME, (expr) => { + if (parser.scope.isAsmJs) return; + if (!parser.state.module) return; + return evaluateToString( + cachedParseResource(parser.state.module.resource).query + )(expr); + }); + parser.hooks.expression + .for("__resourceQuery") + .tap(PLUGIN_NAME, (expr) => { + if (parser.scope.isAsmJs) return; + if (!parser.state.module) return; + const dep = new CachedConstDependency( + JSON.stringify( + cachedParseResource(parser.state.module.resource).query + ), + /** @type {Range} */ (expr.range), + "__resourceQuery" + ); + dep.loc = /** @type {SourceLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + parser.hooks.evaluateIdentifier + .for("__resourceFragment") + .tap(PLUGIN_NAME, (expr) => { + if (parser.scope.isAsmJs) return; + if (!parser.state.module) return; + return evaluateToString( + cachedParseResource(parser.state.module.resource).fragment + )(expr); + }); + parser.hooks.expression + .for("__resourceFragment") + .tap(PLUGIN_NAME, (expr) => { + if (parser.scope.isAsmJs) return; + if (!parser.state.module) return; + const dep = new CachedConstDependency( + JSON.stringify( + cachedParseResource(parser.state.module.resource).fragment + ), + /** @type {Range} */ (expr.range), + "__resourceFragment" + ); + dep.loc = /** @type {SourceLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } + + /** + * Eliminate an unused statement. + * @param {JavascriptParser} parser the parser + * @param {Statement} statement the statement to remove + * @param {boolean} alwaysInBlock whether to always generate curly brackets + * @returns {void} + */ + eliminateUnusedStatement(parser, statement, alwaysInBlock) { + // Before removing the unused branch, the hoisted declarations + // must be collected. + // + // Given the following code: + // + // if (true) f() else g() + // if (false) { + // function f() {} + // const g = function g() {} + // if (someTest) { + // let a = 1 + // var x, {y, z} = obj + // } + // } else { + // … + // } + // + // the generated code is: + // + // if (true) f() else {} + // if (false) { + // var f, x, y, z; (in loose mode) + // var x, y, z; (in strict mode) + // } else { + // … + // } + // + // NOTE: When code runs in strict mode, `var` declarations + // are hoisted but `function` declarations don't. + // + const declarations = parser.scope.isStrict + ? getHoistedDeclarations(statement, false) + : getHoistedDeclarations(statement, true); + + const inBlock = alwaysInBlock || statement.type === "BlockStatement"; + + let replacement = inBlock ? "{" : ""; + replacement += + declarations.length > 0 ? ` var ${declarations.join(", ")}; ` : ""; + replacement += inBlock ? "}" : ""; + + const dep = new ConstDependency( + `// removed by dead control flow\n${replacement}`, + /** @type {Range} */ (statement.range) + ); + dep.loc = /** @type {SourceLocation} */ (statement.loc); + parser.state.module.addPresentationalDependency(dep); + } +} + +module.exports = ConstPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextExclusionPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextExclusionPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..6bd57c6e0d220f8df69fbbc0d553951c1a42918a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextExclusionPlugin.js @@ -0,0 +1,34 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */ + +const PLUGIN_NAME = "ContextExclusionPlugin"; + +class ContextExclusionPlugin { + /** + * @param {RegExp} negativeMatcher Matcher regular expression + */ + constructor(negativeMatcher) { + this.negativeMatcher = negativeMatcher; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, (cmf) => { + cmf.hooks.contextModuleFiles.tap(PLUGIN_NAME, (files) => + files.filter((filePath) => !this.negativeMatcher.test(filePath)) + ); + }); + } +} + +module.exports = ContextExclusionPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextModule.js new file mode 100644 index 0000000000000000000000000000000000000000..207854d4d1feec471ff3658a37d7b3bf7f01e2f5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextModule.js @@ -0,0 +1,1261 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { OriginalSource, RawSource } = require("webpack-sources"); +const AsyncDependenciesBlock = require("./AsyncDependenciesBlock"); +const { makeWebpackError } = require("./HookWebpackError"); +const Module = require("./Module"); +const { JS_TYPES } = require("./ModuleSourceTypesConstants"); +const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const Template = require("./Template"); +const WebpackError = require("./WebpackError"); +const { + compareLocations, + compareModulesById, + compareSelect, + concatComparators, + keepOriginalOrder +} = require("./util/comparators"); +const { + contextify, + makePathsRelative, + parseResource +} = require("./util/identifier"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Chunk").ChunkId} ChunkId */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator").SourceTypes} SourceTypes */ +/** @typedef {import("./Module").BuildCallback} BuildCallback */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ +/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ +/** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @template T @typedef {import("./util/LazySet")} LazySet */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ + +/** + * @typedef {object} ContextOptions + * @property {ContextMode} mode + * @property {boolean} recursive + * @property {RegExp} regExp + * @property {("strict" | boolean)=} namespaceObject + * @property {string=} addon + * @property {(string | null)=} chunkName + * @property {(RegExp | null)=} include + * @property {(RegExp | null)=} exclude + * @property {RawChunkGroupOptions=} groupOptions + * @property {string=} typePrefix + * @property {string=} category + * @property {(string[][] | null)=} referencedExports exports referenced from modules (won't be mangled) + * @property {string=} layer + * @property {ImportAttributes=} attributes + */ + +/** + * @typedef {object} ContextModuleOptionsExtras + * @property {false | string | string[]} resource + * @property {string=} resourceQuery + * @property {string=} resourceFragment + * @property {ResolveOptions=} resolveOptions + */ + +/** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */ + +/** + * @callback ResolveDependenciesCallback + * @param {Error | null} err + * @param {ContextElementDependency[]=} dependencies + */ + +/** + * @callback ResolveDependencies + * @param {InputFileSystem} fs + * @param {ContextModuleOptions} options + * @param {ResolveDependenciesCallback} callback + */ + +/** @typedef {1 | 3 | 7 | 9} FakeMapType */ + +/** @typedef {Record} FakeMap */ + +const SNAPSHOT_OPTIONS = { timestamp: true }; + +class ContextModule extends Module { + /** + * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context + * @param {ContextModuleOptions} options options object + */ + constructor(resolveDependencies, options) { + if (!options || typeof options.resource === "string") { + const parsed = parseResource( + options ? /** @type {string} */ (options.resource) : "" + ); + const resource = parsed.path; + const resourceQuery = (options && options.resourceQuery) || parsed.query; + const resourceFragment = + (options && options.resourceFragment) || parsed.fragment; + const layer = options && options.layer; + + super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, resource, layer); + /** @type {ContextModuleOptions} */ + this.options = { + ...options, + resource, + resourceQuery, + resourceFragment + }; + } else { + super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, undefined, options.layer); + /** @type {ContextModuleOptions} */ + this.options = { + ...options, + resource: options.resource, + resourceQuery: options.resourceQuery || "", + resourceFragment: options.resourceFragment || "" + }; + } + + // Info from Factory + /** @type {ResolveDependencies | undefined} */ + this.resolveDependencies = resolveDependencies; + if (options && options.resolveOptions !== undefined) { + this.resolveOptions = options.resolveOptions; + } + + if (options && typeof options.mode !== "string") { + throw new Error("options.mode is a required option"); + } + + this._identifier = this._createIdentifier(); + this._forceBuild = true; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return JS_TYPES; + } + + /** + * Assuming this module is in the cache. Update the (cached) module with + * the fresh module from the factory. Usually updates internal references + * and properties. + * @param {Module} module fresh module + * @returns {void} + */ + updateCacheModule(module) { + const m = /** @type {ContextModule} */ (module); + this.resolveDependencies = m.resolveDependencies; + this.options = m.options; + } + + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + super.cleanupForCache(); + this.resolveDependencies = undefined; + } + + /** + * @private + * @param {RegExp} regexString RegExp as a string + * @param {boolean=} stripSlash do we need to strip a slsh + * @returns {string} pretty RegExp + */ + _prettyRegExp(regexString, stripSlash = true) { + const str = stripSlash + ? regexString.source + regexString.flags + : `${regexString}`; + return str.replace(/!/g, "%21").replace(/\|/g, "%7C"); + } + + _createIdentifier() { + let identifier = + this.context || + (typeof this.options.resource === "string" || + this.options.resource === false + ? `${this.options.resource}` + : this.options.resource.join("|")); + if (this.options.resourceQuery) { + identifier += `|${this.options.resourceQuery}`; + } + if (this.options.resourceFragment) { + identifier += `|${this.options.resourceFragment}`; + } + if (this.options.mode) { + identifier += `|${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += "|nonrecursive"; + } + if (this.options.addon) { + identifier += `|${this.options.addon}`; + } + if (this.options.regExp) { + identifier += `|${this._prettyRegExp(this.options.regExp, false)}`; + } + if (this.options.include) { + identifier += `|include: ${this._prettyRegExp( + this.options.include, + false + )}`; + } + if (this.options.exclude) { + identifier += `|exclude: ${this._prettyRegExp( + this.options.exclude, + false + )}`; + } + if (this.options.referencedExports) { + identifier += `|referencedExports: ${JSON.stringify( + this.options.referencedExports + )}`; + } + if (this.options.chunkName) { + identifier += `|chunkName: ${this.options.chunkName}`; + } + if (this.options.groupOptions) { + identifier += `|groupOptions: ${JSON.stringify( + this.options.groupOptions + )}`; + } + if (this.options.namespaceObject === "strict") { + identifier += "|strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += "|namespace object"; + } + if (this.layer) { + identifier += `|layer: ${this.layer}`; + } + + return identifier; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this._identifier; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + let identifier; + if (this.context) { + identifier = `${requestShortener.shorten(this.context)}/`; + } else if ( + typeof this.options.resource === "string" || + this.options.resource === false + ) { + identifier = `${requestShortener.shorten(`${this.options.resource}`)}/`; + } else { + identifier = this.options.resource + .map((r) => `${requestShortener.shorten(r)}/`) + .join(" "); + } + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; + } + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${requestShortener.shorten(this.options.addon)}`; + } + if (this.options.regExp) { + identifier += ` ${this._prettyRegExp(this.options.regExp)}`; + } + if (this.options.include) { + identifier += ` include: ${this._prettyRegExp(this.options.include)}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; + } + if (this.options.referencedExports) { + identifier += ` referencedExports: ${this.options.referencedExports + .map((e) => e.join(".")) + .join(", ")}`; + } + if (this.options.chunkName) { + identifier += ` chunkName: ${this.options.chunkName}`; + } + if (this.options.groupOptions) { + const groupOptions = this.options.groupOptions; + for (const key of Object.keys(groupOptions)) { + identifier += ` ${key}: ${ + groupOptions[/** @type {keyof RawChunkGroupOptions} */ (key)] + }`; + } + } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } + + return identifier; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + let identifier; + + if (this.context) { + identifier = contextify( + options.context, + this.context, + options.associatedObjectForCache + ); + } else if (typeof this.options.resource === "string") { + identifier = contextify( + options.context, + this.options.resource, + options.associatedObjectForCache + ); + } else if (this.options.resource === false) { + identifier = "false"; + } else { + identifier = this.options.resource + .map((res) => + contextify(options.context, res, options.associatedObjectForCache) + ) + .join(" "); + } + + if (this.layer) identifier = `(${this.layer})/${identifier}`; + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (this.options.recursive) { + identifier += " recursive"; + } + if (this.options.addon) { + identifier += ` ${contextify( + options.context, + this.options.addon, + options.associatedObjectForCache + )}`; + } + if (this.options.regExp) { + identifier += ` ${this._prettyRegExp(this.options.regExp)}`; + } + if (this.options.include) { + identifier += ` include: ${this._prettyRegExp(this.options.include)}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; + } + if (this.options.referencedExports) { + identifier += ` referencedExports: ${this.options.referencedExports + .map((e) => e.join(".")) + .join(", ")}`; + } + + return identifier; + } + + /** + * @returns {void} + */ + invalidateBuild() { + this._forceBuild = true; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild({ fileSystemInfo }, callback) { + // build if enforced + if (this._forceBuild) return callback(null, true); + + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + // always build when we have no snapshot and context + if (!buildInfo.snapshot) { + return callback(null, Boolean(this.context || this.options.resource)); + } + + fileSystemInfo.checkSnapshotValid(buildInfo.snapshot, (err, valid) => { + callback(err, !valid); + }); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this._forceBuild = false; + /** @type {BuildMeta} */ + this.buildMeta = { + exportsType: "default", + defaultObject: "redirect-warn" + }; + this.buildInfo = { + snapshot: undefined + }; + this.dependencies.length = 0; + this.blocks.length = 0; + const startTime = Date.now(); + /** @type {ResolveDependencies} */ + (this.resolveDependencies)(fs, this.options, (err, dependencies) => { + if (err) { + return callback( + makeWebpackError(err, "ContextModule.resolveDependencies") + ); + } + + // abort if something failed + // this will create an empty context + if (!dependencies) { + callback(); + return; + } + + // enhance dependencies with meta info + for (const dep of dependencies) { + dep.loc = { + name: dep.userRequest + }; + dep.request = this.options.addon + dep.request; + } + dependencies.sort( + concatComparators( + compareSelect((a) => a.loc, compareLocations), + keepOriginalOrder(this.dependencies) + ) + ); + + if (this.options.mode === "sync" || this.options.mode === "eager") { + // if we have an sync or eager context + // just add all dependencies and continue + this.dependencies = dependencies; + } else if (this.options.mode === "lazy-once") { + // for the lazy-once mode create a new async dependency block + // and add that block to this context + if (dependencies.length > 0) { + const block = new AsyncDependenciesBlock({ + ...this.options.groupOptions, + name: this.options.chunkName + }); + for (const dep of dependencies) { + block.addDependency(dep); + } + this.addBlock(block); + } + } else if ( + this.options.mode === "weak" || + this.options.mode === "async-weak" + ) { + // we mark all dependencies as weak + for (const dep of dependencies) { + dep.weak = true; + } + this.dependencies = dependencies; + } else if (this.options.mode === "lazy") { + // if we are lazy create a new async dependency block per dependency + // and add all blocks to this context + let index = 0; + for (const dep of dependencies) { + let chunkName = this.options.chunkName; + if (chunkName) { + if (!/\[(index|request)\]/.test(chunkName)) { + chunkName += "[index]"; + } + chunkName = chunkName.replace(/\[index\]/g, `${index++}`); + chunkName = chunkName.replace( + /\[request\]/g, + Template.toPath(dep.userRequest) + ); + } + const block = new AsyncDependenciesBlock( + { + ...this.options.groupOptions, + name: chunkName + }, + dep.loc, + dep.userRequest + ); + block.addDependency(dep); + this.addBlock(block); + } + } else { + callback( + new WebpackError(`Unsupported mode "${this.options.mode}" in context`) + ); + return; + } + if (!this.context && !this.options.resource) return callback(); + + compilation.fileSystemInfo.createSnapshot( + startTime, + null, + this.context + ? [this.context] + : typeof this.options.resource === "string" + ? [this.options.resource] + : /** @type {string[]} */ (this.options.resource), + null, + SNAPSHOT_OPTIONS, + (err, snapshot) => { + if (err) return callback(err); + /** @type {BuildInfo} */ + (this.buildInfo).snapshot = snapshot; + callback(); + } + ); + }); + } + + /** + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to + */ + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) { + if (this.context) { + contextDependencies.add(this.context); + } else if (typeof this.options.resource === "string") { + contextDependencies.add(this.options.resource); + } else if (this.options.resource === false) { + // Do nothing + } else { + for (const res of this.options.resource) contextDependencies.add(res); + } + } + + /** + * @param {Dependency[]} dependencies all dependencies + * @param {ChunkGraph} chunkGraph chunk graph + * @returns {Map} map with user requests + */ + getUserRequestMap(dependencies, chunkGraph) { + const moduleGraph = chunkGraph.moduleGraph; + // if we filter first we get a new array + // therefore we don't need to create a clone of dependencies explicitly + // therefore the order of this is !important! + const sortedDependencies = + /** @type {ContextElementDependency[]} */ + (dependencies) + .filter((dependency) => moduleGraph.getModule(dependency)) + .sort((a, b) => { + if (a.userRequest === b.userRequest) { + return 0; + } + return a.userRequest < b.userRequest ? -1 : 1; + }); + const map = Object.create(null); + for (const dep of sortedDependencies) { + const module = /** @type {Module} */ (moduleGraph.getModule(dep)); + map[dep.userRequest] = chunkGraph.getModuleId(module); + } + return map; + } + + /** + * @param {Dependency[]} dependencies all dependencies + * @param {ChunkGraph} chunkGraph chunk graph + * @returns {FakeMap | FakeMapType} fake map + */ + getFakeMap(dependencies, chunkGraph) { + if (!this.options.namespaceObject) { + return 9; + } + const moduleGraph = chunkGraph.moduleGraph; + // bitfield + let hasType = 0; + const comparator = compareModulesById(chunkGraph); + // if we filter first we get a new array + // therefore we don't need to create a clone of dependencies explicitly + // therefore the order of this is !important! + const sortedModules = dependencies + .map( + (dependency) => + /** @type {Module} */ (moduleGraph.getModule(dependency)) + ) + .filter(Boolean) + .sort(comparator); + /** @type {FakeMap} */ + const fakeMap = Object.create(null); + for (const module of sortedModules) { + const exportsType = module.getExportsType( + moduleGraph, + this.options.namespaceObject === "strict" + ); + const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module)); + switch (exportsType) { + case "namespace": + fakeMap[id] = 9; + hasType |= 1; + break; + case "dynamic": + fakeMap[id] = 7; + hasType |= 2; + break; + case "default-only": + fakeMap[id] = 1; + hasType |= 4; + break; + case "default-with-named": + fakeMap[id] = 3; + hasType |= 8; + break; + default: + throw new Error(`Unexpected exports type ${exportsType}`); + } + } + if (hasType === 1) { + return 9; + } + if (hasType === 2) { + return 7; + } + if (hasType === 4) { + return 1; + } + if (hasType === 8) { + return 3; + } + if (hasType === 0) { + return 9; + } + return fakeMap; + } + + /** + * @param {FakeMap | FakeMapType} fakeMap fake map + * @returns {string} fake map init statement + */ + getFakeMapInitStatement(fakeMap) { + return typeof fakeMap === "object" + ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` + : ""; + } + + /** + * @param {FakeMapType} type type + * @param {boolean=} asyncModule is async module + * @returns {string} return result + */ + getReturn(type, asyncModule) { + if (type === 9) { + return `${RuntimeGlobals.require}(id)`; + } + return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${ + asyncModule ? " | 16" : "" + })`; + } + + /** + * @param {FakeMap | FakeMapType} fakeMap fake map + * @param {boolean=} asyncModule us async module + * @param {string=} fakeMapDataExpression fake map data expression + * @returns {string} module object source + */ + getReturnModuleObjectSource( + fakeMap, + asyncModule, + fakeMapDataExpression = "fakeMap[id]" + ) { + if (typeof fakeMap === "number") { + return `return ${this.getReturn(fakeMap, asyncModule)};`; + } + return `return ${ + RuntimeGlobals.createFakeNamespaceObject + }(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`; + } + + /** + * @param {Dependency[]} dependencies dependencies + * @param {ModuleId} id module id + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {string} source code + */ + getSyncSource(dependencies, id, chunkGraph) { + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackContext(req) { + var id = webpackContextResolve(req); + ${returnModuleObject} +} +function webpackContextResolve(req) { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +module.exports = webpackContext; +webpackContext.id = ${JSON.stringify(id)};`; + } + + /** + * @param {Dependency[]} dependencies dependencies + * @param {ModuleId} id module id + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {string} source code + */ + getWeakSyncSource(dependencies, id, chunkGraph) { + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackContext(req) { + var id = webpackContextResolve(req); + if(!${RuntimeGlobals.moduleFactories}[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + ${returnModuleObject} +} +function webpackContextResolve(req) { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +webpackContext.id = ${JSON.stringify(id)}; +module.exports = webpackContext;`; + } + + /** + * @param {Dependency[]} dependencies dependencies + * @param {ModuleId} id module id + * @param {object} context context + * @param {ChunkGraph} context.chunkGraph the chunk graph + * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph + * @returns {string} source code + */ + getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) { + const arrow = runtimeTemplate.supportsArrowFunction(); + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true); + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${ + arrow ? "id =>" : "function(id)" + } { + if(!${RuntimeGlobals.moduleFactories}[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + ${returnModuleObject} + }); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + /** + * @param {Dependency[]} dependencies dependencies + * @param {ModuleId} id module id + * @param {object} context context + * @param {ChunkGraph} context.chunkGraph the chunk graph + * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph + * @returns {string} source code + */ + getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) { + const arrow = runtimeTemplate.supportsArrowFunction(); + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const thenFunction = + fakeMap !== 9 + ? `${arrow ? "id =>" : "function(id)"} { + ${this.getReturnModuleObjectSource(fakeMap, true)} + }` + : RuntimeGlobals.require; + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + /** + * @param {AsyncDependenciesBlock} block block + * @param {Dependency[]} dependencies dependencies + * @param {ModuleId} id module id + * @param {object} options options object + * @param {RuntimeTemplate} options.runtimeTemplate the runtime template + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @returns {string} source code + */ + getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) { + const promise = runtimeTemplate.blockPromise({ + chunkGraph, + block, + message: "lazy-once context", + runtimeRequirements: new Set() + }); + const arrow = runtimeTemplate.supportsArrowFunction(); + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const thenFunction = + fakeMap !== 9 + ? `${arrow ? "id =>" : "function(id)"} { + ${this.getReturnModuleObjectSource(fakeMap, true)}; + }` + : RuntimeGlobals.require; + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + return ${promise}.then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + /** + * @param {AsyncDependenciesBlock[]} blocks blocks + * @param {ModuleId} id module id + * @param {object} context context + * @param {ChunkGraph} context.chunkGraph the chunk graph + * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph + * @returns {string} source code + */ + getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) { + const moduleGraph = chunkGraph.moduleGraph; + const arrow = runtimeTemplate.supportsArrowFunction(); + let hasMultipleOrNoChunks = false; + let hasNoChunk = true; + const fakeMap = this.getFakeMap( + blocks.map((b) => b.dependencies[0]), + chunkGraph + ); + const hasFakeMap = typeof fakeMap === "object"; + /** @typedef {{userRequest: string, dependency: ContextElementDependency, chunks: undefined | Chunk[], module: Module, block: AsyncDependenciesBlock}} Item */ + /** + * @type {Item[]} + */ + const items = blocks + .map((block) => { + const dependency = + /** @type {ContextElementDependency} */ + (block.dependencies[0]); + return { + dependency, + module: /** @type {Module} */ (moduleGraph.getModule(dependency)), + block, + userRequest: dependency.userRequest, + chunks: undefined + }; + }) + .filter((item) => item.module); + for (const item of items) { + const chunkGroup = chunkGraph.getBlockChunkGroup(item.block); + const chunks = (chunkGroup && chunkGroup.chunks) || []; + item.chunks = chunks; + if (chunks.length > 0) { + hasNoChunk = false; + } + if (chunks.length !== 1) { + hasMultipleOrNoChunks = true; + } + } + const shortMode = hasNoChunk && !hasFakeMap; + const sortedItems = items.sort((a, b) => { + if (a.userRequest === b.userRequest) return 0; + return a.userRequest < b.userRequest ? -1 : 1; + }); + /** @type {Record} */ + const map = Object.create(null); + for (const item of sortedItems) { + const moduleId = + /** @type {ModuleId} */ + (chunkGraph.getModuleId(item.module)); + if (shortMode) { + map[item.userRequest] = moduleId; + } else { + /** @type {(ModuleId | ChunkId)[]} */ + const arrayStart = [moduleId]; + if (hasFakeMap) { + arrayStart.push(fakeMap[moduleId]); + } + map[item.userRequest] = [ + ...arrayStart, + .../** @type {Chunk[]} */ + (item.chunks).map((chunk) => /** @type {ChunkId} */ (chunk.id)) + ]; + } + } + + const chunksStartPosition = hasFakeMap ? 2 : 1; + const requestPrefix = hasNoChunk + ? "Promise.resolve()" + : hasMultipleOrNoChunks + ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))` + : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`; + const returnModuleObject = this.getReturnModuleObjectSource( + fakeMap, + true, + shortMode ? "invalid" : "ids[1]" + ); + + const webpackAsyncContext = + requestPrefix === "Promise.resolve()" + ? ` +function webpackAsyncContext(req) { + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + + ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"} + ${returnModuleObject} + }); +}` + : `function webpackAsyncContext(req) { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); + } + + var ids = map[req], id = ids[0]; + return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} { + ${returnModuleObject} + }); +}`; + + return `var map = ${JSON.stringify(map, null, "\t")}; +${webpackAsyncContext} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + /** + * @param {ModuleId} id module id + * @param {RuntimeTemplate} runtimeTemplate runtime template + * @returns {string} source for empty async context + */ + getSourceForEmptyContext(id, runtimeTemplate) { + return `function webpackEmptyContext(req) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; +} +webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")}; +webpackEmptyContext.resolve = webpackEmptyContext; +webpackEmptyContext.id = ${JSON.stringify(id)}; +module.exports = webpackEmptyContext;`; + } + + /** + * @param {ModuleId} id module id + * @param {RuntimeTemplate} runtimeTemplate runtime template + * @returns {string} source for empty async context + */ + getSourceForEmptyAsyncContext(id, runtimeTemplate) { + const arrow = runtimeTemplate.supportsArrowFunction(); + return `function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")}; +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackEmptyAsyncContext;`; + } + + /** + * @param {string} asyncMode module mode + * @param {CodeGenerationContext} context context info + * @returns {string} the source code + */ + getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) { + const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(this)); + if (asyncMode === "lazy") { + if (this.blocks && this.blocks.length > 0) { + return this.getLazySource(this.blocks, id, { + runtimeTemplate, + chunkGraph + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); + } + if (asyncMode === "eager") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getEagerSource(this.dependencies, id, { + chunkGraph, + runtimeTemplate + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); + } + if (asyncMode === "lazy-once") { + const block = this.blocks[0]; + if (block) { + return this.getLazyOnceSource(block, block.dependencies, id, { + runtimeTemplate, + chunkGraph + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); + } + if (asyncMode === "async-weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getAsyncWeakSource(this.dependencies, id, { + chunkGraph, + runtimeTemplate + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); + } + if ( + asyncMode === "weak" && + this.dependencies && + this.dependencies.length > 0 + ) { + return this.getWeakSyncSource(this.dependencies, id, chunkGraph); + } + if (this.dependencies && this.dependencies.length > 0) { + return this.getSyncSource(this.dependencies, id, chunkGraph); + } + return this.getSourceForEmptyContext(id, runtimeTemplate); + } + + /** + * @param {string} sourceString source content + * @param {Compilation=} compilation the compilation + * @returns {Source} generated source + */ + getSource(sourceString, compilation) { + if (this.useSourceMap || this.useSimpleSourceMap) { + return new OriginalSource( + sourceString, + `webpack://${makePathsRelative( + (compilation && compilation.compiler.context) || "", + this.identifier(), + compilation && compilation.compiler.root + )}` + ); + } + return new RawSource(sourceString); + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + const { chunkGraph, compilation } = context; + const sources = new Map(); + sources.set( + "javascript", + this.getSource( + this.getSourceString(this.options.mode, context), + compilation + ) + ); + const set = new Set(); + const allDeps = + this.dependencies.length > 0 + ? /** @type {ContextElementDependency[]} */ [...this.dependencies] + : []; + for (const block of this.blocks) { + for (const dep of block.dependencies) { + allDeps.push(/** @type {ContextElementDependency} */ (dep)); + } + } + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.hasOwnProperty); + if (allDeps.length > 0) { + const asyncMode = this.options.mode; + set.add(RuntimeGlobals.require); + if (asyncMode === "weak") { + set.add(RuntimeGlobals.moduleFactories); + } else if (asyncMode === "async-weak") { + set.add(RuntimeGlobals.moduleFactories); + set.add(RuntimeGlobals.ensureChunk); + } else if (asyncMode === "lazy" || asyncMode === "lazy-once") { + set.add(RuntimeGlobals.ensureChunk); + } + if (this.getFakeMap(allDeps, chunkGraph) !== 9) { + set.add(RuntimeGlobals.createFakeNamespaceObject); + } + } + return { + sources, + runtimeRequirements: set + }; + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + // base penalty + let size = 160; + + // if we don't have dependencies we stop here. + for (const dependency of this.dependencies) { + const element = /** @type {ContextElementDependency} */ (dependency); + size += 5 + element.userRequest.length; + } + return size; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this._identifier); + write(this._forceBuild); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this._identifier = read(); + this._forceBuild = read(); + super.deserialize(context); + } +} + +makeSerializable(ContextModule, "webpack/lib/ContextModule"); + +module.exports = ContextModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextModuleFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextModuleFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..03e9b3e3a2d0b9858ae243d1b9e6b14f50168c9d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextModuleFactory.js @@ -0,0 +1,481 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const asyncLib = require("neo-async"); +const { AsyncSeriesWaterfallHook, SyncWaterfallHook } = require("tapable"); +const ContextModule = require("./ContextModule"); +const ModuleFactory = require("./ModuleFactory"); +const ContextElementDependency = require("./dependencies/ContextElementDependency"); +const LazySet = require("./util/LazySet"); +const { cachedSetProperty } = require("./util/cleverMerge"); +const { createFakeHook } = require("./util/deprecation"); +const { join } = require("./util/fs"); + +/** @typedef {import("./ContextModule").ContextModuleOptions} ContextModuleOptions */ +/** @typedef {import("./ContextModule").ResolveDependenciesCallback} ResolveDependenciesCallback */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("./ResolverFactory")} ResolverFactory */ +/** @typedef {import("./dependencies/ContextDependency")} ContextDependency */ +/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */ +/** + * @template T + * @typedef {import("./util/deprecation").FakeHook} FakeHook + */ +/** @typedef {import("./util/fs").IStats} IStats */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {{ context: string, request: string }} ContextAlternativeRequest */ + +const EMPTY_RESOLVE_OPTIONS = {}; + +module.exports = class ContextModuleFactory extends ModuleFactory { + /** + * @param {ResolverFactory} resolverFactory resolverFactory + */ + constructor(resolverFactory) { + super(); + /** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[], ContextModuleOptions]>} */ + const alternativeRequests = new AsyncSeriesWaterfallHook([ + "modules", + "options" + ]); + this.hooks = Object.freeze({ + /** @type {AsyncSeriesWaterfallHook<[TODO]>} */ + beforeResolve: new AsyncSeriesWaterfallHook(["data"]), + /** @type {AsyncSeriesWaterfallHook<[TODO]>} */ + afterResolve: new AsyncSeriesWaterfallHook(["data"]), + /** @type {SyncWaterfallHook<[string[]]>} */ + contextModuleFiles: new SyncWaterfallHook(["files"]), + /** @type {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">>} */ + alternatives: createFakeHook( + { + name: "alternatives", + /** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["intercept"]} */ + intercept: (interceptor) => { + throw new Error( + "Intercepting fake hook ContextModuleFactory.hooks.alternatives is not possible, use ContextModuleFactory.hooks.alternativeRequests instead" + ); + }, + /** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tap"]} */ + tap: (options, fn) => { + alternativeRequests.tap(options, fn); + }, + /** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tapAsync"]} */ + tapAsync: (options, fn) => { + alternativeRequests.tapAsync(options, (items, _options, callback) => + fn(items, callback) + ); + }, + /** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tapPromise"]} */ + tapPromise: (options, fn) => { + alternativeRequests.tapPromise(options, fn); + } + }, + "ContextModuleFactory.hooks.alternatives has deprecated in favor of ContextModuleFactory.hooks.alternativeRequests with an additional options argument.", + "DEP_WEBPACK_CONTEXT_MODULE_FACTORY_ALTERNATIVES" + ), + alternativeRequests + }); + this.resolverFactory = resolverFactory; + } + + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create(data, callback) { + const context = data.context; + const dependencies = data.dependencies; + const resolveOptions = data.resolveOptions; + const dependency = /** @type {ContextDependency} */ (dependencies[0]); + const fileDependencies = new LazySet(); + const missingDependencies = new LazySet(); + const contextDependencies = new LazySet(); + this.hooks.beforeResolve.callAsync( + { + context, + dependencies, + layer: data.contextInfo.issuerLayer, + resolveOptions, + fileDependencies, + missingDependencies, + contextDependencies, + ...dependency.options + }, + (err, beforeResolveResult) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies + }); + } + + // Ignored + if (!beforeResolveResult) { + return callback(null, { + fileDependencies, + missingDependencies, + contextDependencies + }); + } + + const context = beforeResolveResult.context; + const request = beforeResolveResult.request; + const resolveOptions = beforeResolveResult.resolveOptions; + + let loaders; + let resource; + let loadersPrefix = ""; + const idx = request.lastIndexOf("!"); + if (idx >= 0) { + let loadersRequest = request.slice(0, idx + 1); + let i; + for ( + i = 0; + i < loadersRequest.length && loadersRequest[i] === "!"; + i++ + ) { + loadersPrefix += "!"; + } + loadersRequest = loadersRequest + .slice(i) + .replace(/!+$/, "") + .replace(/!!+/g, "!"); + loaders = loadersRequest === "" ? [] : loadersRequest.split("!"); + resource = request.slice(idx + 1); + } else { + loaders = []; + resource = request; + } + + const contextResolver = this.resolverFactory.get( + "context", + dependencies.length > 0 + ? cachedSetProperty( + resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + dependencies[0].category + ) + : resolveOptions + ); + const loaderResolver = this.resolverFactory.get("loader"); + + asyncLib.parallel( + [ + (callback) => { + const results = /** @type ResolveRequest[] */ ([]); + /** + * @param {ResolveRequest} obj obj + * @returns {void} + */ + const yield_ = (obj) => { + results.push(obj); + }; + + contextResolver.resolve( + {}, + context, + resource, + { + fileDependencies, + missingDependencies, + contextDependencies, + yield: yield_ + }, + (err) => { + if (err) return callback(err); + callback(null, results); + } + ); + }, + (callback) => { + asyncLib.map( + loaders, + (loader, callback) => { + loaderResolver.resolve( + {}, + context, + loader, + { + fileDependencies, + missingDependencies, + contextDependencies + }, + (err, result) => { + if (err) return callback(err); + callback(null, /** @type {string} */ (result)); + } + ); + }, + callback + ); + } + ], + (err, result) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies + }); + } + let [contextResult, loaderResult] = + /** @type {[ResolveRequest[], string[]]} */ (result); + if (contextResult.length > 1) { + const first = contextResult[0]; + contextResult = contextResult.filter((r) => r.path); + if (contextResult.length === 0) contextResult.push(first); + } + this.hooks.afterResolve.callAsync( + { + addon: + loadersPrefix + + loaderResult.join("!") + + (loaderResult.length > 0 ? "!" : ""), + resource: + contextResult.length > 1 + ? contextResult.map((r) => r.path) + : contextResult[0].path, + resolveDependencies: this.resolveDependencies.bind(this), + resourceQuery: contextResult[0].query, + resourceFragment: contextResult[0].fragment, + ...beforeResolveResult + }, + (err, result) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies + }); + } + + // Ignored + if (!result) { + return callback(null, { + fileDependencies, + missingDependencies, + contextDependencies + }); + } + + return callback(null, { + module: new ContextModule(result.resolveDependencies, result), + fileDependencies, + missingDependencies, + contextDependencies + }); + } + ); + } + ); + } + ); + } + + /** + * @param {InputFileSystem} fs file system + * @param {ContextModuleOptions} options options + * @param {ResolveDependenciesCallback} callback callback function + * @returns {void} + */ + resolveDependencies(fs, options, callback) { + const cmf = this; + const { + resource, + resourceQuery, + resourceFragment, + recursive, + regExp, + include, + exclude, + referencedExports, + category, + typePrefix, + attributes + } = options; + if (!regExp || !resource) return callback(null, []); + + /** + * @param {string} ctx context + * @param {string} directory directory + * @param {Set} visited visited + * @param {ResolveDependenciesCallback} callback callback + */ + const addDirectoryChecked = (ctx, directory, visited, callback) => { + /** @type {NonNullable} */ + (fs.realpath)(directory, (err, _realPath) => { + if (err) return callback(err); + const realPath = /** @type {string} */ (_realPath); + if (visited.has(realPath)) return callback(null, []); + /** @type {Set | undefined} */ + let recursionStack; + addDirectory( + ctx, + directory, + (_, dir, callback) => { + if (recursionStack === undefined) { + recursionStack = new Set(visited); + recursionStack.add(realPath); + } + addDirectoryChecked(ctx, dir, recursionStack, callback); + }, + callback + ); + }); + }; + + /** + * @param {string} ctx context + * @param {string} directory directory + * @param {(context: string, subResource: string, callback: () => void) => void} addSubDirectory addSubDirectoryFn + * @param {ResolveDependenciesCallback} callback callback + */ + const addDirectory = (ctx, directory, addSubDirectory, callback) => { + fs.readdir(directory, (err, files) => { + if (err) return callback(err); + const processedFiles = cmf.hooks.contextModuleFiles.call( + /** @type {string[]} */ (files).map((file) => file.normalize("NFC")) + ); + if (!processedFiles || processedFiles.length === 0) { + return callback(null, []); + } + asyncLib.map( + processedFiles.filter((p) => p.indexOf(".") !== 0), + (segment, callback) => { + const subResource = join(fs, directory, segment); + + if (!exclude || !exclude.test(subResource)) { + fs.stat(subResource, (err, _stat) => { + if (err) { + if (err.code === "ENOENT") { + // ENOENT is ok here because the file may have been deleted between + // the readdir and stat calls. + return callback(); + } + return callback(err); + } + + const stat = /** @type {IStats} */ (_stat); + + if (stat.isDirectory()) { + if (!recursive) return callback(); + addSubDirectory(ctx, subResource, callback); + } else if ( + stat.isFile() && + (!include || include.test(subResource)) + ) { + /** @type {{ context: string, request: string }} */ + const obj = { + context: ctx, + request: `.${subResource.slice(ctx.length).replace(/\\/g, "/")}` + }; + + this.hooks.alternativeRequests.callAsync( + [obj], + options, + (err, alternatives) => { + if (err) return callback(err); + callback( + null, + /** @type {ContextAlternativeRequest[]} */ + (alternatives) + .filter((obj) => + regExp.test(/** @type {string} */ (obj.request)) + ) + .map((obj) => { + const dep = new ContextElementDependency( + `${obj.request}${resourceQuery}${resourceFragment}`, + obj.request, + typePrefix, + /** @type {string} */ + (category), + referencedExports, + obj.context, + attributes + ); + dep.optional = true; + return dep; + }) + ); + } + ); + } else { + callback(); + } + }); + } else { + callback(); + } + }, + (err, result) => { + if (err) return callback(err); + + if (!result) return callback(null, []); + + const flattenedResult = []; + + for (const item of result) { + if (item) flattenedResult.push(...item); + } + + callback(null, flattenedResult); + } + ); + }); + }; + + /** + * @param {string} ctx context + * @param {string} dir dir + * @param {ResolveDependenciesCallback} callback callback + * @returns {void} + */ + const addSubDirectory = (ctx, dir, callback) => + addDirectory(ctx, dir, addSubDirectory, callback); + + /** + * @param {string} resource resource + * @param {ResolveDependenciesCallback} callback callback + */ + const visitResource = (resource, callback) => { + if (typeof fs.realpath === "function") { + addDirectoryChecked(resource, resource, new Set(), callback); + } else { + addDirectory(resource, resource, addSubDirectory, callback); + } + }; + + if (typeof resource === "string") { + visitResource(resource, callback); + } else { + asyncLib.map(resource, visitResource, (err, _result) => { + if (err) return callback(err); + const result = /** @type {ContextElementDependency[][]} */ (_result); + + // result dependencies should have unique userRequest + // ordered by resolve result + /** @type {Set} */ + const temp = new Set(); + /** @type {ContextElementDependency[]} */ + const res = []; + for (let i = 0; i < result.length; i++) { + const inner = result[i]; + for (const el of inner) { + if (temp.has(el.userRequest)) continue; + res.push(el); + temp.add(el.userRequest); + } + } + callback(null, res); + }); + } + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextReplacementPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextReplacementPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..76188c29cd1bbf351d11a3ec94d4c1cbc87f8881 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ContextReplacementPlugin.js @@ -0,0 +1,204 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ContextElementDependency = require("./dependencies/ContextElementDependency"); +const { join } = require("./util/fs"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./ContextModule").ContextModuleOptions} ContextModuleOptions */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +/** @typedef {Record} NewContentCreateContextMap */ + +const PLUGIN_NAME = "ContextReplacementPlugin"; + +class ContextReplacementPlugin { + /** + * @param {RegExp} resourceRegExp A regular expression that determines which files will be selected + * @param {(string | ((context: TODO) => void) | RegExp | boolean)=} newContentResource A new resource to replace the match + * @param {(boolean | NewContentCreateContextMap | RegExp)=} newContentRecursive If true, all subdirectories are searched for matches + * @param {RegExp=} newContentRegExp A regular expression that determines which files will be selected + */ + constructor( + resourceRegExp, + newContentResource, + newContentRecursive, + newContentRegExp + ) { + this.resourceRegExp = resourceRegExp; + + // new webpack.ContextReplacementPlugin(/selector/, (context) => { /* Logic */ }); + if (typeof newContentResource === "function") { + this.newContentCallback = newContentResource; + } + // new ContextReplacementPlugin(/selector/, './folder', { './request': './request' }); + else if ( + typeof newContentResource === "string" && + typeof newContentRecursive === "object" + ) { + this.newContentResource = newContentResource; + /** + * @param {InputFileSystem} fs input file system + * @param {(err: null | Error, newContentRecursive: NewContentCreateContextMap) => void} callback callback + */ + this.newContentCreateContextMap = (fs, callback) => { + callback( + null, + /** @type {NewContentCreateContextMap} */ (newContentRecursive) + ); + }; + } + // new ContextReplacementPlugin(/selector/, './folder', (context) => { /* Logic */ }); + else if ( + typeof newContentResource === "string" && + typeof newContentRecursive === "function" + ) { + this.newContentResource = newContentResource; + this.newContentCreateContextMap = newContentRecursive; + } else { + // new webpack.ContextReplacementPlugin(/selector/, false, /reg-exp/); + if (typeof newContentResource !== "string") { + newContentRegExp = /** @type {RegExp} */ (newContentRecursive); + newContentRecursive = /** @type {boolean} */ (newContentResource); + newContentResource = undefined; + } + // new webpack.ContextReplacementPlugin(/selector/, /de|fr|hu/); + if (typeof newContentRecursive !== "boolean") { + newContentRegExp = /** @type {RegExp} */ (newContentRecursive); + newContentRecursive = undefined; + } + // new webpack.ContextReplacementPlugin(/selector/, './folder', false, /selector/); + this.newContentResource = + /** @type {string | undefined} */ + (newContentResource); + this.newContentRecursive = + /** @type {boolean | undefined} */ + (newContentRecursive); + this.newContentRegExp = + /** @type {RegExp | undefined} */ + (newContentRegExp); + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const resourceRegExp = this.resourceRegExp; + const newContentCallback = this.newContentCallback; + const newContentResource = this.newContentResource; + const newContentRecursive = this.newContentRecursive; + const newContentRegExp = this.newContentRegExp; + const newContentCreateContextMap = this.newContentCreateContextMap; + + compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, (cmf) => { + cmf.hooks.beforeResolve.tap(PLUGIN_NAME, (result) => { + if (!result) return; + if (resourceRegExp.test(result.request)) { + if (newContentResource !== undefined) { + result.request = newContentResource; + } + if (newContentRecursive !== undefined) { + result.recursive = newContentRecursive; + } + if (newContentRegExp !== undefined) { + result.regExp = newContentRegExp; + } + if (typeof newContentCallback === "function") { + newContentCallback(result); + } else { + for (const d of result.dependencies) { + if (d.critical) d.critical = false; + } + } + } + return result; + }); + cmf.hooks.afterResolve.tap(PLUGIN_NAME, (result) => { + if (!result) return; + if (resourceRegExp.test(result.resource)) { + if (newContentResource !== undefined) { + if ( + newContentResource.startsWith("/") || + (newContentResource.length > 1 && newContentResource[1] === ":") + ) { + result.resource = newContentResource; + } else { + result.resource = join( + /** @type {InputFileSystem} */ + (compiler.inputFileSystem), + result.resource, + newContentResource + ); + } + } + if (newContentRecursive !== undefined) { + result.recursive = newContentRecursive; + } + if (newContentRegExp !== undefined) { + result.regExp = newContentRegExp; + } + if (typeof newContentCreateContextMap === "function") { + result.resolveDependencies = + createResolveDependenciesFromContextMap( + newContentCreateContextMap + ); + } + if (typeof newContentCallback === "function") { + const origResource = result.resource; + newContentCallback(result); + if ( + result.resource !== origResource && + !result.resource.startsWith("/") && + (result.resource.length <= 1 || result.resource[1] !== ":") + ) { + // When the function changed it to an relative path + result.resource = join( + /** @type {InputFileSystem} */ + (compiler.inputFileSystem), + origResource, + result.resource + ); + } + } else { + for (const d of result.dependencies) { + if (d.critical) d.critical = false; + } + } + } + return result; + }); + }); + } +} + +/** + * @param {(fs: InputFileSystem, callback: (err: null | Error, map: NewContentCreateContextMap) => void) => void} createContextMap create context map function + * @returns {(fs: InputFileSystem, options: ContextModuleOptions, callback: (err: null | Error, dependencies?: ContextElementDependency[]) => void) => void} resolve resolve dependencies from context map function + */ +const createResolveDependenciesFromContextMap = + (createContextMap) => (fs, options, callback) => { + createContextMap(fs, (err, map) => { + if (err) return callback(err); + const dependencies = Object.keys(map).map( + (key) => + new ContextElementDependency( + map[key] + options.resourceQuery + options.resourceFragment, + key, + options.typePrefix, + /** @type {string} */ + (options.category), + options.referencedExports + ) + ); + callback(null, dependencies); + }); + }; + +module.exports = ContextReplacementPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CssModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CssModule.js new file mode 100644 index 0000000000000000000000000000000000000000..90095c505a19d9080d36bd5279cb5f0f1552f91c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/CssModule.js @@ -0,0 +1,174 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Alexander Akait @alexander-akait +*/ + +"use strict"; + +const NormalModule = require("./NormalModule"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./NormalModule").NormalModuleCreateData} NormalModuleCreateData */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** @typedef {string | undefined} CssLayer */ +/** @typedef {string | undefined} Supports */ +/** @typedef {string | undefined} Media */ +/** @typedef {[CssLayer, Supports, Media]} InheritanceItem */ +/** @typedef {InheritanceItem[]} Inheritance */ + +/** @typedef {NormalModuleCreateData & { cssLayer: CssLayer, supports: Supports, media: Media, inheritance?: Inheritance }} CSSModuleCreateData */ + +class CssModule extends NormalModule { + /** + * @param {CSSModuleCreateData} options options object + */ + constructor(options) { + super(options); + + // Avoid override `layer` for `Module` class, because it is a feature to run module in specific layer + this.cssLayer = options.cssLayer; + this.supports = options.supports; + this.media = options.media; + this.inheritance = options.inheritance; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + let identifier = super.identifier(); + + if (this.cssLayer) { + identifier += `|${this.cssLayer}`; + } + + if (this.supports) { + identifier += `|${this.supports}`; + } + + if (this.media) { + identifier += `|${this.media}`; + } + + if (this.inheritance) { + const inheritance = this.inheritance.map( + (item, index) => + `inheritance_${index}|${item[0] || ""}|${item[1] || ""}|${ + item[2] || "" + }` + ); + + identifier += `|${inheritance.join("|")}`; + } + + // We generate extra code for HMR, so we need to invalidate the module + if (this.hot) { + identifier += `|${this.hot}`; + } + + return identifier; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + const readableIdentifier = super.readableIdentifier(requestShortener); + + let identifier = `css ${readableIdentifier}`; + + if (this.cssLayer) { + identifier += ` (layer: ${this.cssLayer})`; + } + + if (this.supports) { + identifier += ` (supports: ${this.supports})`; + } + + if (this.media) { + identifier += ` (media: ${this.media})`; + } + + return identifier; + } + + /** + * Assuming this module is in the cache. Update the (cached) module with + * the fresh module from the factory. Usually updates internal references + * and properties. + * @param {Module} module fresh module + * @returns {void} + */ + updateCacheModule(module) { + super.updateCacheModule(module); + const m = /** @type {CssModule} */ (module); + this.cssLayer = m.cssLayer; + this.supports = m.supports; + this.media = m.media; + this.inheritance = m.inheritance; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.cssLayer); + write(this.supports); + write(this.media); + write(this.inheritance); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {CssModule} the deserialized object + */ + static deserialize(context) { + const obj = new CssModule({ + // will be deserialized by Module + layer: /** @type {EXPECTED_ANY} */ (null), + type: "", + // will be filled by updateCacheModule + resource: "", + context: "", + request: /** @type {EXPECTED_ANY} */ (null), + userRequest: /** @type {EXPECTED_ANY} */ (null), + rawRequest: /** @type {EXPECTED_ANY} */ (null), + loaders: /** @type {EXPECTED_ANY} */ (null), + matchResource: /** @type {EXPECTED_ANY} */ (null), + parser: /** @type {EXPECTED_ANY} */ (null), + parserOptions: /** @type {EXPECTED_ANY} */ (null), + generator: /** @type {EXPECTED_ANY} */ (null), + generatorOptions: /** @type {EXPECTED_ANY} */ (null), + resolveOptions: /** @type {EXPECTED_ANY} */ (null), + cssLayer: /** @type {EXPECTED_ANY} */ (null), + supports: /** @type {EXPECTED_ANY} */ (null), + media: /** @type {EXPECTED_ANY} */ (null), + inheritance: /** @type {EXPECTED_ANY} */ (null) + }); + obj.deserialize(context); + return obj; + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.cssLayer = read(); + this.supports = read(); + this.media = read(); + this.inheritance = read(); + super.deserialize(context); + } +} + +makeSerializable(CssModule, "webpack/lib/CssModule"); + +module.exports = CssModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DefinePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DefinePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b3270f75d67ef3e80e6ae2eef1d81370b06ecb33 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DefinePlugin.js @@ -0,0 +1,844 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const WebpackError = require("./WebpackError"); +const ConstDependency = require("./dependencies/ConstDependency"); +const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression"); +const { VariableInfo } = require("./javascript/JavascriptParser"); +const { + evaluateToString, + toConstantDependency +} = require("./javascript/JavascriptParserHelpers"); +const createHash = require("./util/createHash"); + +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */ +/** @typedef {import("./NormalModule")} NormalModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ +/** @typedef {import("./logging/Logger").Logger} Logger */ + +/** @typedef {null | undefined | RegExp | EXPECTED_FUNCTION | string | number | boolean | bigint | undefined} CodeValuePrimitive */ +/** @typedef {RecursiveArrayOrRecord} CodeValue */ + +/** + * @typedef {object} RuntimeValueOptions + * @property {string[]=} fileDependencies + * @property {string[]=} contextDependencies + * @property {string[]=} missingDependencies + * @property {string[]=} buildDependencies + * @property {string| (() => string)=} version + */ + +/** @typedef {string | Set} ValueCacheVersion */ +/** @typedef {(value: { module: NormalModule, key: string, readonly version: ValueCacheVersion }) => CodeValuePrimitive} GeneratorFn */ + +class RuntimeValue { + /** + * @param {GeneratorFn} fn generator function + * @param {true | string[] | RuntimeValueOptions=} options options + */ + constructor(fn, options) { + this.fn = fn; + if (Array.isArray(options)) { + options = { + fileDependencies: options + }; + } + this.options = options || {}; + } + + get fileDependencies() { + return this.options === true ? true : this.options.fileDependencies; + } + + /** + * @param {JavascriptParser} parser the parser + * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions + * @param {string} key the defined key + * @returns {CodeValuePrimitive} code + */ + exec(parser, valueCacheVersions, key) { + const buildInfo = /** @type {BuildInfo} */ (parser.state.module.buildInfo); + if (this.options === true) { + buildInfo.cacheable = false; + } else { + if (this.options.fileDependencies) { + for (const dep of this.options.fileDependencies) { + /** @type {NonNullable} */ + (buildInfo.fileDependencies).add(dep); + } + } + if (this.options.contextDependencies) { + for (const dep of this.options.contextDependencies) { + /** @type {NonNullable} */ + (buildInfo.contextDependencies).add(dep); + } + } + if (this.options.missingDependencies) { + for (const dep of this.options.missingDependencies) { + /** @type {NonNullable} */ + (buildInfo.missingDependencies).add(dep); + } + } + if (this.options.buildDependencies) { + for (const dep of this.options.buildDependencies) { + /** @type {NonNullable} */ + (buildInfo.buildDependencies).add(dep); + } + } + } + + return this.fn({ + module: parser.state.module, + key, + get version() { + return /** @type {ValueCacheVersion} */ ( + valueCacheVersions.get(VALUE_DEP_PREFIX + key) + ); + } + }); + } + + getCacheVersion() { + return this.options === true + ? undefined + : (typeof this.options.version === "function" + ? this.options.version() + : this.options.version) || "unset"; + } +} + +/** + * @param {Set | undefined} properties properties + * @returns {Set | undefined} used keys + */ +function getObjKeys(properties) { + if (!properties) return; + return new Set([...properties].map((p) => p.id)); +} + +/** @typedef {Set | null} ObjKeys */ +/** @typedef {boolean | undefined | null} AsiSafe */ + +/** + * @param {EXPECTED_ANY[] | {[k: string]: EXPECTED_ANY}} obj obj + * @param {JavascriptParser} parser Parser + * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions + * @param {string} key the defined key + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Logger} logger the logger object + * @param {AsiSafe=} asiSafe asi safe (undefined: unknown, null: unneeded) + * @param {ObjKeys=} objKeys used keys + * @returns {string} code converted to string that evaluates + */ +const stringifyObj = ( + obj, + parser, + valueCacheVersions, + key, + runtimeTemplate, + logger, + asiSafe, + objKeys +) => { + let code; + const arr = Array.isArray(obj); + if (arr) { + code = `[${obj + .map((code) => + toCode( + code, + parser, + valueCacheVersions, + key, + runtimeTemplate, + logger, + null + ) + ) + .join(",")}]`; + } else { + let keys = Object.keys(obj); + if (objKeys) { + keys = objKeys.size === 0 ? [] : keys.filter((k) => objKeys.has(k)); + } + code = `{${keys + .map((key) => { + const code = obj[key]; + return `${JSON.stringify(key)}:${toCode( + code, + parser, + valueCacheVersions, + key, + runtimeTemplate, + logger, + null + )}`; + }) + .join(",")}}`; + } + + switch (asiSafe) { + case null: + return code; + case true: + return arr ? code : `(${code})`; + case false: + return arr ? `;${code}` : `;(${code})`; + default: + return `/*#__PURE__*/Object(${code})`; + } +}; + +/** + * Convert code to a string that evaluates + * @param {CodeValue} code Code to evaluate + * @param {JavascriptParser} parser Parser + * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions + * @param {string} key the defined key + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Logger} logger the logger object + * @param {boolean | undefined | null=} asiSafe asi safe (undefined: unknown, null: unneeded) + * @param {ObjKeys=} objKeys used keys + * @returns {string} code converted to string that evaluates + */ +const toCode = ( + code, + parser, + valueCacheVersions, + key, + runtimeTemplate, + logger, + asiSafe, + objKeys +) => { + const transformToCode = () => { + if (code === null) { + return "null"; + } + if (code === undefined) { + return "undefined"; + } + if (Object.is(code, -0)) { + return "-0"; + } + if (code instanceof RuntimeValue) { + return toCode( + code.exec(parser, valueCacheVersions, key), + parser, + valueCacheVersions, + key, + runtimeTemplate, + logger, + asiSafe + ); + } + if (code instanceof RegExp && code.toString) { + return code.toString(); + } + if (typeof code === "function" && code.toString) { + return `(${code.toString()})`; + } + if (typeof code === "object") { + return stringifyObj( + code, + parser, + valueCacheVersions, + key, + runtimeTemplate, + logger, + asiSafe, + objKeys + ); + } + if (typeof code === "bigint") { + return runtimeTemplate.supportsBigIntLiteral() + ? `${code}n` + : `BigInt("${code}")`; + } + return `${code}`; + }; + + const strCode = transformToCode(); + + logger.debug(`Replaced "${key}" with "${strCode}"`); + + return strCode; +}; + +/** + * @param {CodeValue} code code + * @returns {string | undefined} result + */ +const toCacheVersion = (code) => { + if (code === null) { + return "null"; + } + if (code === undefined) { + return "undefined"; + } + if (Object.is(code, -0)) { + return "-0"; + } + if (code instanceof RuntimeValue) { + return code.getCacheVersion(); + } + if (code instanceof RegExp && code.toString) { + return code.toString(); + } + if (typeof code === "function" && code.toString) { + return `(${code.toString()})`; + } + if (typeof code === "object") { + const items = Object.keys(code).map((key) => ({ + key, + value: toCacheVersion( + /** @type {Record} */ + (code)[key] + ) + })); + if (items.some(({ value }) => value === undefined)) return; + return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`; + } + if (typeof code === "bigint") { + return `${code}n`; + } + return `${code}`; +}; + +const PLUGIN_NAME = "DefinePlugin"; +const VALUE_DEP_PREFIX = `webpack/${PLUGIN_NAME} `; +const VALUE_DEP_MAIN = `webpack/${PLUGIN_NAME}_hash`; +const TYPEOF_OPERATOR_REGEXP = /^typeof\s+/; +const WEBPACK_REQUIRE_FUNCTION_REGEXP = new RegExp( + `${RuntimeGlobals.require}\\s*(!?\\.)` +); +const WEBPACK_REQUIRE_IDENTIFIER_REGEXP = new RegExp(RuntimeGlobals.require); + +class DefinePlugin { + /** + * Create a new define plugin + * @param {Record} definitions A map of global object definitions + */ + constructor(definitions) { + this.definitions = definitions; + } + + /** + * @param {GeneratorFn} fn generator function + * @param {true | string[] | RuntimeValueOptions=} options options + * @returns {RuntimeValue} runtime value + */ + static runtimeValue(fn, options) { + return new RuntimeValue(fn, options); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const definitions = this.definitions; + + /** + * @type {Map>} + */ + const finalByNestedKey = new Map(); + /** + * @type {Map>} + */ + const nestedByFinalKey = new Map(); + + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + const logger = compilation.getLogger("webpack.DefinePlugin"); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const { runtimeTemplate } = compilation; + + const mainHash = createHash( + /** @type {HashFunction} */ + (compilation.outputOptions.hashFunction) + ); + mainHash.update( + /** @type {string} */ + (compilation.valueCacheVersions.get(VALUE_DEP_MAIN)) || "" + ); + + /** + * Handler + * @param {JavascriptParser} parser Parser + * @returns {void} + */ + const handler = (parser) => { + const hooked = new Set(); + const mainValue = + /** @type {ValueCacheVersion} */ + (compilation.valueCacheVersions.get(VALUE_DEP_MAIN)); + parser.hooks.program.tap(PLUGIN_NAME, () => { + const buildInfo = /** @type {BuildInfo} */ ( + parser.state.module.buildInfo + ); + if (!buildInfo.valueDependencies) { + buildInfo.valueDependencies = new Map(); + } + buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue); + }); + + /** + * @param {string} key key + */ + const addValueDependency = (key) => { + const buildInfo = + /** @type {BuildInfo} */ + (parser.state.module.buildInfo); + /** @type {NonNullable} */ + (buildInfo.valueDependencies).set( + VALUE_DEP_PREFIX + key, + /** @type {ValueCacheVersion} */ + (compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)) + ); + }; + + /** + * @template T + * @param {string} key key + * @param {(expression: Expression) => T} fn fn + * @returns {(expression: Expression) => T} result + */ + const withValueDependency = + (key, fn) => + (...args) => { + addValueDependency(key); + return fn(...args); + }; + + /** + * Walk definitions + * @param {Record} definitions Definitions map + * @param {string} prefix Prefix string + * @returns {void} + */ + const walkDefinitions = (definitions, prefix) => { + for (const key of Object.keys(definitions)) { + const code = definitions[key]; + if ( + code && + typeof code === "object" && + !(code instanceof RuntimeValue) && + !(code instanceof RegExp) + ) { + walkDefinitions( + /** @type {Record} */ (code), + `${prefix + key}.` + ); + applyObjectDefine(prefix + key, code); + continue; + } + applyDefineKey(prefix, key); + applyDefine(prefix + key, code); + } + }; + + /** + * Apply define key + * @param {string} prefix Prefix + * @param {string} key Key + * @returns {void} + */ + const applyDefineKey = (prefix, key) => { + const splittedKey = key.split("."); + const firstKey = splittedKey[0]; + for (const [i, _] of splittedKey.slice(1).entries()) { + const fullKey = prefix + splittedKey.slice(0, i + 1).join("."); + parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => { + addValueDependency(key); + if ( + parser.scope.definitions.get(firstKey) instanceof VariableInfo + ) { + return false; + } + return true; + }); + } + if (prefix === "") { + const final = splittedKey[splittedKey.length - 1]; + const nestedSet = nestedByFinalKey.get(final); + if (!nestedSet || nestedSet.size <= 0) return; + for (const nested of /** @type {Set} */ (nestedSet)) { + if (nested && !hooked.has(nested)) { + // only detect the same nested key once + hooked.add(nested); + parser.hooks.collectDestructuringAssignmentProperties.tap( + PLUGIN_NAME, + (expr) => { + const nameInfo = parser.getNameForExpression(expr); + if (nameInfo && nameInfo.name === nested) return true; + } + ); + parser.hooks.expression.for(nested).tap( + { + name: PLUGIN_NAME, + // why 100? Ensures it runs after object define + stage: 100 + }, + (expr) => { + const destructed = + parser.destructuringAssignmentPropertiesFor(expr); + if (destructed === undefined) { + return; + } + /** @type {Record} */ + const obj = {}; + const finalSet = finalByNestedKey.get(nested); + for (const { id } of destructed) { + const fullKey = `${nested}.${id}`; + if ( + !finalSet || + !finalSet.has(id) || + !definitions[fullKey] + ) { + return; + } + obj[id] = definitions[fullKey]; + } + let strCode = stringifyObj( + obj, + parser, + compilation.valueCacheVersions, + key, + runtimeTemplate, + logger, + !parser.isAsiPosition( + /** @type {Range} */ (expr.range)[0] + ), + getObjKeys(destructed) + ); + if (parser.scope.inShorthand) { + strCode = `${parser.scope.inShorthand}:${strCode}`; + } + return toConstantDependency(parser, strCode)(expr); + } + ); + } + } + } + }; + + /** + * Apply Code + * @param {string} key Key + * @param {CodeValue} code Code + * @returns {void} + */ + const applyDefine = (key, code) => { + const originalKey = key; + const isTypeof = TYPEOF_OPERATOR_REGEXP.test(key); + if (isTypeof) key = key.replace(TYPEOF_OPERATOR_REGEXP, ""); + let recurse = false; + let recurseTypeof = false; + if (!isTypeof) { + parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => { + addValueDependency(originalKey); + return true; + }); + parser.hooks.evaluateIdentifier + .for(key) + .tap(PLUGIN_NAME, (expr) => { + /** + * this is needed in case there is a recursion in the DefinePlugin + * to prevent an endless recursion + * e.g.: new DefinePlugin({ + * "a": "b", + * "b": "a" + * }); + */ + if (recurse) return; + addValueDependency(originalKey); + recurse = true; + const res = parser.evaluate( + toCode( + code, + parser, + compilation.valueCacheVersions, + key, + runtimeTemplate, + logger, + null + ) + ); + recurse = false; + res.setRange(/** @type {Range} */ (expr.range)); + return res; + }); + parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => { + addValueDependency(originalKey); + let strCode = toCode( + code, + parser, + compilation.valueCacheVersions, + originalKey, + runtimeTemplate, + logger, + !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]), + null + ); + + if (parser.scope.inShorthand) { + strCode = `${parser.scope.inShorthand}:${strCode}`; + } + + if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) { + return toConstantDependency(parser, strCode, [ + RuntimeGlobals.require + ])(expr); + } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) { + return toConstantDependency(parser, strCode, [ + RuntimeGlobals.requireScope + ])(expr); + } + return toConstantDependency(parser, strCode)(expr); + }); + } + parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, (expr) => { + /** + * this is needed in case there is a recursion in the DefinePlugin + * to prevent an endless recursion + * e.g.: new DefinePlugin({ + * "typeof a": "typeof b", + * "typeof b": "typeof a" + * }); + */ + if (recurseTypeof) return; + recurseTypeof = true; + addValueDependency(originalKey); + const codeCode = toCode( + code, + parser, + compilation.valueCacheVersions, + originalKey, + runtimeTemplate, + logger, + null + ); + const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`; + const res = parser.evaluate(typeofCode); + recurseTypeof = false; + res.setRange(/** @type {Range} */ (expr.range)); + return res; + }); + parser.hooks.typeof.for(key).tap(PLUGIN_NAME, (expr) => { + addValueDependency(originalKey); + const codeCode = toCode( + code, + parser, + compilation.valueCacheVersions, + originalKey, + runtimeTemplate, + logger, + null + ); + const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`; + const res = parser.evaluate(typeofCode); + if (!res.isString()) return; + return toConstantDependency( + parser, + JSON.stringify(res.string) + ).bind(parser)(expr); + }); + }; + + /** + * Apply Object + * @param {string} key Key + * @param {object} obj Object + * @returns {void} + */ + const applyObjectDefine = (key, obj) => { + parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => { + addValueDependency(key); + return true; + }); + parser.hooks.evaluateIdentifier + .for(key) + .tap(PLUGIN_NAME, (expr) => { + addValueDependency(key); + return new BasicEvaluatedExpression() + .setTruthy() + .setSideEffects(false) + .setRange(/** @type {Range} */ (expr.range)); + }); + parser.hooks.evaluateTypeof + .for(key) + .tap( + PLUGIN_NAME, + withValueDependency(key, evaluateToString("object")) + ); + parser.hooks.collectDestructuringAssignmentProperties.tap( + PLUGIN_NAME, + (expr) => { + const nameInfo = parser.getNameForExpression(expr); + if (nameInfo && nameInfo.name === key) return true; + } + ); + parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => { + addValueDependency(key); + let strCode = stringifyObj( + obj, + parser, + compilation.valueCacheVersions, + key, + runtimeTemplate, + logger, + !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]), + getObjKeys(parser.destructuringAssignmentPropertiesFor(expr)) + ); + + if (parser.scope.inShorthand) { + strCode = `${parser.scope.inShorthand}:${strCode}`; + } + + if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) { + return toConstantDependency(parser, strCode, [ + RuntimeGlobals.require + ])(expr); + } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) { + return toConstantDependency(parser, strCode, [ + RuntimeGlobals.requireScope + ])(expr); + } + return toConstantDependency(parser, strCode)(expr); + }); + parser.hooks.typeof + .for(key) + .tap( + PLUGIN_NAME, + withValueDependency( + key, + toConstantDependency(parser, JSON.stringify("object")) + ) + ); + }; + + walkDefinitions(definitions, ""); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + + /** + * Walk definitions + * @param {Record} definitions Definitions map + * @param {string} prefix Prefix string + * @returns {void} + */ + const walkDefinitionsForValues = (definitions, prefix) => { + for (const key of Object.keys(definitions)) { + const code = definitions[key]; + const version = /** @type {string} */ (toCacheVersion(code)); + const name = VALUE_DEP_PREFIX + prefix + key; + mainHash.update(`|${prefix}${key}`); + const oldVersion = compilation.valueCacheVersions.get(name); + if (oldVersion === undefined) { + compilation.valueCacheVersions.set(name, version); + } else if (oldVersion !== version) { + const warning = new WebpackError( + `${PLUGIN_NAME}\nConflicting values for '${prefix + key}'` + ); + warning.details = `'${oldVersion}' !== '${version}'`; + warning.hideStack = true; + compilation.warnings.push(warning); + } + if ( + code && + typeof code === "object" && + !(code instanceof RuntimeValue) && + !(code instanceof RegExp) + ) { + walkDefinitionsForValues( + /** @type {Record} */ (code), + `${prefix + key}.` + ); + } + } + }; + + /** + * @param {Record} definitions Definitions map + * @returns {void} + */ + const walkDefinitionsForKeys = (definitions) => { + /** + * @param {Map>} map Map + * @param {string} key key + * @param {string} value v + * @returns {void} + */ + const addToMap = (map, key, value) => { + if (map.has(key)) { + /** @type {Set} */ + (map.get(key)).add(value); + } else { + map.set(key, new Set([value])); + } + }; + for (const key of Object.keys(definitions)) { + const code = definitions[key]; + if ( + !code || + typeof code === "object" || + TYPEOF_OPERATOR_REGEXP.test(key) + ) { + continue; + } + const idx = key.lastIndexOf("."); + if (idx <= 0 || idx >= key.length - 1) { + continue; + } + const nested = key.slice(0, idx); + const final = key.slice(idx + 1); + addToMap(finalByNestedKey, nested, final); + addToMap(nestedByFinalKey, final, nested); + } + }; + + walkDefinitionsForKeys(definitions); + walkDefinitionsForValues(definitions, ""); + + compilation.valueCacheVersions.set( + VALUE_DEP_MAIN, + /** @type {string} */ (mainHash.digest("hex").slice(0, 8)) + ); + } + ); + } +} + +module.exports = DefinePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DelegatedModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DelegatedModule.js new file mode 100644 index 0000000000000000000000000000000000000000..f798e3c7fa8a9d3c08f3273449e11b8a363bcdde --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DelegatedModule.js @@ -0,0 +1,274 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { OriginalSource, RawSource } = require("webpack-sources"); +const Module = require("./Module"); +const { JS_TYPES } = require("./ModuleSourceTypesConstants"); +const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); +const StaticExportsDependency = require("./dependencies/StaticExportsDependency"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator").SourceTypes} SourceTypes */ +/** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */ +/** @typedef {import("./Module").BuildCallback} BuildCallback */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ +/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").SourceContext} SourceContext */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +/** @typedef {string} DelegatedModuleSourceRequest */ + +/** @typedef {NonNullable} DelegatedModuleType */ + +/** + * @typedef {object} DelegatedModuleData + * @property {BuildMeta=} buildMeta build meta + * @property {true | string[]=} exports exports + * @property {number | string} id module id + */ + +const RUNTIME_REQUIREMENTS = new Set([ + RuntimeGlobals.module, + RuntimeGlobals.require +]); + +class DelegatedModule extends Module { + /** + * @param {DelegatedModuleSourceRequest} sourceRequest source request + * @param {DelegatedModuleData} data data + * @param {DelegatedModuleType} type type + * @param {string} userRequest user request + * @param {string | Module} originalRequest original request + */ + constructor(sourceRequest, data, type, userRequest, originalRequest) { + super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null); + + // Info from Factory + this.sourceRequest = sourceRequest; + this.request = data.id; + this.delegationType = type; + this.userRequest = userRequest; + this.originalRequest = originalRequest; + this.delegateData = data; + + // Build info + this.delegatedSourceDependency = undefined; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return JS_TYPES; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return typeof this.originalRequest === "string" + ? this.originalRequest + : this.originalRequest.libIdent(options); + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `delegated ${JSON.stringify(this.request)} from ${ + this.sourceRequest + }`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `delegated ${this.userRequest} from ${this.sourceRequest}`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + const delegateData = /** @type {ManifestModuleData} */ (this.delegateData); + this.buildMeta = { ...delegateData.buildMeta }; + this.buildInfo = {}; + this.dependencies.length = 0; + this.delegatedSourceDependency = new DelegatedSourceDependency( + this.sourceRequest + ); + this.addDependency(this.delegatedSourceDependency); + this.addDependency( + new StaticExportsDependency(delegateData.exports || true, false) + ); + callback(); + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { + const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); + const sourceModule = moduleGraph.getModule(dep); + let str; + + if (!sourceModule) { + str = runtimeTemplate.throwMissingModuleErrorBlock({ + request: this.sourceRequest + }); + } else { + str = `module.exports = (${runtimeTemplate.moduleExports({ + module: sourceModule, + chunkGraph, + request: dep.request, + runtimeRequirements: new Set() + })})`; + + switch (this.delegationType) { + case "require": + str += `(${JSON.stringify(this.request)})`; + break; + case "object": + str += `[${JSON.stringify(this.request)}]`; + break; + } + + str += ";"; + } + + const sources = new Map(); + if (this.useSourceMap || this.useSimpleSourceMap) { + sources.set("javascript", new OriginalSource(str, this.identifier())); + } else { + sources.set("javascript", new RawSource(str)); + } + + return { + sources, + runtimeRequirements: RUNTIME_REQUIREMENTS + }; + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return 42; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(this.delegationType); + hash.update(JSON.stringify(this.request)); + super.updateHash(hash, context); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + // constructor + write(this.sourceRequest); + write(this.delegateData); + write(this.delegationType); + write(this.userRequest); + write(this.originalRequest); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context\ + * @returns {DelegatedModule} DelegatedModule + */ + static deserialize(context) { + const { read } = context; + const obj = new DelegatedModule( + read(), // sourceRequest + read(), // delegateData + read(), // delegationType + read(), // userRequest + read() // originalRequest + ); + obj.deserialize(context); + return obj; + } + + /** + * Assuming this module is in the cache. Update the (cached) module with + * the fresh module from the factory. Usually updates internal references + * and properties. + * @param {Module} module fresh module + * @returns {void} + */ + updateCacheModule(module) { + super.updateCacheModule(module); + const m = /** @type {DelegatedModule} */ (module); + this.delegationType = m.delegationType; + this.userRequest = m.userRequest; + this.originalRequest = m.originalRequest; + this.delegateData = m.delegateData; + } + + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + super.cleanupForCache(); + this.delegateData = + /** @type {EXPECTED_ANY} */ + (undefined); + } +} + +makeSerializable(DelegatedModule, "webpack/lib/DelegatedModule"); + +module.exports = DelegatedModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DelegatedModuleFactoryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DelegatedModuleFactoryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..32d80a005b1c3495e3d445e12025c24789417fe1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DelegatedModuleFactoryPlugin.js @@ -0,0 +1,114 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DelegatedModule = require("./DelegatedModule"); + +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */ +/** @typedef {import("./DelegatedModule").DelegatedModuleSourceRequest} DelegatedModuleSourceRequest */ +/** @typedef {import("./DelegatedModule").DelegatedModuleType} DelegatedModuleType */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ + +/** + * @typedef {object} Options + * @property {DelegatedModuleSourceRequest} source source + * @property {NonNullable} context absolute context path to which lib ident is relative to + * @property {DllReferencePluginOptionsContent} content content + * @property {DllReferencePluginOptions["type"]} type type + * @property {DllReferencePluginOptions["extensions"]} extensions extensions + * @property {DllReferencePluginOptions["scope"]} scope scope + * @property {AssociatedObjectForCache=} associatedObjectForCache object for caching + */ + +const PLUGIN_NAME = "DelegatedModuleFactoryPlugin"; + +class DelegatedModuleFactoryPlugin { + /** + * @param {Options} options options + */ + constructor(options) { + this.options = options; + options.type = options.type || "require"; + options.extensions = options.extensions || ["", ".js", ".json", ".wasm"]; + } + + /** + * @param {NormalModuleFactory} normalModuleFactory the normal module factory + * @returns {void} + */ + apply(normalModuleFactory) { + const scope = this.options.scope; + if (scope) { + normalModuleFactory.hooks.factorize.tapAsync( + PLUGIN_NAME, + (data, callback) => { + const [dependency] = data.dependencies; + const { request } = dependency; + if (request && request.startsWith(`${scope}/`)) { + const innerRequest = `.${request.slice(scope.length)}`; + let resolved; + if (innerRequest in this.options.content) { + resolved = this.options.content[innerRequest]; + return callback( + null, + new DelegatedModule( + this.options.source, + resolved, + /** @type {DelegatedModuleType} */ + (this.options.type), + innerRequest, + request + ) + ); + } + const extensions = + /** @type {string[]} */ + (this.options.extensions); + for (let i = 0; i < extensions.length; i++) { + const extension = extensions[i]; + const requestPlusExt = innerRequest + extension; + if (requestPlusExt in this.options.content) { + resolved = this.options.content[requestPlusExt]; + return callback( + null, + new DelegatedModule( + this.options.source, + resolved, + /** @type {DelegatedModuleType} */ + (this.options.type), + requestPlusExt, + request + extension + ) + ); + } + } + } + return callback(); + } + ); + } else { + normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module) => { + const request = module.libIdent(this.options); + if (request && request in this.options.content) { + const resolved = this.options.content[request]; + return new DelegatedModule( + this.options.source, + resolved, + /** @type {DelegatedModuleType} */ + (this.options.type), + request, + module + ); + } + return module; + }); + } + } +} + +module.exports = DelegatedModuleFactoryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DelegatedPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DelegatedPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..64f3941f99395d163a85fa689cc976a306e50e42 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DelegatedPlugin.js @@ -0,0 +1,49 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); +const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./DelegatedModuleFactoryPlugin").Options} Options */ + +const PLUGIN_NAME = "DelegatedPlugin"; + +class DelegatedPlugin { + /** + * @param {Options} options options + */ + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + DelegatedSourceDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.compile.tap(PLUGIN_NAME, ({ normalModuleFactory }) => { + new DelegatedModuleFactoryPlugin({ + associatedObjectForCache: compiler.root, + ...this.options + }).apply(normalModuleFactory); + }); + } +} + +module.exports = DelegatedPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DependenciesBlock.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DependenciesBlock.js new file mode 100644 index 0000000000000000000000000000000000000000..a952b643b568757fd460c425e335b9a53f5fdf2b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DependenciesBlock.js @@ -0,0 +1,122 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ + +/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ + +/** + * DependenciesBlock is the base class for all Module classes in webpack. It describes a + * "block" of dependencies which are pointers to other DependenciesBlock instances. For example + * when a Module has a CommonJs require statement, the DependencyBlock for the CommonJs module + * would be added as a dependency to the Module. DependenciesBlock is inherited by two types of classes: + * Module subclasses and AsyncDependenciesBlock subclasses. The only difference between the two is that + * AsyncDependenciesBlock subclasses are used for code-splitting (async boundary) and Module subclasses are not. + */ +class DependenciesBlock { + constructor() { + /** @type {Dependency[]} */ + this.dependencies = []; + /** @type {AsyncDependenciesBlock[]} */ + this.blocks = []; + /** @type {DependenciesBlock | undefined} */ + this.parent = undefined; + } + + getRootBlock() { + /** @type {DependenciesBlock} */ + let current = this; + while (current.parent) current = current.parent; + return current; + } + + /** + * Adds a DependencyBlock to DependencyBlock relationship. + * This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting) + * @param {AsyncDependenciesBlock} block block being added + * @returns {void} + */ + addBlock(block) { + this.blocks.push(block); + block.parent = this; + } + + /** + * @param {Dependency} dependency dependency being tied to block. + * This is an "edge" pointing to another "node" on module graph. + * @returns {void} + */ + addDependency(dependency) { + this.dependencies.push(dependency); + } + + /** + * @param {Dependency} dependency dependency being removed + * @returns {void} + */ + removeDependency(dependency) { + const idx = this.dependencies.indexOf(dependency); + if (idx >= 0) { + this.dependencies.splice(idx, 1); + } + } + + /** + * Removes all dependencies and blocks + * @returns {void} + */ + clearDependenciesAndBlocks() { + this.dependencies.length = 0; + this.blocks.length = 0; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + for (const dep of this.dependencies) { + dep.updateHash(hash, context); + } + for (const block of this.blocks) { + block.updateHash(hash, context); + } + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize({ write }) { + write(this.dependencies); + write(this.blocks); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize({ read }) { + this.dependencies = read(); + this.blocks = read(); + for (const block of this.blocks) { + block.parent = this; + } + } +} + +makeSerializable(DependenciesBlock, "webpack/lib/DependenciesBlock"); + +module.exports = DependenciesBlock; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Dependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Dependency.js new file mode 100644 index 0000000000000000000000000000000000000000..d447181e14164420f0a323281150827af97ec0d6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Dependency.js @@ -0,0 +1,380 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const memoize = require("./util/memoize"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @typedef {object} UpdateHashContext + * @property {ChunkGraph} chunkGraph + * @property {RuntimeSpec} runtime + * @property {RuntimeTemplate=} runtimeTemplate + */ + +/** + * @typedef {object} SourcePosition + * @property {number} line + * @property {number=} column + */ + +/** + * @typedef {object} RealDependencyLocation + * @property {SourcePosition} start + * @property {SourcePosition=} end + * @property {number=} index + */ + +/** + * @typedef {object} SyntheticDependencyLocation + * @property {string} name + * @property {number=} index + */ + +/** @typedef {SyntheticDependencyLocation | RealDependencyLocation} DependencyLocation */ + +/** + * @typedef {object} ExportSpec + * @property {string} name the name of the export + * @property {boolean=} canMangle can the export be renamed (defaults to true) + * @property {boolean=} terminalBinding is the export a terminal binding that should be checked for export star conflicts + * @property {(string | ExportSpec)[]=} exports nested exports + * @property {ModuleGraphConnection=} from when reexported: from which module + * @property {string[] | null=} export when reexported: from which export + * @property {number=} priority when reexported: with which priority + * @property {boolean=} hidden export is not visible, because another export blends over it + */ + +/** + * @typedef {object} ExportsSpec + * @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports + * @property {Set=} excludeExports when exports = true, list of unaffected exports + * @property {(Set | null)=} hideExports list of maybe prior exposed, but now hidden exports + * @property {ModuleGraphConnection=} from when reexported: from which module + * @property {number=} priority when reexported: with which priority + * @property {boolean=} canMangle can the export be renamed (defaults to true) + * @property {boolean=} terminalBinding are the exports terminal bindings that should be checked for export star conflicts + * @property {Module[]=} dependencies module on which the result depends on + */ + +/** + * @typedef {object} ReferencedExport + * @property {string[]} name name of the referenced export + * @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true + */ + +/** @typedef {(moduleGraphConnection: ModuleGraphConnection, runtime: RuntimeSpec) => ConnectionState} GetConditionFn */ + +const TRANSITIVE = Symbol("transitive"); + +const getIgnoredModule = memoize(() => { + const RawModule = require("./RawModule"); + + const module = new RawModule("/* (ignored) */", "ignored", "(ignored)"); + module.factoryMeta = { sideEffectFree: true }; + return module; +}); + +class Dependency { + constructor() { + /** @type {Module | undefined} */ + this._parentModule = undefined; + /** @type {DependenciesBlock | undefined} */ + this._parentDependenciesBlock = undefined; + /** @type {number} */ + this._parentDependenciesBlockIndex = -1; + // TODO check if this can be moved into ModuleDependency + /** @type {boolean} */ + this.weak = false; + // TODO check if this can be moved into ModuleDependency + /** @type {boolean | undefined} */ + this.defer = false; + // TODO check if this can be moved into ModuleDependency + /** @type {boolean | undefined} */ + this.optional = false; + this._locSL = 0; + this._locSC = 0; + this._locEL = 0; + this._locEC = 0; + this._locI = undefined; + this._locN = undefined; + this._loc = undefined; + } + + /** + * @returns {string} a display name for the type of dependency + */ + get type() { + return "unknown"; + } + + /** + * @returns {string} a dependency category, typical categories are "commonjs", "amd", "esm" + */ + get category() { + return "unknown"; + } + + /** + * @returns {DependencyLocation} location + */ + get loc() { + if (this._loc !== undefined) return this._loc; + + /** @type {SyntheticDependencyLocation & RealDependencyLocation} */ + const loc = {}; + + if (this._locSL > 0) { + loc.start = { line: this._locSL, column: this._locSC }; + } + if (this._locEL > 0) { + loc.end = { line: this._locEL, column: this._locEC }; + } + if (this._locN !== undefined) { + loc.name = this._locN; + } + if (this._locI !== undefined) { + loc.index = this._locI; + } + + return (this._loc = loc); + } + + set loc(loc) { + if ("start" in loc && typeof loc.start === "object") { + this._locSL = loc.start.line || 0; + this._locSC = loc.start.column || 0; + } else { + this._locSL = 0; + this._locSC = 0; + } + if ("end" in loc && typeof loc.end === "object") { + this._locEL = loc.end.line || 0; + this._locEC = loc.end.column || 0; + } else { + this._locEL = 0; + this._locEC = 0; + } + this._locI = "index" in loc ? loc.index : undefined; + this._locN = "name" in loc ? loc.name : undefined; + this._loc = loc; + } + + /** + * @param {number} startLine start line + * @param {number} startColumn start column + * @param {number} endLine end line + * @param {number} endColumn end column + */ + setLoc(startLine, startColumn, endLine, endColumn) { + this._locSL = startLine; + this._locSC = startColumn; + this._locEL = endLine; + this._locEC = endColumn; + this._locI = undefined; + this._locN = undefined; + this._loc = undefined; + } + + /** + * @returns {string | undefined} a request context + */ + getContext() { + return undefined; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return null; + } + + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return TRANSITIVE; + } + + /** + * Returns the referenced module and export + * @deprecated + * @param {ModuleGraph} moduleGraph module graph + * @returns {never} throws error + */ + getReference(moduleGraph) { + throw new Error( + "Dependency.getReference was removed in favor of Dependency.getReferencedExports, ModuleGraph.getModule and ModuleGraph.getConnection().active" + ); + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + return Dependency.EXPORTS_OBJECT_REFERENCED; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | GetConditionFn} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return null; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return undefined; + } + + /** + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | null | undefined} warnings + */ + getWarnings(moduleGraph) { + return null; + } + + /** + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | null | undefined} errors + */ + getErrors(moduleGraph) { + return null; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) {} + + /** + * implement this method to allow the occurrence order plugin to count correctly + * @returns {number} count how often the id is used in this dependency + */ + getNumberOfIdOccurrences() { + return 1; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return true; + } + + /** + * @param {string} context context directory + * @returns {Module} ignored module + */ + createIgnoredModule(context) { + return getIgnoredModule(); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize({ write }) { + write(this.weak); + write(this.optional); + write(this._locSL); + write(this._locSC); + write(this._locEL); + write(this._locEC); + write(this._locI); + write(this._locN); + write(this.defer); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize({ read }) { + this.weak = read(); + this.optional = read(); + this._locSL = read(); + this._locSC = read(); + this._locEL = read(); + this._locEC = read(); + this._locI = read(); + this._locN = read(); + this.defer = read(); + } +} + +/** @type {string[][]} */ +Dependency.NO_EXPORTS_REFERENCED = []; +/** @type {string[][]} */ +Dependency.EXPORTS_OBJECT_REFERENCED = [[]]; + +// TODO remove in webpack 6 +Object.defineProperty(Dependency.prototype, "module", { + /** + * @deprecated + * @returns {EXPECTED_ANY} throws + */ + get() { + throw new Error( + "module property was removed from Dependency (use compilation.moduleGraph.getModule(dependency) instead)" + ); + }, + + /** + * @deprecated + * @returns {never} throws + */ + set() { + throw new Error( + "module property was removed from Dependency (use compilation.moduleGraph.updateModule(dependency, module) instead)" + ); + } +}); + +// TODO remove in webpack 6 +Object.defineProperty(Dependency.prototype, "disconnect", { + /** + * @deprecated + * @returns {EXPECTED_ANY} throws + */ + get() { + throw new Error( + "disconnect was removed from Dependency (Dependency no longer carries graph specific information)" + ); + } +}); + +Dependency.TRANSITIVE = TRANSITIVE; + +module.exports = Dependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DependencyTemplate.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DependencyTemplate.js new file mode 100644 index 0000000000000000000000000000000000000000..a898659439e45a71caed4a4b078dd049ded70692 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DependencyTemplate.js @@ -0,0 +1,70 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator").GenerateContext} GenerateContext */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ + +/** + * @template T + * @typedef {import("./InitFragment")} InitFragment + */ + +/** + * @typedef {object} DependencyTemplateContext + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {RuntimeRequirements} runtimeRequirements the requirements for runtime + * @property {Module} module current module + * @property {RuntimeSpec} runtime current runtimes, for which code is generated + * @property {InitFragment[]} initFragments mutable array of init fragments for the current module + * @property {ConcatenationScope=} concatenationScope when in a concatenated module, information about other concatenated modules + * @property {CodeGenerationResults} codeGenerationResults the code generation results + * @property {InitFragment[]} chunkInitFragments chunkInitFragments + */ + +/** + * @typedef {object} CssDependencyTemplateContextExtras + * @property {CssData} cssData the css exports data + */ + +/** + * @typedef {object} CssData + * @property {boolean} esModule whether export __esModule + * @property {Map} exports the css exports + */ + +/** @typedef {DependencyTemplateContext & CssDependencyTemplateContextExtras} CssDependencyTemplateContext */ + +class DependencyTemplate { + /* istanbul ignore next */ + /** + * @abstract + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } +} + +module.exports = DependencyTemplate; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DependencyTemplates.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DependencyTemplates.js new file mode 100644 index 0000000000000000000000000000000000000000..4eeaa0e05cd5f46a322c69f644ca7bb4ea0856e7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DependencyTemplates.js @@ -0,0 +1,68 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { DEFAULTS } = require("./config/defaults"); +const createHash = require("./util/createHash"); + +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ +/** @typedef {typeof import("./util/Hash")} Hash */ + +/** @typedef {new (...args: EXPECTED_ANY[]) => Dependency} DependencyConstructor */ + +class DependencyTemplates { + /** + * @param {string | Hash} hashFunction the hash function to use + */ + constructor(hashFunction = DEFAULTS.HASH_FUNCTION) { + /** @type {Map} */ + this._map = new Map(); + /** @type {string} */ + this._hash = "31d6cfe0d16ae931b73c59d7e0c089c0"; + this._hashFunction = hashFunction; + } + + /** + * @param {DependencyConstructor} dependency Constructor of Dependency + * @returns {DependencyTemplate | undefined} template for this dependency + */ + get(dependency) { + return this._map.get(dependency); + } + + /** + * @param {DependencyConstructor} dependency Constructor of Dependency + * @param {DependencyTemplate} dependencyTemplate template for this dependency + * @returns {void} + */ + set(dependency, dependencyTemplate) { + this._map.set(dependency, dependencyTemplate); + } + + /** + * @param {string} part additional hash contributor + * @returns {void} + */ + updateHash(part) { + const hash = createHash(this._hashFunction); + hash.update(`${this._hash}${part}`); + this._hash = /** @type {string} */ (hash.digest("hex")); + } + + getHash() { + return this._hash; + } + + clone() { + const newInstance = new DependencyTemplates(this._hashFunction); + newInstance._map = new Map(this._map); + newInstance._hash = this._hash; + return newInstance; + } +} + +module.exports = DependencyTemplates; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllEntryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllEntryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..a63946cf96b984655800d8990bc9f2db490a28a9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllEntryPlugin.js @@ -0,0 +1,76 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DllModuleFactory = require("./DllModuleFactory"); +const DllEntryDependency = require("./dependencies/DllEntryDependency"); +const EntryDependency = require("./dependencies/EntryDependency"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ + +/** @typedef {string[]} Entries */ +/** @typedef {EntryOptions & { name: string }} Options */ + +const PLUGIN_NAME = "DllEntryPlugin"; + +class DllEntryPlugin { + /** + * @param {string} context context + * @param {Entries} entries entry names + * @param {Options} options options + */ + constructor(context, entries, options) { + this.context = context; + this.entries = entries; + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + const dllModuleFactory = new DllModuleFactory(); + compilation.dependencyFactories.set( + DllEntryDependency, + dllModuleFactory + ); + compilation.dependencyFactories.set( + EntryDependency, + normalModuleFactory + ); + } + ); + compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { + compilation.addEntry( + this.context, + new DllEntryDependency( + this.entries.map((e, idx) => { + const dep = new EntryDependency(e); + dep.loc = { + name: this.options.name, + index: idx + }; + return dep; + }), + this.options.name + ), + this.options, + (error) => { + if (error) return callback(error); + callback(); + } + ); + }); + } +} + +module.exports = DllEntryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllModule.js new file mode 100644 index 0000000000000000000000000000000000000000..58b06b0ecf78aee6e805af88b3245c4b919e6dc1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllModule.js @@ -0,0 +1,176 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const Module = require("./Module"); +const { JS_TYPES } = require("./ModuleSourceTypesConstants"); +const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator").SourceTypes} SourceTypes */ +/** @typedef {import("./Module").BuildCallback} BuildCallback */ +/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").SourceContext} SourceContext */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +const RUNTIME_REQUIREMENTS = new Set([ + RuntimeGlobals.require, + RuntimeGlobals.module +]); + +class DllModule extends Module { + /** + * @param {string} context context path + * @param {Dependency[]} dependencies dependencies + * @param {string} name name + */ + constructor(context, dependencies, name) { + super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, context); + + // Info from Factory + /** @type {Dependency[]} */ + this.dependencies = dependencies; + this.name = name; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return JS_TYPES; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `dll ${this.name}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `dll ${this.name}`; + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = {}; + return callback(); + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + const sources = new Map(); + sources.set( + "javascript", + new RawSource(`module.exports = ${RuntimeGlobals.require};`) + ); + return { + sources, + runtimeRequirements: RUNTIME_REQUIREMENTS + }; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return 12; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(`dll module${this.name || ""}`); + super.updateHash(hash, context); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + context.write(this.name); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + this.name = context.read(); + super.deserialize(context); + } + + /** + * Assuming this module is in the cache. Update the (cached) module with + * the fresh module from the factory. Usually updates internal references + * and properties. + * @param {Module} module fresh module + * @returns {void} + */ + updateCacheModule(module) { + super.updateCacheModule(module); + this.dependencies = module.dependencies; + } + + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + super.cleanupForCache(); + this.dependencies = /** @type {EXPECTED_ANY} */ (undefined); + } +} + +makeSerializable(DllModule, "webpack/lib/DllModule"); + +module.exports = DllModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllModuleFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllModuleFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..41aa1610726354812c8138c7a1249fbb18812e18 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllModuleFactory.js @@ -0,0 +1,38 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DllModule = require("./DllModule"); +const ModuleFactory = require("./ModuleFactory"); + +/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ + +class DllModuleFactory extends ModuleFactory { + constructor() { + super(); + this.hooks = Object.freeze({}); + } + + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create(data, callback) { + const dependency = /** @type {DllEntryDependency} */ (data.dependencies[0]); + callback(null, { + module: new DllModule( + data.context, + dependency.dependencies, + dependency.name + ) + }); + } +} + +module.exports = DllModuleFactory; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..1dc009f24bc0e009388c1d7ba669fd48a92b05ed --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllPlugin.js @@ -0,0 +1,73 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DllEntryPlugin = require("./DllEntryPlugin"); +const FlagAllModulesAsUsedPlugin = require("./FlagAllModulesAsUsedPlugin"); +const LibManifestPlugin = require("./LibManifestPlugin"); +const createSchemaValidation = require("./util/create-schema-validation"); + +/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./DllEntryPlugin").Entries} Entries */ +/** @typedef {import("./DllEntryPlugin").Options} Options */ + +const validate = createSchemaValidation( + require("../schemas/plugins/DllPlugin.check"), + () => require("../schemas/plugins/DllPlugin.json"), + { + name: "Dll Plugin", + baseDataPath: "options" + } +); + +const PLUGIN_NAME = "DllPlugin"; + +class DllPlugin { + /** + * @param {DllPluginOptions} options options object + */ + constructor(options) { + validate(options); + this.options = { + ...options, + entryOnly: options.entryOnly !== false + }; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.entryOption.tap(PLUGIN_NAME, (context, entry) => { + if (typeof entry !== "function") { + for (const name of Object.keys(entry)) { + /** @type {Options} */ + const options = { name }; + new DllEntryPlugin( + context, + /** @type {Entries} */ + (entry[name].import), + options + ).apply(compiler); + } + } else { + throw new Error( + `${PLUGIN_NAME} doesn't support dynamic entry (function) yet` + ); + } + return true; + }); + new LibManifestPlugin(this.options).apply(compiler); + if (!this.options.entryOnly) { + new FlagAllModulesAsUsedPlugin(PLUGIN_NAME).apply(compiler); + } + } +} + +module.exports = DllPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllReferencePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllReferencePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..927feb5704b202fa96785ec71b5ecedf2593ecb3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DllReferencePlugin.js @@ -0,0 +1,190 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const parseJson = require("json-parse-even-better-errors"); +const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); +const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); +const WebpackError = require("./WebpackError"); +const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); +const createSchemaValidation = require("./util/create-schema-validation"); +const makePathsRelative = require("./util/identifier").makePathsRelative; + +/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Compiler").CompilationParams} CompilationParams */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +const validate = createSchemaValidation( + require("../schemas/plugins/DllReferencePlugin.check"), + () => require("../schemas/plugins/DllReferencePlugin.json"), + { + name: "Dll Reference Plugin", + baseDataPath: "options" + } +); + +/** @typedef {{ path: string, data: DllReferencePluginOptionsManifest | undefined, error: Error | undefined }} CompilationDataItem */ + +const PLUGIN_NAME = "DllReferencePlugin"; + +class DllReferencePlugin { + /** + * @param {DllReferencePluginOptions} options options object + */ + constructor(options) { + validate(options); + this.options = options; + /** @type {WeakMap} */ + this._compilationData = new WeakMap(); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + DelegatedSourceDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.beforeCompile.tapAsync(PLUGIN_NAME, (params, callback) => { + if ("manifest" in this.options) { + const manifest = this.options.manifest; + if (typeof manifest === "string") { + /** @type {InputFileSystem} */ + (compiler.inputFileSystem).readFile(manifest, (err, result) => { + if (err) return callback(err); + /** @type {CompilationDataItem} */ + const data = { + path: manifest, + data: undefined, + error: undefined + }; + // Catch errors parsing the manifest so that blank + // or malformed manifest files don't kill the process. + try { + data.data = parseJson( + /** @type {Buffer} */ (result).toString("utf8") + ); + } catch (parseErr) { + // Store the error in the params so that it can + // be added as a compilation error later on. + const manifestPath = makePathsRelative( + /** @type {string} */ (compiler.options.context), + manifest, + compiler.root + ); + data.error = new DllManifestError( + manifestPath, + /** @type {Error} */ (parseErr).message + ); + } + this._compilationData.set(params, data); + return callback(); + }); + return; + } + } + return callback(); + }); + + compiler.hooks.compile.tap(PLUGIN_NAME, (params) => { + let name = this.options.name; + let sourceType = this.options.sourceType; + let resolvedContent = + "content" in this.options ? this.options.content : undefined; + if ("manifest" in this.options) { + const manifestParameter = this.options.manifest; + let manifest; + if (typeof manifestParameter === "string") { + const data = + /** @type {CompilationDataItem} */ + (this._compilationData.get(params)); + // If there was an error parsing the manifest + // file, exit now because the error will be added + // as a compilation error in the "compilation" hook. + if (data.error) { + return; + } + manifest = data.data; + } else { + manifest = manifestParameter; + } + if (manifest) { + if (!name) name = manifest.name; + if (!sourceType) sourceType = manifest.type; + if (!resolvedContent) resolvedContent = manifest.content; + } + } + /** @type {Externals} */ + const externals = {}; + const source = `dll-reference ${name}`; + externals[source] = /** @type {string} */ (name); + const normalModuleFactory = params.normalModuleFactory; + new ExternalModuleFactoryPlugin(sourceType || "var", externals).apply( + normalModuleFactory + ); + new DelegatedModuleFactoryPlugin({ + source, + type: this.options.type, + scope: this.options.scope, + context: + /** @type {string} */ + (this.options.context || compiler.options.context), + content: + /** @type {DllReferencePluginOptionsContent} */ + (resolvedContent), + extensions: this.options.extensions, + associatedObjectForCache: compiler.root + }).apply(normalModuleFactory); + }); + + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, params) => { + if ("manifest" in this.options) { + const manifest = this.options.manifest; + if (typeof manifest === "string") { + const data = /** @type {CompilationDataItem} */ ( + this._compilationData.get(params) + ); + // If there was an error parsing the manifest file, add the + // error as a compilation error to make the compilation fail. + if (data.error) { + compilation.errors.push( + /** @type {DllManifestError} */ (data.error) + ); + } + compilation.fileDependencies.add(manifest); + } + } + }); + } +} + +class DllManifestError extends WebpackError { + /** + * @param {string} filename filename of the manifest + * @param {string} message error message + */ + constructor(filename, message) { + super(); + + this.name = "DllManifestError"; + this.message = `Dll manifest ${filename}\n${message}`; + } +} + +module.exports = DllReferencePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DynamicEntryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DynamicEntryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d30acbae10a0fbd723c3bc690d1e59610dc2e50e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/DynamicEntryPlugin.js @@ -0,0 +1,88 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Naoyuki Kanezawa @nkzawa +*/ + +"use strict"; + +const EntryOptionPlugin = require("./EntryOptionPlugin"); +const EntryPlugin = require("./EntryPlugin"); +const EntryDependency = require("./dependencies/EntryDependency"); + +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescriptionNormalized */ +/** @typedef {import("../declarations/WebpackOptions").EntryDynamicNormalized} EntryDynamic */ +/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */ +/** @typedef {import("../declarations/WebpackOptions").EntryStaticNormalized} EntryStatic */ +/** @typedef {import("./Compiler")} Compiler */ + +const PLUGIN_NAME = "DynamicEntryPlugin"; + +class DynamicEntryPlugin { + /** + * @param {string} context the context path + * @param {EntryDynamic} entry the entry value + */ + constructor(context, entry) { + this.context = context; + this.entry = entry; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + EntryDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.make.tapPromise(PLUGIN_NAME, (compilation) => + Promise.resolve(this.entry()) + .then((entry) => { + const promises = []; + for (const name of Object.keys(entry)) { + const desc = entry[name]; + const options = EntryOptionPlugin.entryDescriptionToOptions( + compiler, + name, + desc + ); + for (const entry of /** @type {NonNullable} */ ( + desc.import + )) { + promises.push( + new Promise( + /** + * @param {(value?: undefined) => void} resolve resolve + * @param {(reason?: Error) => void} reject reject + */ + (resolve, reject) => { + compilation.addEntry( + this.context, + EntryPlugin.createDependency(entry, options), + options, + (err) => { + if (err) return reject(err); + resolve(); + } + ); + } + ) + ); + } + } + return Promise.all(promises); + }) + .then(() => {}) + ); + } +} + +module.exports = DynamicEntryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EntryOptionPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EntryOptionPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f2ce504f54b2b681b11cb60bf603f8339e6f3bc9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EntryOptionPlugin.js @@ -0,0 +1,103 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ +/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ + +const PLUGIN_NAME = "EntryOptionPlugin"; + +class EntryOptionPlugin { + /** + * @param {Compiler} compiler the compiler instance one is tapping into + * @returns {void} + */ + apply(compiler) { + compiler.hooks.entryOption.tap(PLUGIN_NAME, (context, entry) => { + EntryOptionPlugin.applyEntryOption(compiler, context, entry); + return true; + }); + } + + /** + * @param {Compiler} compiler the compiler + * @param {string} context context directory + * @param {Entry} entry request + * @returns {void} + */ + static applyEntryOption(compiler, context, entry) { + if (typeof entry === "function") { + const DynamicEntryPlugin = require("./DynamicEntryPlugin"); + + new DynamicEntryPlugin(context, entry).apply(compiler); + } else { + const EntryPlugin = require("./EntryPlugin"); + + for (const name of Object.keys(entry)) { + const desc = entry[name]; + const options = EntryOptionPlugin.entryDescriptionToOptions( + compiler, + name, + desc + ); + const descImport = + /** @type {Exclude} */ + (desc.import); + for (const entry of descImport) { + new EntryPlugin(context, entry, options).apply(compiler); + } + } + } + } + + /** + * @param {Compiler} compiler the compiler + * @param {string} name entry name + * @param {EntryDescription} desc entry description + * @returns {EntryOptions} options for the entry + */ + static entryDescriptionToOptions(compiler, name, desc) { + /** @type {EntryOptions} */ + const options = { + name, + filename: desc.filename, + runtime: desc.runtime, + layer: desc.layer, + dependOn: desc.dependOn, + baseUri: desc.baseUri, + publicPath: desc.publicPath, + chunkLoading: desc.chunkLoading, + asyncChunks: desc.asyncChunks, + wasmLoading: desc.wasmLoading, + library: desc.library + }; + if (desc.layer !== undefined && !compiler.options.experiments.layers) { + throw new Error( + "'entryOptions.layer' is only allowed when 'experiments.layers' is enabled" + ); + } + if (desc.chunkLoading) { + const EnableChunkLoadingPlugin = require("./javascript/EnableChunkLoadingPlugin"); + + EnableChunkLoadingPlugin.checkEnabled(compiler, desc.chunkLoading); + } + if (desc.wasmLoading) { + const EnableWasmLoadingPlugin = require("./wasm/EnableWasmLoadingPlugin"); + + EnableWasmLoadingPlugin.checkEnabled(compiler, desc.wasmLoading); + } + if (desc.library) { + const EnableLibraryPlugin = require("./library/EnableLibraryPlugin"); + + EnableLibraryPlugin.checkEnabled(compiler, desc.library.type); + } + return options; + } +} + +module.exports = EntryOptionPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EntryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EntryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..35392d871ba4aab53d8ea1a060e24597f0e45d96 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EntryPlugin.js @@ -0,0 +1,72 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const EntryDependency = require("./dependencies/EntryDependency"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ + +const PLUGIN_NAME = "EntryPlugin"; + +class EntryPlugin { + /** + * An entry plugin which will handle creation of the EntryDependency + * @param {string} context context path + * @param {string} entry entry path + * @param {EntryOptions | string=} options entry options (passing a string is deprecated) + */ + constructor(context, entry, options) { + this.context = context; + this.entry = entry; + this.options = options || ""; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + EntryDependency, + normalModuleFactory + ); + } + ); + + const { entry, options, context } = this; + const dep = EntryPlugin.createDependency(entry, options); + + compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { + compilation.addEntry(context, dep, options, (err) => { + callback(err); + }); + }); + } + + /** + * @param {string} entry entry request + * @param {EntryOptions | string} options entry options (passing string is deprecated) + * @returns {EntryDependency} the dependency + */ + static createDependency(entry, options) { + const dep = new EntryDependency(entry); + // TODO webpack 6 remove string option + dep.loc = { + name: + typeof options === "object" + ? /** @type {string} */ (options.name) + : options + }; + return dep; + } +} + +module.exports = EntryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Entrypoint.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Entrypoint.js new file mode 100644 index 0000000000000000000000000000000000000000..d04086fc4485034835cdb1bd0cbc7885e249e01a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Entrypoint.js @@ -0,0 +1,120 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ChunkGroup = require("./ChunkGroup"); +const SortableSet = require("./util/SortableSet"); + +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ +/** @typedef {import("./Chunk")} Chunk */ + +/** @typedef {{ name?: string } & Omit} EntryOptions */ + +/** + * Entrypoint serves as an encapsulation primitive for chunks that are + * a part of a single ChunkGroup. They represent all bundles that need to be loaded for a + * single instance of a page. Multi-page application architectures will typically yield multiple Entrypoint objects + * inside of the compilation, whereas a Single Page App may only contain one with many lazy-loaded chunks. + */ +class Entrypoint extends ChunkGroup { + /** + * Creates an instance of Entrypoint. + * @param {EntryOptions | string} entryOptions the options for the entrypoint (or name) + * @param {boolean=} initial false, when the entrypoint is not initial loaded + */ + constructor(entryOptions, initial = true) { + if (typeof entryOptions === "string") { + entryOptions = { name: entryOptions }; + } + super({ + name: entryOptions.name + }); + this.options = entryOptions; + /** @type {Chunk=} */ + this._runtimeChunk = undefined; + /** @type {Chunk=} */ + this._entrypointChunk = undefined; + /** @type {boolean} */ + this._initial = initial; + /** @type {SortableSet} */ + this._dependOn = new SortableSet(); + } + + /** + * @returns {boolean} true, when this chunk group will be loaded on initial page load + */ + isInitial() { + return this._initial; + } + + /** + * Sets the runtimeChunk for an entrypoint. + * @param {Chunk} chunk the chunk being set as the runtime chunk. + * @returns {void} + */ + setRuntimeChunk(chunk) { + this._runtimeChunk = chunk; + } + + /** + * Fetches the chunk reference containing the webpack bootstrap code + * @returns {Chunk | null} returns the runtime chunk or null if there is none + */ + getRuntimeChunk() { + if (this._runtimeChunk) return this._runtimeChunk; + for (const parent of this.parentsIterable) { + if (parent instanceof Entrypoint) return parent.getRuntimeChunk(); + } + return null; + } + + /** + * Sets the chunk with the entrypoint modules for an entrypoint. + * @param {Chunk} chunk the chunk being set as the entrypoint chunk. + * @returns {void} + */ + setEntrypointChunk(chunk) { + this._entrypointChunk = chunk; + } + + /** + * Returns the chunk which contains the entrypoint modules + * (or at least the execution of them) + * @returns {Chunk} chunk + */ + getEntrypointChunk() { + return /** @type {Chunk} */ (this._entrypointChunk); + } + + /** + * @param {Chunk} oldChunk chunk to be replaced + * @param {Chunk} newChunk New chunk that will be replaced with + * @returns {boolean | undefined} returns true if the replacement was successful + */ + replaceChunk(oldChunk, newChunk) { + if (this._runtimeChunk === oldChunk) this._runtimeChunk = newChunk; + if (this._entrypointChunk === oldChunk) this._entrypointChunk = newChunk; + return super.replaceChunk(oldChunk, newChunk); + } + + /** + * @param {Entrypoint} entrypoint the entrypoint + * @returns {void} + */ + addDependOn(entrypoint) { + this._dependOn.add(entrypoint); + } + + /** + * @param {Entrypoint} entrypoint the entrypoint + * @returns {boolean} true if the entrypoint is in the dependOn set + */ + dependOn(entrypoint) { + return this._dependOn.has(entrypoint); + } +} + +module.exports = Entrypoint; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EnvironmentNotSupportAsyncWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EnvironmentNotSupportAsyncWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..1a1ea9ece666d480b52598cce5d7fed1b5f48343 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EnvironmentNotSupportAsyncWarning.js @@ -0,0 +1,52 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Gengkun He @ahabhgk +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {"asyncWebAssembly" | "topLevelAwait" | "external promise" | "external script" | "external import" | "external module"} Feature */ + +class EnvironmentNotSupportAsyncWarning extends WebpackError { + /** + * Creates an instance of EnvironmentNotSupportAsyncWarning. + * @param {Module} module module + * @param {Feature} feature feature + */ + constructor(module, feature) { + const message = `The generated code contains 'async/await' because this module is using "${feature}". +However, your target environment does not appear to support 'async/await'. +As a result, the code may not run as expected or may cause runtime errors.`; + super(message); + + this.name = "EnvironmentNotSupportAsyncWarning"; + this.module = module; + } + + /** + * Creates an instance of EnvironmentNotSupportAsyncWarning. + * @param {Module} module module + * @param {RuntimeTemplate} runtimeTemplate compilation + * @param {Feature} feature feature + */ + static check(module, runtimeTemplate, feature) { + if (!runtimeTemplate.supportsAsyncFunction()) { + module.addWarning(new EnvironmentNotSupportAsyncWarning(module, feature)); + } + } +} + +makeSerializable( + EnvironmentNotSupportAsyncWarning, + "webpack/lib/EnvironmentNotSupportAsyncWarning" +); + +module.exports = EnvironmentNotSupportAsyncWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EnvironmentPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EnvironmentPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..3bf01f096736c8db4ce9451b74dd7823ee00a04d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EnvironmentPlugin.js @@ -0,0 +1,71 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Authors Simen Brekken @simenbrekken, Einar Löve @einarlove +*/ + +"use strict"; + +const DefinePlugin = require("./DefinePlugin"); +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */ + +const PLUGIN_NAME = "EnvironmentPlugin"; + +class EnvironmentPlugin { + /** + * @param {(string | string[] | Record)[]} keys keys + */ + constructor(...keys) { + if (keys.length === 1 && Array.isArray(keys[0])) { + /** @type {string[]} */ + this.keys = keys[0]; + this.defaultValues = {}; + } else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") { + this.keys = Object.keys(keys[0]); + this.defaultValues = + /** @type {Record} */ + (keys[0]); + } else { + this.keys = /** @type {string[]} */ (keys); + this.defaultValues = {}; + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + /** @type {Record} */ + const definitions = {}; + for (const key of this.keys) { + const value = + process.env[key] !== undefined + ? process.env[key] + : this.defaultValues[key]; + + if (value === undefined) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const error = new WebpackError( + `${PLUGIN_NAME} - ${key} environment variable is undefined.\n\n` + + "You can pass an object with default values to suppress this warning.\n" + + "See https://webpack.js.org/plugins/environment-plugin for example." + ); + + error.name = "EnvVariableNotDefinedError"; + compilation.errors.push(error); + }); + } + + definitions[`process.env.${key}`] = + value === undefined ? "undefined" : JSON.stringify(value); + } + + new DefinePlugin(definitions).apply(compiler); + } +} + +module.exports = EnvironmentPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ErrorHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ErrorHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..b23d1f1b4210650c1de49ea99c569ecf45efff0e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ErrorHelpers.js @@ -0,0 +1,100 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const loaderFlag = "LOADER_EXECUTION"; + +const webpackOptionsFlag = "WEBPACK_OPTIONS"; + +/** + * @param {string} stack stack trace + * @param {string} flag flag to cut off + * @returns {string} stack trace without the specified flag included + */ +const cutOffByFlag = (stack, flag) => { + const errorStack = stack.split("\n"); + for (let i = 0; i < errorStack.length; i++) { + if (errorStack[i].includes(flag)) { + errorStack.length = i; + } + } + return errorStack.join("\n"); +}; + +/** + * @param {string} stack stack trace + * @returns {string} stack trace without the loader execution flag included + */ +const cutOffLoaderExecution = (stack) => cutOffByFlag(stack, loaderFlag); + +/** + * @param {string} stack stack trace + * @returns {string} stack trace without the webpack options flag included + */ +const cutOffWebpackOptions = (stack) => cutOffByFlag(stack, webpackOptionsFlag); + +/** + * @param {string} stack stack trace + * @param {string} message error message + * @returns {string} stack trace without the message included + */ +const cutOffMultilineMessage = (stack, message) => { + const stackSplitByLines = stack.split("\n"); + const messageSplitByLines = message.split("\n"); + + /** @type {string[]} */ + const result = []; + + for (const [idx, line] of stackSplitByLines.entries()) { + if (!line.includes(messageSplitByLines[idx])) result.push(line); + } + + return result.join("\n"); +}; + +/** + * @param {string} stack stack trace + * @param {string} message error message + * @returns {string} stack trace without the message included + */ +const cutOffMessage = (stack, message) => { + const nextLine = stack.indexOf("\n"); + if (nextLine === -1) { + return stack === message ? "" : stack; + } + const firstLine = stack.slice(0, nextLine); + return firstLine === message ? stack.slice(nextLine + 1) : stack; +}; + +/** + * @param {string} stack stack trace + * @param {string} message error message + * @returns {string} stack trace without the loader execution flag and message included + */ +const cleanUp = (stack, message) => { + stack = cutOffLoaderExecution(stack); + stack = cutOffMessage(stack, message); + return stack; +}; + +/** + * @param {string} stack stack trace + * @param {string} message error message + * @returns {string} stack trace without the webpack options flag and message included + */ +const cleanUpWebpackOptions = (stack, message) => { + stack = cutOffWebpackOptions(stack); + stack = cutOffMultilineMessage(stack, message); + return stack; +}; + +module.exports.cleanUp = cleanUp; +module.exports.cleanUpWebpackOptions = cleanUpWebpackOptions; +module.exports.cutOffByFlag = cutOffByFlag; +module.exports.cutOffLoaderExecution = cutOffLoaderExecution; +module.exports.cutOffMessage = cutOffMessage; +module.exports.cutOffMultilineMessage = cutOffMultilineMessage; +module.exports.cutOffWebpackOptions = cutOffWebpackOptions; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EvalDevToolModulePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EvalDevToolModulePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f5ca3d1958bd9aea8a3d4d34073b6f26f2ee8e1c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EvalDevToolModulePlugin.js @@ -0,0 +1,131 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource, RawSource } = require("webpack-sources"); +const ExternalModule = require("./ExternalModule"); +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("./Compiler")} Compiler */ + +/** @type {WeakMap} */ +const cache = new WeakMap(); + +const devtoolWarning = new RawSource(`/* + * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). + * This devtool is neither made for production nor for readable output files. + * It uses "eval()" calls to create a separate source file in the browser devtools. + * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) + * or disable the default devtool with "devtool: false". + * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). + */ +`); + +/** + * @typedef {object} EvalDevToolModulePluginOptions + * @property {OutputOptions["devtoolNamespace"]=} namespace namespace + * @property {string=} sourceUrlComment source url comment + * @property {OutputOptions["devtoolModuleFilenameTemplate"]=} moduleFilenameTemplate module filename template + */ + +const PLUGIN_NAME = "EvalDevToolModulePlugin"; + +class EvalDevToolModulePlugin { + /** + * @param {EvalDevToolModulePluginOptions=} options options + */ + constructor(options = {}) { + this.namespace = options.namespace || ""; + this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[loaders]"; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + hooks.renderModuleContent.tap( + PLUGIN_NAME, + (source, module, { chunk, runtimeTemplate, chunkGraph }) => { + const cacheEntry = cache.get(source); + if (cacheEntry !== undefined) return cacheEntry; + if (module instanceof ExternalModule) { + cache.set(source, source); + return source; + } + const content = source.source(); + const namespace = compilation.getPath(this.namespace, { + chunk + }); + const str = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace + }, + { + requestShortener: runtimeTemplate.requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction + } + ); + const footer = `\n${this.sourceUrlComment.replace( + /\[url\]/g, + encodeURI(str) + .replace(/%2F/g, "/") + .replace(/%20/g, "_") + .replace(/%5E/g, "^") + .replace(/%5C/g, "\\") + .replace(/^\//, "") + )}`; + const result = new RawSource( + `eval(${ + compilation.outputOptions.trustedTypes + ? `${RuntimeGlobals.createScript}(${JSON.stringify( + `{${content + footer}\n}` + )})` + : JSON.stringify(`{${content + footer}\n}`) + });` + ); + cache.set(source, result); + return result; + } + ); + hooks.inlineInRuntimeBailout.tap( + PLUGIN_NAME, + () => "the eval devtool is used." + ); + hooks.render.tap( + PLUGIN_NAME, + (source) => new ConcatSource(devtoolWarning, source) + ); + hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash) => { + hash.update(PLUGIN_NAME); + hash.update("2"); + }); + if (compilation.outputOptions.trustedTypes) { + compilation.hooks.additionalModuleRuntimeRequirements.tap( + PLUGIN_NAME, + (module, set, _context) => { + set.add(RuntimeGlobals.createScript); + } + ); + } + }); + } +} + +module.exports = EvalDevToolModulePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EvalSourceMapDevToolPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EvalSourceMapDevToolPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..a8c6ce318d4a7ff2b2a0cced9bc7b20dba2e86b7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/EvalSourceMapDevToolPlugin.js @@ -0,0 +1,226 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource, RawSource } = require("webpack-sources"); +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); +const NormalModule = require("./NormalModule"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin"); +const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); +const ConcatenatedModule = require("./optimize/ConcatenatedModule"); +const generateDebugId = require("./util/generateDebugId"); +const { makePathsAbsolute } = require("./util/identifier"); + +/** @typedef {import("webpack-sources").RawSourceMap} RawSourceMap */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").DevTool} DevToolOptions */ +/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./Compiler")} Compiler */ + +/** @type {WeakMap} */ +const cache = new WeakMap(); + +const devtoolWarning = new RawSource(`/* + * ATTENTION: An "eval-source-map" devtool has been used. + * This devtool is neither made for production nor for readable output files. + * It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools. + * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) + * or disable the default devtool with "devtool: false". + * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). + */ +`); + +const PLUGIN_NAME = "EvalSourceMapDevToolPlugin"; + +class EvalSourceMapDevToolPlugin { + /** + * @param {SourceMapDevToolPluginOptions | string} inputOptions Options object + */ + constructor(inputOptions) { + /** @type {SourceMapDevToolPluginOptions} */ + let options; + if (typeof inputOptions === "string") { + options = { + append: inputOptions + }; + } else { + options = inputOptions; + } + this.sourceMapComment = + options.append && typeof options.append !== "function" + ? options.append + : "//# sourceURL=[module]\n//# sourceMappingURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resource-path]?[hash]"; + this.namespace = options.namespace || ""; + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); + const matchModule = ModuleFilenameHelpers.matchObject.bind( + ModuleFilenameHelpers, + options + ); + hooks.renderModuleContent.tap( + PLUGIN_NAME, + (source, m, { chunk, runtimeTemplate, chunkGraph }) => { + const cachedSource = cache.get(source); + if (cachedSource !== undefined) { + return cachedSource; + } + + /** + * @param {Source} r result + * @returns {Source} result + */ + const result = (r) => { + cache.set(source, r); + return r; + }; + + if (m instanceof NormalModule) { + const module = /** @type {NormalModule} */ (m); + if (!matchModule(module.resource)) { + return result(source); + } + } else if (m instanceof ConcatenatedModule) { + const concatModule = /** @type {ConcatenatedModule} */ (m); + if (concatModule.rootModule instanceof NormalModule) { + const module = /** @type {NormalModule} */ ( + concatModule.rootModule + ); + if (!matchModule(module.resource)) { + return result(source); + } + } else { + return result(source); + } + } else { + return result(source); + } + + const namespace = compilation.getPath(this.namespace, { + chunk + }); + /** @type {RawSourceMap} */ + let sourceMap; + let content; + if (source.sourceAndMap) { + const sourceAndMap = source.sourceAndMap(options); + sourceMap = /** @type {RawSourceMap} */ (sourceAndMap.map); + content = sourceAndMap.source; + } else { + sourceMap = /** @type {RawSourceMap} */ (source.map(options)); + content = source.source(); + } + if (!sourceMap) { + return result(source); + } + + // Clone (flat) the sourcemap to ensure that the mutations below do not persist. + sourceMap = { ...sourceMap }; + const context = /** @type {string} */ (compiler.options.context); + const root = compiler.root; + const modules = sourceMap.sources.map((source) => { + if (!source.startsWith("webpack://")) return source; + source = makePathsAbsolute(context, source.slice(10), root); + const module = compilation.findModule(source); + return module || source; + }); + let moduleFilenames = modules.map((module) => + ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace + }, + { + requestShortener: runtimeTemplate.requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction + } + ) + ); + moduleFilenames = ModuleFilenameHelpers.replaceDuplicates( + moduleFilenames, + (filename, i, n) => { + for (let j = 0; j < n; j++) filename += "*"; + return filename; + } + ); + sourceMap.sources = moduleFilenames; + if (options.noSources) { + sourceMap.sourcesContent = undefined; + } + sourceMap.sourceRoot = options.sourceRoot || ""; + const moduleId = + /** @type {ModuleId} */ + (chunkGraph.getModuleId(m)); + sourceMap.file = + typeof moduleId === "number" ? `${moduleId}.js` : moduleId; + + if (options.debugIds) { + sourceMap.debugId = generateDebugId(content, sourceMap.file); + } + + const footer = `${this.sourceMapComment.replace( + /\[url\]/g, + `data:application/json;charset=utf-8;base64,${Buffer.from( + JSON.stringify(sourceMap), + "utf8" + ).toString("base64")}` + )}\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug + + return result( + new RawSource( + `eval(${ + compilation.outputOptions.trustedTypes + ? `${RuntimeGlobals.createScript}(${JSON.stringify( + `{${content + footer}\n}` + )})` + : JSON.stringify(`{${content + footer}\n}`) + });` + ) + ); + } + ); + hooks.inlineInRuntimeBailout.tap( + PLUGIN_NAME, + () => "the eval-source-map devtool is used." + ); + hooks.render.tap( + PLUGIN_NAME, + (source) => new ConcatSource(devtoolWarning, source) + ); + hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash) => { + hash.update(PLUGIN_NAME); + hash.update("2"); + }); + if (compilation.outputOptions.trustedTypes) { + compilation.hooks.additionalModuleRuntimeRequirements.tap( + PLUGIN_NAME, + (module, set, context) => { + set.add(RuntimeGlobals.createScript); + } + ); + } + }); + } +} + +module.exports = EvalSourceMapDevToolPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExportsInfo.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExportsInfo.js new file mode 100644 index 0000000000000000000000000000000000000000..695511ba8f6f4d48132b239936fbb33817ebfb64 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExportsInfo.js @@ -0,0 +1,1684 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { equals } = require("./util/ArrayHelpers"); +const SortableSet = require("./util/SortableSet"); +const makeSerializable = require("./util/makeSerializable"); +const { forEachRuntime } = require("./util/runtime"); + +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ + +/** @typedef {typeof UsageState.OnlyPropertiesUsed | typeof UsageState.NoInfo | typeof UsageState.Unknown | typeof UsageState.Used} RuntimeUsageStateType */ +/** @typedef {typeof UsageState.Unused | RuntimeUsageStateType} UsageStateType */ + +const UsageState = Object.freeze({ + Unused: /** @type {0} */ (0), + OnlyPropertiesUsed: /** @type {1} */ (1), + NoInfo: /** @type {2} */ (2), + Unknown: /** @type {3} */ (3), + Used: /** @type {4} */ (4) +}); + +const RETURNS_TRUE = () => true; + +const CIRCULAR = Symbol("circular target"); + +/** + * @typedef {object} RestoreProvidedDataExports + * @property {ExportInfoName} name + * @property {ExportInfo["provided"]} provided + * @property {ExportInfo["canMangleProvide"]} canMangleProvide + * @property {ExportInfo["terminalBinding"]} terminalBinding + * @property {RestoreProvidedData | undefined} exportsInfo + */ + +class RestoreProvidedData { + /** + * @param {RestoreProvidedDataExports[]} exports exports + * @param {ExportInfo["provided"]} otherProvided other provided + * @param {ExportInfo["canMangleProvide"]} otherCanMangleProvide other can mangle provide + * @param {ExportInfo["terminalBinding"]} otherTerminalBinding other terminal binding + */ + constructor( + exports, + otherProvided, + otherCanMangleProvide, + otherTerminalBinding + ) { + this.exports = exports; + this.otherProvided = otherProvided; + this.otherCanMangleProvide = otherCanMangleProvide; + this.otherTerminalBinding = otherTerminalBinding; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize({ write }) { + write(this.exports); + write(this.otherProvided); + write(this.otherCanMangleProvide); + write(this.otherTerminalBinding); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {RestoreProvidedData} RestoreProvidedData + */ + static deserialize({ read }) { + return new RestoreProvidedData(read(), read(), read(), read()); + } +} + +makeSerializable( + RestoreProvidedData, + "webpack/lib/ModuleGraph", + "RestoreProvidedData" +); + +/** @typedef {Map} Exports */ +/** @typedef {string | string[] | false} UsedName */ + +class ExportsInfo { + constructor() { + /** @type {Exports} */ + this._exports = new Map(); + this._otherExportsInfo = new ExportInfo(/** @type {TODO} */ (null)); + this._sideEffectsOnlyInfo = new ExportInfo("*side effects only*"); + this._exportsAreOrdered = false; + /** @type {ExportsInfo=} */ + this._redirectTo = undefined; + } + + /** + * @returns {Iterable} all owned exports in any order + */ + get ownedExports() { + return this._exports.values(); + } + + /** + * @returns {Iterable} all owned exports in order + */ + get orderedOwnedExports() { + if (!this._exportsAreOrdered) { + this._sortExports(); + } + return this._exports.values(); + } + + /** + * @returns {Iterable} all exports in any order + */ + get exports() { + if (this._redirectTo !== undefined) { + const map = new Map(this._redirectTo._exports); + for (const [key, value] of this._exports) { + map.set(key, value); + } + return map.values(); + } + return this._exports.values(); + } + + /** + * @returns {Iterable} all exports in order + */ + get orderedExports() { + if (!this._exportsAreOrdered) { + this._sortExports(); + } + if (this._redirectTo !== undefined) { + /** @type {Exports} */ + const map = new Map( + Array.from(this._redirectTo.orderedExports, (item) => [item.name, item]) + ); + for (const [key, value] of this._exports) { + map.set(key, value); + } + // sorting should be pretty fast as map contains + // a lot of presorted items + this._sortExportsMap(map); + return map.values(); + } + return this._exports.values(); + } + + /** + * @returns {ExportInfo} the export info of unlisted exports + */ + get otherExportsInfo() { + if (this._redirectTo !== undefined) { + return this._redirectTo.otherExportsInfo; + } + return this._otherExportsInfo; + } + + /** + * @param {Exports} exports exports + * @private + */ + _sortExportsMap(exports) { + if (exports.size > 1) { + /** @type {string[]} */ + const namesInOrder = []; + for (const entry of exports.values()) { + namesInOrder.push(entry.name); + } + namesInOrder.sort(); + let i = 0; + for (const entry of exports.values()) { + const name = namesInOrder[i]; + if (entry.name !== name) break; + i++; + } + for (; i < namesInOrder.length; i++) { + const name = namesInOrder[i]; + const correctEntry = /** @type {ExportInfo} */ (exports.get(name)); + exports.delete(name); + exports.set(name, correctEntry); + } + } + } + + _sortExports() { + this._sortExportsMap(this._exports); + this._exportsAreOrdered = true; + } + + /** + * @param {ExportsInfo | undefined} exportsInfo exports info + * @returns {boolean} result + */ + setRedirectNamedTo(exportsInfo) { + if (this._redirectTo === exportsInfo) return false; + this._redirectTo = exportsInfo; + return true; + } + + setHasProvideInfo() { + for (const exportInfo of this._exports.values()) { + if (exportInfo.provided === undefined) { + exportInfo.provided = false; + } + if (exportInfo.canMangleProvide === undefined) { + exportInfo.canMangleProvide = true; + } + } + if (this._redirectTo !== undefined) { + this._redirectTo.setHasProvideInfo(); + } else { + if (this._otherExportsInfo.provided === undefined) { + this._otherExportsInfo.provided = false; + } + if (this._otherExportsInfo.canMangleProvide === undefined) { + this._otherExportsInfo.canMangleProvide = true; + } + } + } + + setHasUseInfo() { + for (const exportInfo of this._exports.values()) { + exportInfo.setHasUseInfo(); + } + this._sideEffectsOnlyInfo.setHasUseInfo(); + if (this._redirectTo !== undefined) { + this._redirectTo.setHasUseInfo(); + } else { + this._otherExportsInfo.setHasUseInfo(); + } + } + + /** + * @param {ExportInfoName} name export name + * @returns {ExportInfo} export info for this name + */ + getOwnExportInfo(name) { + const info = this._exports.get(name); + if (info !== undefined) return info; + const newInfo = new ExportInfo(name, this._otherExportsInfo); + this._exports.set(name, newInfo); + this._exportsAreOrdered = false; + return newInfo; + } + + /** + * @param {ExportInfoName} name export name + * @returns {ExportInfo} export info for this name + */ + getExportInfo(name) { + const info = this._exports.get(name); + if (info !== undefined) return info; + if (this._redirectTo !== undefined) { + return this._redirectTo.getExportInfo(name); + } + const newInfo = new ExportInfo(name, this._otherExportsInfo); + this._exports.set(name, newInfo); + this._exportsAreOrdered = false; + return newInfo; + } + + /** + * @param {ExportInfoName} name export name + * @returns {ExportInfo} export info for this name + */ + getReadOnlyExportInfo(name) { + const info = this._exports.get(name); + if (info !== undefined) return info; + if (this._redirectTo !== undefined) { + return this._redirectTo.getReadOnlyExportInfo(name); + } + return this._otherExportsInfo; + } + + /** + * @param {ExportInfoName[]} name export name + * @returns {ExportInfo | undefined} export info for this name + */ + getReadOnlyExportInfoRecursive(name) { + const exportInfo = this.getReadOnlyExportInfo(name[0]); + if (name.length === 1) return exportInfo; + if (!exportInfo.exportsInfo) return; + return exportInfo.exportsInfo.getReadOnlyExportInfoRecursive(name.slice(1)); + } + + /** + * @param {ExportInfoName[]=} name the export name + * @returns {ExportsInfo | undefined} the nested exports info + */ + getNestedExportsInfo(name) { + if (Array.isArray(name) && name.length > 0) { + const info = this.getReadOnlyExportInfo(name[0]); + if (!info.exportsInfo) return; + return info.exportsInfo.getNestedExportsInfo(name.slice(1)); + } + return this; + } + + /** + * @param {boolean=} canMangle true, if exports can still be mangled (defaults to false) + * @param {Set=} excludeExports list of unaffected exports + * @param {Dependency=} targetKey use this as key for the target + * @param {ModuleGraphConnection=} targetModule set this module as target + * @param {number=} priority priority + * @returns {boolean} true, if this call changed something + */ + setUnknownExportsProvided( + canMangle, + excludeExports, + targetKey, + targetModule, + priority + ) { + let changed = false; + if (excludeExports) { + for (const name of excludeExports) { + // Make sure these entries exist, so they can get different info + this.getExportInfo(name); + } + } + for (const exportInfo of this._exports.values()) { + if (!canMangle && exportInfo.canMangleProvide !== false) { + exportInfo.canMangleProvide = false; + changed = true; + } + if (excludeExports && excludeExports.has(exportInfo.name)) continue; + if (exportInfo.provided !== true && exportInfo.provided !== null) { + exportInfo.provided = null; + changed = true; + } + if (targetKey) { + exportInfo.setTarget( + targetKey, + /** @type {ModuleGraphConnection} */ + (targetModule), + [exportInfo.name], + -1 + ); + } + } + if (this._redirectTo !== undefined) { + if ( + this._redirectTo.setUnknownExportsProvided( + canMangle, + excludeExports, + targetKey, + targetModule, + priority + ) + ) { + changed = true; + } + } else { + if ( + this._otherExportsInfo.provided !== true && + this._otherExportsInfo.provided !== null + ) { + this._otherExportsInfo.provided = null; + changed = true; + } + if (!canMangle && this._otherExportsInfo.canMangleProvide !== false) { + this._otherExportsInfo.canMangleProvide = false; + changed = true; + } + if (targetKey) { + this._otherExportsInfo.setTarget( + targetKey, + /** @type {ModuleGraphConnection} */ (targetModule), + undefined, + priority + ); + } + } + return changed; + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setUsedInUnknownWay(runtime) { + let changed = false; + for (const exportInfo of this._exports.values()) { + if (exportInfo.setUsedInUnknownWay(runtime)) { + changed = true; + } + } + if (this._redirectTo !== undefined) { + if (this._redirectTo.setUsedInUnknownWay(runtime)) { + changed = true; + } + } else { + if ( + this._otherExportsInfo.setUsedConditionally( + (used) => used < UsageState.Unknown, + UsageState.Unknown, + runtime + ) + ) { + changed = true; + } + if (this._otherExportsInfo.canMangleUse !== false) { + this._otherExportsInfo.canMangleUse = false; + changed = true; + } + } + return changed; + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setUsedWithoutInfo(runtime) { + let changed = false; + for (const exportInfo of this._exports.values()) { + if (exportInfo.setUsedWithoutInfo(runtime)) { + changed = true; + } + } + if (this._redirectTo !== undefined) { + if (this._redirectTo.setUsedWithoutInfo(runtime)) { + changed = true; + } + } else { + if (this._otherExportsInfo.setUsed(UsageState.NoInfo, runtime)) { + changed = true; + } + if (this._otherExportsInfo.canMangleUse !== false) { + this._otherExportsInfo.canMangleUse = false; + changed = true; + } + } + return changed; + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setAllKnownExportsUsed(runtime) { + let changed = false; + for (const exportInfo of this._exports.values()) { + if (!exportInfo.provided) continue; + if (exportInfo.setUsed(UsageState.Used, runtime)) { + changed = true; + } + } + return changed; + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setUsedForSideEffectsOnly(runtime) { + return this._sideEffectsOnlyInfo.setUsedConditionally( + (used) => used === UsageState.Unused, + UsageState.Used, + runtime + ); + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when the module exports are used in any way + */ + isUsed(runtime) { + if (this._redirectTo !== undefined) { + if (this._redirectTo.isUsed(runtime)) { + return true; + } + } else if (this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + return true; + } + for (const exportInfo of this._exports.values()) { + if (exportInfo.getUsed(runtime) !== UsageState.Unused) { + return true; + } + } + return false; + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when the module is used in any way + */ + isModuleUsed(runtime) { + if (this.isUsed(runtime)) return true; + if (this._sideEffectsOnlyInfo.getUsed(runtime) !== UsageState.Unused) { + return true; + } + return false; + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {SortableSet | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown) + */ + getUsedExports(runtime) { + switch (this._otherExportsInfo.getUsed(runtime)) { + case UsageState.NoInfo: + return null; + case UsageState.Unknown: + case UsageState.OnlyPropertiesUsed: + case UsageState.Used: + return true; + } + + const array = []; + if (!this._exportsAreOrdered) this._sortExports(); + for (const exportInfo of this._exports.values()) { + switch (exportInfo.getUsed(runtime)) { + case UsageState.NoInfo: + return null; + case UsageState.Unknown: + return true; + case UsageState.OnlyPropertiesUsed: + case UsageState.Used: + array.push(exportInfo.name); + } + } + if (this._redirectTo !== undefined) { + const inner = this._redirectTo.getUsedExports(runtime); + if (inner === null) return null; + if (inner === true) return true; + if (inner !== false) { + for (const item of inner) { + array.push(item); + } + } + } + if (array.length === 0) { + switch (this._sideEffectsOnlyInfo.getUsed(runtime)) { + case UsageState.NoInfo: + return null; + case UsageState.Unused: + return false; + } + } + return /** @type {SortableSet} */ (new SortableSet(array)); + } + + /** + * @returns {null | true | string[]} list of exports when known + */ + getProvidedExports() { + switch (this._otherExportsInfo.provided) { + case undefined: + return null; + case null: + return true; + case true: + return true; + } + + /** @type {string[]} */ + const array = []; + if (!this._exportsAreOrdered) this._sortExports(); + for (const exportInfo of this._exports.values()) { + switch (exportInfo.provided) { + case undefined: + return null; + case null: + return true; + case true: + array.push(exportInfo.name); + } + } + if (this._redirectTo !== undefined) { + const inner = this._redirectTo.getProvidedExports(); + if (inner === null) return null; + if (inner === true) return true; + for (const item of inner) { + if (!array.includes(item)) { + array.push(item); + } + } + } + return array; + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {ExportInfo[]} exports that are relevant (not unused and potential provided) + */ + getRelevantExports(runtime) { + const list = []; + for (const exportInfo of this._exports.values()) { + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) continue; + if (exportInfo.provided === false) continue; + list.push(exportInfo); + } + if (this._redirectTo !== undefined) { + for (const exportInfo of this._redirectTo.getRelevantExports(runtime)) { + if (!this._exports.has(exportInfo.name)) list.push(exportInfo); + } + } + if ( + this._otherExportsInfo.provided !== false && + this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused + ) { + list.push(this._otherExportsInfo); + } + return list; + } + + /** + * @param {ExportInfoName | ExportInfoName[]} name the name of the export + * @returns {boolean | undefined | null} if the export is provided + */ + isExportProvided(name) { + if (Array.isArray(name)) { + const info = this.getReadOnlyExportInfo(name[0]); + if (info.exportsInfo && name.length > 1) { + return info.exportsInfo.isExportProvided(name.slice(1)); + } + return info.provided ? name.length === 1 || undefined : info.provided; + } + const info = this.getReadOnlyExportInfo(name); + return info.provided; + } + + /** + * @param {RuntimeSpec} runtime runtime + * @returns {string} key representing the usage + */ + getUsageKey(runtime) { + const key = []; + if (this._redirectTo !== undefined) { + key.push(this._redirectTo.getUsageKey(runtime)); + } else { + key.push(this._otherExportsInfo.getUsed(runtime)); + } + key.push(this._sideEffectsOnlyInfo.getUsed(runtime)); + for (const exportInfo of this.orderedOwnedExports) { + key.push(exportInfo.getUsed(runtime)); + } + return key.join("|"); + } + + /** + * @param {RuntimeSpec} runtimeA first runtime + * @param {RuntimeSpec} runtimeB second runtime + * @returns {boolean} true, when equally used + */ + isEquallyUsed(runtimeA, runtimeB) { + if (this._redirectTo !== undefined) { + if (!this._redirectTo.isEquallyUsed(runtimeA, runtimeB)) return false; + } else if ( + this._otherExportsInfo.getUsed(runtimeA) !== + this._otherExportsInfo.getUsed(runtimeB) + ) { + return false; + } + if ( + this._sideEffectsOnlyInfo.getUsed(runtimeA) !== + this._sideEffectsOnlyInfo.getUsed(runtimeB) + ) { + return false; + } + for (const exportInfo of this.ownedExports) { + if (exportInfo.getUsed(runtimeA) !== exportInfo.getUsed(runtimeB)) { + return false; + } + } + return true; + } + + /** + * @param {ExportInfoName | ExportInfoName[]} name export name + * @param {RuntimeSpec} runtime check usage for this runtime only + * @returns {UsageStateType} usage status + */ + getUsed(name, runtime) { + if (Array.isArray(name)) { + if (name.length === 0) return this.otherExportsInfo.getUsed(runtime); + const info = this.getReadOnlyExportInfo(name[0]); + if (info.exportsInfo && name.length > 1) { + return info.exportsInfo.getUsed(name.slice(1), runtime); + } + return info.getUsed(runtime); + } + const info = this.getReadOnlyExportInfo(name); + return info.getUsed(runtime); + } + + /** + * @param {ExportInfoName | ExportInfoName[]} name the export name + * @param {RuntimeSpec} runtime check usage for this runtime only + * @returns {UsedName} the used name + */ + getUsedName(name, runtime) { + if (Array.isArray(name)) { + // TODO improve this + if (name.length === 0) { + if (!this.isUsed(runtime)) return false; + return name; + } + const info = this.getReadOnlyExportInfo(name[0]); + const x = info.getUsedName(name[0], runtime); + if (x === false) return false; + const arr = + /** @type {ExportInfoName[]} */ + (x === name[0] && name.length === 1 ? name : [x]); + if (name.length === 1) { + return arr; + } + if ( + info.exportsInfo && + info.getUsed(runtime) === UsageState.OnlyPropertiesUsed + ) { + const nested = info.exportsInfo.getUsedName(name.slice(1), runtime); + if (!nested) return false; + return [...arr, ...(Array.isArray(nested) ? nested : [nested])]; + } + return [...arr, ...name.slice(1)]; + } + const info = this.getReadOnlyExportInfo(name); + const usedName = info.getUsedName(name, runtime); + return usedName; + } + + /** + * @param {Hash} hash the hash + * @param {RuntimeSpec} runtime the runtime + * @returns {void} + */ + updateHash(hash, runtime) { + this._updateHash(hash, runtime, new Set()); + } + + /** + * @param {Hash} hash the hash + * @param {RuntimeSpec} runtime the runtime + * @param {Set} alreadyVisitedExportsInfo for circular references + * @returns {void} + */ + _updateHash(hash, runtime, alreadyVisitedExportsInfo) { + const set = new Set(alreadyVisitedExportsInfo); + set.add(this); + for (const exportInfo of this.orderedExports) { + if (exportInfo.hasInfo(this._otherExportsInfo, runtime)) { + exportInfo._updateHash(hash, runtime, set); + } + } + this._sideEffectsOnlyInfo._updateHash(hash, runtime, set); + this._otherExportsInfo._updateHash(hash, runtime, set); + if (this._redirectTo !== undefined) { + this._redirectTo._updateHash(hash, runtime, set); + } + } + + /** + * @returns {RestoreProvidedData} restore provided data + */ + getRestoreProvidedData() { + const otherProvided = this._otherExportsInfo.provided; + const otherCanMangleProvide = this._otherExportsInfo.canMangleProvide; + const otherTerminalBinding = this._otherExportsInfo.terminalBinding; + /** @type {RestoreProvidedDataExports[]} */ + const exports = []; + for (const exportInfo of this.orderedExports) { + if ( + exportInfo.provided !== otherProvided || + exportInfo.canMangleProvide !== otherCanMangleProvide || + exportInfo.terminalBinding !== otherTerminalBinding || + exportInfo.exportsInfoOwned + ) { + exports.push({ + name: exportInfo.name, + provided: exportInfo.provided, + canMangleProvide: exportInfo.canMangleProvide, + terminalBinding: exportInfo.terminalBinding, + exportsInfo: exportInfo.exportsInfoOwned + ? /** @type {NonNullable} */ + (exportInfo.exportsInfo).getRestoreProvidedData() + : undefined + }); + } + } + return new RestoreProvidedData( + exports, + otherProvided, + otherCanMangleProvide, + otherTerminalBinding + ); + } + + /** + * @param {RestoreProvidedData} data data + */ + restoreProvided({ + otherProvided, + otherCanMangleProvide, + otherTerminalBinding, + exports + }) { + let wasEmpty = true; + for (const exportInfo of this._exports.values()) { + wasEmpty = false; + exportInfo.provided = otherProvided; + exportInfo.canMangleProvide = otherCanMangleProvide; + exportInfo.terminalBinding = otherTerminalBinding; + } + this._otherExportsInfo.provided = otherProvided; + this._otherExportsInfo.canMangleProvide = otherCanMangleProvide; + this._otherExportsInfo.terminalBinding = otherTerminalBinding; + for (const exp of exports) { + const exportInfo = this.getExportInfo(exp.name); + exportInfo.provided = exp.provided; + exportInfo.canMangleProvide = exp.canMangleProvide; + exportInfo.terminalBinding = exp.terminalBinding; + if (exp.exportsInfo) { + const exportsInfo = exportInfo.createNestedExportsInfo(); + exportsInfo.restoreProvided(exp.exportsInfo); + } + } + if (wasEmpty) this._exportsAreOrdered = true; + } +} + +/** @typedef {Map} UsedInRuntime */ + +/** @typedef {{ module: Module, export: string[], deferred: boolean }} TargetItemWithoutConnection */ + +/** @typedef {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} TargetItemWithConnection */ + +/** @typedef {(target: TargetItemWithConnection) => boolean} ResolveTargetFilter */ + +/** @typedef {(module: Module) => boolean} ValidTargetModuleFilter */ + +/** @typedef {{ connection: ModuleGraphConnection, export: string[], priority: number }} TargetItem */ + +/** @typedef {Map} Target */ + +/** @typedef {string} ExportInfoName */ +/** @typedef {string | null} ExportInfoUsedName */ +/** @typedef {boolean | null} ExportInfoProvided */ + +class ExportInfo { + /** + * @param {ExportInfoName} name the original name of the export + * @param {ExportInfo=} initFrom init values from this ExportInfo + */ + constructor(name, initFrom) { + /** @type {ExportInfoName} */ + this.name = name; + /** + * @private + * @type {ExportInfoUsedName} + */ + this._usedName = initFrom ? initFrom._usedName : null; + /** + * @private + * @type {UsageStateType | undefined} + */ + this._globalUsed = initFrom ? initFrom._globalUsed : undefined; + /** + * @private + * @type {UsedInRuntime | undefined} + */ + this._usedInRuntime = + initFrom && initFrom._usedInRuntime + ? new Map(initFrom._usedInRuntime) + : undefined; + /** + * @private + * @type {boolean} + */ + this._hasUseInRuntimeInfo = initFrom + ? initFrom._hasUseInRuntimeInfo + : false; + /** + * true: it is provided + * false: it is not provided + * null: only the runtime knows if it is provided + * undefined: it was not determined if it is provided + * @type {ExportInfoProvided | undefined} + */ + this.provided = initFrom ? initFrom.provided : undefined; + /** + * is the export a terminal binding that should be checked for export star conflicts + * @type {boolean} + */ + this.terminalBinding = initFrom ? initFrom.terminalBinding : false; + /** + * true: it can be mangled + * false: is can not be mangled + * undefined: it was not determined if it can be mangled + * @type {boolean | undefined} + */ + this.canMangleProvide = initFrom ? initFrom.canMangleProvide : undefined; + /** + * true: it can be mangled + * false: is can not be mangled + * undefined: it was not determined if it can be mangled + * @type {boolean | undefined} + */ + this.canMangleUse = initFrom ? initFrom.canMangleUse : undefined; + /** @type {boolean} */ + this.exportsInfoOwned = false; + /** @type {ExportsInfo | undefined} */ + this.exportsInfo = undefined; + /** @type {Target | undefined} */ + this._target = undefined; + if (initFrom && initFrom._target) { + this._target = new Map(); + for (const [key, value] of initFrom._target) { + this._target.set(key, { + connection: value.connection, + export: value.export || [name], + priority: value.priority + }); + } + } + /** @type {Target | undefined} */ + this._maxTarget = undefined; + } + + // TODO webpack 5 remove + /** + * @private + * @param {EXPECTED_ANY} v v + */ + set used(v) { + throw new Error("REMOVED"); + } + + // TODO webpack 5 remove + /** @private */ + get used() { + throw new Error("REMOVED"); + } + + // TODO webpack 5 remove + /** + * @private + * @param {EXPECTED_ANY} v v + */ + set usedName(v) { + throw new Error("REMOVED"); + } + + // TODO webpack 5 remove + /** @private */ + get usedName() { + throw new Error("REMOVED"); + } + + get canMangle() { + switch (this.canMangleProvide) { + case undefined: + return this.canMangleUse === false ? false : undefined; + case false: + return false; + case true: + switch (this.canMangleUse) { + case undefined: + return undefined; + case false: + return false; + case true: + return true; + } + } + throw new Error( + `Unexpected flags for canMangle ${this.canMangleProvide} ${this.canMangleUse}` + ); + } + + /** + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true, when something changed + */ + setUsedInUnknownWay(runtime) { + let changed = false; + if ( + this.setUsedConditionally( + (used) => used < UsageState.Unknown, + UsageState.Unknown, + runtime + ) + ) { + changed = true; + } + if (this.canMangleUse !== false) { + this.canMangleUse = false; + changed = true; + } + return changed; + } + + /** + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true, when something changed + */ + setUsedWithoutInfo(runtime) { + let changed = false; + if (this.setUsed(UsageState.NoInfo, runtime)) { + changed = true; + } + if (this.canMangleUse !== false) { + this.canMangleUse = false; + changed = true; + } + return changed; + } + + setHasUseInfo() { + if (!this._hasUseInRuntimeInfo) { + this._hasUseInRuntimeInfo = true; + } + if (this.canMangleUse === undefined) { + this.canMangleUse = true; + } + if (this.exportsInfoOwned) { + /** @type {ExportsInfo} */ + (this.exportsInfo).setHasUseInfo(); + } + } + + /** + * @param {(condition: UsageStateType) => boolean} condition compare with old value + * @param {UsageStateType} newValue set when condition is true + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true when something has changed + */ + setUsedConditionally(condition, newValue, runtime) { + if (runtime === undefined) { + if (this._globalUsed === undefined) { + this._globalUsed = newValue; + return true; + } + if (this._globalUsed !== newValue && condition(this._globalUsed)) { + this._globalUsed = newValue; + return true; + } + } else if (this._usedInRuntime === undefined) { + if (newValue !== UsageState.Unused && condition(UsageState.Unused)) { + this._usedInRuntime = new Map(); + forEachRuntime(runtime, (runtime) => + /** @type {UsedInRuntime} */ + (this._usedInRuntime).set(/** @type {string} */ (runtime), newValue) + ); + return true; + } + } else { + let changed = false; + forEachRuntime(runtime, (_runtime) => { + const runtime = /** @type {string} */ (_runtime); + const usedInRuntime = + /** @type {UsedInRuntime} */ + (this._usedInRuntime); + let oldValue = + /** @type {UsageStateType} */ + (usedInRuntime.get(runtime)); + if (oldValue === undefined) oldValue = UsageState.Unused; + if (newValue !== oldValue && condition(oldValue)) { + if (newValue === UsageState.Unused) { + usedInRuntime.delete(runtime); + } else { + usedInRuntime.set(runtime, newValue); + } + changed = true; + } + }); + if (changed) { + if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; + return true; + } + } + return false; + } + + /** + * @param {UsageStateType} newValue new value of the used state + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true when something has changed + */ + setUsed(newValue, runtime) { + if (runtime === undefined) { + if (this._globalUsed !== newValue) { + this._globalUsed = newValue; + return true; + } + } else if (this._usedInRuntime === undefined) { + if (newValue !== UsageState.Unused) { + this._usedInRuntime = new Map(); + forEachRuntime(runtime, (runtime) => + /** @type {UsedInRuntime} */ + (this._usedInRuntime).set(/** @type {string} */ (runtime), newValue) + ); + return true; + } + } else { + let changed = false; + forEachRuntime(runtime, (_runtime) => { + const runtime = /** @type {string} */ (_runtime); + const usedInRuntime = + /** @type {UsedInRuntime} */ + (this._usedInRuntime); + let oldValue = + /** @type {UsageStateType} */ + (usedInRuntime.get(runtime)); + if (oldValue === undefined) oldValue = UsageState.Unused; + if (newValue !== oldValue) { + if (newValue === UsageState.Unused) { + usedInRuntime.delete(runtime); + } else { + usedInRuntime.set(runtime, newValue); + } + changed = true; + } + }); + if (changed) { + if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; + return true; + } + } + return false; + } + + /** + * @param {Dependency} key the key + * @returns {boolean} true, if something has changed + */ + unsetTarget(key) { + if (!this._target) return false; + if (this._target.delete(key)) { + this._maxTarget = undefined; + return true; + } + return false; + } + + /** + * @param {Dependency} key the key + * @param {ModuleGraphConnection} connection the target module if a single one + * @param {(string[] | null)=} exportName the exported name + * @param {number=} priority priority + * @returns {boolean} true, if something has changed + */ + setTarget(key, connection, exportName, priority = 0) { + if (exportName) exportName = [...exportName]; + if (!this._target) { + this._target = new Map(); + this._target.set(key, { + connection, + export: /** @type {string[]} */ (exportName), + priority + }); + return true; + } + const oldTarget = this._target.get(key); + if (!oldTarget) { + if (oldTarget === null && !connection) return false; + this._target.set(key, { + connection, + export: /** @type {string[]} */ (exportName), + priority + }); + this._maxTarget = undefined; + return true; + } + if ( + oldTarget.connection !== connection || + oldTarget.priority !== priority || + (exportName + ? !oldTarget.export || !equals(oldTarget.export, exportName) + : oldTarget.export) + ) { + oldTarget.connection = connection; + oldTarget.export = /** @type {string[]} */ (exportName); + oldTarget.priority = priority; + this._maxTarget = undefined; + return true; + } + return false; + } + + /** + * @param {RuntimeSpec} runtime for this runtime + * @returns {UsageStateType} usage state + */ + getUsed(runtime) { + if (!this._hasUseInRuntimeInfo) return UsageState.NoInfo; + if (this._globalUsed !== undefined) return this._globalUsed; + if (this._usedInRuntime === undefined) { + return UsageState.Unused; + } else if (typeof runtime === "string") { + const value = this._usedInRuntime.get(runtime); + return value === undefined ? UsageState.Unused : value; + } else if (runtime === undefined) { + /** @type {UsageStateType} */ + let max = UsageState.Unused; + for (const value of this._usedInRuntime.values()) { + if (value === UsageState.Used) { + return UsageState.Used; + } + if (max < value) max = value; + } + return max; + } + + /** @type {UsageStateType} */ + let max = UsageState.Unused; + for (const item of runtime) { + const value = this._usedInRuntime.get(item); + if (value !== undefined) { + if (value === UsageState.Used) { + return UsageState.Used; + } + if (max < value) max = value; + } + } + return max; + } + + /** + * get used name + * @param {string | undefined} fallbackName fallback name for used exports with no name + * @param {RuntimeSpec} runtime check usage for this runtime only + * @returns {string | false} used name + */ + getUsedName(fallbackName, runtime) { + if (this._hasUseInRuntimeInfo) { + if (this._globalUsed !== undefined) { + if (this._globalUsed === UsageState.Unused) return false; + } else { + if (this._usedInRuntime === undefined) return false; + if (typeof runtime === "string") { + if (!this._usedInRuntime.has(runtime)) { + return false; + } + } else if ( + runtime !== undefined && + [...runtime].every( + (runtime) => + !(/** @type {UsedInRuntime} */ (this._usedInRuntime).has(runtime)) + ) + ) { + return false; + } + } + } + if (this._usedName !== null) return this._usedName; + return /** @type {string | false} */ (this.name || fallbackName); + } + + /** + * @returns {boolean} true, when a mangled name of this export is set + */ + hasUsedName() { + return this._usedName !== null; + } + + /** + * Sets the mangled name of this export + * @param {string} name the new name + * @returns {void} + */ + setUsedName(name) { + this._usedName = name; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ResolveTargetFilter} resolveTargetFilter filter function to further resolve target + * @returns {ExportInfo | ExportsInfo | undefined} the terminal binding export(s) info if known + */ + getTerminalBinding(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { + if (this.terminalBinding) return this; + const target = this.getTarget(moduleGraph, resolveTargetFilter); + if (!target) return; + const exportsInfo = moduleGraph.getExportsInfo(target.module); + if (!target.export) return exportsInfo; + return exportsInfo.getReadOnlyExportInfoRecursive(target.export); + } + + isReexport() { + return !this.terminalBinding && this._target && this._target.size > 0; + } + + _getMaxTarget() { + if (this._maxTarget !== undefined) return this._maxTarget; + if (/** @type {Target} */ (this._target).size <= 1) { + return (this._maxTarget = this._target); + } + let maxPriority = -Infinity; + let minPriority = Infinity; + for (const { priority } of /** @type {Target} */ (this._target).values()) { + if (maxPriority < priority) maxPriority = priority; + if (minPriority > priority) minPriority = priority; + } + // This should be very common + if (maxPriority === minPriority) return (this._maxTarget = this._target); + + // This is an edge case + /** @type {Target} */ + const map = new Map(); + for (const [key, value] of /** @type {Target} */ (this._target)) { + if (maxPriority === value.priority) { + map.set(key, value); + } + } + this._maxTarget = map; + return map; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ValidTargetModuleFilter} validTargetModuleFilter a valid target module + * @returns {TargetItemWithoutConnection | null | undefined | false} the target, undefined when there is no target, false when no target is valid + */ + findTarget(moduleGraph, validTargetModuleFilter) { + return this._findTarget(moduleGraph, validTargetModuleFilter, new Set()); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ValidTargetModuleFilter} validTargetModuleFilter a valid target module + * @param {Set} alreadyVisited set of already visited export info to avoid circular references + * @returns {TargetItemWithoutConnection | null | undefined | false} the target, undefined when there is no target, false when no target is valid + */ + _findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) { + if (!this._target || this._target.size === 0) return; + const rawTarget = + /** @type {Target} */ + (this._getMaxTarget()).values().next().value; + if (!rawTarget) return; + /** @type {TargetItemWithoutConnection} */ + let target = { + module: rawTarget.connection.module, + export: rawTarget.export, + deferred: Boolean( + rawTarget.connection.dependency && rawTarget.connection.dependency.defer + ) + }; + for (;;) { + if (validTargetModuleFilter(target.module)) return target; + const exportsInfo = moduleGraph.getExportsInfo(target.module); + const exportInfo = exportsInfo.getExportInfo(target.export[0]); + if (alreadyVisited.has(exportInfo)) return null; + const newTarget = exportInfo._findTarget( + moduleGraph, + validTargetModuleFilter, + alreadyVisited + ); + if (!newTarget) return false; + if (target.export.length === 1) { + target = newTarget; + } else { + target = { + module: newTarget.module, + export: newTarget.export + ? [...newTarget.export, ...target.export.slice(1)] + : target.export.slice(1), + deferred: newTarget.deferred + }; + } + } + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ResolveTargetFilter} resolveTargetFilter filter function to further resolve target + * @returns {TargetItemWithConnection | undefined} the target + */ + getTarget(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { + const result = this._getTarget(moduleGraph, resolveTargetFilter, undefined); + if (result === CIRCULAR) return; + return result; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ResolveTargetFilter} resolveTargetFilter filter function to further resolve target + * @param {Set | undefined} alreadyVisited set of already visited export info to avoid circular references + * @returns {TargetItemWithConnection | CIRCULAR | undefined} the target + */ + _getTarget(moduleGraph, resolveTargetFilter, alreadyVisited) { + /** + * @param {TargetItem | undefined | null} inputTarget unresolved target + * @param {Set} alreadyVisited set of already visited export info to avoid circular references + * @returns {TargetItemWithConnection | CIRCULAR | null} resolved target + */ + const resolveTarget = (inputTarget, alreadyVisited) => { + if (!inputTarget) return null; + if (!inputTarget.export) { + return { + module: inputTarget.connection.module, + connection: inputTarget.connection, + export: undefined + }; + } + /** @type {TargetItemWithConnection} */ + let target = { + module: inputTarget.connection.module, + connection: inputTarget.connection, + export: inputTarget.export + }; + if (!resolveTargetFilter(target)) return target; + let alreadyVisitedOwned = false; + for (;;) { + const exportsInfo = moduleGraph.getExportsInfo(target.module); + const exportInfo = exportsInfo.getExportInfo( + /** @type {NonNullable} */ + (target.export)[0] + ); + if (!exportInfo) return target; + if (alreadyVisited.has(exportInfo)) return CIRCULAR; + const newTarget = exportInfo._getTarget( + moduleGraph, + resolveTargetFilter, + alreadyVisited + ); + if (newTarget === CIRCULAR) return CIRCULAR; + if (!newTarget) return target; + if ( + /** @type {NonNullable} */ + (target.export).length === 1 + ) { + target = newTarget; + if (!target.export) return target; + } else { + target = { + module: newTarget.module, + connection: newTarget.connection, + export: newTarget.export + ? [ + ...newTarget.export, + .../** @type {NonNullable} */ + (target.export).slice(1) + ] + : /** @type {NonNullable} */ + (target.export).slice(1) + }; + } + if (!resolveTargetFilter(target)) return target; + if (!alreadyVisitedOwned) { + alreadyVisited = new Set(alreadyVisited); + alreadyVisitedOwned = true; + } + alreadyVisited.add(exportInfo); + } + }; + + if (!this._target || this._target.size === 0) return; + if (alreadyVisited && alreadyVisited.has(this)) return CIRCULAR; + const newAlreadyVisited = new Set(alreadyVisited); + newAlreadyVisited.add(this); + const values = /** @type {Target} */ (this._getMaxTarget()).values(); + const target = resolveTarget(values.next().value, newAlreadyVisited); + if (target === CIRCULAR) return CIRCULAR; + if (target === null) return; + let result = values.next(); + while (!result.done) { + const t = resolveTarget(result.value, newAlreadyVisited); + if (t === CIRCULAR) return CIRCULAR; + if (t === null) return; + if (t.module !== target.module) return; + if (!t.export !== !target.export) return; + if ( + target.export && + !equals(/** @type {ArrayLike} */ (t.export), target.export) + ) { + return; + } + result = values.next(); + } + return target; + } + + /** + * Move the target forward as long resolveTargetFilter is fulfilled + * @param {ModuleGraph} moduleGraph the module graph + * @param {ResolveTargetFilter} resolveTargetFilter filter function to further resolve target + * @param {(target: TargetItemWithConnection) => ModuleGraphConnection=} updateOriginalConnection updates the original connection instead of using the target connection + * @returns {TargetItemWithConnection | undefined} the resolved target when moved + */ + moveTarget(moduleGraph, resolveTargetFilter, updateOriginalConnection) { + const target = this._getTarget(moduleGraph, resolveTargetFilter, undefined); + if (target === CIRCULAR) return; + if (!target) return; + const originalTarget = + /** @type {TargetItem} */ + ( + /** @type {Target} */ + (this._getMaxTarget()).values().next().value + ); + if ( + originalTarget.connection === target.connection && + originalTarget.export === target.export + ) { + return; + } + /** @type {Target} */ + (this._target).clear(); + /** @type {Target} */ + (this._target).set(undefined, { + connection: updateOriginalConnection + ? updateOriginalConnection(target) + : target.connection, + export: /** @type {NonNullable} */ ( + target.export + ), + priority: 0 + }); + return target; + } + + /** + * @returns {ExportsInfo} an exports info + */ + createNestedExportsInfo() { + if (this.exportsInfoOwned) { + return /** @type {ExportsInfo} */ (this.exportsInfo); + } + this.exportsInfoOwned = true; + const oldExportsInfo = this.exportsInfo; + this.exportsInfo = new ExportsInfo(); + this.exportsInfo.setHasProvideInfo(); + if (oldExportsInfo) { + this.exportsInfo.setRedirectNamedTo(oldExportsInfo); + } + return this.exportsInfo; + } + + getNestedExportsInfo() { + return this.exportsInfo; + } + + /** + * @param {ExportInfo} baseInfo base info + * @param {RuntimeSpec} runtime runtime + * @returns {boolean} true when has info, otherwise false + */ + hasInfo(baseInfo, runtime) { + return ( + (this._usedName && this._usedName !== this.name) || + this.provided || + this.terminalBinding || + this.getUsed(runtime) !== baseInfo.getUsed(runtime) + ); + } + + /** + * @param {Hash} hash the hash + * @param {RuntimeSpec} runtime the runtime + * @returns {void} + */ + updateHash(hash, runtime) { + this._updateHash(hash, runtime, new Set()); + } + + /** + * @param {Hash} hash the hash + * @param {RuntimeSpec} runtime the runtime + * @param {Set} alreadyVisitedExportsInfo for circular references + */ + _updateHash(hash, runtime, alreadyVisitedExportsInfo) { + hash.update( + `${this._usedName || this.name}${this.getUsed(runtime)}${this.provided}${ + this.terminalBinding + }` + ); + if (this.exportsInfo && !alreadyVisitedExportsInfo.has(this.exportsInfo)) { + this.exportsInfo._updateHash(hash, runtime, alreadyVisitedExportsInfo); + } + } + + getUsedInfo() { + if (this._globalUsed !== undefined) { + switch (this._globalUsed) { + case UsageState.Unused: + return "unused"; + case UsageState.NoInfo: + return "no usage info"; + case UsageState.Unknown: + return "maybe used (runtime-defined)"; + case UsageState.Used: + return "used"; + case UsageState.OnlyPropertiesUsed: + return "only properties used"; + } + } else if (this._usedInRuntime !== undefined) { + /** @type {Map} */ + const map = new Map(); + for (const [runtime, used] of this._usedInRuntime) { + const list = map.get(used); + if (list !== undefined) list.push(runtime); + else map.set(used, [runtime]); + } + // eslint-disable-next-line array-callback-return + const specificInfo = Array.from(map, ([used, runtimes]) => { + switch (used) { + case UsageState.NoInfo: + return `no usage info in ${runtimes.join(", ")}`; + case UsageState.Unknown: + return `maybe used in ${runtimes.join(", ")} (runtime-defined)`; + case UsageState.Used: + return `used in ${runtimes.join(", ")}`; + case UsageState.OnlyPropertiesUsed: + return `only properties used in ${runtimes.join(", ")}`; + } + }); + if (specificInfo.length > 0) { + return specificInfo.join("; "); + } + } + return this._hasUseInRuntimeInfo ? "unused" : "no usage info"; + } + + getProvidedInfo() { + switch (this.provided) { + case undefined: + return "no provided info"; + case null: + return "maybe provided (runtime-defined)"; + case true: + return "provided"; + case false: + return "not provided"; + } + } + + getRenameInfo() { + if (this._usedName !== null && this._usedName !== this.name) { + return `renamed to ${JSON.stringify(this._usedName).slice(1, -1)}`; + } + switch (this.canMangleProvide) { + case undefined: + switch (this.canMangleUse) { + case undefined: + return "missing provision and use info prevents renaming"; + case false: + return "usage prevents renaming (no provision info)"; + case true: + return "missing provision info prevents renaming"; + } + break; + case true: + switch (this.canMangleUse) { + case undefined: + return "missing usage info prevents renaming"; + case false: + return "usage prevents renaming"; + case true: + return "could be renamed"; + } + break; + case false: + switch (this.canMangleUse) { + case undefined: + return "provision prevents renaming (no use info)"; + case false: + return "usage and provision prevents renaming"; + case true: + return "provision prevents renaming"; + } + break; + } + throw new Error( + `Unexpected flags for getRenameInfo ${this.canMangleProvide} ${this.canMangleUse}` + ); + } +} + +module.exports = ExportsInfo; +module.exports.ExportInfo = ExportInfo; +module.exports.RestoreProvidedData = RestoreProvidedData; +module.exports.UsageState = UsageState; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExportsInfoApiPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExportsInfoApiPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..2fdf8bdbecd4471678390743ed72a3a7087c6d69 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExportsInfoApiPlugin.js @@ -0,0 +1,87 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("./ModuleTypeConstants"); +const ConstDependency = require("./dependencies/ConstDependency"); +const ExportsInfoDependency = require("./dependencies/ExportsInfoDependency"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "ExportsInfoApiPlugin"; + +class ExportsInfoApiPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ExportsInfoDependency, + new ExportsInfoDependency.Template() + ); + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const handler = (parser) => { + parser.hooks.expressionMemberChain + .for("__webpack_exports_info__") + .tap(PLUGIN_NAME, (expr, members) => { + const dep = + members.length >= 2 + ? new ExportsInfoDependency( + /** @type {Range} */ (expr.range), + members.slice(0, -1), + members[members.length - 1] + ) + : new ExportsInfoDependency( + /** @type {Range} */ (expr.range), + null, + members[0] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + return true; + }); + parser.hooks.expression + .for("__webpack_exports_info__") + .tap(PLUGIN_NAME, (expr) => { + const dep = new ConstDependency( + "true", + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + }; + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = ExportsInfoApiPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExternalModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExternalModule.js new file mode 100644 index 0000000000000000000000000000000000000000..de7b38919fec254c6203300984e57ea8ccd9e1a3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExternalModule.js @@ -0,0 +1,1128 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { OriginalSource, RawSource } = require("webpack-sources"); +const ConcatenationScope = require("./ConcatenationScope"); +const EnvironmentNotSupportAsyncWarning = require("./EnvironmentNotSupportAsyncWarning"); +const { UsageState } = require("./ExportsInfo"); +const InitFragment = require("./InitFragment"); +const Module = require("./Module"); +const { + CSS_IMPORT_TYPES, + CSS_URL_TYPES, + JS_TYPES +} = require("./ModuleSourceTypesConstants"); +const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const Template = require("./Template"); +const { DEFAULTS } = require("./config/defaults"); +const StaticExportsDependency = require("./dependencies/StaticExportsDependency"); +const createHash = require("./util/createHash"); +const extractUrlAndGlobal = require("./util/extractUrlAndGlobal"); +const makeSerializable = require("./util/makeSerializable"); +const propertyAccess = require("./util/propertyAccess"); +const { register } = require("./util/serialization"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compilation").UnsafeCacheData} UnsafeCacheData */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./ExportsInfo")} ExportsInfo */ +/** @typedef {import("./Generator").GenerateContext} GenerateContext */ +/** @typedef {import("./Generator").SourceTypes} SourceTypes */ +/** @typedef {import("./Module").BuildCallback} BuildCallback */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** @typedef {{ attributes?: ImportAttributes, externalType: "import" | "module" | undefined }} ImportDependencyMeta */ +/** @typedef {{ layer?: string, supports?: string, media?: string }} CssImportDependencyMeta */ +/** @typedef {{ sourceType: "css-url" }} AssetDependencyMeta */ + +/** @typedef {ImportDependencyMeta | CssImportDependencyMeta | AssetDependencyMeta} DependencyMeta */ + +/** + * @typedef {object} SourceData + * @property {boolean=} iife + * @property {string=} init + * @property {string} expression + * @property {InitFragment[]=} chunkInitFragments + * @property {ReadOnlyRuntimeRequirements=} runtimeRequirements + * @property {[string, string][]=} specifiers + */ + +/** @typedef {true | [string, string][]} Imported */ + +const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); +const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]); +const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([ + RuntimeGlobals.definePropertyGetters +]); +const EMPTY_RUNTIME_REQUIREMENTS = new Set([]); + +/** + * @param {string|string[]} variableName the variable name or path + * @param {string} type the module system + * @returns {SourceData} the generated source + */ +const getSourceForGlobalVariableExternal = (variableName, type) => { + if (!Array.isArray(variableName)) { + // make it an array as the look up works the same basically + variableName = [variableName]; + } + + // needed for e.g. window["some"]["thing"] + const objectLookup = variableName + .map((r) => `[${JSON.stringify(r)}]`) + .join(""); + return { + iife: type === "this", + expression: `${type}${objectLookup}` + }; +}; + +/** + * @param {string|string[]} moduleAndSpecifiers the module request + * @returns {SourceData} the generated source + */ +const getSourceForCommonJsExternal = (moduleAndSpecifiers) => { + if (!Array.isArray(moduleAndSpecifiers)) { + return { + expression: `require(${JSON.stringify(moduleAndSpecifiers)})` + }; + } + const moduleName = moduleAndSpecifiers[0]; + return { + expression: `require(${JSON.stringify(moduleName)})${propertyAccess( + moduleAndSpecifiers, + 1 + )}` + }; +}; + +/** + * @param {string | string[]} moduleAndSpecifiers the module request + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @returns {SourceData} the generated source + */ +const getSourceForCommonJsExternalInNodeModule = ( + moduleAndSpecifiers, + runtimeTemplate +) => { + const importMetaName = + /** @type {string} */ + (runtimeTemplate.outputOptions.importMetaName); + + // /** @type {boolean} */ + // (runtimeTemplate.supportNodePrefixForCoreModules()) + + const chunkInitFragments = [ + new InitFragment( + `import { createRequire as __WEBPACK_EXTERNAL_createRequire } from ${runtimeTemplate.renderNodePrefixForCoreModule("module")};\n`, + InitFragment.STAGE_HARMONY_IMPORTS, + 0, + "external module node-commonjs" + ) + ]; + if (!Array.isArray(moduleAndSpecifiers)) { + return { + chunkInitFragments, + expression: `__WEBPACK_EXTERNAL_createRequire(${importMetaName}.url)(${JSON.stringify( + moduleAndSpecifiers + )})` + }; + } + const moduleName = moduleAndSpecifiers[0]; + return { + chunkInitFragments, + expression: `__WEBPACK_EXTERNAL_createRequire(${importMetaName}.url)(${JSON.stringify( + moduleName + )})${propertyAccess(moduleAndSpecifiers, 1)}` + }; +}; + +/** + * @param {string|string[]} moduleAndSpecifiers the module request + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {ImportDependencyMeta=} dependencyMeta the dependency meta + * @returns {SourceData} the generated source + */ +const getSourceForImportExternal = ( + moduleAndSpecifiers, + runtimeTemplate, + dependencyMeta +) => { + const importName = runtimeTemplate.outputOptions.importFunctionName; + if ( + !runtimeTemplate.supportsDynamicImport() && + (importName === "import" || importName === "module-import") + ) { + throw new Error( + "The target environment doesn't support 'import()' so it's not possible to use external type 'import'" + ); + } + const attributes = + dependencyMeta && dependencyMeta.attributes + ? dependencyMeta.attributes._isLegacyAssert + ? `, { assert: ${JSON.stringify( + dependencyMeta.attributes, + importAssertionReplacer + )} }` + : `, { with: ${JSON.stringify(dependencyMeta.attributes)} }` + : ""; + if (!Array.isArray(moduleAndSpecifiers)) { + return { + expression: `${importName}(${JSON.stringify( + moduleAndSpecifiers + )}${attributes});` + }; + } + if (moduleAndSpecifiers.length === 1) { + return { + expression: `${importName}(${JSON.stringify( + moduleAndSpecifiers[0] + )}${attributes});` + }; + } + const moduleName = moduleAndSpecifiers[0]; + return { + expression: `${importName}(${JSON.stringify( + moduleName + )}${attributes}).then(${runtimeTemplate.returningFunction( + `module${propertyAccess(moduleAndSpecifiers, 1)}`, + "module" + )});` + }; +}; + +/** + * @param {string} key key + * @param {ImportAttributes | string | boolean | undefined} value value + * @returns {ImportAttributes | string | boolean | undefined} replaced value + */ +const importAssertionReplacer = (key, value) => { + if (key === "_isLegacyAssert") { + return; + } + + return value; +}; + +/** + * @extends {InitFragment} + */ +class ModuleExternalInitFragment extends InitFragment { + /** + * @param {string} request import source + * @param {Imported} imported the imported specifiers + * @param {string=} ident recomputed ident + * @param {ImportDependencyMeta=} dependencyMeta the dependency meta + * @param {HashFunction=} hashFunction the hash function to use + */ + constructor( + request, + imported, + ident, + dependencyMeta, + hashFunction = DEFAULTS.HASH_FUNCTION + ) { + if (ident === undefined) { + ident = Template.toIdentifier(request); + if (ident !== request) { + ident += `_${createHash(hashFunction) + .update(request) + .digest("hex") + .slice(0, 8)}`; + } + } + + const identifier = `__WEBPACK_EXTERNAL_MODULE_${ident}__`; + super( + "", + InitFragment.STAGE_HARMONY_IMPORTS, + 0, + `external module import ${ident} ${imported === true ? imported : imported.join(" ")}` + ); + this._ident = ident; + this._request = request; + this._dependencyMeta = dependencyMeta; + this._imported = imported; + this._identifier = identifier; + } + + /** + * @returns {Imported} imported + */ + getImported() { + return this._imported; + } + + /** + * @param {Imported} imported imported + */ + setImported(imported) { + this._imported = imported; + } + + /** + * @param {GenerateContext} context context + * @returns {string | Source | undefined} the source code that will be included as initialization code + */ + getContent(context) { + const { + _dependencyMeta: dependencyMeta, + _imported: imported, + _request: request, + _identifier: identifier + } = this; + const attributes = + dependencyMeta && dependencyMeta.attributes + ? dependencyMeta.attributes._isLegacyAssert && + dependencyMeta.attributes._isLegacyAssert + ? ` assert ${JSON.stringify( + dependencyMeta.attributes, + importAssertionReplacer + )}` + : ` with ${JSON.stringify(dependencyMeta.attributes)}` + : ""; + let content = ""; + if (imported === true) { + // namespace + content = `import * as ${identifier} from ${JSON.stringify(request)}${ + attributes + };\n`; + } else if (imported.length === 0) { + // just import, no use + content = `import ${JSON.stringify(request)}${attributes};\n`; + } else { + content = `import { ${imported + .map(([name, finalName]) => { + if (name !== finalName) { + return `${name} as ${finalName}`; + } + return name; + }) + .join(", ")} } from ${JSON.stringify(request)}${attributes};\n`; + } + return content; + } + + getNamespaceIdentifier() { + return this._identifier; + } +} + +register( + ModuleExternalInitFragment, + "webpack/lib/ExternalModule", + "ModuleExternalInitFragment", + { + serialize(obj, { write }) { + write(obj._request); + write(obj._imported); + write(obj._ident); + write(obj._dependencyMeta); + }, + deserialize({ read }) { + return new ModuleExternalInitFragment(read(), read(), read(), read()); + } + } +); + +/** + * @param {string} input input + * @param {ExportsInfo} exportsInfo the exports info + * @param {RuntimeSpec=} runtime the runtime + * @param {RuntimeTemplate=} runtimeTemplate the runtime template + * @returns {string | undefined} the module remapping + */ +const generateModuleRemapping = ( + input, + exportsInfo, + runtime, + runtimeTemplate +) => { + if (exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused) { + const properties = []; + for (const exportInfo of exportsInfo.orderedExports) { + const used = exportInfo.getUsedName(exportInfo.name, runtime); + if (!used) continue; + const nestedInfo = exportInfo.getNestedExportsInfo(); + if (nestedInfo) { + const nestedExpr = generateModuleRemapping( + `${input}${propertyAccess([exportInfo.name])}`, + nestedInfo + ); + if (nestedExpr) { + properties.push(`[${JSON.stringify(used)}]: y(${nestedExpr})`); + continue; + } + } + properties.push( + `[${JSON.stringify(used)}]: ${ + /** @type {RuntimeTemplate} */ (runtimeTemplate).returningFunction( + `${input}${propertyAccess([exportInfo.name])}` + ) + }` + ); + } + return `x({ ${properties.join(", ")} })`; + } +}; + +/** + * @param {string|string[]} moduleAndSpecifiers the module request + * @param {ExportsInfo} exportsInfo exports info of this module + * @param {RuntimeSpec} runtime the runtime + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {ImportDependencyMeta} dependencyMeta the dependency meta + * @param {ConcatenationScope=} concatenationScope concatenationScope + * @returns {SourceData} the generated source + */ +const getSourceForModuleExternal = ( + moduleAndSpecifiers, + exportsInfo, + runtime, + runtimeTemplate, + dependencyMeta, + concatenationScope +) => { + if (!Array.isArray(moduleAndSpecifiers)) { + moduleAndSpecifiers = [moduleAndSpecifiers]; + } + + /** @type {Imported} */ + let imported = true; + if (concatenationScope) { + const usedExports = exportsInfo.getUsedExports(runtime); + switch (usedExports) { + case true: + case null: + // unknown exports + imported = true; + break; + case false: + // no used exports + imported = []; + break; + default: + imported = []; + if (exportsInfo.isUsed(runtime) === false) { + // no used, only + } + for (const [name] of usedExports.entries()) { + let counter = 0; + let finalName = name; + + if (concatenationScope) { + while (!concatenationScope.registerUsedName(finalName)) { + finalName = `${name}_${counter++}`; + } + } + imported.push([name, finalName]); + } + } + } + + const initFragment = new ModuleExternalInitFragment( + moduleAndSpecifiers[0], + imported, + undefined, + dependencyMeta, + runtimeTemplate.outputOptions.hashFunction + ); + const specifiers = imported === true ? undefined : imported; + const baseAccess = `${initFragment.getNamespaceIdentifier()}${propertyAccess( + moduleAndSpecifiers, + 1 + )}`; + let expression = baseAccess; + + const useNamespace = imported === true; + let moduleRemapping; + if (useNamespace) { + moduleRemapping = generateModuleRemapping( + baseAccess, + exportsInfo, + runtime, + runtimeTemplate + ); + expression = moduleRemapping || baseAccess; + } + return { + expression, + init: moduleRemapping + ? `var x = ${runtimeTemplate.basicFunction( + "y", + `var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x` + )} \nvar y = ${runtimeTemplate.returningFunction( + runtimeTemplate.returningFunction("x"), + "x" + )}` + : undefined, + specifiers, + runtimeRequirements: moduleRemapping + ? RUNTIME_REQUIREMENTS_FOR_MODULE + : undefined, + chunkInitFragments: [ + /** @type {InitFragment} */ (initFragment) + ] + }; +}; + +/** + * @param {string|string[]} urlAndGlobal the script request + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @returns {SourceData} the generated source + */ +const getSourceForScriptExternal = (urlAndGlobal, runtimeTemplate) => { + if (typeof urlAndGlobal === "string") { + urlAndGlobal = extractUrlAndGlobal(urlAndGlobal); + } + const url = urlAndGlobal[0]; + const globalName = urlAndGlobal[1]; + return { + init: "var __webpack_error__ = new Error();", + expression: `new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + `if(typeof ${globalName} !== "undefined") return resolve();`, + `${RuntimeGlobals.loadScript}(${JSON.stringify( + url + )}, ${runtimeTemplate.basicFunction("event", [ + `if(typeof ${globalName} !== "undefined") return resolve();`, + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "__webpack_error__.message = 'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';", + "__webpack_error__.name = 'ScriptExternalLoadError';", + "__webpack_error__.type = errorType;", + "__webpack_error__.request = realSrc;", + "reject(__webpack_error__);" + ])}, ${JSON.stringify(globalName)});` + ] + )}).then(${runtimeTemplate.returningFunction( + `${globalName}${propertyAccess(urlAndGlobal, 2)}` + )})`, + runtimeRequirements: RUNTIME_REQUIREMENTS_FOR_SCRIPT + }; +}; + +/** + * @param {string} variableName the variable name to check + * @param {string} request the request path + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @returns {string} the generated source + */ +const checkExternalVariable = (variableName, request, runtimeTemplate) => + `if(typeof ${variableName} === 'undefined') { ${runtimeTemplate.throwMissingModuleErrorBlock( + { request } + )} }\n`; + +/** + * @param {string|number} id the module id + * @param {boolean} optional true, if the module is optional + * @param {string|string[]} request the request path + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @returns {SourceData} the generated source + */ +const getSourceForAmdOrUmdExternal = ( + id, + optional, + request, + runtimeTemplate +) => { + const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${id}` + )}__`; + return { + init: optional + ? checkExternalVariable( + externalVariable, + Array.isArray(request) ? request.join(".") : request, + runtimeTemplate + ) + : undefined, + expression: externalVariable + }; +}; + +/** + * @param {boolean} optional true, if the module is optional + * @param {string|string[]} request the request path + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @returns {SourceData} the generated source + */ +const getSourceForDefaultCase = (optional, request, runtimeTemplate) => { + if (!Array.isArray(request)) { + // make it an array as the look up works the same basically + request = [request]; + } + + const variableName = request[0]; + const objectLookup = propertyAccess(request, 1); + return { + init: optional + ? checkExternalVariable(variableName, request.join("."), runtimeTemplate) + : undefined, + expression: `${variableName}${objectLookup}` + }; +}; + +/** @typedef {Record} RequestRecord */ + +class ExternalModule extends Module { + /** + * @param {string | string[] | RequestRecord} request request + * @param {string} type type + * @param {string} userRequest user request + * @param {DependencyMeta=} dependencyMeta dependency meta + */ + constructor(request, type, userRequest, dependencyMeta) { + super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null); + + // Info from Factory + /** @type {string | string[] | Record} */ + this.request = request; + /** @type {string} */ + this.externalType = type; + /** @type {string} */ + this.userRequest = userRequest; + /** @type {DependencyMeta=} */ + this.dependencyMeta = dependencyMeta; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + if ( + this.externalType === "asset" && + this.dependencyMeta && + /** @type {AssetDependencyMeta} */ + (this.dependencyMeta).sourceType === "css-url" + ) { + return CSS_URL_TYPES; + } else if (this.externalType === "css-import") { + return CSS_IMPORT_TYPES; + } + + return JS_TYPES; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return this.userRequest; + } + + /** + * @param {Chunk} chunk the chunk which condition should be checked + * @param {Compilation} compilation the compilation + * @returns {boolean} true, if the chunk is ok for the module + */ + chunkCondition(chunk, { chunkGraph }) { + return this.externalType === "css-import" + ? true + : chunkGraph.getNumberOfEntryModules(chunk) > 0; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `external ${this._resolveExternalType(this.externalType)} ${JSON.stringify(this.request)}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `external ${JSON.stringify(this.request)}`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = { + async: false, + exportsType: undefined + }; + this.buildInfo = { + strict: true, + topLevelDeclarations: new Set(), + javascriptModule: compilation.outputOptions.module + }; + const { request, externalType } = this._getRequestAndExternalType(); + this.buildMeta.exportsType = "dynamic"; + let canMangle = false; + this.clearDependenciesAndBlocks(); + switch (externalType) { + case "this": + this.buildInfo.strict = false; + break; + case "system": + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = true; + } + break; + case "module": + if (this.buildInfo.javascriptModule) { + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = true; + } + } else { + this.buildMeta.async = true; + EnvironmentNotSupportAsyncWarning.check( + this, + compilation.runtimeTemplate, + "external module" + ); + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = false; + } + } + break; + case "script": + this.buildMeta.async = true; + EnvironmentNotSupportAsyncWarning.check( + this, + compilation.runtimeTemplate, + "external script" + ); + break; + case "promise": + this.buildMeta.async = true; + EnvironmentNotSupportAsyncWarning.check( + this, + compilation.runtimeTemplate, + "external promise" + ); + break; + case "import": + this.buildMeta.async = true; + EnvironmentNotSupportAsyncWarning.check( + this, + compilation.runtimeTemplate, + "external import" + ); + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = false; + } + break; + } + this.addDependency(new StaticExportsDependency(true, canMangle)); + callback(); + } + + /** + * restore unsafe cache data + * @param {UnsafeCacheData} unsafeCacheData data from getUnsafeCacheData + * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching + */ + restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); + } + + /** + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(context) { + switch (this.externalType) { + case "amd": + case "amd-require": + case "umd": + case "umd2": + case "system": + case "jsonp": + return `${this.externalType} externals can't be concatenated`; + } + return undefined; + } + + _getRequestAndExternalType() { + let { request, externalType } = this; + if (typeof request === "object" && !Array.isArray(request)) { + request = request[externalType]; + } + externalType = this._resolveExternalType(externalType); + return { request, externalType }; + } + + /** + * Resolve the detailed external type from the raw external type. + * e.g. resolve "module" or "import" from "module-import" type + * @param {string} externalType raw external type + * @returns {string} resolved external type + */ + _resolveExternalType(externalType) { + if (externalType === "module-import") { + if ( + this.dependencyMeta && + /** @type {ImportDependencyMeta} */ + (this.dependencyMeta).externalType + ) { + return /** @type {ImportDependencyMeta} */ (this.dependencyMeta) + .externalType; + } + return "module"; + } else if (externalType === "asset") { + if ( + this.dependencyMeta && + /** @type {AssetDependencyMeta} */ + (this.dependencyMeta).sourceType + ) { + return /** @type {AssetDependencyMeta} */ (this.dependencyMeta) + .sourceType; + } + + return "asset"; + } + + return externalType; + } + + /** + * @private + * @param {string | string[]} request request + * @param {string} externalType the external type + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {RuntimeSpec} runtime the runtime + * @param {DependencyMeta | undefined} dependencyMeta the dependency meta + * @param {ConcatenationScope=} concatenationScope concatenationScope + * @returns {SourceData} the source data + */ + _getSourceData( + request, + externalType, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + dependencyMeta, + concatenationScope + ) { + switch (externalType) { + case "this": + case "window": + case "self": + return getSourceForGlobalVariableExternal(request, this.externalType); + case "global": + return getSourceForGlobalVariableExternal( + request, + runtimeTemplate.globalObject + ); + case "commonjs": + case "commonjs2": + case "commonjs-module": + case "commonjs-static": + return getSourceForCommonJsExternal(request); + case "node-commonjs": + return /** @type {BuildInfo} */ (this.buildInfo).javascriptModule + ? getSourceForCommonJsExternalInNodeModule(request, runtimeTemplate) + : getSourceForCommonJsExternal(request); + case "amd": + case "amd-require": + case "umd": + case "umd2": + case "system": + case "jsonp": { + const id = chunkGraph.getModuleId(this); + return getSourceForAmdOrUmdExternal( + id !== null ? id : this.identifier(), + this.isOptional(moduleGraph), + request, + runtimeTemplate + ); + } + case "import": + return getSourceForImportExternal( + request, + runtimeTemplate, + /** @type {ImportDependencyMeta} */ (dependencyMeta) + ); + case "script": + return getSourceForScriptExternal(request, runtimeTemplate); + case "module": { + if (!(/** @type {BuildInfo} */ (this.buildInfo).javascriptModule)) { + if (!runtimeTemplate.supportsDynamicImport()) { + throw new Error( + `The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script${ + runtimeTemplate.supportsEcmaScriptModuleSyntax() + ? "\nDid you mean to build a EcmaScript Module ('output.module: true')?" + : "" + }` + ); + } + return getSourceForImportExternal( + request, + runtimeTemplate, + /** @type {ImportDependencyMeta} */ (dependencyMeta) + ); + } + if (!runtimeTemplate.supportsEcmaScriptModuleSyntax()) { + throw new Error( + "The target environment doesn't support EcmaScriptModule syntax so it's not possible to use external type 'module'" + ); + } + return getSourceForModuleExternal( + request, + moduleGraph.getExportsInfo(this), + runtime, + runtimeTemplate, + /** @type {ImportDependencyMeta} */ (dependencyMeta), + concatenationScope + ); + } + case "var": + case "promise": + case "const": + case "let": + case "assign": + default: + return getSourceForDefaultCase( + this.isOptional(moduleGraph), + request, + runtimeTemplate + ); + } + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + concatenationScope + }) { + const { request, externalType } = this._getRequestAndExternalType(); + switch (externalType) { + case "asset": { + const sources = new Map(); + sources.set( + "javascript", + new RawSource(`module.exports = ${JSON.stringify(request)};`) + ); + const data = new Map(); + data.set("url", { javascript: request }); + return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS, data }; + } + case "css-url": { + const sources = new Map(); + const data = new Map(); + data.set("url", { "css-url": request }); + return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS, data }; + } + case "css-import": { + const sources = new Map(); + const dependencyMeta = /** @type {CssImportDependencyMeta} */ ( + this.dependencyMeta + ); + const layer = + dependencyMeta.layer !== undefined + ? ` layer(${dependencyMeta.layer})` + : ""; + const supports = dependencyMeta.supports + ? ` supports(${dependencyMeta.supports})` + : ""; + const media = dependencyMeta.media ? ` ${dependencyMeta.media}` : ""; + sources.set( + "css-import", + new RawSource( + `@import url(${JSON.stringify( + request + )})${layer}${supports}${media};` + ) + ); + return { + sources, + runtimeRequirements: EMPTY_RUNTIME_REQUIREMENTS + }; + } + default: { + const sourceData = this._getSourceData( + request, + externalType, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + this.dependencyMeta, + concatenationScope + ); + + // sourceString can be empty str only when there is concatenationScope + let sourceString = sourceData.expression; + if (sourceData.iife) { + sourceString = `(function() { return ${sourceString}; }())`; + } + + const specifiers = sourceData.specifiers; + if (specifiers) { + sourceString = ""; + const scope = /** @type {ConcatenationScope} */ (concatenationScope); + for (const [specifier, finalName] of specifiers) { + scope.registerRawExport(specifier, finalName); + } + } else if (concatenationScope) { + sourceString = `${ + runtimeTemplate.supportsConst() ? "const" : "var" + } ${ConcatenationScope.NAMESPACE_OBJECT_EXPORT} = ${sourceString};`; + concatenationScope.registerNamespaceExport( + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + ); + } else { + sourceString = `module.exports = ${sourceString};`; + } + if (sourceData.init) { + sourceString = `${sourceData.init}\n${sourceString}`; + } + + let data; + if (sourceData.chunkInitFragments) { + data = new Map(); + data.set("chunkInitFragments", sourceData.chunkInitFragments); + } + + const sources = new Map(); + if (this.useSourceMap || this.useSimpleSourceMap) { + sources.set( + "javascript", + new OriginalSource(sourceString, this.identifier()) + ); + } else { + sources.set("javascript", new RawSource(sourceString)); + } + + let runtimeRequirements = sourceData.runtimeRequirements; + if (!concatenationScope) { + if (!runtimeRequirements) { + runtimeRequirements = RUNTIME_REQUIREMENTS; + } else { + const set = new Set(runtimeRequirements); + set.add(RuntimeGlobals.module); + runtimeRequirements = set; + } + } + + return { + sources, + runtimeRequirements: + runtimeRequirements || EMPTY_RUNTIME_REQUIREMENTS, + data + }; + } + } + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return 42; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const { chunkGraph } = context; + hash.update( + `${this._resolveExternalType(this.externalType)}${JSON.stringify(this.request)}${this.isOptional( + chunkGraph.moduleGraph + )}` + ); + super.updateHash(hash, context); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.request); + write(this.externalType); + write(this.userRequest); + write(this.dependencyMeta); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.request = read(); + this.externalType = read(); + this.userRequest = read(); + this.dependencyMeta = read(); + + super.deserialize(context); + } +} + +makeSerializable(ExternalModule, "webpack/lib/ExternalModule"); + +module.exports = ExternalModule; +module.exports.ModuleExternalInitFragment = ModuleExternalInitFragment; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExternalModuleFactoryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExternalModuleFactoryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..e011ae0e9ebc43f3d452373b6533830519c89ebb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExternalModuleFactoryPlugin.js @@ -0,0 +1,341 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const ExternalModule = require("./ExternalModule"); +const ContextElementDependency = require("./dependencies/ContextElementDependency"); +const CssImportDependency = require("./dependencies/CssImportDependency"); +const CssUrlDependency = require("./dependencies/CssUrlDependency"); +const HarmonyImportDependency = require("./dependencies/HarmonyImportDependency"); +const ImportDependency = require("./dependencies/ImportDependency"); +const { cachedSetProperty, resolveByProperty } = require("./util/cleverMerge"); + +/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunctionData} ExternalItemFunctionData */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemObjectKnown} ExternalItemObjectKnown */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemObjectUnknown} ExternalItemObjectUnknown */ +/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ +/** @typedef {import("./Compilation").DepConstructor} DepConstructor */ +/** @typedef {import("./ExternalModule").DependencyMeta} DependencyMeta */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleFactory").IssuerLayer} IssuerLayer */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ + +const UNSPECIFIED_EXTERNAL_TYPE_REGEXP = /^[a-z0-9-]+ /; +const EMPTY_RESOLVE_OPTIONS = {}; + +// TODO webpack 6 remove this +const callDeprecatedExternals = util.deprecate( + /** + * @param {EXPECTED_FUNCTION} externalsFunction externals function + * @param {string} context context + * @param {string} request request + * @param {(err: Error | null | undefined, value: ExternalValue | undefined, ty: ExternalType | undefined) => void} cb cb + */ + (externalsFunction, context, request, cb) => { + // eslint-disable-next-line no-useless-call + externalsFunction.call(null, context, request, cb); + }, + "The externals-function should be defined like ({context, request}, cb) => { ... }", + "DEP_WEBPACK_EXTERNALS_FUNCTION_PARAMETERS" +); + +/** @typedef {ExternalItemObjectKnown & ExternalItemObjectUnknown} ExternalItemObject */ + +/** + * @template {ExternalItemObject} T + * @typedef {WeakMap>>} ExternalWeakCache + */ + +/** @type {ExternalWeakCache} */ +const cache = new WeakMap(); + +/** + * @param {ExternalItemObject} obj obj + * @param {IssuerLayer} layer layer + * @returns {Omit} result + */ +const resolveLayer = (obj, layer) => { + let map = cache.get(obj); + if (map === undefined) { + map = new Map(); + cache.set(obj, map); + } else { + const cacheEntry = map.get(layer); + if (cacheEntry !== undefined) return cacheEntry; + } + const result = resolveByProperty(obj, "byLayer", layer); + map.set(layer, result); + return result; +}; + +/** @typedef {string | string[] | boolean | Record} ExternalValue */ +/** @typedef {string | undefined} ExternalType */ + +const PLUGIN_NAME = "ExternalModuleFactoryPlugin"; + +class ExternalModuleFactoryPlugin { + /** + * @param {string | undefined} type default external type + * @param {Externals} externals externals config + */ + constructor(type, externals) { + this.type = type; + this.externals = externals; + } + + /** + * @param {NormalModuleFactory} normalModuleFactory the normal module factory + * @returns {void} + */ + apply(normalModuleFactory) { + const globalType = this.type; + normalModuleFactory.hooks.factorize.tapAsync( + PLUGIN_NAME, + (data, callback) => { + const context = data.context; + const contextInfo = data.contextInfo; + const dependency = data.dependencies[0]; + const dependencyType = data.dependencyType; + + /** @typedef {(err?: Error | null, externalModule?: ExternalModule) => void} HandleExternalCallback */ + + /** + * @param {ExternalValue} value the external config + * @param {ExternalType | undefined} type type of external + * @param {HandleExternalCallback} callback callback + * @returns {void} + */ + const handleExternal = (value, type, callback) => { + if (value === false) { + // Not externals, fallback to original factory + return callback(); + } + /** @type {string | string[] | Record} */ + let externalConfig = value === true ? dependency.request : value; + // When no explicit type is specified, extract it from the externalConfig + if (type === undefined) { + if ( + typeof externalConfig === "string" && + UNSPECIFIED_EXTERNAL_TYPE_REGEXP.test(externalConfig) + ) { + const idx = externalConfig.indexOf(" "); + type = externalConfig.slice(0, idx); + externalConfig = externalConfig.slice(idx + 1); + } else if ( + Array.isArray(externalConfig) && + externalConfig.length > 0 && + UNSPECIFIED_EXTERNAL_TYPE_REGEXP.test(externalConfig[0]) + ) { + const firstItem = externalConfig[0]; + const idx = firstItem.indexOf(" "); + type = firstItem.slice(0, idx); + externalConfig = [ + firstItem.slice(idx + 1), + ...externalConfig.slice(1) + ]; + } + } + + const resolvedType = /** @type {string} */ (type || globalType); + + // TODO make it pluggable/add hooks to `ExternalModule` to allow output modules own externals? + /** @type {DependencyMeta | undefined} */ + let dependencyMeta; + + if ( + dependency instanceof HarmonyImportDependency || + dependency instanceof ImportDependency || + dependency instanceof ContextElementDependency + ) { + const externalType = + dependency instanceof HarmonyImportDependency + ? "module" + : dependency instanceof ImportDependency + ? "import" + : undefined; + + dependencyMeta = { + attributes: dependency.assertions, + externalType + }; + } else if (dependency instanceof CssImportDependency) { + dependencyMeta = { + layer: dependency.layer, + supports: dependency.supports, + media: dependency.media + }; + } + + if ( + resolvedType === "asset" && + dependency instanceof CssUrlDependency + ) { + dependencyMeta = { sourceType: "css-url" }; + } + + callback( + null, + new ExternalModule( + externalConfig, + resolvedType, + dependency.request, + dependencyMeta + ) + ); + }; + + /** + * @param {Externals} externals externals config + * @param {HandleExternalCallback} callback callback + * @returns {void} + */ + const handleExternals = (externals, callback) => { + if (typeof externals === "string") { + if (externals === dependency.request) { + return handleExternal(dependency.request, undefined, callback); + } + } else if (Array.isArray(externals)) { + let i = 0; + const next = () => { + /** @type {boolean | undefined} */ + let asyncFlag; + /** + * @param {(Error | null)=} err err + * @param {ExternalModule=} module module + * @returns {void} + */ + const handleExternalsAndCallback = (err, module) => { + if (err) return callback(err); + if (!module) { + if (asyncFlag) { + asyncFlag = false; + return; + } + return next(); + } + callback(null, module); + }; + + do { + asyncFlag = true; + if (i >= externals.length) return callback(); + handleExternals(externals[i++], handleExternalsAndCallback); + } while (!asyncFlag); + asyncFlag = false; + }; + + next(); + return; + } else if (externals instanceof RegExp) { + if (externals.test(dependency.request)) { + return handleExternal(dependency.request, undefined, callback); + } + } else if (typeof externals === "function") { + /** + * @param {Error | null | undefined} err err + * @param {ExternalValue=} value value + * @param {ExternalType=} type type + * @returns {void} + */ + const cb = (err, value, type) => { + if (err) return callback(err); + if (value !== undefined) { + handleExternal(value, type, callback); + } else { + callback(); + } + }; + if (externals.length === 3) { + // TODO webpack 6 remove this + callDeprecatedExternals( + externals, + context, + dependency.request, + cb + ); + } else { + const promise = externals( + { + context, + request: dependency.request, + dependencyType, + contextInfo, + getResolve: (options) => (context, request, callback) => { + const resolveContext = { + fileDependencies: data.fileDependencies, + missingDependencies: data.missingDependencies, + contextDependencies: data.contextDependencies + }; + let resolver = normalModuleFactory.getResolver( + "normal", + dependencyType + ? cachedSetProperty( + data.resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + dependencyType + ) + : data.resolveOptions + ); + if (options) resolver = resolver.withOptions(options); + if (callback) { + resolver.resolve( + {}, + context, + request, + resolveContext, + callback + ); + } else { + return new Promise((resolve, reject) => { + resolver.resolve( + {}, + context, + request, + resolveContext, + (err, result) => { + if (err) reject(err); + else resolve(result); + } + ); + }); + } + } + }, + cb + ); + if (promise && promise.then) promise.then((r) => cb(null, r), cb); + } + return; + } else if (typeof externals === "object") { + const resolvedExternals = resolveLayer( + externals, + /** @type {IssuerLayer} */ + (contextInfo.issuerLayer) + ); + if ( + Object.prototype.hasOwnProperty.call( + resolvedExternals, + dependency.request + ) + ) { + return handleExternal( + resolvedExternals[dependency.request], + undefined, + callback + ); + } + } + callback(); + }; + + handleExternals(this.externals, callback); + } + ); + } +} + +module.exports = ExternalModuleFactoryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExternalsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExternalsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b713357ec3cdf11c8ce193c9730119bcafccb24f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ExternalsPlugin.js @@ -0,0 +1,84 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ModuleExternalInitFragment } = require("./ExternalModule"); +const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); +const ConcatenatedModule = require("./optimize/ConcatenatedModule"); + +/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */ + +const PLUGIN_NAME = "ExternalsPlugin"; + +class ExternalsPlugin { + /** + * @param {string | undefined} type default external type + * @param {Externals} externals externals config + */ + constructor(type, externals) { + this.type = type; + this.externals = externals; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compile.tap(PLUGIN_NAME, ({ normalModuleFactory }) => { + new ExternalModuleFactoryPlugin(this.type, this.externals).apply( + normalModuleFactory + ); + }); + + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const { concatenatedModuleInfo } = + ConcatenatedModule.getCompilationHooks(compilation); + concatenatedModuleInfo.tap(PLUGIN_NAME, (updatedInfo, moduleInfo) => { + const rawExportMap = + /** @type {ConcatenatedModuleInfo} */ updatedInfo.rawExportMap; + + if (!rawExportMap) { + return; + } + + const chunkInitFragments = + /** @type {ConcatenatedModuleInfo} */ moduleInfo.chunkInitFragments; + const moduleExternalInitFragments = chunkInitFragments + ? chunkInitFragments.filter( + (fragment) => fragment instanceof ModuleExternalInitFragment + ) + : []; + + let initFragmentChanged = false; + + for (const fragment of moduleExternalInitFragments) { + const imported = fragment.getImported(); + + if (Array.isArray(imported)) { + const newImported = imported.map(([specifier, finalName]) => [ + specifier, + rawExportMap.has(specifier) + ? rawExportMap.get(specifier) + : finalName + ]); + fragment.setImported(newImported); + initFragmentChanged = true; + } + } + + if (initFragmentChanged) { + return true; + } + }); + }); + } +} + +module.exports = ExternalsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FalseIIFEUmdWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FalseIIFEUmdWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..79eaa54ae03dddb898dcb7075f948dd2e81ffe86 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FalseIIFEUmdWarning.js @@ -0,0 +1,19 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Arka Pratim Chaudhuri @arkapratimc +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +class FalseIIFEUmdWarning extends WebpackError { + constructor() { + super(); + this.name = "FalseIIFEUmdWarning"; + this.message = + "Configuration:\nSetting 'output.iife' to 'false' is incompatible with 'output.library.type' set to 'umd'. This configuration may cause unexpected behavior, as UMD libraries are expected to use an IIFE (Immediately Invoked Function Expression) to support various module formats. Consider setting 'output.iife' to 'true' or choosing a different 'library.type' to ensure compatibility.\nLearn more: https://webpack.js.org/configuration/output/"; + } +} + +module.exports = FalseIIFEUmdWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FileSystemInfo.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FileSystemInfo.js new file mode 100644 index 0000000000000000000000000000000000000000..8ae2f7ffc204f3b0f8e562dc45309947f79dd8f4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FileSystemInfo.js @@ -0,0 +1,4092 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const nodeModule = require("module"); +const { isAbsolute } = require("path"); +const { create: createResolver } = require("enhanced-resolve"); +const asyncLib = require("neo-async"); +const { DEFAULTS } = require("./config/defaults"); +const AsyncQueue = require("./util/AsyncQueue"); +const StackedCacheMap = require("./util/StackedCacheMap"); +const createHash = require("./util/createHash"); +const { dirname, join, lstatReadlinkAbsolute, relative } = require("./util/fs"); +const makeSerializable = require("./util/makeSerializable"); +const memoize = require("./util/memoize"); +const processAsyncTree = require("./util/processAsyncTree"); + +/** @typedef {import("enhanced-resolve").Resolver} Resolver */ +/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */ +/** @typedef {import("enhanced-resolve").ResolveFunctionAsync} ResolveFunctionAsync */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("./util/fs").IStats} IStats */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/fs").PathLike} PathLike */ +/** @typedef {import("./util/fs").StringCallback} StringCallback */ +/** + * @template T + * @typedef {import("./util/AsyncQueue").Callback} ProcessorCallback + */ +/** + * @template T, R + * @typedef {import("./util/AsyncQueue").Processor} Processor + */ + +const supportsEsm = Number(process.versions.modules) >= 83; + +/** @type {Set} */ +const builtinModules = new Set(nodeModule.builtinModules); + +let FS_ACCURACY = 2000; + +const EMPTY_SET = new Set(); + +const RBDT_RESOLVE_CJS = 0; +const RBDT_RESOLVE_ESM = 1; +const RBDT_RESOLVE_DIRECTORY = 2; +const RBDT_RESOLVE_CJS_FILE = 3; +const RBDT_RESOLVE_CJS_FILE_AS_CHILD = 4; +const RBDT_RESOLVE_ESM_FILE = 5; +const RBDT_DIRECTORY = 6; +const RBDT_FILE = 7; +const RBDT_DIRECTORY_DEPENDENCIES = 8; +const RBDT_FILE_DEPENDENCIES = 9; + +/** @typedef {RBDT_RESOLVE_CJS | RBDT_RESOLVE_ESM | RBDT_RESOLVE_DIRECTORY | RBDT_RESOLVE_CJS_FILE | RBDT_RESOLVE_CJS_FILE_AS_CHILD | RBDT_RESOLVE_ESM_FILE | RBDT_DIRECTORY | RBDT_FILE | RBDT_DIRECTORY_DEPENDENCIES | RBDT_FILE_DEPENDENCIES} JobType */ + +const INVALID = Symbol("invalid"); + +/** + * @typedef {object} FileSystemInfoEntry + * @property {number} safeTime + * @property {number=} timestamp + */ + +/** + * @typedef {object} ResolvedContextFileSystemInfoEntry + * @property {number} safeTime + * @property {string=} timestampHash + */ + +/** @typedef {Set} Symlinks */ + +/** + * @typedef {object} ContextFileSystemInfoEntry + * @property {number} safeTime + * @property {string=} timestampHash + * @property {ResolvedContextFileSystemInfoEntry=} resolved + * @property {Symlinks=} symlinks + */ + +/** + * @typedef {object} TimestampAndHash + * @property {number} safeTime + * @property {number=} timestamp + * @property {string} hash + */ + +/** + * @typedef {object} ResolvedContextTimestampAndHash + * @property {number} safeTime + * @property {string=} timestampHash + * @property {string} hash + */ + +/** + * @typedef {object} ContextTimestampAndHash + * @property {number} safeTime + * @property {string=} timestampHash + * @property {string} hash + * @property {ResolvedContextTimestampAndHash=} resolved + * @property {Symlinks=} symlinks + */ + +/** + * @typedef {object} ContextHash + * @property {string} hash + * @property {string=} resolved + * @property {Symlinks=} symlinks + */ + +/** @typedef {Set} SnapshotContent */ + +/** + * @typedef {object} SnapshotOptimizationEntry + * @property {Snapshot} snapshot + * @property {number} shared + * @property {SnapshotContent | undefined} snapshotContent + * @property {Set | undefined} children + */ + +/** @typedef {Map} ResolveResults */ + +/** @typedef {Set} Files */ +/** @typedef {Set} Directories */ +/** @typedef {Set} Missing */ + +/** + * @typedef {object} ResolveDependencies + * @property {Files} files list of files + * @property {Directories} directories list of directories + * @property {Missing} missing list of missing entries + */ + +/** + * @typedef {object} ResolveBuildDependenciesResult + * @property {Files} files list of files + * @property {Directories} directories list of directories + * @property {Missing} missing list of missing entries + * @property {ResolveResults} resolveResults stored resolve results + * @property {ResolveDependencies} resolveDependencies dependencies of the resolving + */ + +/** + * @typedef {object} SnapshotOptions + * @property {boolean=} hash should use hash to snapshot + * @property {boolean=} timestamp should use timestamp to snapshot + */ + +const DONE_ITERATOR_RESULT = new Set().keys().next(); + +// cspell:word tshs +// Tsh = Timestamp + Hash +// Tshs = Timestamp + Hash combinations + +class SnapshotIterator { + /** + * @param {() => IteratorResult} next next + */ + constructor(next) { + this.next = next; + } +} + +/** @typedef {Map | Set | undefined} SnapshotMap */ +/** @typedef {(snapshot: Snapshot) => SnapshotMap[]} GetMapsFunction */ + +class SnapshotIterable { + /** + * @param {Snapshot} snapshot snapshot + * @param {GetMapsFunction} getMaps get maps function + */ + constructor(snapshot, getMaps) { + this.snapshot = snapshot; + this.getMaps = getMaps; + } + + [Symbol.iterator]() { + let state = 0; + /** @type {IterableIterator} */ + let it; + /** @type {GetMapsFunction} */ + let getMaps; + /** @type {SnapshotMap[]} */ + let maps; + /** @type {Snapshot} */ + let snapshot; + /** @type {Snapshot[] | undefined} */ + let queue; + return new SnapshotIterator(() => { + for (;;) { + switch (state) { + case 0: + snapshot = this.snapshot; + getMaps = this.getMaps; + maps = getMaps(snapshot); + state = 1; + /* falls through */ + case 1: + if (maps.length > 0) { + const map = maps.pop(); + if (map !== undefined) { + it = map.keys(); + state = 2; + } else { + break; + } + } else { + state = 3; + break; + } + /* falls through */ + case 2: { + const result = it.next(); + if (!result.done) return result; + state = 1; + break; + } + case 3: { + const children = snapshot.children; + if (children !== undefined) { + if (children.size === 1) { + // shortcut for a single child + // avoids allocation of queue + for (const child of children) snapshot = child; + maps = getMaps(snapshot); + state = 1; + break; + } + if (queue === undefined) queue = []; + for (const child of children) { + queue.push(child); + } + } + if (queue !== undefined && queue.length > 0) { + snapshot = /** @type {Snapshot} */ (queue.pop()); + maps = getMaps(snapshot); + state = 1; + break; + } else { + state = 4; + } + } + /* falls through */ + case 4: + return DONE_ITERATOR_RESULT; + } + } + }); + } +} + +/** @typedef {Map} FileTimestamps */ +/** @typedef {Map} FileHashes */ +/** @typedef {Map} FileTshs */ +/** @typedef {Map} ContextTimestamps */ +/** @typedef {Map} ContextHashes */ +/** @typedef {Map} ContextTshs */ +/** @typedef {Map} MissingExistence */ +/** @typedef {Map} ManagedItemInfo */ +/** @typedef {Set} ManagedFiles */ +/** @typedef {Set} ManagedContexts */ +/** @typedef {Set} ManagedMissing */ +/** @typedef {Set} Children */ + +class Snapshot { + constructor() { + this._flags = 0; + /** @type {Iterable | undefined} */ + this._cachedFileIterable = undefined; + /** @type {Iterable | undefined} */ + this._cachedContextIterable = undefined; + /** @type {Iterable | undefined} */ + this._cachedMissingIterable = undefined; + /** @type {number | undefined} */ + this.startTime = undefined; + /** @type {FileTimestamps | undefined} */ + this.fileTimestamps = undefined; + /** @type {FileHashes | undefined} */ + this.fileHashes = undefined; + /** @type {FileTshs | undefined} */ + this.fileTshs = undefined; + /** @type {ContextTimestamps | undefined} */ + this.contextTimestamps = undefined; + /** @type {ContextHashes | undefined} */ + this.contextHashes = undefined; + /** @type {ContextTshs | undefined} */ + this.contextTshs = undefined; + /** @type {MissingExistence | undefined} */ + this.missingExistence = undefined; + /** @type {ManagedItemInfo | undefined} */ + this.managedItemInfo = undefined; + /** @type {ManagedFiles | undefined} */ + this.managedFiles = undefined; + /** @type {ManagedContexts | undefined} */ + this.managedContexts = undefined; + /** @type {ManagedMissing | undefined} */ + this.managedMissing = undefined; + /** @type {Children | undefined} */ + this.children = undefined; + } + + hasStartTime() { + return (this._flags & 1) !== 0; + } + + /** + * @param {number} value start value + */ + setStartTime(value) { + this._flags |= 1; + this.startTime = value; + } + + /** + * @param {number | undefined} value value + * @param {Snapshot} snapshot snapshot + */ + setMergedStartTime(value, snapshot) { + if (value) { + if (snapshot.hasStartTime()) { + this.setStartTime( + Math.min( + value, + /** @type {NonNullable} */ + (snapshot.startTime) + ) + ); + } else { + this.setStartTime(value); + } + } else if (snapshot.hasStartTime()) { + this.setStartTime( + /** @type {NonNullable} */ + (snapshot.startTime) + ); + } + } + + hasFileTimestamps() { + return (this._flags & 2) !== 0; + } + + /** + * @param {FileTimestamps} value file timestamps + */ + setFileTimestamps(value) { + this._flags |= 2; + this.fileTimestamps = value; + } + + hasFileHashes() { + return (this._flags & 4) !== 0; + } + + /** + * @param {FileHashes} value file hashes + */ + setFileHashes(value) { + this._flags |= 4; + this.fileHashes = value; + } + + hasFileTshs() { + return (this._flags & 8) !== 0; + } + + /** + * @param {FileTshs} value file tshs + */ + setFileTshs(value) { + this._flags |= 8; + this.fileTshs = value; + } + + hasContextTimestamps() { + return (this._flags & 0x10) !== 0; + } + + /** + * @param {ContextTimestamps} value context timestamps + */ + setContextTimestamps(value) { + this._flags |= 0x10; + this.contextTimestamps = value; + } + + hasContextHashes() { + return (this._flags & 0x20) !== 0; + } + + /** + * @param {ContextHashes} value context hashes + */ + setContextHashes(value) { + this._flags |= 0x20; + this.contextHashes = value; + } + + hasContextTshs() { + return (this._flags & 0x40) !== 0; + } + + /** + * @param {ContextTshs} value context tshs + */ + setContextTshs(value) { + this._flags |= 0x40; + this.contextTshs = value; + } + + hasMissingExistence() { + return (this._flags & 0x80) !== 0; + } + + /** + * @param {MissingExistence} value context tshs + */ + setMissingExistence(value) { + this._flags |= 0x80; + this.missingExistence = value; + } + + hasManagedItemInfo() { + return (this._flags & 0x100) !== 0; + } + + /** + * @param {ManagedItemInfo} value managed item info + */ + setManagedItemInfo(value) { + this._flags |= 0x100; + this.managedItemInfo = value; + } + + hasManagedFiles() { + return (this._flags & 0x200) !== 0; + } + + /** + * @param {ManagedFiles} value managed files + */ + setManagedFiles(value) { + this._flags |= 0x200; + this.managedFiles = value; + } + + hasManagedContexts() { + return (this._flags & 0x400) !== 0; + } + + /** + * @param {ManagedContexts} value managed contexts + */ + setManagedContexts(value) { + this._flags |= 0x400; + this.managedContexts = value; + } + + hasManagedMissing() { + return (this._flags & 0x800) !== 0; + } + + /** + * @param {ManagedMissing} value managed missing + */ + setManagedMissing(value) { + this._flags |= 0x800; + this.managedMissing = value; + } + + hasChildren() { + return (this._flags & 0x1000) !== 0; + } + + /** + * @param {Children} value children + */ + setChildren(value) { + this._flags |= 0x1000; + this.children = value; + } + + /** + * @param {Snapshot} child children + */ + addChild(child) { + if (!this.hasChildren()) { + this.setChildren(new Set()); + } + /** @type {Children} */ + (this.children).add(child); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize({ write }) { + write(this._flags); + if (this.hasStartTime()) write(this.startTime); + if (this.hasFileTimestamps()) write(this.fileTimestamps); + if (this.hasFileHashes()) write(this.fileHashes); + if (this.hasFileTshs()) write(this.fileTshs); + if (this.hasContextTimestamps()) write(this.contextTimestamps); + if (this.hasContextHashes()) write(this.contextHashes); + if (this.hasContextTshs()) write(this.contextTshs); + if (this.hasMissingExistence()) write(this.missingExistence); + if (this.hasManagedItemInfo()) write(this.managedItemInfo); + if (this.hasManagedFiles()) write(this.managedFiles); + if (this.hasManagedContexts()) write(this.managedContexts); + if (this.hasManagedMissing()) write(this.managedMissing); + if (this.hasChildren()) write(this.children); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize({ read }) { + this._flags = read(); + if (this.hasStartTime()) this.startTime = read(); + if (this.hasFileTimestamps()) this.fileTimestamps = read(); + if (this.hasFileHashes()) this.fileHashes = read(); + if (this.hasFileTshs()) this.fileTshs = read(); + if (this.hasContextTimestamps()) this.contextTimestamps = read(); + if (this.hasContextHashes()) this.contextHashes = read(); + if (this.hasContextTshs()) this.contextTshs = read(); + if (this.hasMissingExistence()) this.missingExistence = read(); + if (this.hasManagedItemInfo()) this.managedItemInfo = read(); + if (this.hasManagedFiles()) this.managedFiles = read(); + if (this.hasManagedContexts()) this.managedContexts = read(); + if (this.hasManagedMissing()) this.managedMissing = read(); + if (this.hasChildren()) this.children = read(); + } + + /** + * @param {GetMapsFunction} getMaps first + * @returns {Iterable} iterable + */ + _createIterable(getMaps) { + return new SnapshotIterable(this, getMaps); + } + + /** + * @returns {Iterable} iterable + */ + getFileIterable() { + if (this._cachedFileIterable === undefined) { + this._cachedFileIterable = this._createIterable((s) => [ + s.fileTimestamps, + s.fileHashes, + s.fileTshs, + s.managedFiles + ]); + } + return this._cachedFileIterable; + } + + /** + * @returns {Iterable} iterable + */ + getContextIterable() { + if (this._cachedContextIterable === undefined) { + this._cachedContextIterable = this._createIterable((s) => [ + s.contextTimestamps, + s.contextHashes, + s.contextTshs, + s.managedContexts + ]); + } + return this._cachedContextIterable; + } + + /** + * @returns {Iterable} iterable + */ + getMissingIterable() { + if (this._cachedMissingIterable === undefined) { + this._cachedMissingIterable = this._createIterable((s) => [ + s.missingExistence, + s.managedMissing + ]); + } + return this._cachedMissingIterable; + } +} + +makeSerializable(Snapshot, "webpack/lib/FileSystemInfo", "Snapshot"); + +const MIN_COMMON_SNAPSHOT_SIZE = 3; + +/** + * @template U, T + * @typedef {U extends true ? Set : Map} SnapshotOptimizationValue + */ + +/** + * @template T + * @template {boolean} [U=false] + */ +class SnapshotOptimization { + /** + * @param {(snapshot: Snapshot) => boolean} has has value + * @param {(snapshot: Snapshot) => SnapshotOptimizationValue | undefined} get get value + * @param {(snapshot: Snapshot, value: SnapshotOptimizationValue) => void} set set value + * @param {boolean=} useStartTime use the start time of snapshots + * @param {U=} isSet value is an Set instead of a Map + */ + constructor( + has, + get, + set, + useStartTime = true, + isSet = /** @type {U} */ (false) + ) { + this._has = has; + this._get = get; + this._set = set; + this._useStartTime = useStartTime; + /** @type {U} */ + this._isSet = isSet; + /** @type {Map} */ + this._map = new Map(); + this._statItemsShared = 0; + this._statItemsUnshared = 0; + this._statSharedSnapshots = 0; + this._statReusedSharedSnapshots = 0; + } + + getStatisticMessage() { + const total = this._statItemsShared + this._statItemsUnshared; + if (total === 0) return; + return `${ + this._statItemsShared && Math.round((this._statItemsShared * 100) / total) + }% (${this._statItemsShared}/${total}) entries shared via ${ + this._statSharedSnapshots + } shared snapshots (${ + this._statReusedSharedSnapshots + this._statSharedSnapshots + } times referenced)`; + } + + clear() { + this._map.clear(); + this._statItemsShared = 0; + this._statItemsUnshared = 0; + this._statSharedSnapshots = 0; + this._statReusedSharedSnapshots = 0; + } + + /** + * @param {Snapshot} newSnapshot snapshot + * @param {Set} capturedFiles files to snapshot/share + * @returns {void} + */ + optimize(newSnapshot, capturedFiles) { + /** + * @param {SnapshotOptimizationEntry} entry optimization entry + * @returns {void} + */ + const increaseSharedAndStoreOptimizationEntry = (entry) => { + if (entry.children !== undefined) { + for (const child of entry.children) { + increaseSharedAndStoreOptimizationEntry(child); + } + } + entry.shared++; + storeOptimizationEntry(entry); + }; + /** + * @param {SnapshotOptimizationEntry} entry optimization entry + * @returns {void} + */ + const storeOptimizationEntry = (entry) => { + for (const path of /** @type {SnapshotContent} */ ( + entry.snapshotContent + )) { + const old = + /** @type {SnapshotOptimizationEntry} */ + (this._map.get(path)); + if (old.shared < entry.shared) { + this._map.set(path, entry); + } + capturedFiles.delete(path); + } + }; + + /** @type {SnapshotOptimizationEntry | undefined} */ + let newOptimizationEntry; + + const capturedFilesSize = capturedFiles.size; + + /** @type {Set | undefined} */ + const optimizationEntries = new Set(); + + for (const path of capturedFiles) { + const optimizationEntry = this._map.get(path); + if (optimizationEntry === undefined) { + if (newOptimizationEntry === undefined) { + newOptimizationEntry = { + snapshot: newSnapshot, + shared: 0, + snapshotContent: undefined, + children: undefined + }; + } + this._map.set(path, newOptimizationEntry); + } else { + optimizationEntries.add(optimizationEntry); + } + } + + optimizationEntriesLabel: for (const optimizationEntry of optimizationEntries) { + const snapshot = optimizationEntry.snapshot; + if (optimizationEntry.shared > 0) { + // It's a shared snapshot + // We can't change it, so we can only use it when all files match + // and startTime is compatible + if ( + this._useStartTime && + newSnapshot.startTime && + (!snapshot.startTime || snapshot.startTime > newSnapshot.startTime) + ) { + continue; + } + const nonSharedFiles = new Set(); + const snapshotContent = + /** @type {NonNullable} */ + (optimizationEntry.snapshotContent); + const snapshotEntries = + /** @type {SnapshotOptimizationValue} */ + (this._get(snapshot)); + for (const path of snapshotContent) { + if (!capturedFiles.has(path)) { + if (!snapshotEntries.has(path)) { + // File is not shared and can't be removed from the snapshot + // because it's in a child of the snapshot + continue optimizationEntriesLabel; + } + nonSharedFiles.add(path); + } + } + if (nonSharedFiles.size === 0) { + // The complete snapshot is shared + // add it as child + newSnapshot.addChild(snapshot); + increaseSharedAndStoreOptimizationEntry(optimizationEntry); + this._statReusedSharedSnapshots++; + } else { + // Only a part of the snapshot is shared + const sharedCount = snapshotContent.size - nonSharedFiles.size; + if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) { + // Common part it too small + continue; + } + // Extract common timestamps from both snapshots + let commonMap; + if (this._isSet) { + commonMap = new Set(); + for (const path of /** @type {Set} */ (snapshotEntries)) { + if (nonSharedFiles.has(path)) continue; + commonMap.add(path); + snapshotEntries.delete(path); + } + } else { + commonMap = new Map(); + const map = /** @type {Map} */ (snapshotEntries); + for (const [path, value] of map) { + if (nonSharedFiles.has(path)) continue; + commonMap.set(path, value); + snapshotEntries.delete(path); + } + } + // Create and attach snapshot + const commonSnapshot = new Snapshot(); + if (this._useStartTime) { + commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); + } + this._set( + commonSnapshot, + /** @type {SnapshotOptimizationValue} */ (commonMap) + ); + newSnapshot.addChild(commonSnapshot); + snapshot.addChild(commonSnapshot); + // Create optimization entry + const newEntry = { + snapshot: commonSnapshot, + shared: optimizationEntry.shared + 1, + snapshotContent: new Set(commonMap.keys()), + children: undefined + }; + if (optimizationEntry.children === undefined) { + optimizationEntry.children = new Set(); + } + optimizationEntry.children.add(newEntry); + storeOptimizationEntry(newEntry); + this._statSharedSnapshots++; + } + } else { + // It's a unshared snapshot + // We can extract a common shared snapshot + // with all common files + const snapshotEntries = this._get(snapshot); + if (snapshotEntries === undefined) { + // Incomplete snapshot, that can't be used + continue; + } + let commonMap; + if (this._isSet) { + commonMap = new Set(); + const set = /** @type {Set} */ (snapshotEntries); + if (capturedFiles.size < set.size) { + for (const path of capturedFiles) { + if (set.has(path)) commonMap.add(path); + } + } else { + for (const path of set) { + if (capturedFiles.has(path)) commonMap.add(path); + } + } + } else { + commonMap = new Map(); + const map = /** @type {Map} */ (snapshotEntries); + for (const path of capturedFiles) { + const ts = map.get(path); + if (ts === undefined) continue; + commonMap.set(path, ts); + } + } + + if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) { + // Common part it too small + continue; + } + // Create and attach snapshot + const commonSnapshot = new Snapshot(); + if (this._useStartTime) { + commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); + } + this._set( + commonSnapshot, + /** @type {SnapshotOptimizationValue} */ + (commonMap) + ); + newSnapshot.addChild(commonSnapshot); + snapshot.addChild(commonSnapshot); + // Remove files from snapshot + for (const path of commonMap.keys()) snapshotEntries.delete(path); + const sharedCount = commonMap.size; + this._statItemsUnshared -= sharedCount; + this._statItemsShared += sharedCount; + // Create optimization entry + storeOptimizationEntry({ + snapshot: commonSnapshot, + shared: 2, + snapshotContent: new Set(commonMap.keys()), + children: undefined + }); + this._statSharedSnapshots++; + } + } + const unshared = capturedFiles.size; + this._statItemsUnshared += unshared; + this._statItemsShared += capturedFilesSize - unshared; + } +} + +/** + * @param {string} str input + * @returns {string} result + */ +const parseString = (str) => { + if (str[0] === "'" || str[0] === "`") { + str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`; + } + return JSON.parse(str); +}; + +/* istanbul ignore next */ +/** + * @param {number} mtime mtime + */ +const applyMtime = (mtime) => { + if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1; + else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10; + else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100; + else if (FS_ACCURACY > 1000 && mtime % 2000 !== 0) FS_ACCURACY = 1000; +}; + +/** + * @template T + * @template K + * @param {Map | undefined} a source map + * @param {Map | undefined} b joining map + * @returns {Map} joined map + */ +const mergeMaps = (a, b) => { + if (!b || b.size === 0) return /** @type {Map} */ (a); + if (!a || a.size === 0) return /** @type {Map} */ (b); + /** @type {Map} */ + const map = new Map(a); + for (const [key, value] of b) { + map.set(key, value); + } + return map; +}; + +/** + * @template T + * @param {Set | undefined} a source map + * @param {Set | undefined} b joining map + * @returns {Set} joined map + */ +const mergeSets = (a, b) => { + if (!b || b.size === 0) return /** @type {Set} */ (a); + if (!a || a.size === 0) return /** @type {Set} */ (b); + /** @type {Set} */ + const map = new Set(a); + for (const item of b) { + map.add(item); + } + return map; +}; + +/** + * Finding file or directory to manage + * @param {string} managedPath path that is managing by {@link FileSystemInfo} + * @param {string} path path to file or directory + * @returns {string|null} managed item + * @example + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/package/index.js' + * ) === '/Users/user/my-project/node_modules/package' + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/package1/node_modules/package2' + * ) === '/Users/user/my-project/node_modules/package1/node_modules/package2' + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/.bin/script.js' + * ) === null // hidden files are disallowed as managed items + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/package' + * ) === '/Users/user/my-project/node_modules/package' + */ +const getManagedItem = (managedPath, path) => { + let i = managedPath.length; + let slashes = 1; + let startingPosition = true; + loop: while (i < path.length) { + switch (path.charCodeAt(i)) { + case 47: // slash + case 92: // backslash + if (--slashes === 0) break loop; + startingPosition = true; + break; + case 46: // . + // hidden files are disallowed as managed items + // it's probably .yarn-integrity or .cache + if (startingPosition) return null; + break; + case 64: // @ + if (!startingPosition) return null; + slashes++; + break; + default: + startingPosition = false; + break; + } + i++; + } + if (i === path.length) slashes--; + // return null when path is incomplete + if (slashes !== 0) return null; + // if (path.slice(i + 1, i + 13) === "node_modules") + if ( + path.length >= i + 13 && + path.charCodeAt(i + 1) === 110 && + path.charCodeAt(i + 2) === 111 && + path.charCodeAt(i + 3) === 100 && + path.charCodeAt(i + 4) === 101 && + path.charCodeAt(i + 5) === 95 && + path.charCodeAt(i + 6) === 109 && + path.charCodeAt(i + 7) === 111 && + path.charCodeAt(i + 8) === 100 && + path.charCodeAt(i + 9) === 117 && + path.charCodeAt(i + 10) === 108 && + path.charCodeAt(i + 11) === 101 && + path.charCodeAt(i + 12) === 115 + ) { + // if this is the end of the path + if (path.length === i + 13) { + // return the node_modules directory + // it's special + return path; + } + const c = path.charCodeAt(i + 13); + // if next symbol is slash or backslash + if (c === 47 || c === 92) { + // Managed subpath + return getManagedItem(path.slice(0, i + 14), path); + } + } + return path.slice(0, i); +}; + +/** + * @template {ContextFileSystemInfoEntry | ContextTimestampAndHash} T + * @param {T | null} entry entry + * @returns {T["resolved"] | null | undefined} the resolved entry + */ +const getResolvedTimestamp = (entry) => { + if (entry === null) return null; + if (entry.resolved !== undefined) return entry.resolved; + return entry.symlinks === undefined ? entry : undefined; +}; + +/** + * @param {ContextHash | null} entry entry + * @returns {string | null | undefined} the resolved entry + */ +const getResolvedHash = (entry) => { + if (entry === null) return null; + if (entry.resolved !== undefined) return entry.resolved; + return entry.symlinks === undefined ? entry.hash : undefined; +}; + +/** + * @template T + * @param {Set} source source + * @param {Set} target target + */ +const addAll = (source, target) => { + for (const key of source) target.add(key); +}; + +const getEsModuleLexer = memoize(() => require("es-module-lexer")); + +/** @typedef {Set} LoggedPaths */ + +/** @typedef {FileSystemInfoEntry | "ignore" | null} FileTimestamp */ +/** @typedef {ContextFileSystemInfoEntry | "ignore" | null} ContextTimestamp */ +/** @typedef {ResolvedContextFileSystemInfoEntry | "ignore" | null} ResolvedContextTimestamp */ + +/** @typedef {(err?: WebpackError | null, result?: boolean) => void} CheckSnapshotValidCallback */ + +/** + * Used to access information about the filesystem in a cached way + */ +class FileSystemInfo { + /** + * @param {InputFileSystem} fs file system + * @param {object} options options + * @param {Iterable=} options.unmanagedPaths paths that are not managed by a package manager and the contents are subject to change + * @param {Iterable=} options.managedPaths paths that are only managed by a package manager + * @param {Iterable=} options.immutablePaths paths that are immutable + * @param {Logger=} options.logger logger used to log invalid snapshots + * @param {HashFunction=} options.hashFunction the hash function to use + */ + constructor( + fs, + { + unmanagedPaths = [], + managedPaths = [], + immutablePaths = [], + logger, + hashFunction = DEFAULTS.HASH_FUNCTION + } = {} + ) { + this.fs = fs; + this.logger = logger; + this._remainingLogs = logger ? 40 : 0; + /** @type {LoggedPaths | undefined} */ + this._loggedPaths = logger ? new Set() : undefined; + this._hashFunction = hashFunction; + /** @type {WeakMap} */ + this._snapshotCache = new WeakMap(); + this._fileTimestampsOptimization = new SnapshotOptimization( + (s) => s.hasFileTimestamps(), + (s) => s.fileTimestamps, + (s, v) => s.setFileTimestamps(v) + ); + this._fileHashesOptimization = new SnapshotOptimization( + (s) => s.hasFileHashes(), + (s) => s.fileHashes, + (s, v) => s.setFileHashes(v), + false + ); + this._fileTshsOptimization = new SnapshotOptimization( + (s) => s.hasFileTshs(), + (s) => s.fileTshs, + (s, v) => s.setFileTshs(v) + ); + this._contextTimestampsOptimization = new SnapshotOptimization( + (s) => s.hasContextTimestamps(), + (s) => s.contextTimestamps, + (s, v) => s.setContextTimestamps(v) + ); + this._contextHashesOptimization = new SnapshotOptimization( + (s) => s.hasContextHashes(), + (s) => s.contextHashes, + (s, v) => s.setContextHashes(v), + false + ); + this._contextTshsOptimization = new SnapshotOptimization( + (s) => s.hasContextTshs(), + (s) => s.contextTshs, + (s, v) => s.setContextTshs(v) + ); + this._missingExistenceOptimization = new SnapshotOptimization( + (s) => s.hasMissingExistence(), + (s) => s.missingExistence, + (s, v) => s.setMissingExistence(v), + false + ); + this._managedItemInfoOptimization = new SnapshotOptimization( + (s) => s.hasManagedItemInfo(), + (s) => s.managedItemInfo, + (s, v) => s.setManagedItemInfo(v), + false + ); + this._managedFilesOptimization = new SnapshotOptimization( + (s) => s.hasManagedFiles(), + (s) => s.managedFiles, + (s, v) => s.setManagedFiles(v), + false, + true + ); + this._managedContextsOptimization = new SnapshotOptimization( + (s) => s.hasManagedContexts(), + (s) => s.managedContexts, + (s, v) => s.setManagedContexts(v), + false, + true + ); + this._managedMissingOptimization = new SnapshotOptimization( + (s) => s.hasManagedMissing(), + (s) => s.managedMissing, + (s, v) => s.setManagedMissing(v), + false, + true + ); + /** @type {StackedCacheMap} */ + this._fileTimestamps = new StackedCacheMap(); + /** @type {Map} */ + this._fileHashes = new Map(); + /** @type {Map} */ + this._fileTshs = new Map(); + /** @type {StackedCacheMap} */ + this._contextTimestamps = new StackedCacheMap(); + /** @type {Map} */ + this._contextHashes = new Map(); + /** @type {Map} */ + this._contextTshs = new Map(); + /** @type {Map} */ + this._managedItems = new Map(); + /** @type {AsyncQueue} */ + this.fileTimestampQueue = new AsyncQueue({ + name: "file timestamp", + parallelism: 30, + processor: this._readFileTimestamp.bind(this) + }); + /** @type {AsyncQueue} */ + this.fileHashQueue = new AsyncQueue({ + name: "file hash", + parallelism: 10, + processor: this._readFileHash.bind(this) + }); + /** @type {AsyncQueue} */ + this.contextTimestampQueue = new AsyncQueue({ + name: "context timestamp", + parallelism: 2, + processor: this._readContextTimestamp.bind(this) + }); + /** @type {AsyncQueue} */ + this.contextHashQueue = new AsyncQueue({ + name: "context hash", + parallelism: 2, + processor: this._readContextHash.bind(this) + }); + /** @type {AsyncQueue} */ + this.contextTshQueue = new AsyncQueue({ + name: "context hash and timestamp", + parallelism: 2, + processor: this._readContextTimestampAndHash.bind(this) + }); + /** @type {AsyncQueue} */ + this.managedItemQueue = new AsyncQueue({ + name: "managed item info", + parallelism: 10, + processor: this._getManagedItemInfo.bind(this) + }); + /** @type {AsyncQueue>} */ + this.managedItemDirectoryQueue = new AsyncQueue({ + name: "managed item directory info", + parallelism: 10, + processor: this._getManagedItemDirectoryInfo.bind(this) + }); + const _unmanagedPaths = [...unmanagedPaths]; + this.unmanagedPathsWithSlash = + /** @type {string[]} */ + (_unmanagedPaths.filter((p) => typeof p === "string")).map((p) => + join(fs, p, "_").slice(0, -1) + ); + this.unmanagedPathsRegExps = + /** @type {RegExp[]} */ + (_unmanagedPaths.filter((p) => typeof p !== "string")); + + this.managedPaths = [...managedPaths]; + this.managedPathsWithSlash = + /** @type {string[]} */ + (this.managedPaths.filter((p) => typeof p === "string")).map((p) => + join(fs, p, "_").slice(0, -1) + ); + + this.managedPathsRegExps = + /** @type {RegExp[]} */ + (this.managedPaths.filter((p) => typeof p !== "string")); + this.immutablePaths = [...immutablePaths]; + this.immutablePathsWithSlash = + /** @type {string[]} */ + (this.immutablePaths.filter((p) => typeof p === "string")).map((p) => + join(fs, p, "_").slice(0, -1) + ); + this.immutablePathsRegExps = + /** @type {RegExp[]} */ + (this.immutablePaths.filter((p) => typeof p !== "string")); + + this._cachedDeprecatedFileTimestamps = undefined; + this._cachedDeprecatedContextTimestamps = undefined; + + this._warnAboutExperimentalEsmTracking = false; + + this._statCreatedSnapshots = 0; + this._statTestedSnapshotsCached = 0; + this._statTestedSnapshotsNotCached = 0; + this._statTestedChildrenCached = 0; + this._statTestedChildrenNotCached = 0; + this._statTestedEntries = 0; + } + + logStatistics() { + const logger = /** @type {Logger} */ (this.logger); + /** + * @param {string} header header + * @param {string | undefined} message message + */ + const logWhenMessage = (header, message) => { + if (message) { + logger.log(`${header}: ${message}`); + } + }; + logger.log(`${this._statCreatedSnapshots} new snapshots created`); + logger.log( + `${ + this._statTestedSnapshotsNotCached && + Math.round( + (this._statTestedSnapshotsNotCached * 100) / + (this._statTestedSnapshotsCached + + this._statTestedSnapshotsNotCached) + ) + }% root snapshot uncached (${this._statTestedSnapshotsNotCached} / ${ + this._statTestedSnapshotsCached + this._statTestedSnapshotsNotCached + })` + ); + logger.log( + `${ + this._statTestedChildrenNotCached && + Math.round( + (this._statTestedChildrenNotCached * 100) / + (this._statTestedChildrenCached + this._statTestedChildrenNotCached) + ) + }% children snapshot uncached (${this._statTestedChildrenNotCached} / ${ + this._statTestedChildrenCached + this._statTestedChildrenNotCached + })` + ); + logger.log(`${this._statTestedEntries} entries tested`); + logger.log( + `File info in cache: ${this._fileTimestamps.size} timestamps ${this._fileHashes.size} hashes ${this._fileTshs.size} timestamp hash combinations` + ); + logWhenMessage( + "File timestamp snapshot optimization", + this._fileTimestampsOptimization.getStatisticMessage() + ); + logWhenMessage( + "File hash snapshot optimization", + this._fileHashesOptimization.getStatisticMessage() + ); + logWhenMessage( + "File timestamp hash combination snapshot optimization", + this._fileTshsOptimization.getStatisticMessage() + ); + logger.log( + `Directory info in cache: ${this._contextTimestamps.size} timestamps ${this._contextHashes.size} hashes ${this._contextTshs.size} timestamp hash combinations` + ); + logWhenMessage( + "Directory timestamp snapshot optimization", + this._contextTimestampsOptimization.getStatisticMessage() + ); + logWhenMessage( + "Directory hash snapshot optimization", + this._contextHashesOptimization.getStatisticMessage() + ); + logWhenMessage( + "Directory timestamp hash combination snapshot optimization", + this._contextTshsOptimization.getStatisticMessage() + ); + logWhenMessage( + "Missing items snapshot optimization", + this._missingExistenceOptimization.getStatisticMessage() + ); + logger.log(`Managed items info in cache: ${this._managedItems.size} items`); + logWhenMessage( + "Managed items snapshot optimization", + this._managedItemInfoOptimization.getStatisticMessage() + ); + logWhenMessage( + "Managed files snapshot optimization", + this._managedFilesOptimization.getStatisticMessage() + ); + logWhenMessage( + "Managed contexts snapshot optimization", + this._managedContextsOptimization.getStatisticMessage() + ); + logWhenMessage( + "Managed missing snapshot optimization", + this._managedMissingOptimization.getStatisticMessage() + ); + } + + /** + * @private + * @param {string} path path + * @param {string} reason reason + * @param {EXPECTED_ANY[]} args arguments + */ + _log(path, reason, ...args) { + const key = path + reason; + const loggedPaths = /** @type {LoggedPaths} */ (this._loggedPaths); + if (loggedPaths.has(key)) return; + loggedPaths.add(key); + /** @type {Logger} */ + (this.logger).debug(`${path} invalidated because ${reason}`, ...args); + if (--this._remainingLogs === 0) { + /** @type {Logger} */ + (this.logger).debug( + "Logging limit has been reached and no further logging will be emitted by FileSystemInfo" + ); + } + } + + clear() { + this._remainingLogs = this.logger ? 40 : 0; + if (this._loggedPaths !== undefined) this._loggedPaths.clear(); + + this._snapshotCache = new WeakMap(); + this._fileTimestampsOptimization.clear(); + this._fileHashesOptimization.clear(); + this._fileTshsOptimization.clear(); + this._contextTimestampsOptimization.clear(); + this._contextHashesOptimization.clear(); + this._contextTshsOptimization.clear(); + this._missingExistenceOptimization.clear(); + this._managedItemInfoOptimization.clear(); + this._managedFilesOptimization.clear(); + this._managedContextsOptimization.clear(); + this._managedMissingOptimization.clear(); + this._fileTimestamps.clear(); + this._fileHashes.clear(); + this._fileTshs.clear(); + this._contextTimestamps.clear(); + this._contextHashes.clear(); + this._contextTshs.clear(); + this._managedItems.clear(); + this._managedItems.clear(); + + this._cachedDeprecatedFileTimestamps = undefined; + this._cachedDeprecatedContextTimestamps = undefined; + + this._statCreatedSnapshots = 0; + this._statTestedSnapshotsCached = 0; + this._statTestedSnapshotsNotCached = 0; + this._statTestedChildrenCached = 0; + this._statTestedChildrenNotCached = 0; + this._statTestedEntries = 0; + } + + /** + * @param {ReadonlyMap} map timestamps + * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it + * @returns {void} + */ + addFileTimestamps(map, immutable) { + this._fileTimestamps.addAll(map, immutable); + this._cachedDeprecatedFileTimestamps = undefined; + } + + /** + * @param {ReadonlyMap} map timestamps + * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it + * @returns {void} + */ + addContextTimestamps(map, immutable) { + this._contextTimestamps.addAll(map, immutable); + this._cachedDeprecatedContextTimestamps = undefined; + } + + /** + * @param {string} path file path + * @param {(err?: WebpackError | null, fileTimestamp?: FileTimestamp) => void} callback callback function + * @returns {void} + */ + getFileTimestamp(path, callback) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) return callback(null, cache); + this.fileTimestampQueue.add(path, callback); + } + + /** + * @param {string} path context path + * @param {(err?: WebpackError | null, resolvedContextTimestamp?: ResolvedContextTimestamp) => void} callback callback function + * @returns {void} + */ + getContextTimestamp(path, callback) { + const cache = this._contextTimestamps.get(path); + if (cache !== undefined) { + if (cache === "ignore") return callback(null, "ignore"); + const resolved = getResolvedTimestamp(cache); + if (resolved !== undefined) return callback(null, resolved); + return this._resolveContextTimestamp( + /** @type {ResolvedContextFileSystemInfoEntry} */ + (cache), + callback + ); + } + this.contextTimestampQueue.add(path, (err, _entry) => { + if (err) return callback(err); + const entry = /** @type {ContextFileSystemInfoEntry} */ (_entry); + const resolved = getResolvedTimestamp(entry); + if (resolved !== undefined) return callback(null, resolved); + this._resolveContextTimestamp(entry, callback); + }); + } + + /** + * @private + * @param {string} path context path + * @param {(err?: WebpackError | null, contextTimestamp?: ContextTimestamp) => void} callback callback function + * @returns {void} + */ + _getUnresolvedContextTimestamp(path, callback) { + const cache = this._contextTimestamps.get(path); + if (cache !== undefined) return callback(null, cache); + this.contextTimestampQueue.add(path, callback); + } + + /** + * @param {string} path file path + * @param {(err?: WebpackError | null, hash?: string | null) => void} callback callback function + * @returns {void} + */ + getFileHash(path, callback) { + const cache = this._fileHashes.get(path); + if (cache !== undefined) return callback(null, cache); + this.fileHashQueue.add(path, callback); + } + + /** + * @param {string} path context path + * @param {(err?: WebpackError | null, contextHash?: string) => void} callback callback function + * @returns {void} + */ + getContextHash(path, callback) { + const cache = this._contextHashes.get(path); + if (cache !== undefined) { + const resolved = getResolvedHash(cache); + if (resolved !== undefined) { + return callback(null, /** @type {string} */ (resolved)); + } + return this._resolveContextHash(cache, callback); + } + this.contextHashQueue.add(path, (err, _entry) => { + if (err) return callback(err); + const entry = /** @type {ContextHash} */ (_entry); + const resolved = getResolvedHash(entry); + if (resolved !== undefined) { + return callback(null, /** @type {string} */ (resolved)); + } + this._resolveContextHash(entry, callback); + }); + } + + /** + * @private + * @param {string} path context path + * @param {(err?: WebpackError | null, contextHash?: ContextHash | null) => void} callback callback function + * @returns {void} + */ + _getUnresolvedContextHash(path, callback) { + const cache = this._contextHashes.get(path); + if (cache !== undefined) return callback(null, cache); + this.contextHashQueue.add(path, callback); + } + + /** + * @param {string} path context path + * @param {(err?: WebpackError | null, resolvedContextTimestampAndHash?: ResolvedContextTimestampAndHash | null) => void} callback callback function + * @returns {void} + */ + getContextTsh(path, callback) { + const cache = this._contextTshs.get(path); + if (cache !== undefined) { + const resolved = getResolvedTimestamp(cache); + if (resolved !== undefined) return callback(null, resolved); + return this._resolveContextTsh(cache, callback); + } + this.contextTshQueue.add(path, (err, _entry) => { + if (err) return callback(err); + const entry = /** @type {ContextTimestampAndHash} */ (_entry); + const resolved = getResolvedTimestamp(entry); + if (resolved !== undefined) return callback(null, resolved); + this._resolveContextTsh(entry, callback); + }); + } + + /** + * @private + * @param {string} path context path + * @param {(err?: WebpackError | null, contextTimestampAndHash?: ContextTimestampAndHash | null) => void} callback callback function + * @returns {void} + */ + _getUnresolvedContextTsh(path, callback) { + const cache = this._contextTshs.get(path); + if (cache !== undefined) return callback(null, cache); + this.contextTshQueue.add(path, callback); + } + + _createBuildDependenciesResolvers() { + const resolveContext = createResolver({ + resolveToContext: true, + exportsFields: [], + fileSystem: this.fs + }); + const resolveCjs = createResolver({ + extensions: [".js", ".json", ".node"], + conditionNames: ["require", "node"], + exportsFields: ["exports"], + fileSystem: this.fs + }); + const resolveCjsAsChild = createResolver({ + extensions: [".js", ".json", ".node"], + conditionNames: ["require", "node"], + exportsFields: [], + fileSystem: this.fs + }); + const resolveEsm = createResolver({ + extensions: [".js", ".json", ".node"], + fullySpecified: true, + conditionNames: ["import", "node"], + exportsFields: ["exports"], + fileSystem: this.fs + }); + return { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild }; + } + + /** + * @param {string} context context directory + * @param {Iterable} deps dependencies + * @param {(err?: Error | null, resolveBuildDependenciesResult?: ResolveBuildDependenciesResult) => void} callback callback function + * @returns {void} + */ + resolveBuildDependencies(context, deps, callback) { + const { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild } = + this._createBuildDependenciesResolvers(); + + /** @type {Files} */ + const files = new Set(); + /** @type {Symlinks} */ + const fileSymlinks = new Set(); + /** @type {Directories} */ + const directories = new Set(); + /** @type {Symlinks} */ + const directorySymlinks = new Set(); + /** @type {Missing} */ + const missing = new Set(); + /** @type {ResolveDependencies["files"]} */ + const resolveFiles = new Set(); + /** @type {ResolveDependencies["directories"]} */ + const resolveDirectories = new Set(); + /** @type {ResolveDependencies["missing"]} */ + const resolveMissing = new Set(); + /** @type {ResolveResults} */ + const resolveResults = new Map(); + /** @type {Set} */ + const invalidResolveResults = new Set(); + const resolverContext = { + fileDependencies: resolveFiles, + contextDependencies: resolveDirectories, + missingDependencies: resolveMissing + }; + /** + * @param {undefined | boolean | string} expected expected result + * @returns {string} expected result + */ + const expectedToString = (expected) => + expected ? ` (expected ${expected})` : ""; + /** @typedef {{ type: JobType, context: string | undefined, path: string, issuer: Job | undefined, expected: undefined | boolean | string }} Job */ + + /** + * @param {Job} job job + * @returns {`resolve commonjs file ${string}${string}`|`resolve esm file ${string}${string}`|`resolve esm ${string}${string}`|`resolve directory ${string}`|`file ${string}`|`unknown ${string} ${string}`|`resolve commonjs ${string}${string}`|`directory ${string}`|`file dependencies ${string}`|`directory dependencies ${string}`} result + */ + const jobToString = (job) => { + switch (job.type) { + case RBDT_RESOLVE_CJS: + return `resolve commonjs ${job.path}${expectedToString( + job.expected + )}`; + case RBDT_RESOLVE_ESM: + return `resolve esm ${job.path}${expectedToString(job.expected)}`; + case RBDT_RESOLVE_DIRECTORY: + return `resolve directory ${job.path}`; + case RBDT_RESOLVE_CJS_FILE: + return `resolve commonjs file ${job.path}${expectedToString( + job.expected + )}`; + case RBDT_RESOLVE_ESM_FILE: + return `resolve esm file ${job.path}${expectedToString( + job.expected + )}`; + case RBDT_DIRECTORY: + return `directory ${job.path}`; + case RBDT_FILE: + return `file ${job.path}`; + case RBDT_DIRECTORY_DEPENDENCIES: + return `directory dependencies ${job.path}`; + case RBDT_FILE_DEPENDENCIES: + return `file dependencies ${job.path}`; + } + return `unknown ${job.type} ${job.path}`; + }; + /** + * @param {Job} job job + * @returns {string} string value + */ + const pathToString = (job) => { + let result = ` at ${jobToString(job)}`; + /** @type {Job | undefined} */ + (job) = job.issuer; + while (job !== undefined) { + result += `\n at ${jobToString(job)}`; + job = /** @type {Job} */ (job.issuer); + } + return result; + }; + const logger = /** @type {Logger} */ (this.logger); + processAsyncTree( + Array.from( + deps, + (dep) => + /** @type {Job} */ ({ + type: RBDT_RESOLVE_CJS, + context, + path: dep, + expected: undefined, + issuer: undefined + }) + ), + 20, + (job, push, callback) => { + const { type, context, path, expected } = job; + /** + * @param {string} path path + * @returns {void} + */ + const resolveDirectory = (path) => { + const key = `d\n${context}\n${path}`; + if (resolveResults.has(key)) { + return callback(); + } + resolveResults.set(key, undefined); + resolveContext( + /** @type {string} */ (context), + path, + resolverContext, + (err, _, result) => { + if (err) { + if (expected === false) { + resolveResults.set(key, false); + return callback(); + } + invalidResolveResults.add(key); + err.message += `\nwhile resolving '${path}' in ${context} to a directory`; + return callback(err); + } + const resultPath = /** @type {ResolveRequest} */ (result).path; + resolveResults.set(key, resultPath); + push({ + type: RBDT_DIRECTORY, + context: undefined, + path: /** @type {string} */ (resultPath), + expected: undefined, + issuer: job + }); + callback(); + } + ); + }; + /** + * @param {string} path path + * @param {("f" | "c" | "e")=} symbol symbol + * @param {(ResolveFunctionAsync)=} resolve resolve fn + * @returns {void} + */ + const resolveFile = (path, symbol, resolve) => { + const key = `${symbol}\n${context}\n${path}`; + if (resolveResults.has(key)) { + return callback(); + } + resolveResults.set(key, undefined); + /** @type {ResolveFunctionAsync} */ + (resolve)( + /** @type {string} */ (context), + path, + resolverContext, + (err, _, result) => { + if (typeof expected === "string") { + if (!err && result && result.path === expected) { + resolveResults.set(key, result.path); + } else { + invalidResolveResults.add(key); + logger.warn( + `Resolving '${path}' in ${context} for build dependencies doesn't lead to expected result '${expected}', but to '${ + err || (result && result.path) + }' instead. Resolving dependencies are ignored for this path.\n${pathToString( + job + )}` + ); + } + } else { + if (err) { + if (expected === false) { + resolveResults.set(key, false); + return callback(); + } + invalidResolveResults.add(key); + err.message += `\nwhile resolving '${path}' in ${context} as file\n${pathToString( + job + )}`; + return callback(err); + } + const resultPath = /** @type {ResolveRequest} */ (result).path; + resolveResults.set(key, resultPath); + push({ + type: RBDT_FILE, + context: undefined, + path: /** @type {string} */ (resultPath), + expected: undefined, + issuer: job + }); + } + callback(); + } + ); + }; + switch (type) { + case RBDT_RESOLVE_CJS: { + const isDirectory = /[\\/]$/.test(path); + if (isDirectory) { + resolveDirectory(path.slice(0, -1)); + } else { + resolveFile(path, "f", resolveCjs); + } + break; + } + case RBDT_RESOLVE_ESM: { + const isDirectory = /[\\/]$/.test(path); + if (isDirectory) { + resolveDirectory(path.slice(0, -1)); + } else { + resolveFile(path); + } + break; + } + case RBDT_RESOLVE_DIRECTORY: { + resolveDirectory(path); + break; + } + case RBDT_RESOLVE_CJS_FILE: { + resolveFile(path, "f", resolveCjs); + break; + } + case RBDT_RESOLVE_CJS_FILE_AS_CHILD: { + resolveFile(path, "c", resolveCjsAsChild); + break; + } + case RBDT_RESOLVE_ESM_FILE: { + resolveFile(path, "e", resolveEsm); + break; + } + case RBDT_FILE: { + if (files.has(path)) { + callback(); + break; + } + files.add(path); + /** @type {NonNullable} */ + (this.fs.realpath)(path, (err, _realPath) => { + if (err) return callback(err); + const realPath = /** @type {string} */ (_realPath); + if (realPath !== path) { + fileSymlinks.add(path); + resolveFiles.add(path); + if (files.has(realPath)) return callback(); + files.add(realPath); + } + push({ + type: RBDT_FILE_DEPENDENCIES, + context: undefined, + path: realPath, + expected: undefined, + issuer: job + }); + callback(); + }); + break; + } + case RBDT_DIRECTORY: { + if (directories.has(path)) { + callback(); + break; + } + directories.add(path); + /** @type {NonNullable} */ + (this.fs.realpath)(path, (err, _realPath) => { + if (err) return callback(err); + const realPath = /** @type {string} */ (_realPath); + if (realPath !== path) { + directorySymlinks.add(path); + resolveFiles.add(path); + if (directories.has(realPath)) return callback(); + directories.add(realPath); + } + push({ + type: RBDT_DIRECTORY_DEPENDENCIES, + context: undefined, + path: realPath, + expected: undefined, + issuer: job + }); + callback(); + }); + break; + } + case RBDT_FILE_DEPENDENCIES: { + // Check for known files without dependencies + if (/\.json5?$|\.yarn-integrity$|yarn\.lock$|\.ya?ml/.test(path)) { + process.nextTick(callback); + break; + } + // Check commonjs cache for the module + /** @type {NodeModule | undefined} */ + const module = require.cache[path]; + if (module && Array.isArray(module.children)) { + children: for (const child of module.children) { + const childPath = child.filename; + if (childPath) { + push({ + type: RBDT_FILE, + context: undefined, + path: childPath, + expected: undefined, + issuer: job + }); + const context = dirname(this.fs, path); + for (const modulePath of module.paths) { + if (childPath.startsWith(modulePath)) { + const subPath = childPath.slice(modulePath.length + 1); + const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec( + subPath + ); + if (packageMatch) { + push({ + type: RBDT_FILE, + context: undefined, + path: `${ + modulePath + + childPath[modulePath.length] + + packageMatch[0] + + childPath[modulePath.length] + }package.json`, + expected: false, + issuer: job + }); + } + let request = subPath.replace(/\\/g, "/"); + if (request.endsWith(".js")) { + request = request.slice(0, -3); + } + push({ + type: RBDT_RESOLVE_CJS_FILE_AS_CHILD, + context, + path: request, + expected: child.filename, + issuer: job + }); + continue children; + } + } + let request = relative(this.fs, context, childPath); + if (request.endsWith(".js")) request = request.slice(0, -3); + request = request.replace(/\\/g, "/"); + if (!request.startsWith("../") && !isAbsolute(request)) { + request = `./${request}`; + } + push({ + type: RBDT_RESOLVE_CJS_FILE, + context, + path: request, + expected: child.filename, + issuer: job + }); + } + } + } else if (supportsEsm && /\.m?js$/.test(path)) { + if (!this._warnAboutExperimentalEsmTracking) { + logger.log( + "Node.js doesn't offer a (nice) way to introspect the ESM dependency graph yet.\n" + + "Until a full solution is available webpack uses an experimental ESM tracking based on parsing.\n" + + "As best effort webpack parses the ESM files to guess dependencies. But this can lead to expensive and incorrect tracking." + ); + this._warnAboutExperimentalEsmTracking = true; + } + + const lexer = getEsModuleLexer(); + + lexer.init.then(() => { + this.fs.readFile(path, (err, content) => { + if (err) return callback(err); + try { + const context = dirname(this.fs, path); + const source = /** @type {Buffer} */ (content).toString(); + const [imports] = lexer.parse(source); + for (const imp of imports) { + try { + let dependency; + if (imp.d === -1) { + // import ... from "..." + dependency = parseString( + source.slice(imp.s - 1, imp.e + 1) + ); + } else if (imp.d > -1) { + // import() + const expr = source.slice(imp.s, imp.e).trim(); + dependency = parseString(expr); + } else { + // e.g. import.meta + continue; + } + + // we should not track Node.js build dependencies + if (dependency.startsWith("node:")) continue; + if (builtinModules.has(dependency)) continue; + + push({ + type: RBDT_RESOLVE_ESM_FILE, + context, + path: dependency, + expected: imp.d > -1 ? false : undefined, + issuer: job + }); + } catch (err1) { + logger.warn( + `Parsing of ${path} for build dependencies failed at 'import(${source.slice( + imp.s, + imp.e + )})'.\n` + + "Build dependencies behind this expression are ignored and might cause incorrect cache invalidation." + ); + logger.debug(pathToString(job)); + logger.debug(/** @type {Error} */ (err1).stack); + } + } + } catch (err2) { + logger.warn( + `Parsing of ${path} for build dependencies failed and all dependencies of this file are ignored, which might cause incorrect cache invalidation..` + ); + logger.debug(pathToString(job)); + logger.debug(/** @type {Error} */ (err2).stack); + } + process.nextTick(callback); + }); + }, callback); + break; + } else { + logger.log( + `Assuming ${path} has no dependencies as we were unable to assign it to any module system.` + ); + logger.debug(pathToString(job)); + } + process.nextTick(callback); + break; + } + case RBDT_DIRECTORY_DEPENDENCIES: { + const match = + /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(path); + const packagePath = match ? match[1] : path; + const packageJson = join(this.fs, packagePath, "package.json"); + this.fs.readFile(packageJson, (err, content) => { + if (err) { + if (err.code === "ENOENT") { + resolveMissing.add(packageJson); + const parent = dirname(this.fs, packagePath); + if (parent !== packagePath) { + push({ + type: RBDT_DIRECTORY_DEPENDENCIES, + context: undefined, + path: parent, + expected: undefined, + issuer: job + }); + } + callback(); + return; + } + return callback(err); + } + resolveFiles.add(packageJson); + let packageData; + try { + packageData = JSON.parse( + /** @type {Buffer} */ + (content).toString("utf8") + ); + } catch (parseErr) { + return callback(/** @type {Error} */ (parseErr)); + } + const depsObject = packageData.dependencies; + const optionalDepsObject = packageData.optionalDependencies; + const allDeps = new Set(); + const optionalDeps = new Set(); + if (typeof depsObject === "object" && depsObject) { + for (const dep of Object.keys(depsObject)) { + allDeps.add(dep); + } + } + if ( + typeof optionalDepsObject === "object" && + optionalDepsObject + ) { + for (const dep of Object.keys(optionalDepsObject)) { + allDeps.add(dep); + optionalDeps.add(dep); + } + } + for (const dep of allDeps) { + push({ + type: RBDT_RESOLVE_DIRECTORY, + context: packagePath, + path: dep, + expected: !optionalDeps.has(dep), + issuer: job + }); + } + callback(); + }); + break; + } + } + }, + (err) => { + if (err) return callback(err); + for (const l of fileSymlinks) files.delete(l); + for (const l of directorySymlinks) directories.delete(l); + for (const k of invalidResolveResults) resolveResults.delete(k); + callback(null, { + files, + directories, + missing, + resolveResults, + resolveDependencies: { + files: resolveFiles, + directories: resolveDirectories, + missing: resolveMissing + } + }); + } + ); + } + + /** + * @param {ResolveResults} resolveResults results from resolving + * @param {(err?: Error | null, result?: boolean) => void} callback callback with true when resolveResults resolve the same way + * @returns {void} + */ + checkResolveResultsValid(resolveResults, callback) { + const { resolveCjs, resolveCjsAsChild, resolveEsm, resolveContext } = + this._createBuildDependenciesResolvers(); + asyncLib.eachLimit( + resolveResults, + 20, + ([key, expectedResult], callback) => { + const [type, context, path] = key.split("\n"); + switch (type) { + case "d": + resolveContext(context, path, {}, (err, _, result) => { + if (expectedResult === false) { + return callback(err ? undefined : INVALID); + } + if (err) return callback(err); + const resultPath = /** @type {ResolveRequest} */ (result).path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + case "f": + resolveCjs(context, path, {}, (err, _, result) => { + if (expectedResult === false) { + return callback(err ? undefined : INVALID); + } + if (err) return callback(err); + const resultPath = /** @type {ResolveRequest} */ (result).path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + case "c": + resolveCjsAsChild(context, path, {}, (err, _, result) => { + if (expectedResult === false) { + return callback(err ? undefined : INVALID); + } + if (err) return callback(err); + const resultPath = /** @type {ResolveRequest} */ (result).path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + case "e": + resolveEsm(context, path, {}, (err, _, result) => { + if (expectedResult === false) { + return callback(err ? undefined : INVALID); + } + if (err) return callback(err); + const resultPath = /** @type {ResolveRequest} */ (result).path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + default: + callback(new Error("Unexpected type in resolve result key")); + break; + } + }, + /** + * @param {Error | typeof INVALID=} err error or invalid flag + * @returns {void} + */ + (err) => { + if (err === INVALID) { + return callback(null, false); + } + if (err) { + return callback(err); + } + return callback(null, true); + } + ); + } + + /** + * @param {number | null | undefined} startTime when processing the files has started + * @param {Iterable | null | undefined} files all files + * @param {Iterable | null | undefined} directories all directories + * @param {Iterable | null | undefined} missing all missing files or directories + * @param {SnapshotOptions | null | undefined} options options object (for future extensions) + * @param {(err: WebpackError | null, snapshot: Snapshot | null) => void} callback callback function + * @returns {void} + */ + createSnapshot(startTime, files, directories, missing, options, callback) { + /** @type {FileTimestamps} */ + const fileTimestamps = new Map(); + /** @type {FileHashes} */ + const fileHashes = new Map(); + /** @type {FileTshs} */ + const fileTshs = new Map(); + /** @type {ContextTimestamps} */ + const contextTimestamps = new Map(); + /** @type {ContextHashes} */ + const contextHashes = new Map(); + /** @type {ContextTshs} */ + const contextTshs = new Map(); + /** @type {MissingExistence} */ + const missingExistence = new Map(); + /** @type {ManagedItemInfo} */ + const managedItemInfo = new Map(); + /** @type {ManagedFiles} */ + const managedFiles = new Set(); + /** @type {ManagedContexts} */ + const managedContexts = new Set(); + /** @type {ManagedMissing} */ + const managedMissing = new Set(); + /** @type {Children} */ + const children = new Set(); + + const snapshot = new Snapshot(); + if (startTime) snapshot.setStartTime(startTime); + + /** @type {Set} */ + const managedItems = new Set(); + + /** 1 = timestamp, 2 = hash, 3 = timestamp + hash */ + const mode = options && options.hash ? (options.timestamp ? 3 : 2) : 1; + + let jobs = 1; + const jobDone = () => { + if (--jobs === 0) { + if (fileTimestamps.size !== 0) { + snapshot.setFileTimestamps(fileTimestamps); + } + if (fileHashes.size !== 0) { + snapshot.setFileHashes(fileHashes); + } + if (fileTshs.size !== 0) { + snapshot.setFileTshs(fileTshs); + } + if (contextTimestamps.size !== 0) { + snapshot.setContextTimestamps(contextTimestamps); + } + if (contextHashes.size !== 0) { + snapshot.setContextHashes(contextHashes); + } + if (contextTshs.size !== 0) { + snapshot.setContextTshs(contextTshs); + } + if (missingExistence.size !== 0) { + snapshot.setMissingExistence(missingExistence); + } + if (managedItemInfo.size !== 0) { + snapshot.setManagedItemInfo(managedItemInfo); + } + this._managedFilesOptimization.optimize(snapshot, managedFiles); + if (managedFiles.size !== 0) { + snapshot.setManagedFiles(managedFiles); + } + this._managedContextsOptimization.optimize(snapshot, managedContexts); + if (managedContexts.size !== 0) { + snapshot.setManagedContexts(managedContexts); + } + this._managedMissingOptimization.optimize(snapshot, managedMissing); + if (managedMissing.size !== 0) { + snapshot.setManagedMissing(managedMissing); + } + if (children.size !== 0) { + snapshot.setChildren(children); + } + this._snapshotCache.set(snapshot, true); + this._statCreatedSnapshots++; + + callback(null, snapshot); + } + }; + const jobError = () => { + if (jobs > 0) { + // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) + jobs = -100000000; + callback(null, null); + } + }; + /** + * @param {string} path path + * @param {ManagedFiles} managedSet managed set + * @returns {boolean} true when managed + */ + const checkManaged = (path, managedSet) => { + for (const unmanagedPath of this.unmanagedPathsRegExps) { + if (unmanagedPath.test(path)) return false; + } + for (const unmanagedPath of this.unmanagedPathsWithSlash) { + if (path.startsWith(unmanagedPath)) return false; + } + for (const immutablePath of this.immutablePathsRegExps) { + if (immutablePath.test(path)) { + managedSet.add(path); + return true; + } + } + for (const immutablePath of this.immutablePathsWithSlash) { + if (path.startsWith(immutablePath)) { + managedSet.add(path); + return true; + } + } + for (const managedPath of this.managedPathsRegExps) { + const match = managedPath.exec(path); + if (match) { + const managedItem = getManagedItem(match[1], path); + if (managedItem) { + managedItems.add(managedItem); + managedSet.add(path); + return true; + } + } + } + for (const managedPath of this.managedPathsWithSlash) { + if (path.startsWith(managedPath)) { + const managedItem = getManagedItem(managedPath, path); + if (managedItem) { + managedItems.add(managedItem); + managedSet.add(path); + return true; + } + } + } + return false; + }; + /** + * @param {Iterable} items items + * @param {Set} managedSet managed set + * @returns {Set} result + */ + const captureNonManaged = (items, managedSet) => { + /** @type {Set} */ + const capturedItems = new Set(); + for (const path of items) { + if (!checkManaged(path, managedSet)) capturedItems.add(path); + } + return capturedItems; + }; + /** + * @param {ManagedFiles} capturedFiles captured files + */ + const processCapturedFiles = (capturedFiles) => { + switch (mode) { + case 3: + this._fileTshsOptimization.optimize(snapshot, capturedFiles); + for (const path of capturedFiles) { + const cache = this._fileTshs.get(path); + if (cache !== undefined) { + fileTshs.set(path, cache); + } else { + jobs++; + this._getFileTimestampAndHash(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting file timestamp hash combination of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + fileTshs.set(path, /** @type {TimestampAndHash} */ (entry)); + jobDone(); + } + }); + } + } + break; + case 2: + this._fileHashesOptimization.optimize(snapshot, capturedFiles); + for (const path of capturedFiles) { + const cache = this._fileHashes.get(path); + if (cache !== undefined) { + fileHashes.set(path, cache); + } else { + jobs++; + this.fileHashQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting file hash of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + fileHashes.set(path, /** @type {string} */ (entry)); + jobDone(); + } + }); + } + } + break; + case 1: + this._fileTimestampsOptimization.optimize(snapshot, capturedFiles); + for (const path of capturedFiles) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore") { + fileTimestamps.set(path, cache); + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting file timestamp of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + fileTimestamps.set( + path, + /** @type {FileSystemInfoEntry} */ + (entry) + ); + jobDone(); + } + }); + } + } + break; + } + }; + if (files) { + processCapturedFiles(captureNonManaged(files, managedFiles)); + } + /** + * @param {ManagedContexts} capturedDirectories captured directories + */ + const processCapturedDirectories = (capturedDirectories) => { + switch (mode) { + case 3: + this._contextTshsOptimization.optimize(snapshot, capturedDirectories); + for (const path of capturedDirectories) { + const cache = this._contextTshs.get(path); + /** @type {ResolvedContextTimestampAndHash | null | undefined} */ + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + contextTshs.set(path, resolved); + } else { + jobs++; + /** + * @param {(WebpackError | null)=} err error + * @param {(ResolvedContextTimestampAndHash | null)=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting context timestamp hash combination of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + contextTshs.set( + path, + /** @type {ResolvedContextTimestampAndHash | null} */ + (entry) + ); + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextTsh(cache, callback); + } else { + this.getContextTsh(path, callback); + } + } + } + break; + case 2: + this._contextHashesOptimization.optimize( + snapshot, + capturedDirectories + ); + for (const path of capturedDirectories) { + const cache = this._contextHashes.get(path); + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedHash(cache)) !== undefined + ) { + contextHashes.set(path, resolved); + } else { + jobs++; + /** + * @param {(WebpackError | null)=} err err + * @param {string=} entry entry + */ + const callback = (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting context hash of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + contextHashes.set(path, /** @type {string} */ (entry)); + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextHash(cache, callback); + } else { + this.getContextHash(path, callback); + } + } + } + break; + case 1: + this._contextTimestampsOptimization.optimize( + snapshot, + capturedDirectories + ); + for (const path of capturedDirectories) { + const cache = this._contextTimestamps.get(path); + if (cache === "ignore") continue; + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + contextTimestamps.set(path, resolved); + } else { + jobs++; + /** + * @param {(Error | null)=} err error + * @param {FileTimestamp=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting context timestamp of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + contextTimestamps.set( + path, + /** @type {FileSystemInfoEntry | null} */ + (entry) + ); + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextTimestamp( + /** @type {ContextFileSystemInfoEntry} */ + (cache), + callback + ); + } else { + this.getContextTimestamp(path, callback); + } + } + } + break; + } + }; + if (directories) { + processCapturedDirectories( + captureNonManaged(directories, managedContexts) + ); + } + /** + * @param {ManagedMissing} capturedMissing captured missing + */ + const processCapturedMissing = (capturedMissing) => { + this._missingExistenceOptimization.optimize(snapshot, capturedMissing); + for (const path of capturedMissing) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore") { + missingExistence.set(path, Boolean(cache)); + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting missing timestamp of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + missingExistence.set(path, Boolean(entry)); + jobDone(); + } + }); + } + } + }; + if (missing) { + processCapturedMissing(captureNonManaged(missing, managedMissing)); + } + this._managedItemInfoOptimization.optimize(snapshot, managedItems); + for (const path of managedItems) { + const cache = this._managedItems.get(path); + if (cache !== undefined) { + if (!cache.startsWith("*")) { + managedFiles.add(join(this.fs, path, "package.json")); + } else if (cache === "*nested") { + managedMissing.add(join(this.fs, path, "package.json")); + } + managedItemInfo.set(path, cache); + } else { + jobs++; + this.managedItemQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting managed item ${path}: ${err.stack}` + ); + } + jobError(); + } else if (entry) { + if (!entry.startsWith("*")) { + managedFiles.add(join(this.fs, path, "package.json")); + } else if (cache === "*nested") { + managedMissing.add(join(this.fs, path, "package.json")); + } + managedItemInfo.set(path, entry); + jobDone(); + } else { + // Fallback to normal snapshotting + /** + * @param {Set} set set + * @param {(set: Set) => void} fn fn + */ + const process = (set, fn) => { + if (set.size === 0) return; + const captured = new Set(); + for (const file of set) { + if (file.startsWith(path)) captured.add(file); + } + if (captured.size > 0) fn(captured); + }; + process(managedFiles, processCapturedFiles); + process(managedContexts, processCapturedDirectories); + process(managedMissing, processCapturedMissing); + jobDone(); + } + }); + } + } + jobDone(); + } + + /** + * @param {Snapshot} snapshot1 a snapshot + * @param {Snapshot} snapshot2 a snapshot + * @returns {Snapshot} merged snapshot + */ + mergeSnapshots(snapshot1, snapshot2) { + const snapshot = new Snapshot(); + if (snapshot1.hasStartTime() && snapshot2.hasStartTime()) { + snapshot.setStartTime( + Math.min( + /** @type {NonNullable} */ + (snapshot1.startTime), + /** @type {NonNullable} */ + (snapshot2.startTime) + ) + ); + } else if (snapshot2.hasStartTime()) { + snapshot.startTime = snapshot2.startTime; + } else if (snapshot1.hasStartTime()) { + snapshot.startTime = snapshot1.startTime; + } + if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) { + snapshot.setFileTimestamps( + mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps) + ); + } + if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) { + snapshot.setFileHashes( + mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes) + ); + } + if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) { + snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs)); + } + if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) { + snapshot.setContextTimestamps( + mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps) + ); + } + if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) { + snapshot.setContextHashes( + mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes) + ); + } + if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) { + snapshot.setContextTshs( + mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs) + ); + } + if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) { + snapshot.setMissingExistence( + mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence) + ); + } + if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) { + snapshot.setManagedItemInfo( + mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo) + ); + } + if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) { + snapshot.setManagedFiles( + mergeSets(snapshot1.managedFiles, snapshot2.managedFiles) + ); + } + if (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) { + snapshot.setManagedContexts( + mergeSets(snapshot1.managedContexts, snapshot2.managedContexts) + ); + } + if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) { + snapshot.setManagedMissing( + mergeSets(snapshot1.managedMissing, snapshot2.managedMissing) + ); + } + if (snapshot1.hasChildren() || snapshot2.hasChildren()) { + snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children)); + } + if ( + this._snapshotCache.get(snapshot1) === true && + this._snapshotCache.get(snapshot2) === true + ) { + this._snapshotCache.set(snapshot, true); + } + return snapshot; + } + + /** + * @param {Snapshot} snapshot the snapshot made + * @param {CheckSnapshotValidCallback} callback callback function + * @returns {void} + */ + checkSnapshotValid(snapshot, callback) { + const cachedResult = this._snapshotCache.get(snapshot); + if (cachedResult !== undefined) { + this._statTestedSnapshotsCached++; + if (typeof cachedResult === "boolean") { + callback(null, cachedResult); + } else { + cachedResult.push(callback); + } + return; + } + this._statTestedSnapshotsNotCached++; + this._checkSnapshotValidNoCache(snapshot, callback); + } + + /** + * @private + * @param {Snapshot} snapshot the snapshot made + * @param {CheckSnapshotValidCallback} callback callback function + * @returns {void} + */ + _checkSnapshotValidNoCache(snapshot, callback) { + /** @type {number | undefined} */ + let startTime; + if (snapshot.hasStartTime()) { + startTime = snapshot.startTime; + } + let jobs = 1; + const jobDone = () => { + if (--jobs === 0) { + this._snapshotCache.set(snapshot, true); + callback(null, true); + } + }; + const invalid = () => { + if (jobs > 0) { + // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) + jobs = -100000000; + this._snapshotCache.set(snapshot, false); + callback(null, false); + } + }; + /** + * @param {string} path path + * @param {WebpackError} err err + */ + const invalidWithError = (path, err) => { + if (this._remainingLogs > 0) { + this._log(path, "error occurred: %s", err); + } + invalid(); + }; + /** + * @param {string} path file path + * @param {string | null} current current hash + * @param {string | null} snap snapshot hash + * @returns {boolean} true, if ok + */ + const checkHash = (path, current, snap) => { + if (current !== snap) { + // If hash differ it's invalid + if (this._remainingLogs > 0) { + this._log(path, "hashes differ (%s != %s)", current, snap); + } + return false; + } + return true; + }; + /** + * @param {string} path file path + * @param {boolean} current current entry + * @param {boolean} snap entry from snapshot + * @returns {boolean} true, if ok + */ + const checkExistence = (path, current, snap) => { + if (!current !== !snap) { + // If existence of item differs + // it's invalid + if (this._remainingLogs > 0) { + this._log( + path, + current ? "it didn't exist before" : "it does no longer exist" + ); + } + return false; + } + return true; + }; + /** + * @param {string} path file path + * @param {FileSystemInfoEntry | null} c current entry + * @param {FileSystemInfoEntry | null} s entry from snapshot + * @param {boolean} log log reason + * @returns {boolean} true, if ok + */ + const checkFile = (path, c, s, log = true) => { + if (c === s) return true; + if (!checkExistence(path, Boolean(c), Boolean(s))) return false; + if (c) { + // For existing items only + if (typeof startTime === "number" && c.safeTime > startTime) { + // If a change happened after starting reading the item + // this may no longer be valid + if (log && this._remainingLogs > 0) { + this._log( + path, + "it may have changed (%d) after the start time of the snapshot (%d)", + c.safeTime, + startTime + ); + } + return false; + } + const snap = /** @type {FileSystemInfoEntry} */ (s); + if (snap.timestamp !== undefined && c.timestamp !== snap.timestamp) { + // If we have a timestamp (it was a file or symlink) and it differs from current timestamp + // it's invalid + if (log && this._remainingLogs > 0) { + this._log( + path, + "timestamps differ (%d != %d)", + c.timestamp, + snap.timestamp + ); + } + return false; + } + } + return true; + }; + /** + * @param {string} path file path + * @param {ResolvedContextFileSystemInfoEntry | null} c current entry + * @param {ResolvedContextFileSystemInfoEntry | null} s entry from snapshot + * @param {boolean} log log reason + * @returns {boolean} true, if ok + */ + const checkContext = (path, c, s, log = true) => { + if (c === s) return true; + if (!checkExistence(path, Boolean(c), Boolean(s))) return false; + if (c) { + // For existing items only + if (typeof startTime === "number" && c.safeTime > startTime) { + // If a change happened after starting reading the item + // this may no longer be valid + if (log && this._remainingLogs > 0) { + this._log( + path, + "it may have changed (%d) after the start time of the snapshot (%d)", + c.safeTime, + startTime + ); + } + return false; + } + const snap = /** @type {ResolvedContextFileSystemInfoEntry} */ (s); + if ( + snap.timestampHash !== undefined && + c.timestampHash !== snap.timestampHash + ) { + // If we have a timestampHash (it was a directory) and it differs from current timestampHash + // it's invalid + if (log && this._remainingLogs > 0) { + this._log( + path, + "timestamps hashes differ (%s != %s)", + c.timestampHash, + snap.timestampHash + ); + } + return false; + } + } + return true; + }; + if (snapshot.hasChildren()) { + /** + * @param {(WebpackError | null)=} err err + * @param {boolean=} result result + * @returns {void} + */ + const childCallback = (err, result) => { + if (err || !result) return invalid(); + jobDone(); + }; + for (const child of /** @type {Children} */ (snapshot.children)) { + const cache = this._snapshotCache.get(child); + if (cache !== undefined) { + this._statTestedChildrenCached++; + /* istanbul ignore else */ + if (typeof cache === "boolean") { + if (cache === false) { + invalid(); + return; + } + } else { + jobs++; + cache.push(childCallback); + } + } else { + this._statTestedChildrenNotCached++; + jobs++; + this._checkSnapshotValidNoCache(child, childCallback); + } + } + } + if (snapshot.hasFileTimestamps()) { + const fileTimestamps = + /** @type {FileTimestamps} */ + (snapshot.fileTimestamps); + this._statTestedEntries += fileTimestamps.size; + for (const [path, ts] of fileTimestamps) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore" && !checkFile(path, cache, ts)) { + invalid(); + return; + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if ( + !checkFile( + path, + /** @type {FileSystemInfoEntry | null} */ (entry), + ts + ) + ) { + invalid(); + } else { + jobDone(); + } + }); + } + } + } + /** + * @param {string} path file path + * @param {string | null} hash hash + */ + const processFileHashSnapshot = (path, hash) => { + const cache = this._fileHashes.get(path); + if (cache !== undefined) { + if (cache !== "ignore" && !checkHash(path, cache, hash)) { + invalid(); + } + } else { + jobs++; + this.fileHashQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkHash(path, /** @type {string} */ (entry), hash)) { + invalid(); + } else { + jobDone(); + } + }); + } + }; + if (snapshot.hasFileHashes()) { + const fileHashes = /** @type {FileHashes} */ (snapshot.fileHashes); + this._statTestedEntries += fileHashes.size; + for (const [path, hash] of fileHashes) { + processFileHashSnapshot(path, hash); + } + } + if (snapshot.hasFileTshs()) { + const fileTshs = /** @type {FileTshs} */ (snapshot.fileTshs); + this._statTestedEntries += fileTshs.size; + for (const [path, tsh] of fileTshs) { + if (typeof tsh === "string") { + processFileHashSnapshot(path, tsh); + } else { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache === "ignore" || !checkFile(path, cache, tsh, false)) { + processFileHashSnapshot(path, tsh && tsh.hash); + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if ( + !checkFile( + path, + /** @type {FileSystemInfoEntry | null} */ + (entry), + tsh, + false + ) + ) { + processFileHashSnapshot(path, tsh && tsh.hash); + } + jobDone(); + }); + } + } + } + } + if (snapshot.hasContextTimestamps()) { + const contextTimestamps = + /** @type {ContextTimestamps} */ + (snapshot.contextTimestamps); + this._statTestedEntries += contextTimestamps.size; + for (const [path, ts] of contextTimestamps) { + const cache = this._contextTimestamps.get(path); + if (cache === "ignore") continue; + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + if (!checkContext(path, resolved, ts)) { + invalid(); + return; + } + } else { + jobs++; + /** + * @param {(WebpackError | null)=} err error + * @param {ResolvedContextTimestamp=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) return invalidWithError(path, err); + if ( + !checkContext( + path, + /** @type {ResolvedContextFileSystemInfoEntry | null} */ + (entry), + ts + ) + ) { + invalid(); + } else { + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextTimestamp( + /** @type {ContextFileSystemInfoEntry} */ + (cache), + callback + ); + } else { + this.getContextTimestamp(path, callback); + } + } + } + } + /** + * @param {string} path path + * @param {string | null} hash hash + */ + const processContextHashSnapshot = (path, hash) => { + const cache = this._contextHashes.get(path); + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedHash(cache)) !== undefined + ) { + if (!checkHash(path, resolved, hash)) { + invalid(); + } + } else { + jobs++; + /** + * @param {(WebpackError | null)=} err err + * @param {string=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkHash(path, /** @type {string} */ (entry), hash)) { + invalid(); + } else { + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextHash(cache, callback); + } else { + this.getContextHash(path, callback); + } + } + }; + if (snapshot.hasContextHashes()) { + const contextHashes = + /** @type {ContextHashes} */ + (snapshot.contextHashes); + this._statTestedEntries += contextHashes.size; + for (const [path, hash] of contextHashes) { + processContextHashSnapshot(path, hash); + } + } + if (snapshot.hasContextTshs()) { + const contextTshs = /** @type {ContextTshs} */ (snapshot.contextTshs); + this._statTestedEntries += contextTshs.size; + for (const [path, tsh] of contextTshs) { + if (typeof tsh === "string") { + processContextHashSnapshot(path, tsh); + } else { + const cache = this._contextTimestamps.get(path); + if (cache === "ignore") continue; + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + if ( + !checkContext( + path, + /** @type {ResolvedContextFileSystemInfoEntry | null} */ + (resolved), + tsh, + false + ) + ) { + processContextHashSnapshot(path, tsh && tsh.hash); + } + } else { + jobs++; + /** + * @param {(WebpackError | null)=} err error + * @param {ResolvedContextTimestamp=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) return invalidWithError(path, err); + if ( + !checkContext( + path, + // TODO: test with `"ignore"` + /** @type {ResolvedContextFileSystemInfoEntry | null} */ + (entry), + tsh, + false + ) + ) { + processContextHashSnapshot(path, tsh && tsh.hash); + } + jobDone(); + }; + if (cache !== undefined) { + this._resolveContextTimestamp( + /** @type {ContextFileSystemInfoEntry} */ + (cache), + callback + ); + } else { + this.getContextTimestamp(path, callback); + } + } + } + } + } + if (snapshot.hasMissingExistence()) { + const missingExistence = + /** @type {MissingExistence} */ + (snapshot.missingExistence); + this._statTestedEntries += missingExistence.size; + for (const [path, existence] of missingExistence) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if ( + cache !== "ignore" && + !checkExistence(path, Boolean(cache), Boolean(existence)) + ) { + invalid(); + return; + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkExistence(path, Boolean(entry), Boolean(existence))) { + invalid(); + } else { + jobDone(); + } + }); + } + } + } + if (snapshot.hasManagedItemInfo()) { + const managedItemInfo = + /** @type {ManagedItemInfo} */ + (snapshot.managedItemInfo); + this._statTestedEntries += managedItemInfo.size; + for (const [path, info] of managedItemInfo) { + const cache = this._managedItems.get(path); + if (cache !== undefined) { + if (!checkHash(path, cache, info)) { + invalid(); + return; + } + } else { + jobs++; + this.managedItemQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkHash(path, /** @type {string} */ (entry), info)) { + invalid(); + } else { + jobDone(); + } + }); + } + } + } + jobDone(); + + // if there was an async action + // try to join multiple concurrent request for this snapshot + if (jobs > 0) { + const callbacks = [callback]; + callback = (err, result) => { + for (const callback of callbacks) callback(err, result); + }; + this._snapshotCache.set(snapshot, callbacks); + } + } + + /** + * @private + * @type {Processor} + */ + _readFileTimestamp(path, callback) { + this.fs.stat(path, (err, _stat) => { + if (err) { + if (err.code === "ENOENT") { + this._fileTimestamps.set(path, null); + this._cachedDeprecatedFileTimestamps = undefined; + return callback(null, null); + } + return callback(/** @type {WebpackError} */ (err)); + } + const stat = /** @type {IStats} */ (_stat); + let ts; + if (stat.isDirectory()) { + ts = { + safeTime: 0, + timestamp: undefined + }; + } else { + const mtime = Number(stat.mtime); + + if (mtime) applyMtime(mtime); + + ts = { + safeTime: mtime ? mtime + FS_ACCURACY : Infinity, + timestamp: mtime + }; + } + + this._fileTimestamps.set(path, ts); + this._cachedDeprecatedFileTimestamps = undefined; + + callback(null, ts); + }); + } + + /** + * @private + * @type {Processor} + */ + _readFileHash(path, callback) { + this.fs.readFile(path, (err, content) => { + if (err) { + if (err.code === "EISDIR") { + this._fileHashes.set(path, "directory"); + return callback(null, "directory"); + } + if (err.code === "ENOENT") { + this._fileHashes.set(path, null); + return callback(null, null); + } + if (err.code === "ERR_FS_FILE_TOO_LARGE") { + /** @type {Logger} */ + (this.logger).warn(`Ignoring ${path} for hashing as it's very large`); + this._fileHashes.set(path, "too large"); + return callback(null, "too large"); + } + return callback(/** @type {WebpackError} */ (err)); + } + + const hash = createHash(this._hashFunction); + + hash.update(/** @type {string | Buffer} */ (content)); + + const digest = /** @type {string} */ (hash.digest("hex")); + + this._fileHashes.set(path, digest); + + callback(null, digest); + }); + } + + /** + * @private + * @param {string} path path + * @param {(err: WebpackError | null, timestampAndHash?: TimestampAndHash) => void} callback callback + */ + _getFileTimestampAndHash(path, callback) { + /** + * @param {string} hash hash + * @returns {void} + */ + const continueWithHash = (hash) => { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore") { + /** @type {TimestampAndHash} */ + const result = { + .../** @type {FileSystemInfoEntry} */ (cache), + hash + }; + this._fileTshs.set(path, result); + return callback(null, result); + } + this._fileTshs.set(path, hash); + return callback(null, /** @type {TODO} */ (hash)); + } + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) { + return callback(err); + } + /** @type {TimestampAndHash} */ + const result = { + .../** @type {FileSystemInfoEntry} */ (entry), + hash + }; + this._fileTshs.set(path, result); + return callback(null, result); + }); + }; + + const cache = this._fileHashes.get(path); + if (cache !== undefined) { + continueWithHash(/** @type {string} */ (cache)); + } else { + this.fileHashQueue.add(path, (err, entry) => { + if (err) { + return callback(err); + } + continueWithHash(/** @type {string} */ (entry)); + }); + } + } + + /** + * @private + * @template T + * @template ItemType + * @param {object} options options + * @param {string} options.path path + * @param {(value: string) => ItemType} options.fromImmutablePath called when context item is an immutable path + * @param {(value: string) => ItemType} options.fromManagedItem called when context item is a managed path + * @param {(value: string, result: string, callback: (err?: WebpackError | null, itemType?: ItemType) => void) => void} options.fromSymlink called when context item is a symlink + * @param {(value: string, stats: IStats, callback: (err?: WebpackError | null, itemType?: ItemType | null) => void) => void} options.fromFile called when context item is a file + * @param {(value: string, stats: IStats, callback: (err?: WebpackError | null, itemType?: ItemType) => void) => void} options.fromDirectory called when context item is a directory + * @param {(arr: string[], arr1: ItemType[]) => T} options.reduce called from all context items + * @param {(err?: Error | null, result?: T | null) => void} callback callback + */ + _readContext( + { + path, + fromImmutablePath, + fromManagedItem, + fromSymlink, + fromFile, + fromDirectory, + reduce + }, + callback + ) { + this.fs.readdir(path, (err, _files) => { + if (err) { + if (err.code === "ENOENT") { + return callback(null, null); + } + return callback(err); + } + const files = /** @type {string[]} */ (_files) + .map((file) => file.normalize("NFC")) + .filter((file) => !/^\./.test(file)) + .sort(); + asyncLib.map( + files, + (file, callback) => { + const child = join(this.fs, path, file); + for (const immutablePath of this.immutablePathsRegExps) { + if (immutablePath.test(path)) { + // ignore any immutable path for timestamping + return callback(null, fromImmutablePath(path)); + } + } + for (const immutablePath of this.immutablePathsWithSlash) { + if (path.startsWith(immutablePath)) { + // ignore any immutable path for timestamping + return callback(null, fromImmutablePath(path)); + } + } + for (const managedPath of this.managedPathsRegExps) { + const match = managedPath.exec(path); + if (match) { + const managedItem = getManagedItem(match[1], path); + if (managedItem) { + // construct timestampHash from managed info + return this.managedItemQueue.add(managedItem, (err, info) => { + if (err) return callback(err); + return callback( + null, + fromManagedItem(/** @type {string} */ (info)) + ); + }); + } + } + } + for (const managedPath of this.managedPathsWithSlash) { + if (path.startsWith(managedPath)) { + const managedItem = getManagedItem(managedPath, child); + if (managedItem) { + // construct timestampHash from managed info + return this.managedItemQueue.add(managedItem, (err, info) => { + if (err) return callback(err); + return callback( + null, + fromManagedItem(/** @type {string} */ (info)) + ); + }); + } + } + } + + lstatReadlinkAbsolute(this.fs, child, (err, _stat) => { + if (err) return callback(err); + + const stat = /** @type {IStats | string} */ (_stat); + + if (typeof stat === "string") { + return fromSymlink(child, stat, callback); + } + + if (stat.isFile()) { + return fromFile(child, stat, callback); + } + if (stat.isDirectory()) { + return fromDirectory(child, stat, callback); + } + callback(null, null); + }); + }, + (err, results) => { + if (err) return callback(err); + const result = reduce(files, /** @type {ItemType[]} */ (results)); + callback(null, result); + } + ); + }); + } + + /** + * @private + * @type {Processor} + */ + _readContextTimestamp(path, callback) { + this._readContext( + { + path, + fromImmutablePath: () => + /** @type {ContextFileSystemInfoEntry | FileSystemInfoEntry | "ignore" | null} */ + (null), + fromManagedItem: (info) => ({ + safeTime: 0, + timestampHash: info + }), + fromSymlink: (file, target, callback) => { + callback( + null, + /** @type {ContextFileSystemInfoEntry} */ + ({ + timestampHash: target, + symlinks: new Set([target]) + }) + ); + }, + fromFile: (file, stat, callback) => { + // Prefer the cached value over our new stat to report consistent results + const cache = this._fileTimestamps.get(file); + if (cache !== undefined) { + return callback(null, cache === "ignore" ? null : cache); + } + + const mtime = Number(stat.mtime); + + if (mtime) applyMtime(mtime); + + /** @type {FileSystemInfoEntry} */ + const ts = { + safeTime: mtime ? mtime + FS_ACCURACY : Infinity, + timestamp: mtime + }; + + this._fileTimestamps.set(file, ts); + this._cachedDeprecatedFileTimestamps = undefined; + callback(null, ts); + }, + fromDirectory: (directory, stat, callback) => { + this.contextTimestampQueue.increaseParallelism(); + this._getUnresolvedContextTimestamp(directory, (err, tsEntry) => { + this.contextTimestampQueue.decreaseParallelism(); + callback(err, tsEntry); + }); + }, + reduce: (files, tsEntries) => { + let symlinks; + + const hash = createHash(this._hashFunction); + + for (const file of files) hash.update(file); + let safeTime = 0; + for (const _e of tsEntries) { + if (!_e) { + hash.update("n"); + continue; + } + const entry = + /** @type {FileSystemInfoEntry | ContextFileSystemInfoEntry} */ + (_e); + if (/** @type {FileSystemInfoEntry} */ (entry).timestamp) { + hash.update("f"); + hash.update( + `${/** @type {FileSystemInfoEntry} */ (entry).timestamp}` + ); + } else if ( + /** @type {ContextFileSystemInfoEntry} */ (entry).timestampHash + ) { + hash.update("d"); + hash.update( + `${/** @type {ContextFileSystemInfoEntry} */ (entry).timestampHash}` + ); + } + if ( + /** @type {ContextFileSystemInfoEntry} */ + (entry).symlinks !== undefined + ) { + if (symlinks === undefined) symlinks = new Set(); + addAll( + /** @type {ContextFileSystemInfoEntry} */ (entry).symlinks, + symlinks + ); + } + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + } + + const digest = /** @type {string} */ (hash.digest("hex")); + /** @type {ContextFileSystemInfoEntry} */ + const result = { + safeTime, + timestampHash: digest + }; + if (symlinks) result.symlinks = symlinks; + return result; + } + }, + (err, result) => { + if (err) return callback(/** @type {WebpackError} */ (err)); + this._contextTimestamps.set(path, result); + this._cachedDeprecatedContextTimestamps = undefined; + + callback(null, result); + } + ); + } + + /** + * @private + * @param {ContextFileSystemInfoEntry} entry entry + * @param {(err?: WebpackError | null, resolvedContextTimestamp?: ResolvedContextTimestamp) => void} callback callback + * @returns {void} + */ + _resolveContextTimestamp(entry, callback) { + /** @type {string[]} */ + const hashes = []; + let safeTime = 0; + processAsyncTree( + /** @type {NonNullable} */ (entry.symlinks), + 10, + (target, push, callback) => { + this._getUnresolvedContextTimestamp(target, (err, entry) => { + if (err) return callback(err); + if (entry && entry !== "ignore") { + hashes.push(/** @type {string} */ (entry.timestampHash)); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + if (entry.symlinks !== undefined) { + for (const target of entry.symlinks) push(target); + } + } + callback(); + }); + }, + (err) => { + if (err) return callback(/** @type {WebpackError} */ (err)); + const hash = createHash(this._hashFunction); + hash.update(/** @type {string} */ (entry.timestampHash)); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + hashes.sort(); + for (const h of hashes) { + hash.update(h); + } + callback( + null, + (entry.resolved = { + safeTime, + timestampHash: /** @type {string} */ (hash.digest("hex")) + }) + ); + } + ); + } + + /** + * @private + * @type {Processor} + */ + _readContextHash(path, callback) { + this._readContext( + { + path, + fromImmutablePath: () => /** @type {ContextHash | ""} */ (""), + fromManagedItem: (info) => info || "", + fromSymlink: (file, target, callback) => { + callback( + null, + /** @type {ContextHash} */ + ({ + hash: target, + symlinks: new Set([target]) + }) + ); + }, + fromFile: (file, stat, callback) => + this.getFileHash(file, (err, hash) => { + callback(err, hash || ""); + }), + fromDirectory: (directory, stat, callback) => { + this.contextHashQueue.increaseParallelism(); + this._getUnresolvedContextHash(directory, (err, hash) => { + this.contextHashQueue.decreaseParallelism(); + callback(err, hash || ""); + }); + }, + /** + * @param {string[]} files files + * @param {(string | ContextHash)[]} fileHashes hashes + * @returns {ContextHash} reduced hash + */ + reduce: (files, fileHashes) => { + let symlinks; + const hash = createHash(this._hashFunction); + + for (const file of files) hash.update(file); + for (const entry of fileHashes) { + if (typeof entry === "string") { + hash.update(entry); + } else { + hash.update(entry.hash); + if (entry.symlinks) { + if (symlinks === undefined) symlinks = new Set(); + addAll(entry.symlinks, symlinks); + } + } + } + + /** @type {ContextHash} */ + const result = { + hash: /** @type {string} */ (hash.digest("hex")) + }; + if (symlinks) result.symlinks = symlinks; + return result; + } + }, + (err, _result) => { + if (err) return callback(/** @type {WebpackError} */ (err)); + const result = /** @type {ContextHash} */ (_result); + this._contextHashes.set(path, result); + return callback(null, result); + } + ); + } + + /** + * @private + * @param {ContextHash} entry context hash + * @param {(err: WebpackError | null, contextHash?: string) => void} callback callback + * @returns {void} + */ + _resolveContextHash(entry, callback) { + /** @type {string[]} */ + const hashes = []; + processAsyncTree( + /** @type {NonNullable} */ (entry.symlinks), + 10, + (target, push, callback) => { + this._getUnresolvedContextHash(target, (err, hash) => { + if (err) return callback(err); + if (hash) { + hashes.push(hash.hash); + if (hash.symlinks !== undefined) { + for (const target of hash.symlinks) push(target); + } + } + callback(); + }); + }, + (err) => { + if (err) return callback(/** @type {WebpackError} */ (err)); + const hash = createHash(this._hashFunction); + hash.update(entry.hash); + hashes.sort(); + for (const h of hashes) { + hash.update(h); + } + callback( + null, + (entry.resolved = /** @type {string} */ (hash.digest("hex"))) + ); + } + ); + } + + /** + * @private + * @type {Processor} + */ + _readContextTimestampAndHash(path, callback) { + /** + * @param {ContextTimestamp} timestamp timestamp + * @param {ContextHash} hash hash + */ + const finalize = (timestamp, hash) => { + const result = + /** @type {ContextTimestampAndHash} */ + (timestamp === "ignore" ? hash : { ...timestamp, ...hash }); + this._contextTshs.set(path, result); + callback(null, result); + }; + const cachedHash = this._contextHashes.get(path); + const cachedTimestamp = this._contextTimestamps.get(path); + if (cachedHash !== undefined) { + if (cachedTimestamp !== undefined) { + finalize(cachedTimestamp, cachedHash); + } else { + this.contextTimestampQueue.add(path, (err, entry) => { + if (err) return callback(err); + finalize( + /** @type {ContextFileSystemInfoEntry} */ + (entry), + cachedHash + ); + }); + } + } else if (cachedTimestamp !== undefined) { + this.contextHashQueue.add(path, (err, entry) => { + if (err) return callback(err); + finalize(cachedTimestamp, /** @type {ContextHash} */ (entry)); + }); + } else { + this._readContext( + { + path, + fromImmutablePath: () => + /** @type {ContextTimestampAndHash | null} */ (null), + fromManagedItem: (info) => ({ + safeTime: 0, + timestampHash: info, + hash: info || "" + }), + fromSymlink: (file, target, callback) => { + callback( + null, + /** @type {TODO} */ + ({ + timestampHash: target, + hash: target, + symlinks: new Set([target]) + }) + ); + }, + fromFile: (file, stat, callback) => { + this._getFileTimestampAndHash(file, callback); + }, + fromDirectory: (directory, stat, callback) => { + this.contextTshQueue.increaseParallelism(); + this.contextTshQueue.add(directory, (err, result) => { + this.contextTshQueue.decreaseParallelism(); + callback(err, result); + }); + }, + /** + * @param {string[]} files files + * @param {(Partial & Partial | string | null)[]} results results + * @returns {ContextTimestampAndHash} tsh + */ + reduce: (files, results) => { + let symlinks; + + const tsHash = createHash(this._hashFunction); + const hash = createHash(this._hashFunction); + + for (const file of files) { + tsHash.update(file); + hash.update(file); + } + let safeTime = 0; + for (const entry of results) { + if (!entry) { + tsHash.update("n"); + continue; + } + if (typeof entry === "string") { + tsHash.update("n"); + hash.update(entry); + continue; + } + if (entry.timestamp) { + tsHash.update("f"); + tsHash.update(`${entry.timestamp}`); + } else if (entry.timestampHash) { + tsHash.update("d"); + tsHash.update(`${entry.timestampHash}`); + } + if (entry.symlinks !== undefined) { + if (symlinks === undefined) symlinks = new Set(); + addAll(entry.symlinks, symlinks); + } + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + hash.update(/** @type {string} */ (entry.hash)); + } + + /** @type {ContextTimestampAndHash} */ + const result = { + safeTime, + timestampHash: /** @type {string} */ (tsHash.digest("hex")), + hash: /** @type {string} */ (hash.digest("hex")) + }; + if (symlinks) result.symlinks = symlinks; + return result; + } + }, + (err, _result) => { + if (err) return callback(/** @type {WebpackError} */ (err)); + const result = /** @type {ContextTimestampAndHash} */ (_result); + this._contextTshs.set(path, result); + return callback(null, result); + } + ); + } + } + + /** + * @private + * @param {ContextTimestampAndHash} entry entry + * @param {ProcessorCallback} callback callback + * @returns {void} + */ + _resolveContextTsh(entry, callback) { + /** @type {string[]} */ + const hashes = []; + /** @type {string[]} */ + const tsHashes = []; + let safeTime = 0; + processAsyncTree( + /** @type {NonNullable} */ (entry.symlinks), + 10, + (target, push, callback) => { + this._getUnresolvedContextTsh(target, (err, entry) => { + if (err) return callback(err); + if (entry) { + hashes.push(entry.hash); + if (entry.timestampHash) tsHashes.push(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + if (entry.symlinks !== undefined) { + for (const target of entry.symlinks) push(target); + } + } + callback(); + }); + }, + (err) => { + if (err) return callback(/** @type {WebpackError} */ (err)); + const hash = createHash(this._hashFunction); + const tsHash = createHash(this._hashFunction); + hash.update(entry.hash); + if (entry.timestampHash) tsHash.update(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + hashes.sort(); + for (const h of hashes) { + hash.update(h); + } + tsHashes.sort(); + for (const h of tsHashes) { + tsHash.update(h); + } + callback( + null, + (entry.resolved = { + safeTime, + timestampHash: /** @type {string} */ (tsHash.digest("hex")), + hash: /** @type {string} */ (hash.digest("hex")) + }) + ); + } + ); + } + + /** + * @private + * @type {Processor>} + */ + _getManagedItemDirectoryInfo(path, callback) { + this.fs.readdir(path, (err, elements) => { + if (err) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") { + return callback(null, EMPTY_SET); + } + return callback(/** @type {WebpackError} */ (err)); + } + const set = new Set( + /** @type {string[]} */ (elements).map((element) => + join(this.fs, path, element) + ) + ); + callback(null, set); + }); + } + + /** + * @private + * @type {Processor} + */ + _getManagedItemInfo(path, callback) { + const dir = dirname(this.fs, path); + this.managedItemDirectoryQueue.add(dir, (err, elements) => { + if (err) { + return callback(err); + } + if (!(/** @type {Set} */ (elements).has(path))) { + // file or directory doesn't exist + this._managedItems.set(path, "*missing"); + return callback(null, "*missing"); + } + // something exists + // it may be a file or directory + if ( + path.endsWith("node_modules") && + (path.endsWith("/node_modules") || path.endsWith("\\node_modules")) + ) { + // we are only interested in existence of this special directory + this._managedItems.set(path, "*node_modules"); + return callback(null, "*node_modules"); + } + + // we assume it's a directory, as files shouldn't occur in managed paths + const packageJsonPath = join(this.fs, path, "package.json"); + this.fs.readFile(packageJsonPath, (err, content) => { + if (err) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") { + // no package.json or path is not a directory + this.fs.readdir(path, (err, elements) => { + if ( + !err && + /** @type {string[]} */ (elements).length === 1 && + /** @type {string[]} */ (elements)[0] === "node_modules" + ) { + // This is only a grouping folder e.g. used by yarn + // we are only interested in existence of this special directory + this._managedItems.set(path, "*nested"); + return callback(null, "*nested"); + } + /** @type {Logger} */ + (this.logger).warn( + `Managed item ${path} isn't a directory or doesn't contain a package.json (see snapshot.managedPaths option)` + ); + return callback(); + }); + return; + } + return callback(/** @type {WebpackError} */ (err)); + } + let data; + try { + data = JSON.parse(/** @type {Buffer} */ (content).toString("utf8")); + } catch (parseErr) { + return callback(/** @type {WebpackError} */ (parseErr)); + } + if (!data.name) { + /** @type {Logger} */ + (this.logger).warn( + `${packageJsonPath} doesn't contain a "name" property (see snapshot.managedPaths option)` + ); + return callback(); + } + const info = `${data.name || ""}@${data.version || ""}`; + this._managedItems.set(path, info); + callback(null, info); + }); + }); + } + + getDeprecatedFileTimestamps() { + if (this._cachedDeprecatedFileTimestamps !== undefined) { + return this._cachedDeprecatedFileTimestamps; + } + /** @type {Map} */ + const map = new Map(); + for (const [path, info] of this._fileTimestamps) { + if (info) map.set(path, typeof info === "object" ? info.safeTime : null); + } + return (this._cachedDeprecatedFileTimestamps = map); + } + + getDeprecatedContextTimestamps() { + if (this._cachedDeprecatedContextTimestamps !== undefined) { + return this._cachedDeprecatedContextTimestamps; + } + /** @type {Map} */ + const map = new Map(); + for (const [path, info] of this._contextTimestamps) { + if (info) map.set(path, typeof info === "object" ? info.safeTime : null); + } + return (this._cachedDeprecatedContextTimestamps = map); + } +} + +module.exports = FileSystemInfo; +module.exports.Snapshot = Snapshot; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagAllModulesAsUsedPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagAllModulesAsUsedPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..0f5969cac7afea567b58e27da4df43863dcc6a4a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagAllModulesAsUsedPlugin.js @@ -0,0 +1,55 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module").FactoryMeta} FactoryMeta */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +const PLUGIN_NAME = "FlagAllModulesAsUsedPlugin"; +class FlagAllModulesAsUsedPlugin { + /** + * @param {string} explanation explanation + */ + constructor(explanation) { + this.explanation = explanation; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.optimizeDependencies.tap(PLUGIN_NAME, (modules) => { + /** @type {RuntimeSpec} */ + let runtime; + for (const [name, { options }] of compilation.entries) { + runtime = mergeRuntimeOwned( + runtime, + getEntryRuntime(compilation, name, options) + ); + } + for (const module of modules) { + const exportsInfo = moduleGraph.getExportsInfo(module); + exportsInfo.setUsedInUnknownWay(runtime); + moduleGraph.addExtraReason(module, this.explanation); + if (module.factoryMeta === undefined) { + module.factoryMeta = {}; + } + /** @type {FactoryMeta} */ + (module.factoryMeta).sideEffectFree = false; + } + }); + }); + } +} + +module.exports = FlagAllModulesAsUsedPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagDependencyExportsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagDependencyExportsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b26e3b03fafbbd0dc34ed431ef12b05a964bb0c8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagDependencyExportsPlugin.js @@ -0,0 +1,430 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const asyncLib = require("neo-async"); +const Queue = require("./util/Queue"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").ExportSpec} ExportSpec */ +/** @typedef {import("./Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("./ExportsInfo")} ExportsInfo */ +/** @typedef {import("./ExportsInfo").RestoreProvidedData} RestoreProvidedData */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ + +const PLUGIN_NAME = "FlagDependencyExportsPlugin"; +const PLUGIN_LOGGER_NAME = `webpack.${PLUGIN_NAME}`; + +class FlagDependencyExportsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const moduleGraph = compilation.moduleGraph; + const cache = compilation.getCache(PLUGIN_NAME); + compilation.hooks.finishModules.tapAsync( + PLUGIN_NAME, + (modules, callback) => { + const logger = compilation.getLogger(PLUGIN_LOGGER_NAME); + let statRestoredFromMemCache = 0; + let statRestoredFromCache = 0; + let statNoExports = 0; + let statFlaggedUncached = 0; + let statNotCached = 0; + let statQueueItemsProcessed = 0; + + const { moduleMemCaches } = compilation; + + /** @type {Queue} */ + const queue = new Queue(); + + // Step 1: Try to restore cached provided export info from cache + logger.time("restore cached provided exports"); + asyncLib.each( + modules, + (module, callback) => { + const exportsInfo = moduleGraph.getExportsInfo(module); + // If the module doesn't have an exportsType, it's a module + // without declared exports. + if ( + (!module.buildMeta || !module.buildMeta.exportsType) && + exportsInfo.otherExportsInfo.provided !== null + ) { + // It's a module without declared exports + statNoExports++; + exportsInfo.setHasProvideInfo(); + exportsInfo.setUnknownExportsProvided(); + return callback(); + } + // If the module has no hash, it's uncacheable + if ( + typeof (/** @type {BuildInfo} */ (module.buildInfo).hash) !== + "string" + ) { + statFlaggedUncached++; + // Enqueue uncacheable module for determining the exports + queue.enqueue(module); + exportsInfo.setHasProvideInfo(); + return callback(); + } + const memCache = moduleMemCaches && moduleMemCaches.get(module); + const memCacheValue = memCache && memCache.get(this); + if (memCacheValue !== undefined) { + statRestoredFromMemCache++; + exportsInfo.restoreProvided(memCacheValue); + return callback(); + } + cache.get( + module.identifier(), + /** @type {BuildInfo} */ + (module.buildInfo).hash, + (err, result) => { + if (err) return callback(err); + + if (result !== undefined) { + statRestoredFromCache++; + exportsInfo.restoreProvided(result); + } else { + statNotCached++; + // Without cached info enqueue module for determining the exports + queue.enqueue(module); + exportsInfo.setHasProvideInfo(); + } + callback(); + } + ); + }, + (err) => { + logger.timeEnd("restore cached provided exports"); + if (err) return callback(err); + + /** @type {Set} */ + const modulesToStore = new Set(); + + /** @type {Map>} */ + const dependencies = new Map(); + + /** @type {Module} */ + let module; + + /** @type {ExportsInfo} */ + let exportsInfo; + + /** @type {Map} */ + const exportsSpecsFromDependencies = new Map(); + + let cacheable = true; + let changed = false; + + /** + * @param {DependenciesBlock} depBlock the dependencies block + * @returns {void} + */ + const processDependenciesBlock = (depBlock) => { + for (const dep of depBlock.dependencies) { + processDependency(dep); + } + for (const block of depBlock.blocks) { + processDependenciesBlock(block); + } + }; + + /** + * @param {Dependency} dep the dependency + * @returns {void} + */ + const processDependency = (dep) => { + const exportDesc = dep.getExports(moduleGraph); + if (!exportDesc) return; + exportsSpecsFromDependencies.set(dep, exportDesc); + }; + + /** + * @param {Dependency} dep dependency + * @param {ExportsSpec} exportDesc info + * @returns {void} + */ + const processExportsSpec = (dep, exportDesc) => { + const exports = exportDesc.exports; + const globalCanMangle = exportDesc.canMangle; + const globalFrom = exportDesc.from; + const globalPriority = exportDesc.priority; + const globalTerminalBinding = + exportDesc.terminalBinding || false; + const exportDeps = exportDesc.dependencies; + if (exportDesc.hideExports) { + for (const name of exportDesc.hideExports) { + const exportInfo = exportsInfo.getExportInfo(name); + exportInfo.unsetTarget(dep); + } + } + if (exports === true) { + // unknown exports + if ( + exportsInfo.setUnknownExportsProvided( + globalCanMangle, + exportDesc.excludeExports, + globalFrom && dep, + globalFrom, + globalPriority + ) + ) { + changed = true; + } + } else if (Array.isArray(exports)) { + /** + * merge in new exports + * @param {ExportsInfo} exportsInfo own exports info + * @param {(ExportSpec | string)[]} exports list of exports + */ + const mergeExports = (exportsInfo, exports) => { + for (const exportNameOrSpec of exports) { + let name; + let canMangle = globalCanMangle; + let terminalBinding = globalTerminalBinding; + let exports; + let from = globalFrom; + let fromExport; + let priority = globalPriority; + let hidden = false; + if (typeof exportNameOrSpec === "string") { + name = exportNameOrSpec; + } else { + name = exportNameOrSpec.name; + if (exportNameOrSpec.canMangle !== undefined) { + canMangle = exportNameOrSpec.canMangle; + } + if (exportNameOrSpec.export !== undefined) { + fromExport = exportNameOrSpec.export; + } + if (exportNameOrSpec.exports !== undefined) { + exports = exportNameOrSpec.exports; + } + if (exportNameOrSpec.from !== undefined) { + from = exportNameOrSpec.from; + } + if (exportNameOrSpec.priority !== undefined) { + priority = exportNameOrSpec.priority; + } + if (exportNameOrSpec.terminalBinding !== undefined) { + terminalBinding = exportNameOrSpec.terminalBinding; + } + if (exportNameOrSpec.hidden !== undefined) { + hidden = exportNameOrSpec.hidden; + } + } + const exportInfo = exportsInfo.getExportInfo(name); + + if ( + exportInfo.provided === false || + exportInfo.provided === null + ) { + exportInfo.provided = true; + changed = true; + } + + if ( + exportInfo.canMangleProvide !== false && + canMangle === false + ) { + exportInfo.canMangleProvide = false; + changed = true; + } + + if (terminalBinding && !exportInfo.terminalBinding) { + exportInfo.terminalBinding = true; + changed = true; + } + + if (exports) { + const nestedExportsInfo = + exportInfo.createNestedExportsInfo(); + mergeExports( + /** @type {ExportsInfo} */ (nestedExportsInfo), + exports + ); + } + + if ( + from && + (hidden + ? exportInfo.unsetTarget(dep) + : exportInfo.setTarget( + dep, + from, + fromExport === undefined ? [name] : fromExport, + priority + )) + ) { + changed = true; + } + + // Recalculate target exportsInfo + const target = exportInfo.getTarget(moduleGraph); + let targetExportsInfo; + if (target) { + const targetModuleExportsInfo = + moduleGraph.getExportsInfo(target.module); + targetExportsInfo = + targetModuleExportsInfo.getNestedExportsInfo( + target.export + ); + // add dependency for this module + const set = dependencies.get(target.module); + if (set === undefined) { + dependencies.set(target.module, new Set([module])); + } else { + set.add(module); + } + } + + if (exportInfo.exportsInfoOwned) { + if ( + /** @type {ExportsInfo} */ + (exportInfo.exportsInfo).setRedirectNamedTo( + targetExportsInfo + ) + ) { + changed = true; + } + } else if (exportInfo.exportsInfo !== targetExportsInfo) { + exportInfo.exportsInfo = targetExportsInfo; + changed = true; + } + } + }; + mergeExports(exportsInfo, exports); + } + // store dependencies + if (exportDeps) { + cacheable = false; + for (const exportDependency of exportDeps) { + // add dependency for this module + const set = dependencies.get(exportDependency); + if (set === undefined) { + dependencies.set(exportDependency, new Set([module])); + } else { + set.add(module); + } + } + } + }; + + const notifyDependencies = () => { + const deps = dependencies.get(module); + if (deps !== undefined) { + for (const dep of deps) { + queue.enqueue(dep); + } + } + }; + + logger.time("figure out provided exports"); + while (queue.length > 0) { + module = /** @type {Module} */ (queue.dequeue()); + + statQueueItemsProcessed++; + + exportsInfo = moduleGraph.getExportsInfo(module); + + cacheable = true; + changed = false; + + exportsSpecsFromDependencies.clear(); + moduleGraph.freeze(); + processDependenciesBlock(module); + moduleGraph.unfreeze(); + for (const [dep, exportsSpec] of exportsSpecsFromDependencies) { + processExportsSpec(dep, exportsSpec); + } + + if (cacheable) { + modulesToStore.add(module); + } + + if (changed) { + notifyDependencies(); + } + } + logger.timeEnd("figure out provided exports"); + + logger.log( + `${Math.round( + (100 * (statFlaggedUncached + statNotCached)) / + (statRestoredFromMemCache + + statRestoredFromCache + + statNotCached + + statFlaggedUncached + + statNoExports) + )}% of exports of modules have been determined (${statNoExports} no declared exports, ${statNotCached} not cached, ${statFlaggedUncached} flagged uncacheable, ${statRestoredFromCache} from cache, ${statRestoredFromMemCache} from mem cache, ${ + statQueueItemsProcessed - statNotCached - statFlaggedUncached + } additional calculations due to dependencies)` + ); + + logger.time("store provided exports into cache"); + asyncLib.each( + modulesToStore, + (module, callback) => { + if ( + typeof ( + /** @type {BuildInfo} */ + (module.buildInfo).hash + ) !== "string" + ) { + // not cacheable + return callback(); + } + const cachedData = moduleGraph + .getExportsInfo(module) + .getRestoreProvidedData(); + const memCache = + moduleMemCaches && moduleMemCaches.get(module); + if (memCache) { + memCache.set(this, cachedData); + } + cache.store( + module.identifier(), + /** @type {BuildInfo} */ + (module.buildInfo).hash, + cachedData, + callback + ); + }, + (err) => { + logger.timeEnd("store provided exports into cache"); + callback(err); + } + ); + } + ); + } + ); + + /** @type {WeakMap} */ + const providedExportsCache = new WeakMap(); + compilation.hooks.rebuildModule.tap(PLUGIN_NAME, (module) => { + providedExportsCache.set( + module, + moduleGraph.getExportsInfo(module).getRestoreProvidedData() + ); + }); + compilation.hooks.finishRebuildingModule.tap(PLUGIN_NAME, (module) => { + moduleGraph.getExportsInfo(module).restoreProvided( + /** @type {RestoreProvidedData} */ + (providedExportsCache.get(module)) + ); + }); + }); + } +} + +module.exports = FlagDependencyExportsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagDependencyUsagePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagDependencyUsagePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9f6e761f0057e16e13b9d4c41350a768573251b6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagDependencyUsagePlugin.js @@ -0,0 +1,347 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("./Dependency"); +const { UsageState } = require("./ExportsInfo"); +const ModuleGraphConnection = require("./ModuleGraphConnection"); +const { STAGE_DEFAULT } = require("./OptimizationStages"); +const ArrayQueue = require("./util/ArrayQueue"); +const TupleQueue = require("./util/TupleQueue"); +const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime"); + +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("./ExportsInfo")} ExportsInfo */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +const { NO_EXPORTS_REFERENCED, EXPORTS_OBJECT_REFERENCED } = Dependency; + +const PLUGIN_NAME = "FlagDependencyUsagePlugin"; +const PLUGIN_LOGGER_NAME = `webpack.${PLUGIN_NAME}`; + +class FlagDependencyUsagePlugin { + /** + * @param {boolean} global do a global analysis instead of per runtime + */ + constructor(global) { + this.global = global; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.optimizeDependencies.tap( + { name: PLUGIN_NAME, stage: STAGE_DEFAULT }, + (modules) => { + if (compilation.moduleMemCaches) { + throw new Error( + "optimization.usedExports can't be used with cacheUnaffected as export usage is a global effect" + ); + } + + const logger = compilation.getLogger(PLUGIN_LOGGER_NAME); + /** @type {Map} */ + const exportInfoToModuleMap = new Map(); + + /** @type {TupleQueue} */ + const queue = new TupleQueue(); + + /** + * @param {Module} module module to process + * @param {(string[] | ReferencedExport)[]} usedExports list of used exports + * @param {RuntimeSpec} runtime part of which runtime + * @param {boolean} forceSideEffects always apply side effects + * @returns {void} + */ + const processReferencedModule = ( + module, + usedExports, + runtime, + forceSideEffects + ) => { + const exportsInfo = moduleGraph.getExportsInfo(module); + if (usedExports.length > 0) { + if (!module.buildMeta || !module.buildMeta.exportsType) { + if (exportsInfo.setUsedWithoutInfo(runtime)) { + queue.enqueue(module, runtime); + } + return; + } + for (const usedExportInfo of usedExports) { + let usedExport; + let canMangle = true; + if (Array.isArray(usedExportInfo)) { + usedExport = usedExportInfo; + } else { + usedExport = usedExportInfo.name; + canMangle = usedExportInfo.canMangle !== false; + } + if (usedExport.length === 0) { + if (exportsInfo.setUsedInUnknownWay(runtime)) { + queue.enqueue(module, runtime); + } + } else { + let currentExportsInfo = exportsInfo; + for (let i = 0; i < usedExport.length; i++) { + const exportInfo = currentExportsInfo.getExportInfo( + usedExport[i] + ); + if (canMangle === false) { + exportInfo.canMangleUse = false; + } + const lastOne = i === usedExport.length - 1; + if (!lastOne) { + const nestedInfo = exportInfo.getNestedExportsInfo(); + if (nestedInfo) { + if ( + exportInfo.setUsedConditionally( + (used) => used === UsageState.Unused, + UsageState.OnlyPropertiesUsed, + runtime + ) + ) { + const currentModule = + currentExportsInfo === exportsInfo + ? module + : exportInfoToModuleMap.get(currentExportsInfo); + if (currentModule) { + queue.enqueue(currentModule, runtime); + } + } + currentExportsInfo = nestedInfo; + continue; + } + } + if ( + exportInfo.setUsedConditionally( + (v) => v !== UsageState.Used, + UsageState.Used, + runtime + ) + ) { + const currentModule = + currentExportsInfo === exportsInfo + ? module + : exportInfoToModuleMap.get(currentExportsInfo); + if (currentModule) { + queue.enqueue(currentModule, runtime); + } + } + break; + } + } + } + } else { + // for a module without side effects we stop tracking usage here when no export is used + // This module won't be evaluated in this case + // TODO webpack 6 remove this check + if ( + !forceSideEffects && + module.factoryMeta !== undefined && + module.factoryMeta.sideEffectFree + ) { + return; + } + if (exportsInfo.setUsedForSideEffectsOnly(runtime)) { + queue.enqueue(module, runtime); + } + } + }; + + /** + * @param {DependenciesBlock} module the module + * @param {RuntimeSpec} runtime part of which runtime + * @param {boolean} forceSideEffects always apply side effects + * @returns {void} + */ + const processModule = (module, runtime, forceSideEffects) => { + /** @type {Map>} */ + const map = new Map(); + + /** @type {ArrayQueue} */ + const queue = new ArrayQueue(); + queue.enqueue(module); + for (;;) { + const block = queue.dequeue(); + if (block === undefined) break; + for (const b of block.blocks) { + if ( + !this.global && + b.groupOptions && + b.groupOptions.entryOptions + ) { + processModule( + b, + b.groupOptions.entryOptions.runtime || undefined, + true + ); + } else { + queue.enqueue(b); + } + } + for (const dep of block.dependencies) { + const connection = moduleGraph.getConnection(dep); + if (!connection || !connection.module) { + continue; + } + const activeState = connection.getActiveState(runtime); + if (activeState === false) continue; + const { module } = connection; + if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) { + processModule(module, runtime, false); + continue; + } + const oldReferencedExports = map.get(module); + if (oldReferencedExports === EXPORTS_OBJECT_REFERENCED) { + continue; + } + const referencedExports = + compilation.getDependencyReferencedExports(dep, runtime); + if ( + oldReferencedExports === undefined || + oldReferencedExports === NO_EXPORTS_REFERENCED || + referencedExports === EXPORTS_OBJECT_REFERENCED + ) { + map.set(module, referencedExports); + } else if ( + oldReferencedExports !== undefined && + referencedExports === NO_EXPORTS_REFERENCED + ) { + continue; + } else { + let exportsMap; + if (Array.isArray(oldReferencedExports)) { + exportsMap = new Map(); + for (const item of oldReferencedExports) { + if (Array.isArray(item)) { + exportsMap.set(item.join("\n"), item); + } else { + exportsMap.set(item.name.join("\n"), item); + } + } + map.set(module, exportsMap); + } else { + exportsMap = oldReferencedExports; + } + for (const item of referencedExports) { + if (Array.isArray(item)) { + const key = item.join("\n"); + const oldItem = exportsMap.get(key); + if (oldItem === undefined) { + exportsMap.set(key, item); + } + // if oldItem is already an array we have to do nothing + // if oldItem is an ReferencedExport object, we don't have to do anything + // as canMangle defaults to true for arrays + } else { + const key = item.name.join("\n"); + const oldItem = exportsMap.get(key); + if (oldItem === undefined || Array.isArray(oldItem)) { + exportsMap.set(key, item); + } else { + exportsMap.set(key, { + name: item.name, + canMangle: item.canMangle && oldItem.canMangle + }); + } + } + } + } + } + } + + for (const [module, referencedExports] of map) { + if (Array.isArray(referencedExports)) { + processReferencedModule( + module, + referencedExports, + runtime, + forceSideEffects + ); + } else { + processReferencedModule( + module, + [...referencedExports.values()], + runtime, + forceSideEffects + ); + } + } + }; + + logger.time("initialize exports usage"); + for (const module of modules) { + const exportsInfo = moduleGraph.getExportsInfo(module); + exportInfoToModuleMap.set(exportsInfo, module); + exportsInfo.setHasUseInfo(); + } + logger.timeEnd("initialize exports usage"); + + logger.time("trace exports usage in graph"); + + /** + * @param {Dependency} dep dependency + * @param {RuntimeSpec} runtime runtime + */ + const processEntryDependency = (dep, runtime) => { + const module = moduleGraph.getModule(dep); + if (module) { + processReferencedModule( + module, + NO_EXPORTS_REFERENCED, + runtime, + true + ); + } + }; + /** @type {RuntimeSpec} */ + let globalRuntime; + for (const [ + entryName, + { dependencies: deps, includeDependencies: includeDeps, options } + ] of compilation.entries) { + const runtime = this.global + ? undefined + : getEntryRuntime(compilation, entryName, options); + for (const dep of deps) { + processEntryDependency(dep, runtime); + } + for (const dep of includeDeps) { + processEntryDependency(dep, runtime); + } + globalRuntime = mergeRuntimeOwned(globalRuntime, runtime); + } + for (const dep of compilation.globalEntry.dependencies) { + processEntryDependency(dep, globalRuntime); + } + for (const dep of compilation.globalEntry.includeDependencies) { + processEntryDependency(dep, globalRuntime); + } + + while (queue.length) { + const [module, runtime] = /** @type {[Module, RuntimeSpec]} */ ( + queue.dequeue() + ); + processModule(module, runtime, false); + } + logger.timeEnd("trace exports usage in graph"); + } + ); + }); + } +} + +module.exports = FlagDependencyUsagePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagEntryExportAsUsedPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagEntryExportAsUsedPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..71e770d92aeef9ec546efa14f18cf41399bb17af --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/FlagEntryExportAsUsedPlugin.js @@ -0,0 +1,56 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { getEntryRuntime } = require("./util/runtime"); + +/** @typedef {import("./Compiler")} Compiler */ + +const PLUGIN_NAME = "FlagEntryExportAsUsedPlugin"; + +class FlagEntryExportAsUsedPlugin { + /** + * @param {boolean} nsObjectUsed true, if the ns object is used + * @param {string} explanation explanation for the reason + */ + constructor(nsObjectUsed, explanation) { + this.nsObjectUsed = nsObjectUsed; + this.explanation = explanation; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.seal.tap(PLUGIN_NAME, () => { + for (const [ + entryName, + { dependencies: deps, options } + ] of compilation.entries) { + const runtime = getEntryRuntime(compilation, entryName, options); + for (const dep of deps) { + const module = moduleGraph.getModule(dep); + if (module) { + const exportsInfo = moduleGraph.getExportsInfo(module); + if (this.nsObjectUsed) { + exportsInfo.setUsedInUnknownWay(runtime); + } else { + exportsInfo.setAllKnownExportsUsed(runtime); + } + moduleGraph.addExtraReason(module, this.explanation); + } + } + } + }); + }); + } +} + +module.exports = FlagEntryExportAsUsedPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Generator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Generator.js new file mode 100644 index 0000000000000000000000000000000000000000..10d7cb084684abae32961a7c7c034a28bd69c26d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Generator.js @@ -0,0 +1,196 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ +/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */ +/** @typedef {import("./Module").SourceTypes} SourceTypes */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./NormalModule")} NormalModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @template T + * @typedef {import("./InitFragment")} InitFragment + */ + +/** @typedef {Map<"url", { [key: string]: string }> & Map<"fullContentHash", string> & Map<"contentHash", string> & Map<"filename", string> & Map<"assetInfo", AssetInfo> & Map<"chunkInitFragments", InitFragment[]>} KnownGenerateContextData */ + +/** @typedef {KnownGenerateContextData & Record} GenerateContextData */ + +/** + * @typedef {object} GenerateContext + * @property {DependencyTemplates} dependencyTemplates mapping from dependencies to templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {RuntimeRequirements} runtimeRequirements the requirements for runtime + * @property {RuntimeSpec} runtime the runtime + * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules + * @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) + * @property {string} type which kind of code should be generated + * @property {() => GenerateContextData=} getData get access to the code generation data + */ + +/** + * @callback GenerateErrorFn + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + +/** + * @typedef {object} UpdateHashContext + * @property {NormalModule} module the module + * @property {ChunkGraph} chunkGraph + * @property {RuntimeSpec} runtime + * @property {RuntimeTemplate=} runtimeTemplate + */ + +class Generator { + /** + * @param {Record} map map of types + * @returns {ByTypeGenerator} generator by type + */ + static byType(map) { + return new ByTypeGenerator(map); + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate( + module, + { dependencyTemplates, runtimeTemplate, moduleGraph, type } + ) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /** + * @param {NormalModule} module module for which the bailout reason should be determined + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(module, context) { + return `Module Concatenation is not implemented for ${this.constructor.name}`; + } + + /** + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash + */ + updateHash(hash, { module, runtime }) { + // no nothing + } +} + +/** + * @this {ByTypeGenerator} + * @type {GenerateErrorFn} + */ +function generateError(error, module, generateContext) { + const type = generateContext.type; + const generator = + /** @type {Generator & { generateError?: GenerateErrorFn }} */ + (this.map[type]); + if (!generator) { + throw new Error(`Generator.byType: no generator specified for ${type}`); + } + if (typeof generator.generateError === "undefined") { + return null; + } + return generator.generateError(error, module, generateContext); +} + +class ByTypeGenerator extends Generator { + /** + * @param {Record} map map of types + */ + constructor(map) { + super(); + this.map = map; + this._types = new Set(Object.keys(map)); + /** @type {GenerateErrorFn | undefined} */ + this.generateError = generateError.bind(this); + } + + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + return this._types; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type = "javascript") { + const t = type; + const generator = this.map[t]; + return generator ? generator.getSize(module, t) : 0; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate(module, generateContext) { + const type = generateContext.type; + const generator = this.map[type]; + if (!generator) { + throw new Error(`Generator.byType: no generator specified for ${type}`); + } + return generator.generate(module, generateContext); + } +} + +module.exports = Generator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/GraphHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/GraphHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..f5e32658699dbff5cd578caec5a9f28a4604ddb0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/GraphHelpers.js @@ -0,0 +1,49 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import(".").Entrypoint} Entrypoint */ + +/** + * @param {ChunkGroup} chunkGroup the ChunkGroup to connect + * @param {Chunk} chunk chunk to tie to ChunkGroup + * @returns {void} + */ +const connectChunkGroupAndChunk = (chunkGroup, chunk) => { + if (chunkGroup.pushChunk(chunk)) { + chunk.addGroup(chunkGroup); + } +}; + +/** + * @param {ChunkGroup} parent parent ChunkGroup to connect + * @param {ChunkGroup} child child ChunkGroup to connect + * @returns {void} + */ +const connectChunkGroupParentAndChild = (parent, child) => { + if (parent.addChild(child)) { + child.addParent(parent); + } +}; + +/** + * @param {Entrypoint} entrypoint the entrypoint + * @param {Entrypoint} dependOnEntrypoint the dependOnEntrypoint + * @returns {void} + */ +const connectEntrypointAndDependOn = (entrypoint, dependOnEntrypoint) => { + entrypoint.addDependOn(dependOnEntrypoint); +}; + +module.exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; +module.exports.connectChunkGroupParentAndChild = + connectChunkGroupParentAndChild; +module.exports.connectEntrypointAndDependOn = connectEntrypointAndDependOn; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HarmonyLinkingError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HarmonyLinkingError.js new file mode 100644 index 0000000000000000000000000000000000000000..8259beca634c0728089b2ea96c7ad4a4f1d7bb86 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HarmonyLinkingError.js @@ -0,0 +1,16 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +module.exports = class HarmonyLinkingError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "HarmonyLinkingError"; + this.hideStack = true; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HookWebpackError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HookWebpackError.js new file mode 100644 index 0000000000000000000000000000000000000000..2da30b13c1226ae10a282956284140d4ca575e24 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HookWebpackError.js @@ -0,0 +1,92 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Module")} Module */ + +/** + * @template T + * @callback Callback + * @param {Error | null} err + * @param {T=} stats + * @returns {void} + */ + +class HookWebpackError extends WebpackError { + /** + * Creates an instance of HookWebpackError. + * @param {Error} error inner error + * @param {string} hook name of hook + */ + constructor(error, hook) { + super(error.message); + + this.name = "HookWebpackError"; + this.hook = hook; + this.error = error; + this.hideStack = true; + this.details = `caused by plugins in ${hook}\n${error.stack}`; + + this.stack += `\n-- inner error --\n${error.stack}`; + } +} + +module.exports = HookWebpackError; + +/** + * @param {Error} error an error + * @param {string} hook name of the hook + * @returns {WebpackError} a webpack error + */ +const makeWebpackError = (error, hook) => { + if (error instanceof WebpackError) return error; + return new HookWebpackError(error, hook); +}; + +module.exports.makeWebpackError = makeWebpackError; + +/** + * @template T + * @param {(err: WebpackError | null, result?: T) => void} callback webpack error callback + * @param {string} hook name of hook + * @returns {Callback} generic callback + */ +const makeWebpackErrorCallback = (callback, hook) => (err, result) => { + if (err) { + if (err instanceof WebpackError) { + callback(err); + return; + } + callback(new HookWebpackError(err, hook)); + return; + } + callback(null, result); +}; + +module.exports.makeWebpackErrorCallback = makeWebpackErrorCallback; + +/** + * @template T + * @param {() => T} fn function which will be wrapping in try catch + * @param {string} hook name of hook + * @returns {T} the result + */ +const tryRunOrWebpackError = (fn, hook) => { + let r; + try { + r = fn(); + } catch (err) { + if (err instanceof WebpackError) { + throw err; + } + throw new HookWebpackError(/** @type {Error} */ (err), hook); + } + return r; +}; + +module.exports.tryRunOrWebpackError = tryRunOrWebpackError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HotModuleReplacementPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HotModuleReplacementPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9d8fd2d46bb8c0a5d52f1093aeee1ccca06df96a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HotModuleReplacementPlugin.js @@ -0,0 +1,896 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { SyncBailHook } = require("tapable"); +const { RawSource } = require("webpack-sources"); +const ChunkGraph = require("./ChunkGraph"); +const Compilation = require("./Compilation"); +const HotUpdateChunk = require("./HotUpdateChunk"); +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM, + WEBPACK_MODULE_TYPE_RUNTIME +} = require("./ModuleTypeConstants"); +const NormalModule = require("./NormalModule"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const WebpackError = require("./WebpackError"); +const ConstDependency = require("./dependencies/ConstDependency"); +const ImportMetaHotAcceptDependency = require("./dependencies/ImportMetaHotAcceptDependency"); +const ImportMetaHotDeclineDependency = require("./dependencies/ImportMetaHotDeclineDependency"); +const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency"); +const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency"); +const HotModuleReplacementRuntimeModule = require("./hmr/HotModuleReplacementRuntimeModule"); +const JavascriptParser = require("./javascript/JavascriptParser"); +const { + evaluateToIdentifier +} = require("./javascript/JavascriptParserHelpers"); +const { find, isSubset } = require("./util/SetHelpers"); +const TupleSet = require("./util/TupleSet"); +const { compareModulesById } = require("./util/comparators"); +const { + forEachRuntime, + getRuntimeKey, + intersectRuntime, + keyToRuntime, + mergeRuntimeOwned, + subtractRuntime +} = require("./util/runtime"); + +/** @typedef {import("estree").CallExpression} CallExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").SpreadElement} SpreadElement */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputNormalized */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Chunk").ChunkId} ChunkId */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").Records} Records */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {import("./javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("./javascript/JavascriptParserHelpers").Range} Range */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @typedef {object} HMRJavascriptParserHooks + * @property {SyncBailHook<[Expression | SpreadElement, string[]], void>} hotAcceptCallback + * @property {SyncBailHook<[CallExpression, string[]], void>} hotAcceptWithoutCallback + */ + +/** @typedef {number} HotIndex */ +/** @typedef {Record} FullHashChunkModuleHashes */ +/** @typedef {Record} ChunkModuleHashes */ +/** @typedef {Record} ChunkHashes */ +/** @typedef {Record} ChunkRuntime */ +/** @typedef {Record} ChunkModuleIds */ + +/** @typedef {{ updatedChunkIds: Set, removedChunkIds: Set, removedModules: Set, filename: string, assetInfo: AssetInfo }} HotUpdateMainContentByRuntimeItem */ +/** @typedef {Map} HotUpdateMainContentByRuntime */ + +/** @type {WeakMap} */ +const parserHooksMap = new WeakMap(); + +const PLUGIN_NAME = "HotModuleReplacementPlugin"; + +class HotModuleReplacementPlugin { + /** + * @param {JavascriptParser} parser the parser + * @returns {HMRJavascriptParserHooks} the attached hooks + */ + static getParserHooks(parser) { + if (!(parser instanceof JavascriptParser)) { + throw new TypeError( + "The 'parser' argument must be an instance of JavascriptParser" + ); + } + let hooks = parserHooksMap.get(parser); + if (hooks === undefined) { + hooks = { + hotAcceptCallback: new SyncBailHook(["expression", "requests"]), + hotAcceptWithoutCallback: new SyncBailHook(["expression", "requests"]) + }; + parserHooksMap.set(parser, hooks); + } + return hooks; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _backCompat: backCompat } = compiler; + if (compiler.options.output.strictModuleErrorHandling === undefined) { + compiler.options.output.strictModuleErrorHandling = true; + } + const runtimeRequirements = [RuntimeGlobals.module]; + + /** + * @param {JavascriptParser} parser the parser + * @param {typeof ModuleHotAcceptDependency} ParamDependency dependency + * @returns {(expr: CallExpression) => boolean | undefined} callback + */ + const createAcceptHandler = (parser, ParamDependency) => { + const { hotAcceptCallback, hotAcceptWithoutCallback } = + HotModuleReplacementPlugin.getParserHooks(parser); + + return (expr) => { + const module = parser.state.module; + const dep = new ConstDependency( + `${module.moduleArgument}.hot.accept`, + /** @type {Range} */ (expr.callee.range), + runtimeRequirements + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + module.addPresentationalDependency(dep); + /** @type {BuildInfo} */ + (module.buildInfo).moduleConcatenationBailout = + "Hot Module Replacement"; + + if (expr.arguments.length >= 1) { + const arg = parser.evaluateExpression(expr.arguments[0]); + /** @type {BasicEvaluatedExpression[]} */ + let params = []; + if (arg.isString()) { + params = [arg]; + } else if (arg.isArray()) { + params = + /** @type {BasicEvaluatedExpression[]} */ + (arg.items).filter((param) => param.isString()); + } + /** @type {string[]} */ + const requests = []; + if (params.length > 0) { + for (const [idx, param] of params.entries()) { + const request = /** @type {string} */ (param.string); + const dep = new ParamDependency( + request, + /** @type {Range} */ (param.range) + ); + dep.optional = true; + dep.loc = Object.create( + /** @type {DependencyLocation} */ (expr.loc) + ); + dep.loc.index = idx; + module.addDependency(dep); + requests.push(request); + } + if (expr.arguments.length > 1) { + hotAcceptCallback.call(expr.arguments[1], requests); + for (let i = 1; i < expr.arguments.length; i++) { + parser.walkExpression(expr.arguments[i]); + } + return true; + } + hotAcceptWithoutCallback.call(expr, requests); + return true; + } + } + parser.walkExpressions(expr.arguments); + return true; + }; + }; + + /** + * @param {JavascriptParser} parser the parser + * @param {typeof ModuleHotDeclineDependency} ParamDependency dependency + * @returns {(expr: CallExpression) => boolean | undefined} callback + */ + const createDeclineHandler = (parser, ParamDependency) => (expr) => { + const module = parser.state.module; + const dep = new ConstDependency( + `${module.moduleArgument}.hot.decline`, + /** @type {Range} */ (expr.callee.range), + runtimeRequirements + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + module.addPresentationalDependency(dep); + /** @type {BuildInfo} */ + (module.buildInfo).moduleConcatenationBailout = "Hot Module Replacement"; + if (expr.arguments.length === 1) { + const arg = parser.evaluateExpression(expr.arguments[0]); + /** @type {BasicEvaluatedExpression[]} */ + let params = []; + if (arg.isString()) { + params = [arg]; + } else if (arg.isArray()) { + params = + /** @type {BasicEvaluatedExpression[]} */ + (arg.items).filter((param) => param.isString()); + } + for (const [idx, param] of params.entries()) { + const dep = new ParamDependency( + /** @type {string} */ (param.string), + /** @type {Range} */ (param.range) + ); + dep.optional = true; + dep.loc = Object.create(/** @type {DependencyLocation} */ (expr.loc)); + dep.loc.index = idx; + module.addDependency(dep); + } + } + return true; + }; + + /** + * @param {JavascriptParser} parser the parser + * @returns {(expr: Expression) => boolean | undefined} callback + */ + const createHMRExpressionHandler = (parser) => (expr) => { + const module = parser.state.module; + const dep = new ConstDependency( + `${module.moduleArgument}.hot`, + /** @type {Range} */ (expr.range), + runtimeRequirements + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + module.addPresentationalDependency(dep); + /** @type {BuildInfo} */ + (module.buildInfo).moduleConcatenationBailout = "Hot Module Replacement"; + return true; + }; + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const applyModuleHot = (parser) => { + parser.hooks.evaluateIdentifier.for("module.hot").tap( + { + name: PLUGIN_NAME, + before: "NodeStuffPlugin" + }, + (expr) => + evaluateToIdentifier( + "module.hot", + "module", + () => ["hot"], + true + )(expr) + ); + parser.hooks.call + .for("module.hot.accept") + .tap( + PLUGIN_NAME, + createAcceptHandler(parser, ModuleHotAcceptDependency) + ); + parser.hooks.call + .for("module.hot.decline") + .tap( + PLUGIN_NAME, + createDeclineHandler(parser, ModuleHotDeclineDependency) + ); + parser.hooks.expression + .for("module.hot") + .tap(PLUGIN_NAME, createHMRExpressionHandler(parser)); + }; + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const applyImportMetaHot = (parser) => { + parser.hooks.evaluateIdentifier + .for("import.meta.webpackHot") + .tap(PLUGIN_NAME, (expr) => + evaluateToIdentifier( + "import.meta.webpackHot", + "import.meta", + () => ["webpackHot"], + true + )(expr) + ); + parser.hooks.call + .for("import.meta.webpackHot.accept") + .tap( + PLUGIN_NAME, + createAcceptHandler(parser, ImportMetaHotAcceptDependency) + ); + parser.hooks.call + .for("import.meta.webpackHot.decline") + .tap( + PLUGIN_NAME, + createDeclineHandler(parser, ImportMetaHotDeclineDependency) + ); + parser.hooks.expression + .for("import.meta.webpackHot") + .tap(PLUGIN_NAME, createHMRExpressionHandler(parser)); + }; + + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + // This applies the HMR plugin only to the targeted compiler + // It should not affect child compilations + if (compilation.compiler !== compiler) return; + + // #region module.hot.* API + compilation.dependencyFactories.set( + ModuleHotAcceptDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ModuleHotAcceptDependency, + new ModuleHotAcceptDependency.Template() + ); + compilation.dependencyFactories.set( + ModuleHotDeclineDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ModuleHotDeclineDependency, + new ModuleHotDeclineDependency.Template() + ); + // #endregion + + // #region import.meta.webpackHot.* API + compilation.dependencyFactories.set( + ImportMetaHotAcceptDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportMetaHotAcceptDependency, + new ImportMetaHotAcceptDependency.Template() + ); + compilation.dependencyFactories.set( + ImportMetaHotDeclineDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportMetaHotDeclineDependency, + new ImportMetaHotDeclineDependency.Template() + ); + // #endregion + + /** @type {HotIndex} */ + let hotIndex = 0; + /** @type {FullHashChunkModuleHashes} */ + const fullHashChunkModuleHashes = {}; + /** @type {ChunkModuleHashes} */ + const chunkModuleHashes = {}; + + compilation.hooks.record.tap(PLUGIN_NAME, (compilation, records) => { + if (records.hash === compilation.hash) return; + const chunkGraph = compilation.chunkGraph; + records.hash = compilation.hash; + records.hotIndex = hotIndex; + records.fullHashChunkModuleHashes = fullHashChunkModuleHashes; + records.chunkModuleHashes = chunkModuleHashes; + records.chunkHashes = {}; + records.chunkRuntime = {}; + for (const chunk of compilation.chunks) { + const chunkId = /** @type {ChunkId} */ (chunk.id); + records.chunkHashes[chunkId] = /** @type {string} */ (chunk.hash); + records.chunkRuntime[chunkId] = getRuntimeKey(chunk.runtime); + } + records.chunkModuleIds = {}; + for (const chunk of compilation.chunks) { + const chunkId = /** @type {ChunkId} */ (chunk.id); + + records.chunkModuleIds[chunkId] = Array.from( + chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesById(chunkGraph) + ), + (m) => /** @type {ModuleId} */ (chunkGraph.getModuleId(m)) + ); + } + }); + /** @type {TupleSet} */ + const updatedModules = new TupleSet(); + /** @type {TupleSet} */ + const fullHashModules = new TupleSet(); + /** @type {TupleSet} */ + const nonCodeGeneratedModules = new TupleSet(); + compilation.hooks.fullHash.tap(PLUGIN_NAME, (hash) => { + const chunkGraph = compilation.chunkGraph; + const records = /** @type {Records} */ (compilation.records); + for (const chunk of compilation.chunks) { + /** + * @param {Module} module module + * @returns {string} module hash + */ + const getModuleHash = (module) => { + if ( + compilation.codeGenerationResults.has(module, chunk.runtime) + ) { + return compilation.codeGenerationResults.getHash( + module, + chunk.runtime + ); + } + nonCodeGeneratedModules.add(module, chunk.runtime); + return chunkGraph.getModuleHash(module, chunk.runtime); + }; + const fullHashModulesInThisChunk = + chunkGraph.getChunkFullHashModulesSet(chunk); + if (fullHashModulesInThisChunk !== undefined) { + for (const module of fullHashModulesInThisChunk) { + fullHashModules.add(module, chunk); + } + } + const modules = chunkGraph.getChunkModulesIterable(chunk); + if (modules !== undefined) { + if (records.chunkModuleHashes) { + if (fullHashModulesInThisChunk !== undefined) { + for (const module of modules) { + const key = `${chunk.id}|${module.identifier()}`; + const hash = getModuleHash(module); + if ( + fullHashModulesInThisChunk.has( + /** @type {RuntimeModule} */ + (module) + ) + ) { + if ( + /** @type {FullHashChunkModuleHashes} */ + (records.fullHashChunkModuleHashes)[key] !== hash + ) { + updatedModules.add(module, chunk); + } + fullHashChunkModuleHashes[key] = hash; + } else { + if (records.chunkModuleHashes[key] !== hash) { + updatedModules.add(module, chunk); + } + chunkModuleHashes[key] = hash; + } + } + } else { + for (const module of modules) { + const key = `${chunk.id}|${module.identifier()}`; + const hash = getModuleHash(module); + if (records.chunkModuleHashes[key] !== hash) { + updatedModules.add(module, chunk); + } + chunkModuleHashes[key] = hash; + } + } + } else if (fullHashModulesInThisChunk !== undefined) { + for (const module of modules) { + const key = `${chunk.id}|${module.identifier()}`; + const hash = getModuleHash(module); + if ( + fullHashModulesInThisChunk.has( + /** @type {RuntimeModule} */ (module) + ) + ) { + fullHashChunkModuleHashes[key] = hash; + } else { + chunkModuleHashes[key] = hash; + } + } + } else { + for (const module of modules) { + const key = `${chunk.id}|${module.identifier()}`; + const hash = getModuleHash(module); + chunkModuleHashes[key] = hash; + } + } + } + } + + hotIndex = records.hotIndex || 0; + if (updatedModules.size > 0) hotIndex++; + + hash.update(`${hotIndex}`); + }); + compilation.hooks.processAssets.tap( + { + name: PLUGIN_NAME, + stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL + }, + () => { + const chunkGraph = compilation.chunkGraph; + const records = /** @type {Records} */ (compilation.records); + if (records.hash === compilation.hash) return; + if ( + !records.chunkModuleHashes || + !records.chunkHashes || + !records.chunkModuleIds + ) { + return; + } + for (const [module, chunk] of fullHashModules) { + const key = `${chunk.id}|${module.identifier()}`; + const hash = nonCodeGeneratedModules.has(module, chunk.runtime) + ? chunkGraph.getModuleHash(module, chunk.runtime) + : compilation.codeGenerationResults.getHash( + module, + chunk.runtime + ); + if (records.chunkModuleHashes[key] !== hash) { + updatedModules.add(module, chunk); + } + chunkModuleHashes[key] = hash; + } + + /** @type {HotUpdateMainContentByRuntime} */ + const hotUpdateMainContentByRuntime = new Map(); + let allOldRuntime; + const chunkRuntime = + /** @type {ChunkRuntime} */ + (records.chunkRuntime); + for (const key of Object.keys(chunkRuntime)) { + const runtime = keyToRuntime(chunkRuntime[key]); + allOldRuntime = mergeRuntimeOwned(allOldRuntime, runtime); + } + forEachRuntime(allOldRuntime, (runtime) => { + const { path: filename, info: assetInfo } = + compilation.getPathWithInfo( + /** @type {NonNullable} */ + (compilation.outputOptions.hotUpdateMainFilename), + { + hash: records.hash, + runtime + } + ); + hotUpdateMainContentByRuntime.set( + /** @type {string} */ (runtime), + { + updatedChunkIds: new Set(), + removedChunkIds: new Set(), + removedModules: new Set(), + filename, + assetInfo + } + ); + }); + if (hotUpdateMainContentByRuntime.size === 0) return; + + // Create a list of all active modules to verify which modules are removed completely + /** @type {Map} */ + const allModules = new Map(); + for (const module of compilation.modules) { + const id = + /** @type {ModuleId} */ + (chunkGraph.getModuleId(module)); + allModules.set(id, module); + } + + // List of completely removed modules + /** @type {Set} */ + const completelyRemovedModules = new Set(); + + for (const key of Object.keys(records.chunkHashes)) { + const oldRuntime = keyToRuntime( + /** @type {ChunkRuntime} */ + (records.chunkRuntime)[key] + ); + /** @type {Module[]} */ + const remainingModules = []; + // Check which modules are removed + for (const id of records.chunkModuleIds[key]) { + const module = allModules.get(id); + if (module === undefined) { + completelyRemovedModules.add(id); + } else { + remainingModules.push(module); + } + } + + /** @type {ChunkId | null} */ + let chunkId; + let newModules; + let newRuntimeModules; + let newFullHashModules; + let newDependentHashModules; + let newRuntime; + let removedFromRuntime; + const currentChunk = find( + compilation.chunks, + (chunk) => `${chunk.id}` === key + ); + if (currentChunk) { + chunkId = currentChunk.id; + newRuntime = intersectRuntime( + currentChunk.runtime, + allOldRuntime + ); + if (newRuntime === undefined) continue; + newModules = chunkGraph + .getChunkModules(currentChunk) + .filter((module) => updatedModules.has(module, currentChunk)); + newRuntimeModules = [ + ...chunkGraph.getChunkRuntimeModulesIterable(currentChunk) + ].filter((module) => updatedModules.has(module, currentChunk)); + const fullHashModules = + chunkGraph.getChunkFullHashModulesIterable(currentChunk); + newFullHashModules = + fullHashModules && + [...fullHashModules].filter((module) => + updatedModules.has(module, currentChunk) + ); + const dependentHashModules = + chunkGraph.getChunkDependentHashModulesIterable(currentChunk); + newDependentHashModules = + dependentHashModules && + [...dependentHashModules].filter((module) => + updatedModules.has(module, currentChunk) + ); + removedFromRuntime = subtractRuntime(oldRuntime, newRuntime); + } else { + // chunk has completely removed + chunkId = `${Number(key)}` === key ? Number(key) : key; + removedFromRuntime = oldRuntime; + newRuntime = oldRuntime; + } + if (removedFromRuntime) { + // chunk was removed from some runtimes + forEachRuntime(removedFromRuntime, (runtime) => { + const item = + /** @type {HotUpdateMainContentByRuntimeItem} */ + ( + hotUpdateMainContentByRuntime.get( + /** @type {string} */ (runtime) + ) + ); + item.removedChunkIds.add(/** @type {ChunkId} */ (chunkId)); + }); + // dispose modules from the chunk in these runtimes + // where they are no longer in this runtime + for (const module of remainingModules) { + const moduleKey = `${key}|${module.identifier()}`; + const oldHash = records.chunkModuleHashes[moduleKey]; + const runtimes = chunkGraph.getModuleRuntimes(module); + if (oldRuntime === newRuntime && runtimes.has(newRuntime)) { + // Module is still in the same runtime combination + const hash = nonCodeGeneratedModules.has(module, newRuntime) + ? chunkGraph.getModuleHash(module, newRuntime) + : compilation.codeGenerationResults.getHash( + module, + newRuntime + ); + if (hash !== oldHash) { + if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) { + newRuntimeModules = newRuntimeModules || []; + newRuntimeModules.push( + /** @type {RuntimeModule} */ (module) + ); + } else { + newModules = newModules || []; + newModules.push(module); + } + } + } else { + // module is no longer in this runtime combination + // We (incorrectly) assume that it's not in an overlapping runtime combination + // and dispose it from the main runtimes the chunk was removed from + forEachRuntime(removedFromRuntime, (runtime) => { + // If the module is still used in this runtime, do not dispose it + // This could create a bad runtime state where the module is still loaded, + // but no chunk which contains it. This means we don't receive further HMR updates + // to this module and that's bad. + // TODO force load one of the chunks which contains the module + for (const moduleRuntime of runtimes) { + if (typeof moduleRuntime === "string") { + if (moduleRuntime === runtime) return; + } else if ( + moduleRuntime !== undefined && + moduleRuntime.has(/** @type {string} */ (runtime)) + ) { + return; + } + } + const item = + /** @type {HotUpdateMainContentByRuntimeItem} */ ( + hotUpdateMainContentByRuntime.get( + /** @type {string} */ (runtime) + ) + ); + item.removedModules.add(module); + }); + } + } + } + if ( + (newModules && newModules.length > 0) || + (newRuntimeModules && newRuntimeModules.length > 0) + ) { + const hotUpdateChunk = new HotUpdateChunk(); + if (backCompat) { + ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph); + } + hotUpdateChunk.id = chunkId; + hotUpdateChunk.runtime = currentChunk + ? currentChunk.runtime + : newRuntime; + if (currentChunk) { + for (const group of currentChunk.groupsIterable) { + hotUpdateChunk.addGroup(group); + } + } + chunkGraph.attachModules(hotUpdateChunk, newModules || []); + chunkGraph.attachRuntimeModules( + hotUpdateChunk, + newRuntimeModules || [] + ); + if (newFullHashModules) { + chunkGraph.attachFullHashModules( + hotUpdateChunk, + newFullHashModules + ); + } + if (newDependentHashModules) { + chunkGraph.attachDependentHashModules( + hotUpdateChunk, + newDependentHashModules + ); + } + const renderManifest = compilation.getRenderManifest({ + chunk: hotUpdateChunk, + hash: /** @type {string} */ (records.hash), + fullHash: /** @type {string} */ (records.hash), + outputOptions: compilation.outputOptions, + moduleTemplates: compilation.moduleTemplates, + dependencyTemplates: compilation.dependencyTemplates, + codeGenerationResults: compilation.codeGenerationResults, + runtimeTemplate: compilation.runtimeTemplate, + moduleGraph: compilation.moduleGraph, + chunkGraph + }); + for (const entry of renderManifest) { + /** @type {string} */ + let filename; + /** @type {AssetInfo} */ + let assetInfo; + if ("filename" in entry) { + filename = entry.filename; + assetInfo = entry.info; + } else { + ({ path: filename, info: assetInfo } = + compilation.getPathWithInfo( + entry.filenameTemplate, + entry.pathOptions + )); + } + const source = entry.render(); + compilation.additionalChunkAssets.push(filename); + compilation.emitAsset(filename, source, { + hotModuleReplacement: true, + ...assetInfo + }); + if (currentChunk) { + currentChunk.files.add(filename); + compilation.hooks.chunkAsset.call(currentChunk, filename); + } + } + forEachRuntime(newRuntime, (runtime) => { + const item = + /** @type {HotUpdateMainContentByRuntimeItem} */ ( + hotUpdateMainContentByRuntime.get( + /** @type {string} */ (runtime) + ) + ); + item.updatedChunkIds.add(/** @type {ChunkId} */ (chunkId)); + }); + } + } + const completelyRemovedModulesArray = [...completelyRemovedModules]; + const hotUpdateMainContentByFilename = new Map(); + for (const { + removedChunkIds, + removedModules, + updatedChunkIds, + filename, + assetInfo + } of hotUpdateMainContentByRuntime.values()) { + const old = hotUpdateMainContentByFilename.get(filename); + if ( + old && + (!isSubset(old.removedChunkIds, removedChunkIds) || + !isSubset(old.removedModules, removedModules) || + !isSubset(old.updatedChunkIds, updatedChunkIds)) + ) { + compilation.warnings.push( + new WebpackError(`HotModuleReplacementPlugin +The configured output.hotUpdateMainFilename doesn't lead to unique filenames per runtime and HMR update differs between runtimes. +This might lead to incorrect runtime behavior of the applied update. +To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename option, or use the default config.`) + ); + for (const chunkId of removedChunkIds) { + old.removedChunkIds.add(chunkId); + } + for (const chunkId of removedModules) { + old.removedModules.add(chunkId); + } + for (const chunkId of updatedChunkIds) { + old.updatedChunkIds.add(chunkId); + } + continue; + } + hotUpdateMainContentByFilename.set(filename, { + removedChunkIds, + removedModules, + updatedChunkIds, + assetInfo + }); + } + for (const [ + filename, + { removedChunkIds, removedModules, updatedChunkIds, assetInfo } + ] of hotUpdateMainContentByFilename) { + const hotUpdateMainJson = { + c: [...updatedChunkIds], + r: [...removedChunkIds], + m: + removedModules.size === 0 + ? completelyRemovedModulesArray + : [ + ...completelyRemovedModulesArray, + ...Array.from( + removedModules, + (m) => + /** @type {ModuleId} */ (chunkGraph.getModuleId(m)) + ) + ] + }; + + const source = new RawSource( + (filename.endsWith(".json") ? "" : "export default ") + + JSON.stringify(hotUpdateMainJson) + ); + compilation.emitAsset(filename, source, { + hotModuleReplacement: true, + ...assetInfo + }); + } + } + ); + + compilation.hooks.additionalTreeRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, runtimeRequirements) => { + runtimeRequirements.add(RuntimeGlobals.hmrDownloadManifest); + runtimeRequirements.add(RuntimeGlobals.hmrDownloadUpdateHandlers); + runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution); + runtimeRequirements.add(RuntimeGlobals.moduleCache); + compilation.addRuntimeModule( + chunk, + new HotModuleReplacementRuntimeModule() + ); + } + ); + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, (parser) => { + applyModuleHot(parser); + applyImportMetaHot(parser); + }); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, (parser) => { + applyModuleHot(parser); + }); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, (parser) => { + applyImportMetaHot(parser); + }); + normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module) => { + module.hot = true; + return module; + }); + + NormalModule.getCompilationHooks(compilation).loader.tap( + PLUGIN_NAME, + (context) => { + context.hot = true; + } + ); + } + ); + } +} + +module.exports = HotModuleReplacementPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HotUpdateChunk.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HotUpdateChunk.js new file mode 100644 index 0000000000000000000000000000000000000000..d939838527d58585efc930c31b257bb12f306302 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/HotUpdateChunk.js @@ -0,0 +1,19 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Chunk = require("./Chunk"); + +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./util/Hash")} Hash */ + +class HotUpdateChunk extends Chunk { + constructor() { + super(); + } +} + +module.exports = HotUpdateChunk; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/IgnoreErrorModuleFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/IgnoreErrorModuleFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..423277935c36ba5d563910e30a169ae597b941bd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/IgnoreErrorModuleFactory.js @@ -0,0 +1,39 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const ModuleFactory = require("./ModuleFactory"); + +/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ + +/** + * Ignores error when module is unresolved + */ +class IgnoreErrorModuleFactory extends ModuleFactory { + /** + * @param {NormalModuleFactory} normalModuleFactory normalModuleFactory instance + */ + constructor(normalModuleFactory) { + super(); + + this.normalModuleFactory = normalModuleFactory; + } + + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create(data, callback) { + this.normalModuleFactory.create(data, (err, result) => + callback(null, result) + ); + } +} + +module.exports = IgnoreErrorModuleFactory; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/IgnorePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/IgnorePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..310af5ee2f17dc94a4529c82a96ad551afb29a7f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/IgnorePlugin.js @@ -0,0 +1,102 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RawModule = require("./RawModule"); +const EntryDependency = require("./dependencies/EntryDependency"); +const createSchemaValidation = require("./util/create-schema-validation"); + +/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */ + +const validate = createSchemaValidation( + require("../schemas/plugins/IgnorePlugin.check"), + () => require("../schemas/plugins/IgnorePlugin.json"), + { + name: "Ignore Plugin", + baseDataPath: "options" + } +); + +const PLUGIN_NAME = "IgnorePlugin"; + +class IgnorePlugin { + /** + * @param {IgnorePluginOptions} options IgnorePlugin options + */ + constructor(options) { + validate(options); + this.options = options; + this.checkIgnore = this.checkIgnore.bind(this); + } + + /** + * Note that if "contextRegExp" is given, both the "resourceRegExp" and "contextRegExp" have to match. + * @param {ResolveData} resolveData resolve data + * @returns {false|undefined} returns false when the request should be ignored, otherwise undefined + */ + checkIgnore(resolveData) { + if ( + "checkResource" in this.options && + this.options.checkResource && + this.options.checkResource(resolveData.request, resolveData.context) + ) { + return false; + } + + if ( + "resourceRegExp" in this.options && + this.options.resourceRegExp && + this.options.resourceRegExp.test(resolveData.request) + ) { + if ("contextRegExp" in this.options && this.options.contextRegExp) { + // if "contextRegExp" is given, + // both the "resourceRegExp" and "contextRegExp" have to match. + if (this.options.contextRegExp.test(resolveData.context)) { + return false; + } + } else { + return false; + } + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (nmf) => { + nmf.hooks.beforeResolve.tap(PLUGIN_NAME, (resolveData) => { + const result = this.checkIgnore(resolveData); + + if ( + result === false && + resolveData.dependencies.length > 0 && + resolveData.dependencies[0] instanceof EntryDependency + ) { + const module = new RawModule( + "", + "ignored-entry-module", + "(ignored-entry-module)" + ); + module.factoryMeta = { sideEffectFree: true }; + + resolveData.ignoredModule = module; + } + + return result; + }); + }); + compiler.hooks.contextModuleFactory.tap(PLUGIN_NAME, (cmf) => { + cmf.hooks.beforeResolve.tap(PLUGIN_NAME, this.checkIgnore); + }); + } +} + +module.exports = IgnorePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/IgnoreWarningsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/IgnoreWarningsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..de5fd35e23be981563e8879e04c417826bdcb5dc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/IgnoreWarningsPlugin.js @@ -0,0 +1,38 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../declarations/WebpackOptions").IgnoreWarningsNormalized} IgnoreWarningsNormalized */ +/** @typedef {import("./Compiler")} Compiler */ + +const PLUGIN_NAME = "IgnoreWarningsPlugin"; + +class IgnoreWarningsPlugin { + /** + * @param {IgnoreWarningsNormalized} ignoreWarnings conditions to ignore warnings + */ + constructor(ignoreWarnings) { + this._ignoreWarnings = ignoreWarnings; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.processWarnings.tap(PLUGIN_NAME, (warnings) => + warnings.filter( + (warning) => + !this._ignoreWarnings.some((ignore) => ignore(warning, compilation)) + ) + ); + }); + } +} + +module.exports = IgnoreWarningsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/InitFragment.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/InitFragment.js new file mode 100644 index 0000000000000000000000000000000000000000..e06f8e906b674703d1991312426a3907f015b421 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/InitFragment.js @@ -0,0 +1,191 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Generator").GenerateContext} GenerateContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** + * @template T + * @param {InitFragment} fragment the init fragment + * @param {number} index index + * @returns {[InitFragment, number]} tuple with both + */ +const extractFragmentIndex = (fragment, index) => [fragment, index]; + +/** + * @template T + * @param {[InitFragment, number]} a first pair + * @param {[InitFragment, number]} b second pair + * @returns {number} sort value + */ +const sortFragmentWithIndex = ([a, i], [b, j]) => { + const stageCmp = a.stage - b.stage; + if (stageCmp !== 0) return stageCmp; + const positionCmp = a.position - b.position; + if (positionCmp !== 0) return positionCmp; + return i - j; +}; + +/** + * @template GenerateContext + */ +class InitFragment { + /** + * @param {string | Source | undefined} content the source code that will be included as initialization code + * @param {number} stage category of initialization code (contribute to order) + * @param {number} position position in the category (contribute to order) + * @param {string=} key unique key to avoid emitting the same initialization code twice + * @param {string | Source=} endContent the source code that will be included at the end of the module + */ + constructor(content, stage, position, key, endContent) { + this.content = content; + this.stage = stage; + this.position = position; + this.key = key; + this.endContent = endContent; + } + + /** + * @param {GenerateContext} context context + * @returns {string | Source | undefined} the source code that will be included as initialization code + */ + getContent(context) { + return this.content; + } + + /** + * @param {GenerateContext} context context + * @returns {string | Source=} the source code that will be included at the end of the module + */ + getEndContent(context) { + return this.endContent; + } + + /** + * @template Context + * @template T + * @param {Source} source sources + * @param {InitFragment[]} initFragments init fragments + * @param {Context} context context + * @returns {Source} source + */ + static addToSource(source, initFragments, context) { + if (initFragments.length > 0) { + // Sort fragments by position. If 2 fragments have the same position, + // use their index. + const sortedFragments = initFragments + .map(extractFragmentIndex) + .sort(sortFragmentWithIndex); + + // Deduplicate fragments. If a fragment has no key, it is always included. + const keyedFragments = new Map(); + for (const [fragment] of sortedFragments) { + if ( + typeof ( + /** @type {InitFragment & { mergeAll?: (fragments: InitFragment[]) => InitFragment[] }} */ + (fragment).mergeAll + ) === "function" + ) { + if (!fragment.key) { + throw new Error( + `InitFragment with mergeAll function must have a valid key: ${fragment.constructor.name}` + ); + } + const oldValue = keyedFragments.get(fragment.key); + if (oldValue === undefined) { + keyedFragments.set(fragment.key, fragment); + } else if (Array.isArray(oldValue)) { + oldValue.push(fragment); + } else { + keyedFragments.set(fragment.key, [oldValue, fragment]); + } + continue; + } else if (typeof fragment.merge === "function") { + const oldValue = keyedFragments.get(fragment.key); + if (oldValue !== undefined) { + keyedFragments.set(fragment.key, fragment.merge(oldValue)); + continue; + } + } + keyedFragments.set(fragment.key || Symbol("fragment key"), fragment); + } + + const concatSource = new ConcatSource(); + const endContents = []; + for (let fragment of keyedFragments.values()) { + if (Array.isArray(fragment)) { + fragment = fragment[0].mergeAll(fragment); + } + concatSource.add(fragment.getContent(context)); + const endContent = fragment.getEndContent(context); + if (endContent) { + endContents.push(endContent); + } + } + + concatSource.add(source); + for (const content of endContents.reverse()) { + concatSource.add(content); + } + return concatSource; + } + return source; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.content); + write(this.stage); + write(this.position); + write(this.key); + write(this.endContent); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.content = read(); + this.stage = read(); + this.position = read(); + this.key = read(); + this.endContent = read(); + } +} + +makeSerializable(InitFragment, "webpack/lib/InitFragment"); + +InitFragment.prototype.merge = + /** @type {TODO} */ + (undefined); +InitFragment.prototype.getImported = + /** @type {TODO} */ + (undefined); +InitFragment.prototype.setImported = + /** @type {TODO} */ + (undefined); + +InitFragment.STAGE_CONSTANTS = 10; +InitFragment.STAGE_ASYNC_BOUNDARY = 20; +InitFragment.STAGE_HARMONY_EXPORTS = 30; +InitFragment.STAGE_HARMONY_IMPORTS = 40; +InitFragment.STAGE_PROVIDES = 50; +InitFragment.STAGE_ASYNC_DEPENDENCIES = 60; +InitFragment.STAGE_ASYNC_HARMONY_IMPORTS = 70; + +module.exports = InitFragment; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/InvalidDependenciesModuleWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/InvalidDependenciesModuleWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..7fb7d3c6c4a38ceac167c882f3913bfd9c8bda1e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/InvalidDependenciesModuleWarning.js @@ -0,0 +1,44 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ + +class InvalidDependenciesModuleWarning extends WebpackError { + /** + * @param {Module} module module tied to dependency + * @param {Iterable} deps invalid dependencies + */ + constructor(module, deps) { + const orderedDeps = deps ? [...deps].sort() : []; + const depsList = orderedDeps.map((dep) => ` * ${JSON.stringify(dep)}`); + super(`Invalid dependencies have been reported by plugins or loaders for this module. All reported dependencies need to be absolute paths. +Invalid dependencies may lead to broken watching and caching. +As best effort we try to convert all invalid values to absolute paths and converting globs into context dependencies, but this is deprecated behavior. +Loaders: Pass absolute paths to this.addDependency (existing files), this.addMissingDependency (not existing files), and this.addContextDependency (directories). +Plugins: Pass absolute paths to fileDependencies (existing files), missingDependencies (not existing files), and contextDependencies (directories). +Globs: They are not supported. Pass absolute path to the directory as context dependencies. +The following invalid values have been reported: +${depsList.slice(0, 3).join("\n")}${ + depsList.length > 3 ? "\n * and more ..." : "" + }`); + + this.name = "InvalidDependenciesModuleWarning"; + this.details = depsList.slice(3).join("\n"); + this.module = module; + } +} + +makeSerializable( + InvalidDependenciesModuleWarning, + "webpack/lib/InvalidDependenciesModuleWarning" +); + +module.exports = InvalidDependenciesModuleWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/JavascriptMetaInfoPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/JavascriptMetaInfoPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..606dca5e3e2f635de592c986322f5a796d5fed69 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/JavascriptMetaInfoPlugin.js @@ -0,0 +1,78 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("./ModuleTypeConstants"); +const InnerGraph = require("./optimize/InnerGraph"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + +const PLUGIN_NAME = "JavascriptMetaInfoPlugin"; + +class JavascriptMetaInfoPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const handler = (parser) => { + parser.hooks.call.for("eval").tap(PLUGIN_NAME, () => { + const buildInfo = + /** @type {BuildInfo} */ + (parser.state.module.buildInfo); + buildInfo.moduleConcatenationBailout = "eval()"; + const currentSymbol = InnerGraph.getTopLevelSymbol(parser.state); + if (currentSymbol) { + InnerGraph.addUsage(parser.state, null, currentSymbol); + } else { + InnerGraph.bailout(parser.state); + } + }); + parser.hooks.finish.tap(PLUGIN_NAME, () => { + const buildInfo = + /** @type {BuildInfo} */ + (parser.state.module.buildInfo); + let topLevelDeclarations = buildInfo.topLevelDeclarations; + if (topLevelDeclarations === undefined) { + topLevelDeclarations = buildInfo.topLevelDeclarations = new Set(); + } + for (const name of parser.scope.definitions.asSet()) { + if (parser.isVariableDefined(name)) { + topLevelDeclarations.add(name); + } + } + }); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = JavascriptMetaInfoPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LibManifestPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LibManifestPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..4d6a1e8e1ef37b75db424ba25481afe4d03e687a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LibManifestPlugin.js @@ -0,0 +1,145 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const asyncLib = require("neo-async"); +const EntryDependency = require("./dependencies/EntryDependency"); +const { someInIterable } = require("./util/IterableHelpers"); +const { compareModulesById } = require("./util/comparators"); +const { dirname, mkdirp } = require("./util/fs"); + +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Compiler").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ + +/** + * @typedef {object} ManifestModuleData + * @property {string | number} id + * @property {BuildMeta=} buildMeta + * @property {boolean | string[]=} exports + */ + +/** + * @typedef {object} LibManifestPluginOptions + * @property {string=} context Context of requests in the manifest file (defaults to the webpack context). + * @property {boolean=} entryOnly If true, only entry points will be exposed (default: true). + * @property {boolean=} format If true, manifest json file (output) will be formatted. + * @property {string=} name Name of the exposed dll function (external name, use value of 'output.library'). + * @property {string} path Absolute path to the manifest json file (output). + * @property {string=} type Type of the dll bundle (external type, use value of 'output.libraryTarget'). + */ + +const PLUGIN_NAME = "LibManifestPlugin"; + +class LibManifestPlugin { + /** + * @param {LibManifestPluginOptions} options the options + */ + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.emit.tapAsync( + { name: PLUGIN_NAME, stage: 110 }, + (compilation, callback) => { + const moduleGraph = compilation.moduleGraph; + // store used paths to detect issue and output an error. #18200 + const usedPaths = new Set(); + asyncLib.each( + [...compilation.chunks], + (chunk, callback) => { + if (!chunk.canBeInitial()) { + callback(); + return; + } + const chunkGraph = compilation.chunkGraph; + const targetPath = compilation.getPath(this.options.path, { + chunk + }); + if (usedPaths.has(targetPath)) { + callback(new Error("each chunk must have a unique path")); + return; + } + usedPaths.add(targetPath); + const name = + this.options.name && + compilation.getPath(this.options.name, { + chunk, + contentHashType: "javascript" + }); + const content = Object.create(null); + for (const module of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesById(chunkGraph) + )) { + if ( + this.options.entryOnly && + !someInIterable( + moduleGraph.getIncomingConnections(module), + (c) => c.dependency instanceof EntryDependency + ) + ) { + continue; + } + const ident = module.libIdent({ + context: + this.options.context || + /** @type {string} */ + (compiler.options.context), + associatedObjectForCache: compiler.root + }); + if (ident) { + const exportsInfo = moduleGraph.getExportsInfo(module); + const providedExports = exportsInfo.getProvidedExports(); + /** @type {ManifestModuleData} */ + const data = { + id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)), + buildMeta: /** @type {BuildMeta} */ (module.buildMeta), + exports: Array.isArray(providedExports) + ? providedExports + : undefined + }; + content[ident] = data; + } + } + const manifest = { + name, + type: this.options.type, + content + }; + // Apply formatting to content if format flag is true; + const manifestContent = this.options.format + ? JSON.stringify(manifest, null, 2) + : JSON.stringify(manifest); + const buffer = Buffer.from(manifestContent, "utf8"); + const intermediateFileSystem = + /** @type {IntermediateFileSystem} */ ( + compiler.intermediateFileSystem + ); + mkdirp( + intermediateFileSystem, + dirname(intermediateFileSystem, targetPath), + (err) => { + if (err) return callback(err); + intermediateFileSystem.writeFile(targetPath, buffer, callback); + } + ); + }, + callback + ); + } + ); + } +} + +module.exports = LibManifestPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LibraryTemplatePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LibraryTemplatePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..91cc4ab1440c32d544d1b26c4e8782be00b0d18e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LibraryTemplatePlugin.js @@ -0,0 +1,48 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const EnableLibraryPlugin = require("./library/EnableLibraryPlugin"); + +/** @typedef {import("../declarations/WebpackOptions").AuxiliaryComment} AuxiliaryComment */ +/** @typedef {import("../declarations/WebpackOptions").LibraryExport} LibraryExport */ +/** @typedef {import("../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../declarations/WebpackOptions").UmdNamedDefine} UmdNamedDefine */ +/** @typedef {import("./Compiler")} Compiler */ + +// TODO webpack 6 remove +class LibraryTemplatePlugin { + /** + * @param {LibraryName} name name of library + * @param {LibraryType} target type of library + * @param {UmdNamedDefine} umdNamedDefine setting this to true will name the UMD module + * @param {AuxiliaryComment} auxiliaryComment comment in the UMD wrapper + * @param {LibraryExport} exportProperty which export should be exposed as library + */ + constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { + this.library = { + type: target || "var", + name, + umdNamedDefine, + auxiliaryComment, + export: exportProperty + }; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { output } = compiler.options; + output.library = this.library; + new EnableLibraryPlugin(this.library.type).apply(compiler); + } +} + +module.exports = LibraryTemplatePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LoaderOptionsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LoaderOptionsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..4c803f92e9f6a1ebb60217e6f4d97c4b212c7e8c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LoaderOptionsPlugin.js @@ -0,0 +1,90 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); +const NormalModule = require("./NormalModule"); +const createSchemaValidation = require("./util/create-schema-validation"); + +/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./ModuleFilenameHelpers").Matcher} Matcher */ +/** @typedef {import("./ModuleFilenameHelpers").MatchObject} MatchObject */ + +/** + * @template T + * @typedef {import("../declarations/LoaderContext").LoaderContext} LoaderContext + */ + +const validate = createSchemaValidation( + require("../schemas/plugins/LoaderOptionsPlugin.check"), + () => require("../schemas/plugins/LoaderOptionsPlugin.json"), + { + name: "Loader Options Plugin", + baseDataPath: "options" + } +); + +const PLUGIN_NAME = "LoaderOptionsPlugin"; + +class LoaderOptionsPlugin { + /** + * @param {LoaderOptionsPluginOptions & MatchObject} options options object + */ + constructor(options = {}) { + validate(options); + // If no options are set then generate empty options object + if (typeof options !== "object") options = {}; + if (!options.test) { + /** @type {Partial} */ + const defaultTrueMockRegExp = { + test: () => true + }; + + /** @type {RegExp} */ + options.test = + /** @type {RegExp} */ + (defaultTrueMockRegExp); + } + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + NormalModule.getCompilationHooks(compilation).loader.tap( + PLUGIN_NAME, + (context, module) => { + const resource = module.resource; + if (!resource) return; + const i = resource.indexOf("?"); + if ( + ModuleFilenameHelpers.matchObject( + options, + i < 0 ? resource : resource.slice(0, i) + ) + ) { + for (const key of Object.keys(options)) { + if (key === "include" || key === "exclude" || key === "test") { + continue; + } + + /** @type {LoaderContext & Record} */ + (context)[key] = options[key]; + } + } + } + ); + }); + } +} + +module.exports = LoaderOptionsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LoaderTargetPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LoaderTargetPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..8f3664122c3474fe8299dd5e5d7c8627541cb158 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/LoaderTargetPlugin.js @@ -0,0 +1,39 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const NormalModule = require("./NormalModule"); + +/** @typedef {import("./Compiler")} Compiler */ + +const PLUGIN_NAME = "LoaderTargetPlugin"; + +class LoaderTargetPlugin { + /** + * @param {string} target the target + */ + constructor(target) { + this.target = target; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + NormalModule.getCompilationHooks(compilation).loader.tap( + PLUGIN_NAME, + (loaderContext) => { + loaderContext.target = this.target; + } + ); + }); + } +} + +module.exports = LoaderTargetPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MainTemplate.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MainTemplate.js new file mode 100644 index 0000000000000000000000000000000000000000..a793b1a8319acd748165a1ae550892d39f3d6473 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MainTemplate.js @@ -0,0 +1,382 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const { SyncWaterfallHook } = require("tapable"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const memoize = require("./util/memoize"); + +/** @typedef {import("tapable").Tap} Tap */ +/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").InterpolatedPathAndAssetInfo} InterpolatedPathAndAssetInfo */ +/** @typedef {import("./Module")} Module} */ +/** @typedef {import("./util/Hash")} Hash} */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates} */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext} */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderBootstrapContext} RenderBootstrapContext} */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkHashContext} ChunkHashContext} */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate} */ +/** @typedef {import("./ModuleGraph")} ModuleGraph} */ +/** @typedef {import("./ChunkGraph")} ChunkGraph} */ +/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions} */ +/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry} */ +/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath} */ +/** @typedef {import("./TemplatedPathPlugin").PathData} PathData} */ +/** + * @template T + * @typedef {import("tapable").IfSet} IfSet + */ + +const getJavascriptModulesPlugin = memoize(() => + require("./javascript/JavascriptModulesPlugin") +); +const getJsonpTemplatePlugin = memoize(() => + require("./web/JsonpTemplatePlugin") +); +const getLoadScriptRuntimeModule = memoize(() => + require("./runtime/LoadScriptRuntimeModule") +); + +// TODO webpack 6 remove this class +class MainTemplate { + /** + * @param {OutputOptions} outputOptions output options for the MainTemplate + * @param {Compilation} compilation the compilation + */ + constructor(outputOptions, compilation) { + /** @type {OutputOptions} */ + this._outputOptions = outputOptions || {}; + this.hooks = Object.freeze({ + renderManifest: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(renderManifestEntries: RenderManifestEntry[], renderManifestOptions: RenderManifestOptions) => RenderManifestEntry[]} fn fn + */ + (options, fn) => { + compilation.hooks.renderManifest.tap( + options, + (entries, options) => { + if (!options.chunk.hasRuntime()) return entries; + return fn(entries, options); + } + ); + }, + "MainTemplate.hooks.renderManifest is deprecated (use Compilation.hooks.renderManifest instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_RENDER_MANIFEST" + ) + }, + modules: { + tap: () => { + throw new Error( + "MainTemplate.hooks.modules has been removed (there is no replacement, please create an issue to request that)" + ); + } + }, + moduleObj: { + tap: () => { + throw new Error( + "MainTemplate.hooks.moduleObj has been removed (there is no replacement, please create an issue to request that)" + ); + } + }, + require: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(value: string, renderBootstrapContext: RenderBootstrapContext) => string} fn fn + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .renderRequire.tap(options, fn); + }, + "MainTemplate.hooks.require is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderRequire instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE" + ) + }, + beforeStartup: { + tap: () => { + throw new Error( + "MainTemplate.hooks.beforeStartup has been removed (use RuntimeGlobals.startupOnlyBefore instead)" + ); + } + }, + startup: { + tap: () => { + throw new Error( + "MainTemplate.hooks.startup has been removed (use RuntimeGlobals.startup instead)" + ); + } + }, + afterStartup: { + tap: () => { + throw new Error( + "MainTemplate.hooks.afterStartup has been removed (use RuntimeGlobals.startupOnlyAfter instead)" + ); + } + }, + render: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(source: Source, chunk: Chunk, hash: string | undefined, moduleTemplate: ModuleTemplate, dependencyTemplates: DependencyTemplates) => Source} fn fn + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .render.tap(options, (source, renderContext) => { + if ( + renderContext.chunkGraph.getNumberOfEntryModules( + renderContext.chunk + ) === 0 || + !renderContext.chunk.hasRuntime() + ) { + return source; + } + return fn( + source, + renderContext.chunk, + compilation.hash, + compilation.moduleTemplates.javascript, + compilation.dependencyTemplates + ); + }); + }, + "MainTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_RENDER" + ) + }, + renderWithEntry: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(source: Source, chunk: Chunk, hash: string | undefined) => Source} fn fn + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .render.tap(options, (source, renderContext) => { + if ( + renderContext.chunkGraph.getNumberOfEntryModules( + renderContext.chunk + ) === 0 || + !renderContext.chunk.hasRuntime() + ) { + return source; + } + return fn(source, renderContext.chunk, compilation.hash); + }); + }, + "MainTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_RENDER_WITH_ENTRY" + ) + }, + assetPath: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(value: string, path: PathData, assetInfo: AssetInfo | undefined) => string} fn fn + */ + (options, fn) => { + compilation.hooks.assetPath.tap(options, fn); + }, + "MainTemplate.hooks.assetPath is deprecated (use Compilation.hooks.assetPath instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_ASSET_PATH" + ), + call: util.deprecate( + /** + * @param {TemplatePath} filename used to get asset path with hash + * @param {PathData} options context data + * @returns {string} interpolated path + */ + (filename, options) => compilation.getAssetPath(filename, options), + "MainTemplate.hooks.assetPath is deprecated (use Compilation.hooks.assetPath instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_ASSET_PATH" + ) + }, + hash: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(hash: Hash) => void} fn fn + */ + (options, fn) => { + compilation.hooks.fullHash.tap(options, fn); + }, + "MainTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_HASH" + ) + }, + hashForChunk: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(hash: Hash, chunk: Chunk) => void} fn fn + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .chunkHash.tap(options, (chunk, hash) => { + if (!chunk.hasRuntime()) return; + return fn(hash, chunk); + }); + }, + "MainTemplate.hooks.hashForChunk is deprecated (use JavascriptModulesPlugin.getCompilationHooks().chunkHash instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_HASH_FOR_CHUNK" + ) + }, + globalHashPaths: { + tap: util.deprecate( + () => {}, + "MainTemplate.hooks.globalHashPaths has been removed (it's no longer needed)", + "DEP_WEBPACK_MAIN_TEMPLATE_HASH_FOR_CHUNK" + ) + }, + globalHash: { + tap: util.deprecate( + () => {}, + "MainTemplate.hooks.globalHash has been removed (it's no longer needed)", + "DEP_WEBPACK_MAIN_TEMPLATE_HASH_FOR_CHUNK" + ) + }, + hotBootstrap: { + tap: () => { + throw new Error( + "MainTemplate.hooks.hotBootstrap has been removed (use your own RuntimeModule instead)" + ); + } + }, + + // for compatibility: + /** @type {SyncWaterfallHook<[string, Chunk, string, ModuleTemplate, DependencyTemplates]>} */ + bootstrap: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + /** @type {SyncWaterfallHook<[string, Chunk, string]>} */ + localVars: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook<[string, Chunk, string]>} */ + requireExtensions: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook<[string, Chunk, string, string]>} */ + requireEnsure: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "chunkIdExpression" + ]), + get jsonpScript() { + const hooks = + getLoadScriptRuntimeModule().getCompilationHooks(compilation); + return hooks.createScript; + }, + get linkPrefetch() { + const hooks = getJsonpTemplatePlugin().getCompilationHooks(compilation); + return hooks.linkPrefetch; + }, + get linkPreload() { + const hooks = getJsonpTemplatePlugin().getCompilationHooks(compilation); + return hooks.linkPreload; + } + }); + + this.renderCurrentHashCode = util.deprecate( + /** + * @deprecated + * @param {string} hash the hash + * @param {number=} length length of the hash + * @returns {string} generated code + */ + (hash, length) => { + if (length) { + return `${RuntimeGlobals.getFullHash} ? ${ + RuntimeGlobals.getFullHash + }().slice(0, ${length}) : ${hash.slice(0, length)}`; + } + return `${RuntimeGlobals.getFullHash} ? ${RuntimeGlobals.getFullHash}() : ${hash}`; + }, + "MainTemplate.renderCurrentHashCode is deprecated (use RuntimeGlobals.getFullHash runtime function instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_RENDER_CURRENT_HASH_CODE" + ); + + this.getPublicPath = util.deprecate( + /** + * @param {PathData} options context data + * @returns {string} interpolated path + */ (options) => + compilation.getAssetPath( + /** @type {string} */ + (compilation.outputOptions.publicPath), + options + ), + "MainTemplate.getPublicPath is deprecated (use Compilation.getAssetPath(compilation.outputOptions.publicPath, options) instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_GET_PUBLIC_PATH" + ); + + this.getAssetPath = util.deprecate( + /** + * @param {TemplatePath} path used to get asset path with hash + * @param {PathData} options context data + * @returns {string} interpolated path + */ + (path, options) => compilation.getAssetPath(path, options), + "MainTemplate.getAssetPath is deprecated (use Compilation.getAssetPath instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_GET_ASSET_PATH" + ); + + this.getAssetPathWithInfo = util.deprecate( + /** + * @param {TemplatePath} path used to get asset path with hash + * @param {PathData} options context data + * @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info + */ + (path, options) => compilation.getAssetPathWithInfo(path, options), + "MainTemplate.getAssetPathWithInfo is deprecated (use Compilation.getAssetPath instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_GET_ASSET_PATH_WITH_INFO" + ); + } +} + +Object.defineProperty(MainTemplate.prototype, "requireFn", { + get: util.deprecate( + () => RuntimeGlobals.require, + `MainTemplate.requireFn is deprecated (use "${RuntimeGlobals.require}")`, + "DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE_FN" + ) +}); + +Object.defineProperty(MainTemplate.prototype, "outputOptions", { + get: util.deprecate( + /** + * @this {MainTemplate} + * @returns {OutputOptions} output options + */ + function outputOptions() { + return this._outputOptions; + }, + "MainTemplate.outputOptions is deprecated (use Compilation.outputOptions instead)", + "DEP_WEBPACK_MAIN_TEMPLATE_OUTPUT_OPTIONS" + ) +}); + +module.exports = MainTemplate; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Module.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Module.js new file mode 100644 index 0000000000000000000000000000000000000000..c5504fda639168a61c43ee4e5786d7554f839945 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Module.js @@ -0,0 +1,1252 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const ChunkGraph = require("./ChunkGraph"); +const DependenciesBlock = require("./DependenciesBlock"); +const ModuleGraph = require("./ModuleGraph"); +const { JS_TYPES } = require("./ModuleSourceTypesConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const { first } = require("./util/SetHelpers"); +const { compareChunksById } = require("./util/comparators"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").UnsafeCacheData} UnsafeCacheData */ +/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplate").CssData} CssData */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./ExportsInfo").UsageStateType} UsageStateType */ +/** @typedef {import("./FileSystemInfo")} FileSystemInfo */ +/** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./json/JsonData")} JsonData */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {"namespace" | "default-only" | "default-with-named" | "dynamic"} ExportsType */ + +/** + * @template T + * @typedef {import("./util/LazySet")} LazySet + */ + +/** + * @template T + * @typedef {import("./util/SortableSet")} SortableSet + */ + +/** + * @typedef {object} SourceContext + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {RuntimeSpec} runtime the runtimes code should be generated for + * @property {string=} type the type of source that should be generated + */ + +/** @typedef {ReadonlySet} SourceTypes */ + +// TODO webpack 6: compilation will be required in CodeGenerationContext +/** + * @typedef {object} CodeGenerationContext + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {RuntimeSpec} runtime the runtimes code should be generated for + * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules + * @property {CodeGenerationResults | undefined} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) + * @property {Compilation=} compilation the compilation + * @property {SourceTypes=} sourceTypes source types + */ + +/** + * @typedef {object} ConcatenationBailoutReasonContext + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + */ + +/** @typedef {Set} RuntimeRequirements */ +/** @typedef {ReadonlySet} ReadOnlyRuntimeRequirements */ + +/** + * @typedef {object} CodeGenerationResult + * @property {Map} sources the resulting sources for all source types + * @property {Map=} data the resulting data for all source types + * @property {ReadOnlyRuntimeRequirements | null} runtimeRequirements the runtime requirements + * @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided) + */ + +/** + * @typedef {object} LibIdentOptions + * @property {string} context absolute context path to which lib ident is relative to + * @property {AssociatedObjectForCache=} associatedObjectForCache object for caching + */ + +/** + * @typedef {object} KnownBuildMeta + * @property {("default" | "namespace" | "flagged" | "dynamic")=} exportsType + * @property {(false | "redirect" | "redirect-warn")=} defaultObject + * @property {boolean=} strictHarmonyModule + * @property {boolean=} async + * @property {boolean=} sideEffectFree + * @property {boolean=} isCSSModule + * @property {Record=} jsIncompatibleExports + * @property {Record=} exportsFinalName + * @property {string=} factoryExportsBinding + */ + +/** + * @typedef {object} KnownBuildInfo + * @property {boolean=} cacheable + * @property {boolean=} parsed + * @property {boolean=} strict + * @property {string=} moduleArgument using in AMD + * @property {string=} exportsArgument using in AMD + * @property {string=} moduleConcatenationBailout using in CommonJs + * @property {boolean=} needCreateRequire using in APIPlugin + * @property {string=} resourceIntegrity using in HttpUriPlugin + * @property {LazySet=} fileDependencies using in NormalModule + * @property {LazySet=} contextDependencies using in NormalModule + * @property {LazySet=} missingDependencies using in NormalModule + * @property {LazySet=} buildDependencies using in NormalModule + * @property {ValueCacheVersions=} valueDependencies using in NormalModule + * @property {Record=} assets using in NormalModule + * @property {Map=} assetsInfo using in NormalModule + * @property {string=} hash using in NormalModule + * @property {(Snapshot | null)=} snapshot using in ContextModule + * @property {string=} fullContentHash for assets modules + * @property {string=} filename for assets modules + * @property {boolean=} dataUrl for assets modules + * @property {AssetInfo=} assetInfo for assets modules + * @property {boolean=} javascriptModule for external modules + * @property {boolean=} active for lazy compilation modules + * @property {CssData=} cssData for css modules + * @property {JsonData=} jsonData for json modules + * @property {Set=} topLevelDeclarations top level declaration names + */ + +/** @typedef {Map>} ValueCacheVersions */ + +/** + * @typedef {object} NeedBuildContext + * @property {Compilation} compilation + * @property {FileSystemInfo} fileSystemInfo + * @property {ValueCacheVersions} valueCacheVersions + */ + +/** @typedef {(err?: WebpackError | null, needBuild?: boolean) => void} NeedBuildCallback */ + +/** @typedef {(err?: WebpackError) => void} BuildCallback */ + +/** @typedef {KnownBuildMeta & Record} BuildMeta */ +/** @typedef {KnownBuildInfo & Record} BuildInfo */ + +/** + * @typedef {object} FactoryMeta + * @property {boolean=} sideEffectFree + */ + +const EMPTY_RESOLVE_OPTIONS = {}; + +let debugId = 1000; + +const DEFAULT_TYPES_UNKNOWN = new Set(["unknown"]); + +const deprecatedNeedRebuild = util.deprecate( + /** + * @param {Module} module the module + * @param {NeedBuildContext} context context info + * @returns {boolean} true, when rebuild is needed + */ + (module, context) => + module.needRebuild( + context.fileSystemInfo.getDeprecatedFileTimestamps(), + context.fileSystemInfo.getDeprecatedContextTimestamps() + ), + "Module.needRebuild is deprecated in favor of Module.needBuild", + "DEP_WEBPACK_MODULE_NEED_REBUILD" +); + +/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ + +class Module extends DependenciesBlock { + /** + * @param {ModuleTypes | ""} type the module type, when deserializing the type is not known and is an empty string + * @param {(string | null)=} context an optional context + * @param {(string | null)=} layer an optional layer in which the module is + */ + constructor(type, context = null, layer = null) { + super(); + + /** @type {ModuleTypes} */ + this.type = type; + /** @type {string | null} */ + this.context = context; + /** @type {string | null} */ + this.layer = layer; + /** @type {boolean} */ + this.needId = true; + + // Unique Id + /** @type {number} */ + this.debugId = debugId++; + + // Info from Factory + /** @type {ResolveOptions | undefined} */ + this.resolveOptions = EMPTY_RESOLVE_OPTIONS; + /** @type {FactoryMeta | undefined} */ + this.factoryMeta = undefined; + // TODO refactor this -> options object filled from Factory + // TODO webpack 6: use an enum + /** @type {boolean} */ + this.useSourceMap = false; + /** @type {boolean} */ + this.useSimpleSourceMap = false; + + // Is in hot context, i.e. HotModuleReplacementPlugin.js enabled + // TODO do we need hot here? + /** @type {boolean} */ + this.hot = false; + // Info from Build + /** @type {WebpackError[] | undefined} */ + this._warnings = undefined; + /** @type {WebpackError[] | undefined} */ + this._errors = undefined; + /** @type {BuildMeta | undefined} */ + this.buildMeta = undefined; + /** @type {BuildInfo | undefined} */ + this.buildInfo = undefined; + /** @type {Dependency[] | undefined} */ + this.presentationalDependencies = undefined; + /** @type {Dependency[] | undefined} */ + this.codeGenerationDependencies = undefined; + } + + // TODO remove in webpack 6 + // BACKWARD-COMPAT START + /** + * @returns {ModuleId | null} module id + */ + get id() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.id", + "DEP_WEBPACK_MODULE_ID" + ).getModuleId(this); + } + + /** + * @param {ModuleId} value value + */ + set id(value) { + if (value === "") { + this.needId = false; + return; + } + ChunkGraph.getChunkGraphForModule( + this, + "Module.id", + "DEP_WEBPACK_MODULE_ID" + ).setModuleId(this, value); + } + + /** + * @returns {string} the hash of the module + */ + get hash() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.hash", + "DEP_WEBPACK_MODULE_HASH" + ).getModuleHash(this, undefined); + } + + /** + * @returns {string} the shortened hash of the module + */ + get renderedHash() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.renderedHash", + "DEP_WEBPACK_MODULE_RENDERED_HASH" + ).getRenderedModuleHash(this, undefined); + } + + get profile() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.profile", + "DEP_WEBPACK_MODULE_PROFILE" + ).getProfile(this); + } + + set profile(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.profile", + "DEP_WEBPACK_MODULE_PROFILE" + ).setProfile(this, value); + } + + /** + * @returns {number | null} the pre order index + */ + get index() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.index", + "DEP_WEBPACK_MODULE_INDEX" + ).getPreOrderIndex(this); + } + + /** + * @param {number} value the pre order index + */ + set index(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.index", + "DEP_WEBPACK_MODULE_INDEX" + ).setPreOrderIndex(this, value); + } + + /** + * @returns {number | null} the post order index + */ + get index2() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.index2", + "DEP_WEBPACK_MODULE_INDEX2" + ).getPostOrderIndex(this); + } + + /** + * @param {number} value the post order index + */ + set index2(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.index2", + "DEP_WEBPACK_MODULE_INDEX2" + ).setPostOrderIndex(this, value); + } + + /** + * @returns {number | null} the depth + */ + get depth() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.depth", + "DEP_WEBPACK_MODULE_DEPTH" + ).getDepth(this); + } + + /** + * @param {number} value the depth + */ + set depth(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.depth", + "DEP_WEBPACK_MODULE_DEPTH" + ).setDepth(this, value); + } + + /** + * @returns {Module | null | undefined} issuer + */ + get issuer() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.issuer", + "DEP_WEBPACK_MODULE_ISSUER" + ).getIssuer(this); + } + + /** + * @param {Module | null} value issuer + */ + set issuer(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.issuer", + "DEP_WEBPACK_MODULE_ISSUER" + ).setIssuer(this, value); + } + + get usedExports() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.usedExports", + "DEP_WEBPACK_MODULE_USED_EXPORTS" + ).getUsedExports(this, undefined); + } + + /** + * @deprecated + * @returns {(string | OptimizationBailoutFunction)[]} list + */ + get optimizationBailout() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.optimizationBailout", + "DEP_WEBPACK_MODULE_OPTIMIZATION_BAILOUT" + ).getOptimizationBailout(this); + } + + get optional() { + return this.isOptional( + ModuleGraph.getModuleGraphForModule( + this, + "Module.optional", + "DEP_WEBPACK_MODULE_OPTIONAL" + ) + ); + } + + /** + * @param {Chunk} chunk the chunk + * @returns {boolean} true, when the module was added + */ + addChunk(chunk) { + const chunkGraph = ChunkGraph.getChunkGraphForModule( + this, + "Module.addChunk", + "DEP_WEBPACK_MODULE_ADD_CHUNK" + ); + if (chunkGraph.isModuleInChunk(this, chunk)) return false; + chunkGraph.connectChunkAndModule(chunk, this); + return true; + } + + /** + * @param {Chunk} chunk the chunk + * @returns {void} + */ + removeChunk(chunk) { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.removeChunk", + "DEP_WEBPACK_MODULE_REMOVE_CHUNK" + ).disconnectChunkAndModule(chunk, this); + } + + /** + * @param {Chunk} chunk the chunk + * @returns {boolean} true, when the module is in the chunk + */ + isInChunk(chunk) { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.isInChunk", + "DEP_WEBPACK_MODULE_IS_IN_CHUNK" + ).isModuleInChunk(this, chunk); + } + + isEntryModule() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.isEntryModule", + "DEP_WEBPACK_MODULE_IS_ENTRY_MODULE" + ).isEntryModule(this); + } + + getChunks() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.getChunks", + "DEP_WEBPACK_MODULE_GET_CHUNKS" + ).getModuleChunks(this); + } + + getNumberOfChunks() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.getNumberOfChunks", + "DEP_WEBPACK_MODULE_GET_NUMBER_OF_CHUNKS" + ).getNumberOfModuleChunks(this); + } + + get chunksIterable() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.chunksIterable", + "DEP_WEBPACK_MODULE_CHUNKS_ITERABLE" + ).getOrderedModuleChunksIterable(this, compareChunksById); + } + + /** + * @param {string} exportName a name of an export + * @returns {boolean | null} true, if the export is provided why the module. + * null, if it's unknown. + * false, if it's not provided. + */ + isProvided(exportName) { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.usedExports", + "DEP_WEBPACK_MODULE_USED_EXPORTS" + ).isExportProvided(this, exportName); + } + // BACKWARD-COMPAT END + + /** + * @returns {string} name of the exports argument + */ + get exportsArgument() { + return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; + } + + /** + * @returns {string} name of the module argument + */ + get moduleArgument() { + return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {boolean | undefined} strict the importing module is strict + * @returns {ExportsType} export type + * "namespace": Exports is already a namespace object. namespace = exports. + * "dynamic": Check at runtime if __esModule is set. When set: namespace = { ...exports, default: exports }. When not set: namespace = { default: exports }. + * "default-only": Provide a namespace object with only default export. namespace = { default: exports } + * "default-with-named": Provide a namespace object with named and default export. namespace = { ...exports, default: exports } + */ + getExportsType(moduleGraph, strict) { + switch (this.buildMeta && this.buildMeta.exportsType) { + case "flagged": + return strict ? "default-with-named" : "namespace"; + case "namespace": + return "namespace"; + case "default": + switch (/** @type {BuildMeta} */ (this.buildMeta).defaultObject) { + case "redirect": + return "default-with-named"; + case "redirect-warn": + return strict ? "default-only" : "default-with-named"; + default: + return "default-only"; + } + case "dynamic": { + if (strict) return "default-with-named"; + // Try to figure out value of __esModule by following reexports + const handleDefault = () => { + switch (/** @type {BuildMeta} */ (this.buildMeta).defaultObject) { + case "redirect": + case "redirect-warn": + return "default-with-named"; + default: + return "default-only"; + } + }; + const exportInfo = moduleGraph.getReadOnlyExportInfo( + this, + "__esModule" + ); + if (exportInfo.provided === false) { + return handleDefault(); + } + const target = exportInfo.getTarget(moduleGraph); + if ( + !target || + !target.export || + target.export.length !== 1 || + target.export[0] !== "__esModule" + ) { + return "dynamic"; + } + switch ( + target.module.buildMeta && + target.module.buildMeta.exportsType + ) { + case "flagged": + case "namespace": + return "namespace"; + case "default": + return handleDefault(); + default: + return "dynamic"; + } + } + default: + return strict ? "default-with-named" : "dynamic"; + } + } + + /** + * @param {Dependency} presentationalDependency dependency being tied to module. + * This is a Dependency without edge in the module graph. It's only for presentation. + * @returns {void} + */ + addPresentationalDependency(presentationalDependency) { + if (this.presentationalDependencies === undefined) { + this.presentationalDependencies = []; + } + this.presentationalDependencies.push(presentationalDependency); + } + + /** + * @param {Dependency} codeGenerationDependency dependency being tied to module. + * This is a Dependency where the code generation result of the referenced module is needed during code generation. + * The Dependency should also be added to normal dependencies via addDependency. + * @returns {void} + */ + addCodeGenerationDependency(codeGenerationDependency) { + if (this.codeGenerationDependencies === undefined) { + this.codeGenerationDependencies = []; + } + this.codeGenerationDependencies.push(codeGenerationDependency); + } + + /** + * Removes all dependencies and blocks + * @returns {void} + */ + clearDependenciesAndBlocks() { + if (this.presentationalDependencies !== undefined) { + this.presentationalDependencies.length = 0; + } + if (this.codeGenerationDependencies !== undefined) { + this.codeGenerationDependencies.length = 0; + } + super.clearDependenciesAndBlocks(); + } + + /** + * @param {WebpackError} warning the warning + * @returns {void} + */ + addWarning(warning) { + if (this._warnings === undefined) { + this._warnings = []; + } + this._warnings.push(warning); + } + + /** + * @returns {Iterable | undefined} list of warnings if any + */ + getWarnings() { + return this._warnings; + } + + /** + * @returns {number} number of warnings + */ + getNumberOfWarnings() { + return this._warnings !== undefined ? this._warnings.length : 0; + } + + /** + * @param {WebpackError} error the error + * @returns {void} + */ + addError(error) { + if (this._errors === undefined) { + this._errors = []; + } + this._errors.push(error); + } + + /** + * @returns {Iterable | undefined} list of errors if any + */ + getErrors() { + return this._errors; + } + + /** + * @returns {number} number of errors + */ + getNumberOfErrors() { + return this._errors !== undefined ? this._errors.length : 0; + } + + /** + * removes all warnings and errors + * @returns {void} + */ + clearWarningsAndErrors() { + if (this._warnings !== undefined) { + this._warnings.length = 0; + } + if (this._errors !== undefined) { + this._errors.length = 0; + } + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {boolean} true, if the module is optional + */ + isOptional(moduleGraph) { + let hasConnections = false; + for (const r of moduleGraph.getIncomingConnections(this)) { + if ( + !r.dependency || + !r.dependency.optional || + !r.isTargetActive(undefined) + ) { + return false; + } + hasConnections = true; + } + return hasConnections; + } + + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} chunk a chunk + * @param {Chunk=} ignoreChunk chunk to be ignored + * @returns {boolean} true, if the module is accessible from "chunk" when ignoring "ignoreChunk" + */ + isAccessibleInChunk(chunkGraph, chunk, ignoreChunk) { + // Check if module is accessible in ALL chunk groups + for (const chunkGroup of chunk.groupsIterable) { + if (!this.isAccessibleInChunkGroup(chunkGraph, chunkGroup)) return false; + } + return true; + } + + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {ChunkGroup} chunkGroup a chunk group + * @param {Chunk=} ignoreChunk chunk to be ignored + * @returns {boolean} true, if the module is accessible from "chunkGroup" when ignoring "ignoreChunk" + */ + isAccessibleInChunkGroup(chunkGraph, chunkGroup, ignoreChunk) { + const queue = new Set([chunkGroup]); + + // Check if module is accessible from all items of the queue + queueFor: for (const cg of queue) { + // 1. If module is in one of the chunks of the group we can continue checking the next items + // because it's accessible. + for (const chunk of cg.chunks) { + if (chunk !== ignoreChunk && chunkGraph.isModuleInChunk(this, chunk)) { + continue queueFor; + } + } + // 2. If the chunk group is initial, we can break here because it's not accessible. + if (chunkGroup.isInitial()) return false; + // 3. Enqueue all parents because it must be accessible from ALL parents + for (const parent of chunkGroup.parentsIterable) queue.add(parent); + } + // When we processed through the whole list and we didn't bailout, the module is accessible + return true; + } + + /** + * @param {Chunk} chunk a chunk + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {boolean} true, if the module has any reason why "chunk" should be included + */ + hasReasonForChunk(chunk, moduleGraph, chunkGraph) { + // check for each reason if we need the chunk + for (const [ + fromModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(this)) { + if (!connections.some((c) => c.isTargetActive(chunk.runtime))) continue; + for (const originChunk of chunkGraph.getModuleChunksIterable( + /** @type {Module} */ (fromModule) + )) { + // return true if module this is not reachable from originChunk when ignoring chunk + if (!this.isAccessibleInChunk(chunkGraph, originChunk, chunk)) { + return true; + } + } + } + return false; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true if at least one other module depends on this module + */ + hasReasons(moduleGraph, runtime) { + for (const c of moduleGraph.getIncomingConnections(this)) { + if (c.isTargetActive(runtime)) return true; + } + return false; + } + + /** + * @returns {string} for debugging + */ + toString() { + return `Module[${this.debugId}: ${this.identifier()}]`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback( + null, + !this.buildMeta || + this.needRebuild === Module.prototype.needRebuild || + deprecatedNeedRebuild(this, context) + ); + } + + /** + * @deprecated Use needBuild instead + * @param {Map} fileTimestamps timestamps of files + * @param {Map} contextTimestamps timestamps of directories + * @returns {boolean} true, if the module needs a rebuild + */ + needRebuild(fileTimestamps, contextTimestamps) { + return true; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash( + hash, + context = { + chunkGraph: ChunkGraph.getChunkGraphForModule( + this, + "Module.updateHash", + "DEP_WEBPACK_MODULE_UPDATE_HASH" + ), + runtime: undefined + } + ) { + const { chunkGraph, runtime } = context; + hash.update(chunkGraph.getModuleGraphHash(this, runtime)); + if (this.presentationalDependencies !== undefined) { + for (const dep of this.presentationalDependencies) { + dep.updateHash(hash, context); + } + } + super.updateHash(hash, context); + } + + /** + * @returns {void} + */ + invalidateBuild() { + // should be overridden to support this feature + } + + /* istanbul ignore next */ + /** + * @abstract + * @returns {string} a unique identifier of the module + */ + identifier() { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /** + * @abstract + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + // Better override this method to return the correct types + if (this.source === Module.prototype.source) { + return DEFAULT_TYPES_UNKNOWN; + } + return JS_TYPES; + } + + /** + * @abstract + * @deprecated Use codeGeneration() instead + * @param {DependencyTemplates} dependencyTemplates the dependency templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string=} type the type of source that should be generated + * @returns {Source} generated source + */ + source(dependencyTemplates, runtimeTemplate, type = "javascript") { + if (this.codeGeneration === Module.prototype.codeGeneration) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } + const chunkGraph = ChunkGraph.getChunkGraphForModule( + this, + "Module.source() is deprecated. Use Compilation.codeGenerationResults.getSource(module, runtime, type) instead", + "DEP_WEBPACK_MODULE_SOURCE" + ); + /** @type {CodeGenerationContext} */ + const codeGenContext = { + dependencyTemplates, + runtimeTemplate, + moduleGraph: chunkGraph.moduleGraph, + chunkGraph, + runtime: undefined, + codeGenerationResults: undefined + }; + const sources = this.codeGeneration(codeGenContext).sources; + + return /** @type {Source} */ ( + type + ? sources.get(type) + : sources.get(/** @type {string} */ (first(this.getSourceTypes()))) + ); + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return null; + } + + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + return null; + } + + /** + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(context) { + return `Module Concatenation is not implemented for ${this.constructor.name}`; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + */ + getSideEffectsConnectionState(moduleGraph) { + return true; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + // Best override this method + const sources = new Map(); + for (const type of this.getSourceTypes()) { + if (type !== "unknown") { + sources.set( + type, + this.source( + context.dependencyTemplates, + context.runtimeTemplate, + type + ) + ); + } + } + return { + sources, + runtimeRequirements: new Set([ + RuntimeGlobals.module, + RuntimeGlobals.exports, + RuntimeGlobals.require + ]) + }; + } + + /** + * @param {Chunk} chunk the chunk which condition should be checked + * @param {Compilation} compilation the compilation + * @returns {boolean} true, if the chunk is ok for the module + */ + chunkCondition(chunk, compilation) { + return true; + } + + hasChunkCondition() { + return this.chunkCondition !== Module.prototype.chunkCondition; + } + + /** + * Assuming this module is in the cache. Update the (cached) module with + * the fresh module from the factory. Usually updates internal references + * and properties. + * @param {Module} module fresh module + * @returns {void} + */ + updateCacheModule(module) { + this.type = module.type; + this.layer = module.layer; + this.context = module.context; + this.factoryMeta = module.factoryMeta; + this.resolveOptions = module.resolveOptions; + } + + /** + * Module should be unsafe cached. Get data that's needed for that. + * This data will be passed to restoreFromUnsafeCache later. + * @returns {UnsafeCacheData} cached data + */ + getUnsafeCacheData() { + return { + factoryMeta: this.factoryMeta, + resolveOptions: this.resolveOptions + }; + } + + /** + * restore unsafe cache data + * @param {UnsafeCacheData} unsafeCacheData data from getUnsafeCacheData + * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching + */ + _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + this.factoryMeta = unsafeCacheData.factoryMeta; + this.resolveOptions = unsafeCacheData.resolveOptions; + } + + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + this.factoryMeta = undefined; + this.resolveOptions = undefined; + } + + /** + * @returns {Source | null} the original source for the module before webpack transformation + */ + originalSource() { + return null; + } + + /** + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to + */ + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) {} + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.type); + write(this.layer); + write(this.context); + write(this.resolveOptions); + write(this.factoryMeta); + write(this.useSourceMap); + write(this.useSimpleSourceMap); + write(this.hot); + write( + this._warnings !== undefined && this._warnings.length === 0 + ? undefined + : this._warnings + ); + write( + this._errors !== undefined && this._errors.length === 0 + ? undefined + : this._errors + ); + write(this.buildMeta); + write(this.buildInfo); + write(this.presentationalDependencies); + write(this.codeGenerationDependencies); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.type = read(); + this.layer = read(); + this.context = read(); + this.resolveOptions = read(); + this.factoryMeta = read(); + this.useSourceMap = read(); + this.useSimpleSourceMap = read(); + this.hot = read(); + this._warnings = read(); + this._errors = read(); + this.buildMeta = read(); + this.buildInfo = read(); + this.presentationalDependencies = read(); + this.codeGenerationDependencies = read(); + super.deserialize(context); + } +} + +makeSerializable(Module, "webpack/lib/Module"); + +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "hasEqualsChunks", { + /** + * @deprecated + * @returns {EXPECTED_ANY} throw an error + */ + get() { + throw new Error( + "Module.hasEqualsChunks was renamed (use hasEqualChunks instead)" + ); + } +}); + +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "isUsed", { + /** + * @deprecated + * @returns {EXPECTED_ANY} throw an error + */ + get() { + throw new Error( + "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)" + ); + } +}); + +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "errors", { + /** + * @deprecated + * @returns {WebpackError[]} errors + */ + get: util.deprecate( + /** + * @this {Module} + * @returns {WebpackError[]} errors + */ + function errors() { + if (this._errors === undefined) { + this._errors = []; + } + return this._errors; + }, + "Module.errors was removed (use getErrors instead)", + "DEP_WEBPACK_MODULE_ERRORS" + ) +}); + +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "warnings", { + /** + * @deprecated + * @returns {WebpackError[]} warnings + */ + get: util.deprecate( + /** + * @this {Module} + * @returns {WebpackError[]} warnings + */ + function warnings() { + if (this._warnings === undefined) { + this._warnings = []; + } + return this._warnings; + }, + "Module.warnings was removed (use getWarnings instead)", + "DEP_WEBPACK_MODULE_WARNINGS" + ) +}); + +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "used", { + /** + * @deprecated + * @returns {EXPECTED_ANY} throw an error + */ + get() { + throw new Error( + "Module.used was refactored (use ModuleGraph.getUsedExports instead)" + ); + }, + /** + * @param {EXPECTED_ANY} value value + */ + set(value) { + throw new Error( + "Module.used was refactored (use ModuleGraph.setUsedExports instead)" + ); + } +}); + +module.exports = Module; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleBuildError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleBuildError.js new file mode 100644 index 0000000000000000000000000000000000000000..15f16955ac2a5bd112f7cade5c6a78029df89e20 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleBuildError.js @@ -0,0 +1,81 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { cutOffLoaderExecution } = require("./ErrorHelpers"); +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** @typedef {Error & { hideStack?: boolean }} ErrorWithHideStack */ + +class ModuleBuildError extends WebpackError { + /** + * @param {string | ErrorWithHideStack} err error thrown + * @param {{from?: string|null}} info additional info + */ + constructor(err, { from = null } = {}) { + let message = "Module build failed"; + let details; + + message += from ? ` (from ${from}):\n` : ": "; + + if (err !== null && typeof err === "object") { + if (typeof err.stack === "string" && err.stack) { + const stack = cutOffLoaderExecution(err.stack); + + if (!err.hideStack) { + message += stack; + } else { + details = stack; + + message += + typeof err.message === "string" && err.message ? err.message : err; + } + } else if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += String(err); + } + } else { + message += String(err); + } + + super(message); + + this.name = "ModuleBuildError"; + this.details = details; + this.error = err; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.error); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.error = read(); + + super.deserialize(context); + } +} + +makeSerializable(ModuleBuildError, "webpack/lib/ModuleBuildError"); + +module.exports = ModuleBuildError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleDependencyError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleDependencyError.js new file mode 100644 index 0000000000000000000000000000000000000000..374f610b8b5ee68695dc54d9f4685b327cbfc62e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleDependencyError.js @@ -0,0 +1,43 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleBuildError").ErrorWithHideStack} ErrorWithHideStack */ + +class ModuleDependencyError extends WebpackError { + /** + * Creates an instance of ModuleDependencyError. + * @param {Module} module module tied to dependency + * @param {ErrorWithHideStack} err error thrown + * @param {DependencyLocation} loc location of dependency + */ + constructor(module, err, loc) { + super(err.message); + + this.name = "ModuleDependencyError"; + this.details = + err && !err.hideStack + ? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") + : undefined; + this.module = module; + this.loc = loc; + /** error is not (de)serialized, so it might be undefined after deserialization */ + this.error = err; + + if (err && err.hideStack && err.stack) { + this.stack = /** @type {string} */ `${err.stack + .split("\n") + .slice(1) + .join("\n")}\n\n${this.stack}`; + } + } +} + +module.exports = ModuleDependencyError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleDependencyWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleDependencyWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..dc4c4f3435b6a8bd1a3bc162baa881eb1e8ef861 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleDependencyWarning.js @@ -0,0 +1,48 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleDependencyError").ErrorWithHideStack} ErrorWithHideStack */ + +class ModuleDependencyWarning extends WebpackError { + /** + * @param {Module} module module tied to dependency + * @param {ErrorWithHideStack} err error thrown + * @param {DependencyLocation} loc location of dependency + */ + constructor(module, err, loc) { + super(err ? err.message : ""); + + this.name = "ModuleDependencyWarning"; + this.details = + err && !err.hideStack + ? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") + : undefined; + this.module = module; + this.loc = loc; + /** error is not (de)serialized, so it might be undefined after deserialization */ + this.error = err; + + if (err && err.hideStack && err.stack) { + this.stack = /** @type {string} */ `${err.stack + .split("\n") + .slice(1) + .join("\n")}\n\n${this.stack}`; + } + } +} + +makeSerializable( + ModuleDependencyWarning, + "webpack/lib/ModuleDependencyWarning" +); + +module.exports = ModuleDependencyWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleError.js new file mode 100644 index 0000000000000000000000000000000000000000..f8227a8fc48e89b42066334a791e3eef577d3b32 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleError.js @@ -0,0 +1,66 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { cleanUp } = require("./ErrorHelpers"); +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class ModuleError extends WebpackError { + /** + * @param {Error} err error thrown + * @param {{from?: string|null}} info additional info + */ + constructor(err, { from = null } = {}) { + let message = "Module Error"; + + message += from ? ` (from ${from}):\n` : ": "; + + if (err && typeof err === "object" && err.message) { + message += err.message; + } else if (err) { + message += err; + } + + super(message); + + this.name = "ModuleError"; + this.error = err; + this.details = + err && typeof err === "object" && err.stack + ? cleanUp(err.stack, this.message) + : undefined; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.error); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.error = read(); + + super.deserialize(context); + } +} + +makeSerializable(ModuleError, "webpack/lib/ModuleError"); + +module.exports = ModuleError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..a38ae2a67b29c9e1b688399aefc669c09eb49af9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleFactory.js @@ -0,0 +1,57 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Module")} Module */ + +/** + * @typedef {object} ModuleFactoryResult + * @property {Module=} module the created module or unset if no module was created + * @property {Set=} fileDependencies + * @property {Set=} contextDependencies + * @property {Set=} missingDependencies + * @property {boolean=} cacheable allow to use the unsafe cache + */ + +/** @typedef {string | null} IssuerLayer */ + +/** + * @typedef {object} ModuleFactoryCreateDataContextInfo + * @property {string} issuer + * @property {IssuerLayer=} issuerLayer + * @property {string=} compiler + */ + +/** + * @typedef {object} ModuleFactoryCreateData + * @property {ModuleFactoryCreateDataContextInfo} contextInfo + * @property {ResolveOptions=} resolveOptions + * @property {string} context + * @property {Dependency[]} dependencies + */ + +/** + * @typedef {(err?: Error | null, result?: ModuleFactoryResult) => void} ModuleFactoryCallback + */ + +class ModuleFactory { + /* istanbul ignore next */ + /** + * @abstract + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create(data, callback) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } +} + +module.exports = ModuleFactory; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleFilenameHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleFilenameHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..0ef302e13378ef0d75666407935dde871efda9a7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleFilenameHelpers.js @@ -0,0 +1,369 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const NormalModule = require("./NormalModule"); +const { DEFAULTS } = require("./config/defaults"); +const createHash = require("./util/createHash"); +const memoize = require("./util/memoize"); + +/** @typedef {import("../declarations/WebpackOptions").DevtoolModuleFilenameTemplate} DevtoolModuleFilenameTemplate */ +/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./RequestShortener")} RequestShortener */ + +/** @typedef {string | RegExp | (string | RegExp)[]} Matcher */ +/** @typedef {{ test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */ + +const ModuleFilenameHelpers = module.exports; + +// TODO webpack 6: consider removing these +ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]"; +ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE = + /\[all-?loaders\]\[resource\]/gi; +ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]"; +ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi; +ModuleFilenameHelpers.RESOURCE = "[resource]"; +ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi; +ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]"; +// cSpell:words olute +ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH = + /\[abs(olute)?-?resource-?path\]/gi; +ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]"; +ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi; +ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]"; +ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi; +ModuleFilenameHelpers.LOADERS = "[loaders]"; +ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi; +ModuleFilenameHelpers.QUERY = "[query]"; +ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi; +ModuleFilenameHelpers.ID = "[id]"; +ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi; +ModuleFilenameHelpers.HASH = "[hash]"; +ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi; +ModuleFilenameHelpers.NAMESPACE = "[namespace]"; +ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi; + +/** @typedef {() => string} ReturnStringCallback */ + +/** + * Returns a function that returns the part of the string after the token + * @param {ReturnStringCallback} strFn the function to get the string + * @param {string} token the token to search for + * @returns {ReturnStringCallback} a function that returns the part of the string after the token + */ +const getAfter = (strFn, token) => () => { + const str = strFn(); + const idx = str.indexOf(token); + return idx < 0 ? "" : str.slice(idx); +}; + +/** + * Returns a function that returns the part of the string before the token + * @param {ReturnStringCallback} strFn the function to get the string + * @param {string} token the token to search for + * @returns {ReturnStringCallback} a function that returns the part of the string before the token + */ +const getBefore = (strFn, token) => () => { + const str = strFn(); + const idx = str.lastIndexOf(token); + return idx < 0 ? "" : str.slice(0, idx); +}; + +/** + * Returns a function that returns a hash of the string + * @param {ReturnStringCallback} strFn the function to get the string + * @param {HashFunction=} hashFunction the hash function to use + * @returns {ReturnStringCallback} a function that returns the hash of the string + */ +const getHash = + (strFn, hashFunction = DEFAULTS.HASH_FUNCTION) => + () => { + const hash = createHash(hashFunction); + hash.update(strFn()); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.slice(0, 4); + }; + +/** + * @template T + * Returns a lazy object. The object is lazy in the sense that the properties are + * only evaluated when they are accessed. This is only obtained by setting a function as the value for each key. + * @param {Record T>} obj the object to convert to a lazy access object + * @returns {T} the lazy access object + */ +const lazyObject = (obj) => { + const newObj = /** @type {T} */ ({}); + for (const key of Object.keys(obj)) { + const fn = obj[key]; + Object.defineProperty(newObj, key, { + get: () => fn(), + set: (v) => { + Object.defineProperty(newObj, key, { + value: v, + enumerable: true, + writable: true + }); + }, + enumerable: true, + configurable: true + }); + } + return newObj; +}; + +const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi; + +/** @typedef {((context: TODO) => string)} ModuleFilenameTemplateFunction */ +/** @typedef {string | ModuleFilenameTemplateFunction} ModuleFilenameTemplate */ + +/** + * @param {Module | string} module the module + * @param {{ namespace?: string, moduleFilenameTemplate?: ModuleFilenameTemplate }} options options + * @param {{ requestShortener: RequestShortener, chunkGraph: ChunkGraph, hashFunction?: HashFunction }} contextInfo context info + * @returns {string} the filename + */ +ModuleFilenameHelpers.createFilename = ( + // eslint-disable-next-line default-param-last + module = "", + options, + { requestShortener, chunkGraph, hashFunction = DEFAULTS.HASH_FUNCTION } +) => { + const opts = { + namespace: "", + moduleFilenameTemplate: "", + ...(typeof options === "object" + ? options + : { + moduleFilenameTemplate: options + }) + }; + + /** @type {ReturnStringCallback} */ + let absoluteResourcePath; + let hash; + /** @type {ReturnStringCallback} */ + let identifier; + /** @type {ReturnStringCallback} */ + let moduleId; + /** @type {ReturnStringCallback} */ + let shortIdentifier; + if (typeof module === "string") { + shortIdentifier = + /** @type {ReturnStringCallback} */ + (memoize(() => requestShortener.shorten(module))); + identifier = shortIdentifier; + moduleId = () => ""; + absoluteResourcePath = () => + /** @type {string} */ (module.split("!").pop()); + hash = getHash(identifier, hashFunction); + } else { + shortIdentifier = memoize(() => + module.readableIdentifier(requestShortener) + ); + identifier = + /** @type {ReturnStringCallback} */ + (memoize(() => requestShortener.shorten(module.identifier()))); + moduleId = + /** @type {ReturnStringCallback} */ + (() => chunkGraph.getModuleId(module)); + absoluteResourcePath = () => + module instanceof NormalModule + ? module.resource + : /** @type {string} */ (module.identifier().split("!").pop()); + hash = getHash(identifier, hashFunction); + } + const resource = + /** @type {ReturnStringCallback} */ + (memoize(() => shortIdentifier().split("!").pop())); + + const loaders = getBefore(shortIdentifier, "!"); + const allLoaders = getBefore(identifier, "!"); + const query = getAfter(resource, "?"); + const resourcePath = () => { + const q = query().length; + return q === 0 ? resource() : resource().slice(0, -q); + }; + if (typeof opts.moduleFilenameTemplate === "function") { + return opts.moduleFilenameTemplate( + lazyObject({ + identifier, + shortIdentifier, + resource, + resourcePath: memoize(resourcePath), + absoluteResourcePath: memoize(absoluteResourcePath), + loaders: memoize(loaders), + allLoaders: memoize(allLoaders), + query: memoize(query), + moduleId: memoize(moduleId), + hash: memoize(hash), + namespace: () => opts.namespace + }) + ); + } + + // TODO webpack 6: consider removing alternatives without dashes + /** @type {Map string>} */ + const replacements = new Map([ + ["identifier", identifier], + ["short-identifier", shortIdentifier], + ["resource", resource], + ["resource-path", resourcePath], + // cSpell:words resourcepath + ["resourcepath", resourcePath], + ["absolute-resource-path", absoluteResourcePath], + ["abs-resource-path", absoluteResourcePath], + // cSpell:words absoluteresource + ["absoluteresource-path", absoluteResourcePath], + // cSpell:words absresource + ["absresource-path", absoluteResourcePath], + // cSpell:words resourcepath + ["absolute-resourcepath", absoluteResourcePath], + // cSpell:words resourcepath + ["abs-resourcepath", absoluteResourcePath], + // cSpell:words absoluteresourcepath + ["absoluteresourcepath", absoluteResourcePath], + // cSpell:words absresourcepath + ["absresourcepath", absoluteResourcePath], + ["all-loaders", allLoaders], + // cSpell:words allloaders + ["allloaders", allLoaders], + ["loaders", loaders], + ["query", query], + ["id", moduleId], + ["hash", hash], + ["namespace", () => opts.namespace] + ]); + + // TODO webpack 6: consider removing weird double placeholders + return /** @type {string} */ (opts.moduleFilenameTemplate) + .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, "[identifier]") + .replace( + ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, + "[short-identifier]" + ) + .replace(SQUARE_BRACKET_TAG_REGEXP, (match, content) => { + if (content.length + 2 === match.length) { + const replacement = replacements.get(content.toLowerCase()); + if (replacement !== undefined) { + return replacement(); + } + } else if (match.startsWith("[\\") && match.endsWith("\\]")) { + return `[${match.slice(2, -2)}]`; + } + return match; + }); +}; + +/** + * Replaces duplicate items in an array with new values generated by a callback function. + * The callback function is called with the duplicate item, the index of the duplicate item, and the number of times the item has been replaced. + * The callback function should return the new value for the duplicate item. + * @template T + * @param {T[]} array the array with duplicates to be replaced + * @param {(duplicateItem: T, duplicateItemIndex: number, numberOfTimesReplaced: number) => T} fn callback function to generate new values for the duplicate items + * @param {(firstElement:T, nextElement:T) => -1 | 0 | 1=} comparator optional comparator function to sort the duplicate items + * @returns {T[]} the array with duplicates replaced + * @example + * ```js + * const array = ["a", "b", "c", "a", "b", "a"]; + * const result = ModuleFilenameHelpers.replaceDuplicates(array, (item, index, count) => `${item}-${count}`); + * // result: ["a-1", "b-1", "c", "a-2", "b-2", "a-3"] + * ``` + */ +ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => { + const countMap = Object.create(null); + const posMap = Object.create(null); + + for (const [idx, item] of array.entries()) { + countMap[item] = countMap[item] || []; + countMap[item].push(idx); + posMap[item] = 0; + } + if (comparator) { + for (const item of Object.keys(countMap)) { + countMap[item].sort(comparator); + } + } + return array.map((item, i) => { + if (countMap[item].length > 1) { + if (comparator && countMap[item][0] === i) return item; + return fn(item, i, posMap[item]++); + } + return item; + }); +}; + +/** + * Tests if a string matches a RegExp or an array of RegExp. + * @param {string} str string to test + * @param {Matcher} test value which will be used to match against the string + * @returns {boolean} true, when the RegExp matches + * @example + * ```js + * ModuleFilenameHelpers.matchPart("foo.js", "foo"); // true + * ModuleFilenameHelpers.matchPart("foo.js", "foo.js"); // true + * ModuleFilenameHelpers.matchPart("foo.js", "foo."); // false + * ModuleFilenameHelpers.matchPart("foo.js", "foo*"); // false + * ModuleFilenameHelpers.matchPart("foo.js", "foo.*"); // true + * ModuleFilenameHelpers.matchPart("foo.js", /^foo/); // true + * ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true + * ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true + * ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, /^bar/]); // true + * ModuleFilenameHelpers.matchPart("foo.js", [/^baz/, /^bar/]); // false + * ``` + */ +const matchPart = (str, test) => { + if (!test) return true; + if (Array.isArray(test)) { + return test.some((test) => matchPart(str, test)); + } + if (typeof test === "string") { + return str.startsWith(test); + } + return test.test(str); +}; + +ModuleFilenameHelpers.matchPart = matchPart; + +/** + * Tests if a string matches a match object. The match object can have the following properties: + * - `test`: a RegExp or an array of RegExp + * - `include`: a RegExp or an array of RegExp + * - `exclude`: a RegExp or an array of RegExp + * + * The `test` property is tested first, then `include` and then `exclude`. + * @param {MatchObject} obj a match object to test against the string + * @param {string} str string to test against the matching object + * @returns {boolean} true, when the object matches + * @example + * ```js + * ModuleFilenameHelpers.matchObject({ test: "foo.js" }, "foo.js"); // true + * ModuleFilenameHelpers.matchObject({ test: /^foo/ }, "foo.js"); // true + * ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "foo.js"); // true + * ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "baz.js"); // false + * ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "foo.js"); // true + * ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "bar.js"); // false + * ModuleFilenameHelpers.matchObject({ include: /^foo/ }, "foo.js"); // true + * ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "foo.js"); // true + * ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "baz.js"); // false + * ModuleFilenameHelpers.matchObject({ exclude: "foo.js" }, "foo.js"); // false + * ModuleFilenameHelpers.matchObject({ exclude: [/^foo/, "bar"] }, "foo.js"); // false + * ``` + */ +ModuleFilenameHelpers.matchObject = (obj, str) => { + if (obj.test && !ModuleFilenameHelpers.matchPart(str, obj.test)) { + return false; + } + if (obj.include && !ModuleFilenameHelpers.matchPart(str, obj.include)) { + return false; + } + if (obj.exclude && ModuleFilenameHelpers.matchPart(str, obj.exclude)) { + return false; + } + return true; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleGraph.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleGraph.js new file mode 100644 index 0000000000000000000000000000000000000000..e4572d21daaad537b4e823abf885bb4930db8a2d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleGraph.js @@ -0,0 +1,991 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const ExportsInfo = require("./ExportsInfo"); +const ModuleGraphConnection = require("./ModuleGraphConnection"); +const HarmonyImportDependency = require("./dependencies/HarmonyImportDependency"); +const SortableSet = require("./util/SortableSet"); +const WeakTupleMap = require("./util/WeakTupleMap"); +const { sortWithSourceOrder } = require("./util/comparators"); + +/** @typedef {import("./Compilation").ModuleMemCaches} ModuleMemCaches */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleProfile")} ModuleProfile */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./dependencies/HarmonyImportSideEffectDependency")} HarmonyImportSideEffectDependency */ +/** @typedef {import("./dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */ +/** @typedef {import("./util/comparators").DependencySourceOrder} DependencySourceOrder */ + +/** + * @callback OptimizationBailoutFunction + * @param {RequestShortener} requestShortener + * @returns {string} + */ + +const EMPTY_SET = new Set(); + +/** + * @template {Module | null | undefined} T + * @param {SortableSet} set input + * @param {(connection: ModuleGraphConnection) => T} getKey function to extract key from connection + * @returns {readonly Map} mapped by key + */ +const getConnectionsByKey = (set, getKey) => { + const map = new Map(); + /** @type {T | 0} */ + let lastKey = 0; + /** @type {ModuleGraphConnection[] | undefined} */ + let lastList; + for (const connection of set) { + const key = getKey(connection); + if (lastKey === key) { + /** @type {ModuleGraphConnection[]} */ + (lastList).push(connection); + } else { + lastKey = key; + const list = map.get(key); + if (list !== undefined) { + lastList = list; + list.push(connection); + } else { + const list = [connection]; + lastList = list; + map.set(key, list); + } + } + } + return map; +}; + +/** + * @param {SortableSet} set input + * @returns {readonly Map} mapped by origin module + */ +const getConnectionsByOriginModule = (set) => + getConnectionsByKey(set, (connection) => connection.originModule); + +/** + * @param {SortableSet} set input + * @returns {readonly Map} mapped by module + */ +const getConnectionsByModule = (set) => + getConnectionsByKey(set, (connection) => connection.module); + +/** @typedef {SortableSet} IncomingConnections */ +/** @typedef {SortableSet} OutgoingConnections */ + +class ModuleGraphModule { + constructor() { + /** @type {IncomingConnections} */ + this.incomingConnections = new SortableSet(); + /** @type {OutgoingConnections | undefined} */ + this.outgoingConnections = undefined; + /** @type {Module | null | undefined} */ + this.issuer = undefined; + /** @type {(string | OptimizationBailoutFunction)[]} */ + this.optimizationBailout = []; + /** @type {ExportsInfo} */ + this.exports = new ExportsInfo(); + /** @type {number | null} */ + this.preOrderIndex = null; + /** @type {number | null} */ + this.postOrderIndex = null; + /** @type {number | null} */ + this.depth = null; + /** @type {ModuleProfile | undefined} */ + this.profile = undefined; + /** @type {boolean} */ + this.async = false; + /** @type {ModuleGraphConnection[] | undefined} */ + this._unassignedConnections = undefined; + } +} + +/** @typedef {(moduleGraphConnection: ModuleGraphConnection) => boolean} FilterConnection */ + +/** @typedef {EXPECTED_OBJECT} MetaKey */ +/** @typedef {TODO} Meta */ + +class ModuleGraph { + constructor() { + /** + * @type {WeakMap} + * @private + */ + this._dependencyMap = new WeakMap(); + /** + * @type {Map} + * @private + */ + this._moduleMap = new Map(); + /** + * @type {WeakMap} + * @private + */ + this._metaMap = new WeakMap(); + /** + * @type {WeakTupleMap | undefined} + * @private + */ + this._cache = undefined; + /** + * @type {ModuleMemCaches | undefined} + * @private + */ + this._moduleMemCaches = undefined; + + /** + * @type {string | undefined} + * @private + */ + this._cacheStage = undefined; + + /** + * @type {WeakMap} + * @private + */ + this._dependencySourceOrderMap = new WeakMap(); + } + + /** + * @param {Module} module the module + * @returns {ModuleGraphModule} the internal module + */ + _getModuleGraphModule(module) { + let mgm = this._moduleMap.get(module); + if (mgm === undefined) { + mgm = new ModuleGraphModule(); + this._moduleMap.set(module, mgm); + } + return mgm; + } + + /** + * @param {Dependency} dependency the dependency + * @param {DependenciesBlock} block parent block + * @param {Module} module parent module + * @param {number=} indexInBlock position in block + * @returns {void} + */ + setParents(dependency, block, module, indexInBlock = -1) { + dependency._parentDependenciesBlockIndex = indexInBlock; + dependency._parentDependenciesBlock = block; + dependency._parentModule = module; + } + + /** + * @param {Dependency} dependency the dependency + * @param {number} index the index + * @returns {void} + */ + setParentDependenciesBlockIndex(dependency, index) { + dependency._parentDependenciesBlockIndex = index; + } + + /** + * @param {Dependency} dependency the dependency + * @returns {Module | undefined} parent module + */ + getParentModule(dependency) { + return dependency._parentModule; + } + + /** + * @param {Dependency} dependency the dependency + * @returns {DependenciesBlock | undefined} parent block + */ + getParentBlock(dependency) { + return dependency._parentDependenciesBlock; + } + + /** + * @param {Dependency} dependency the dependency + * @returns {number} index + */ + getParentBlockIndex(dependency) { + return dependency._parentDependenciesBlockIndex; + } + + /** + * @param {Module | null} originModule the referencing module + * @param {Dependency} dependency the referencing dependency + * @param {Module} module the referenced module + * @returns {void} + */ + setResolvedModule(originModule, dependency, module) { + const connection = new ModuleGraphConnection( + originModule, + dependency, + module, + undefined, + dependency.weak, + dependency.getCondition(this) + ); + const connections = this._getModuleGraphModule(module).incomingConnections; + connections.add(connection); + if (originModule) { + const mgm = this._getModuleGraphModule(originModule); + if (mgm._unassignedConnections === undefined) { + mgm._unassignedConnections = []; + } + mgm._unassignedConnections.push(connection); + if (mgm.outgoingConnections === undefined) { + mgm.outgoingConnections = new SortableSet(); + } + mgm.outgoingConnections.add(connection); + } else { + this._dependencyMap.set(dependency, connection); + } + } + + /** + * @param {Dependency} dependency the referencing dependency + * @param {Module} module the referenced module + * @returns {void} + */ + updateModule(dependency, module) { + const connection = + /** @type {ModuleGraphConnection} */ + (this.getConnection(dependency)); + if (connection.module === module) return; + const newConnection = connection.clone(); + newConnection.module = module; + this._dependencyMap.set(dependency, newConnection); + connection.setActive(false); + const originMgm = this._getModuleGraphModule( + /** @type {Module} */ (connection.originModule) + ); + /** @type {OutgoingConnections} */ + (originMgm.outgoingConnections).add(newConnection); + const targetMgm = this._getModuleGraphModule(module); + targetMgm.incomingConnections.add(newConnection); + } + + /** + * @param {Dependency} dependency the need update dependency + * @param {ModuleGraphConnection=} connection the target connection + * @param {Module=} parentModule the parent module + * @returns {void} + */ + updateParent(dependency, connection, parentModule) { + if (this._dependencySourceOrderMap.has(dependency)) { + return; + } + if (!connection || !parentModule) { + return; + } + const originDependency = connection.dependency; + + // src/index.js + // import { c } from "lib/c" -> c = 0 + // import { a, b } from "lib" -> a and b have the same source order -> a = b = 1 + // import { d } from "lib/d" -> d = 2 + const currentSourceOrder = + /** @type { HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */ ( + dependency + ).sourceOrder; + + // lib/index.js (reexport) + // import { a } from "lib/a" -> a = 0 + // import { b } from "lib/b" -> b = 1 + const originSourceOrder = + /** @type { HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */ ( + originDependency + ).sourceOrder; + if ( + typeof currentSourceOrder === "number" && + typeof originSourceOrder === "number" + ) { + // src/index.js + // import { c } from "lib/c" -> c = 0 + // import { a } from "lib/a" -> a = 1.0 = 1(main) + 0.0(sub) + // import { b } from "lib/b" -> b = 1.1 = 1(main) + 0.1(sub) + // import { d } from "lib/d" -> d = 2 + this._dependencySourceOrderMap.set(dependency, { + main: currentSourceOrder, + sub: originSourceOrder + }); + + // If dependencies like HarmonyImportSideEffectDependency and HarmonyImportSpecifierDependency have a SourceOrder, + // we sort based on it; otherwise, we preserve the original order. + sortWithSourceOrder( + parentModule.dependencies, + this._dependencySourceOrderMap + ); + + for (const [index, dep] of parentModule.dependencies.entries()) { + this.setParentDependenciesBlockIndex(dep, index); + } + } + } + + /** + * @param {Dependency} dependency the referencing dependency + * @returns {void} + */ + removeConnection(dependency) { + const connection = + /** @type {ModuleGraphConnection} */ + (this.getConnection(dependency)); + const targetMgm = this._getModuleGraphModule(connection.module); + targetMgm.incomingConnections.delete(connection); + const originMgm = this._getModuleGraphModule( + /** @type {Module} */ (connection.originModule) + ); + /** @type {OutgoingConnections} */ + (originMgm.outgoingConnections).delete(connection); + this._dependencyMap.set(dependency, null); + } + + /** + * @param {Dependency} dependency the referencing dependency + * @param {string} explanation an explanation + * @returns {void} + */ + addExplanation(dependency, explanation) { + const connection = + /** @type {ModuleGraphConnection} */ + (this.getConnection(dependency)); + connection.addExplanation(explanation); + } + + /** + * @param {Module} sourceModule the source module + * @param {Module} targetModule the target module + * @returns {void} + */ + cloneModuleAttributes(sourceModule, targetModule) { + const oldMgm = this._getModuleGraphModule(sourceModule); + const newMgm = this._getModuleGraphModule(targetModule); + newMgm.postOrderIndex = oldMgm.postOrderIndex; + newMgm.preOrderIndex = oldMgm.preOrderIndex; + newMgm.depth = oldMgm.depth; + newMgm.exports = oldMgm.exports; + newMgm.async = oldMgm.async; + } + + /** + * @param {Module} module the module + * @returns {void} + */ + removeModuleAttributes(module) { + const mgm = this._getModuleGraphModule(module); + mgm.postOrderIndex = null; + mgm.preOrderIndex = null; + mgm.depth = null; + mgm.async = false; + } + + /** + * @returns {void} + */ + removeAllModuleAttributes() { + for (const mgm of this._moduleMap.values()) { + mgm.postOrderIndex = null; + mgm.preOrderIndex = null; + mgm.depth = null; + mgm.async = false; + } + } + + /** + * @param {Module} oldModule the old referencing module + * @param {Module} newModule the new referencing module + * @param {FilterConnection} filterConnection filter predicate for replacement + * @returns {void} + */ + moveModuleConnections(oldModule, newModule, filterConnection) { + if (oldModule === newModule) return; + const oldMgm = this._getModuleGraphModule(oldModule); + const newMgm = this._getModuleGraphModule(newModule); + // Outgoing connections + const oldConnections = oldMgm.outgoingConnections; + if (oldConnections !== undefined) { + if (newMgm.outgoingConnections === undefined) { + newMgm.outgoingConnections = new SortableSet(); + } + const newConnections = newMgm.outgoingConnections; + for (const connection of oldConnections) { + if (filterConnection(connection)) { + connection.originModule = newModule; + newConnections.add(connection); + oldConnections.delete(connection); + } + } + } + // Incoming connections + const oldConnections2 = oldMgm.incomingConnections; + const newConnections2 = newMgm.incomingConnections; + for (const connection of oldConnections2) { + if (filterConnection(connection)) { + connection.module = newModule; + newConnections2.add(connection); + oldConnections2.delete(connection); + } + } + } + + /** + * @param {Module} oldModule the old referencing module + * @param {Module} newModule the new referencing module + * @param {FilterConnection} filterConnection filter predicate for replacement + * @returns {void} + */ + copyOutgoingModuleConnections(oldModule, newModule, filterConnection) { + if (oldModule === newModule) return; + const oldMgm = this._getModuleGraphModule(oldModule); + const newMgm = this._getModuleGraphModule(newModule); + // Outgoing connections + const oldConnections = oldMgm.outgoingConnections; + if (oldConnections !== undefined) { + if (newMgm.outgoingConnections === undefined) { + newMgm.outgoingConnections = new SortableSet(); + } + const newConnections = newMgm.outgoingConnections; + for (const connection of oldConnections) { + if (filterConnection(connection)) { + const newConnection = connection.clone(); + newConnection.originModule = newModule; + newConnections.add(newConnection); + if (newConnection.module !== undefined) { + const otherMgm = this._getModuleGraphModule(newConnection.module); + otherMgm.incomingConnections.add(newConnection); + } + } + } + } + } + + /** + * @param {Module} module the referenced module + * @param {string} explanation an explanation why it's referenced + * @returns {void} + */ + addExtraReason(module, explanation) { + const connections = this._getModuleGraphModule(module).incomingConnections; + connections.add(new ModuleGraphConnection(null, null, module, explanation)); + } + + /** + * @param {Dependency} dependency the dependency to look for a referenced module + * @returns {Module | null} the referenced module + */ + getResolvedModule(dependency) { + const connection = this.getConnection(dependency); + return connection !== undefined ? connection.resolvedModule : null; + } + + /** + * @param {Dependency} dependency the dependency to look for a referenced module + * @returns {ModuleGraphConnection | undefined} the connection + */ + getConnection(dependency) { + const connection = this._dependencyMap.get(dependency); + if (connection === undefined) { + const module = this.getParentModule(dependency); + if (module !== undefined) { + const mgm = this._getModuleGraphModule(module); + if ( + mgm._unassignedConnections && + mgm._unassignedConnections.length !== 0 + ) { + let foundConnection; + for (const connection of mgm._unassignedConnections) { + this._dependencyMap.set( + /** @type {Dependency} */ (connection.dependency), + connection + ); + if (connection.dependency === dependency) { + foundConnection = connection; + } + } + mgm._unassignedConnections.length = 0; + if (foundConnection !== undefined) { + return foundConnection; + } + } + } + this._dependencyMap.set(dependency, null); + return; + } + return connection === null ? undefined : connection; + } + + /** + * @param {Dependency} dependency the dependency to look for a referenced module + * @returns {Module | null} the referenced module + */ + getModule(dependency) { + const connection = this.getConnection(dependency); + return connection !== undefined ? connection.module : null; + } + + /** + * @param {Dependency} dependency the dependency to look for a referencing module + * @returns {Module | null} the referencing module + */ + getOrigin(dependency) { + const connection = this.getConnection(dependency); + return connection !== undefined ? connection.originModule : null; + } + + /** + * @param {Dependency} dependency the dependency to look for a referencing module + * @returns {Module | null} the original referencing module + */ + getResolvedOrigin(dependency) { + const connection = this.getConnection(dependency); + return connection !== undefined ? connection.resolvedOriginModule : null; + } + + /** + * @param {Module} module the module + * @returns {Iterable} reasons why a module is included + */ + getIncomingConnections(module) { + const connections = this._getModuleGraphModule(module).incomingConnections; + return connections; + } + + /** + * @param {Module} module the module + * @returns {Iterable} list of outgoing connections + */ + getOutgoingConnections(module) { + const connections = this._getModuleGraphModule(module).outgoingConnections; + return connections === undefined ? EMPTY_SET : connections; + } + + /** + * @param {Module} module the module + * @returns {readonly Map} reasons why a module is included, in a map by source module + */ + getIncomingConnectionsByOriginModule(module) { + const connections = this._getModuleGraphModule(module).incomingConnections; + return connections.getFromUnorderedCache(getConnectionsByOriginModule); + } + + /** + * @param {Module} module the module + * @returns {readonly Map | undefined} connections to modules, in a map by module + */ + getOutgoingConnectionsByModule(module) { + const connections = this._getModuleGraphModule(module).outgoingConnections; + return connections === undefined + ? undefined + : connections.getFromUnorderedCache(getConnectionsByModule); + } + + /** + * @param {Module} module the module + * @returns {ModuleProfile | undefined} the module profile + */ + getProfile(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.profile; + } + + /** + * @param {Module} module the module + * @param {ModuleProfile | undefined} profile the module profile + * @returns {void} + */ + setProfile(module, profile) { + const mgm = this._getModuleGraphModule(module); + mgm.profile = profile; + } + + /** + * @param {Module} module the module + * @returns {Module | null | undefined} the issuer module + */ + getIssuer(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.issuer; + } + + /** + * @param {Module} module the module + * @param {Module | null} issuer the issuer module + * @returns {void} + */ + setIssuer(module, issuer) { + const mgm = this._getModuleGraphModule(module); + mgm.issuer = issuer; + } + + /** + * @param {Module} module the module + * @param {Module | null} issuer the issuer module + * @returns {void} + */ + setIssuerIfUnset(module, issuer) { + const mgm = this._getModuleGraphModule(module); + if (mgm.issuer === undefined) mgm.issuer = issuer; + } + + /** + * @param {Module} module the module + * @returns {(string | OptimizationBailoutFunction)[]} optimization bailouts + */ + getOptimizationBailout(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.optimizationBailout; + } + + /** + * @param {Module} module the module + * @returns {true | string[] | null} the provided exports + */ + getProvidedExports(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.exports.getProvidedExports(); + } + + /** + * @param {Module} module the module + * @param {string | string[]} exportName a name of an export + * @returns {boolean | null} true, if the export is provided by the module. + * null, if it's unknown. + * false, if it's not provided. + */ + isExportProvided(module, exportName) { + const mgm = this._getModuleGraphModule(module); + const result = mgm.exports.isExportProvided(exportName); + return result === undefined ? null : result; + } + + /** + * @param {Module} module the module + * @returns {ExportsInfo} info about the exports + */ + getExportsInfo(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.exports; + } + + /** + * @param {Module} module the module + * @param {string} exportName the export + * @returns {ExportInfo} info about the export + */ + getExportInfo(module, exportName) { + const mgm = this._getModuleGraphModule(module); + return mgm.exports.getExportInfo(exportName); + } + + /** + * @param {Module} module the module + * @param {string} exportName the export + * @returns {ExportInfo} info about the export (do not modify) + */ + getReadOnlyExportInfo(module, exportName) { + const mgm = this._getModuleGraphModule(module); + return mgm.exports.getReadOnlyExportInfo(exportName); + } + + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {false | true | SortableSet | null} the used exports + * false: module is not used at all. + * true: the module namespace/object export is used. + * SortableSet: these export names are used. + * empty SortableSet: module is used but no export. + * null: unknown, worst case should be assumed. + */ + getUsedExports(module, runtime) { + const mgm = this._getModuleGraphModule(module); + return mgm.exports.getUsedExports(runtime); + } + + /** + * @param {Module} module the module + * @returns {number | null} the index of the module + */ + getPreOrderIndex(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.preOrderIndex; + } + + /** + * @param {Module} module the module + * @returns {number | null} the index of the module + */ + getPostOrderIndex(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.postOrderIndex; + } + + /** + * @param {Module} module the module + * @param {number} index the index of the module + * @returns {void} + */ + setPreOrderIndex(module, index) { + const mgm = this._getModuleGraphModule(module); + mgm.preOrderIndex = index; + } + + /** + * @param {Module} module the module + * @param {number} index the index of the module + * @returns {boolean} true, if the index was set + */ + setPreOrderIndexIfUnset(module, index) { + const mgm = this._getModuleGraphModule(module); + if (mgm.preOrderIndex === null) { + mgm.preOrderIndex = index; + return true; + } + return false; + } + + /** + * @param {Module} module the module + * @param {number} index the index of the module + * @returns {void} + */ + setPostOrderIndex(module, index) { + const mgm = this._getModuleGraphModule(module); + mgm.postOrderIndex = index; + } + + /** + * @param {Module} module the module + * @param {number} index the index of the module + * @returns {boolean} true, if the index was set + */ + setPostOrderIndexIfUnset(module, index) { + const mgm = this._getModuleGraphModule(module); + if (mgm.postOrderIndex === null) { + mgm.postOrderIndex = index; + return true; + } + return false; + } + + /** + * @param {Module} module the module + * @returns {number | null} the depth of the module + */ + getDepth(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.depth; + } + + /** + * @param {Module} module the module + * @param {number} depth the depth of the module + * @returns {void} + */ + setDepth(module, depth) { + const mgm = this._getModuleGraphModule(module); + mgm.depth = depth; + } + + /** + * @param {Module} module the module + * @param {number} depth the depth of the module + * @returns {boolean} true, if the depth was set + */ + setDepthIfLower(module, depth) { + const mgm = this._getModuleGraphModule(module); + if (mgm.depth === null || mgm.depth > depth) { + mgm.depth = depth; + return true; + } + return false; + } + + /** + * @param {Module} module the module + * @returns {boolean} true, if the module is async + */ + isAsync(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.async; + } + + /** + * @param {Module} module the module + * @returns {boolean} true, if the module is used as a deferred module at least once + */ + isDeferred(module) { + if (this.isAsync(module)) return false; + const connections = this.getIncomingConnections(module); + for (const connection of connections) { + if ( + !connection.dependency || + !(connection.dependency instanceof HarmonyImportDependency) + ) { + continue; + } + if (connection.dependency.defer) return true; + } + return false; + } + + /** + * @param {Module} module the module + * @returns {void} + */ + setAsync(module) { + const mgm = this._getModuleGraphModule(module); + mgm.async = true; + } + + /** + * @param {MetaKey} thing any thing + * @returns {Meta} metadata + */ + getMeta(thing) { + let meta = this._metaMap.get(thing); + if (meta === undefined) { + meta = Object.create(null); + this._metaMap.set(thing, meta); + } + return meta; + } + + /** + * @param {MetaKey} thing any thing + * @returns {Meta | undefined} metadata + */ + getMetaIfExisting(thing) { + return this._metaMap.get(thing); + } + + /** + * @param {string=} cacheStage a persistent stage name for caching + */ + freeze(cacheStage) { + this._cache = new WeakTupleMap(); + this._cacheStage = cacheStage; + } + + unfreeze() { + this._cache = undefined; + this._cacheStage = undefined; + } + + /** + * @template T + * @template R + * @param {(moduleGraph: ModuleGraph, ...args: T[]) => R} fn computer + * @param {...T} args arguments + * @returns {R} computed value or cached + */ + cached(fn, ...args) { + if (this._cache === undefined) return fn(this, ...args); + return this._cache.provide(fn, ...args, () => fn(this, ...args)); + } + + /** + * @param {ModuleMemCaches} moduleMemCaches mem caches for modules for better caching + */ + setModuleMemCaches(moduleMemCaches) { + this._moduleMemCaches = moduleMemCaches; + } + + /** + * @template {Dependency} D + * @template {EXPECTED_ANY[]} ARGS + * @template R + * @param {D} dependency dependency + * @param {[...ARGS, (moduleGraph: ModuleGraph, dependency: D, ...args: ARGS) => R]} args arguments, last argument is a function called with moduleGraph, dependency, ...args + * @returns {R} computed value or cached + */ + dependencyCacheProvide(dependency, ...args) { + const fn = + /** @type {(moduleGraph: ModuleGraph, dependency: D, ...args: EXPECTED_ANY[]) => R} */ + (args.pop()); + if (this._moduleMemCaches && this._cacheStage) { + const memCache = this._moduleMemCaches.get( + /** @type {Module} */ + (this.getParentModule(dependency)) + ); + if (memCache !== undefined) { + return memCache.provide(dependency, this._cacheStage, ...args, () => + fn(this, dependency, ...args) + ); + } + } + if (this._cache === undefined) return fn(this, dependency, ...args); + return this._cache.provide(dependency, ...args, () => + fn(this, dependency, ...args) + ); + } + + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @param {string} deprecateMessage message for the deprecation message + * @param {string} deprecationCode code for the deprecation + * @returns {ModuleGraph} the module graph + */ + static getModuleGraphForModule(module, deprecateMessage, deprecationCode) { + const fn = deprecateMap.get(deprecateMessage); + if (fn) return fn(module); + const newFn = util.deprecate( + /** + * @param {Module} module the module + * @returns {ModuleGraph} the module graph + */ + (module) => { + const moduleGraph = moduleGraphForModuleMap.get(module); + if (!moduleGraph) { + throw new Error( + `${ + deprecateMessage + }There was no ModuleGraph assigned to the Module for backward-compat (Use the new API)` + ); + } + return moduleGraph; + }, + `${deprecateMessage}: Use new ModuleGraph API`, + deprecationCode + ); + deprecateMap.set(deprecateMessage, newFn); + return newFn(module); + } + + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @param {ModuleGraph} moduleGraph the module graph + * @returns {void} + */ + static setModuleGraphForModule(module, moduleGraph) { + moduleGraphForModuleMap.set(module, moduleGraph); + } + + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @returns {void} + */ + static clearModuleGraphForModule(module) { + moduleGraphForModuleMap.delete(module); + } +} + +// TODO remove in webpack 6 +/** @type {WeakMap} */ +const moduleGraphForModuleMap = new WeakMap(); + +// TODO remove in webpack 6 +/** @type {Map ModuleGraph>} */ +const deprecateMap = new Map(); + +module.exports = ModuleGraph; +module.exports.ModuleGraphConnection = ModuleGraphConnection; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleGraphConnection.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleGraphConnection.js new file mode 100644 index 0000000000000000000000000000000000000000..def4ff759c1de54c5a29df26525cc9ebde2b6dc1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleGraphConnection.js @@ -0,0 +1,199 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").GetConditionFn} GetConditionFn */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * Module itself is not connected, but transitive modules are connected transitively. + */ +const TRANSITIVE_ONLY = Symbol("transitive only"); + +/** + * While determining the active state, this flag is used to signal a circular connection. + */ +const CIRCULAR_CONNECTION = Symbol("circular connection"); + +/** @typedef {boolean | typeof TRANSITIVE_ONLY | typeof CIRCULAR_CONNECTION} ConnectionState */ + +/** + * @param {ConnectionState} a first + * @param {ConnectionState} b second + * @returns {ConnectionState} merged + */ +const addConnectionStates = (a, b) => { + if (a === true || b === true) return true; + if (a === false) return b; + if (b === false) return a; + if (a === TRANSITIVE_ONLY) return b; + if (b === TRANSITIVE_ONLY) return a; + return a; +}; + +/** + * @param {ConnectionState} a first + * @param {ConnectionState} b second + * @returns {ConnectionState} intersected + */ +const intersectConnectionStates = (a, b) => { + if (a === false || b === false) return false; + if (a === true) return b; + if (b === true) return a; + if (a === CIRCULAR_CONNECTION) return b; + if (b === CIRCULAR_CONNECTION) return a; + return a; +}; + +class ModuleGraphConnection { + /** + * @param {Module|null} originModule the referencing module + * @param {Dependency|null} dependency the referencing dependency + * @param {Module} module the referenced module + * @param {string=} explanation some extra detail + * @param {boolean=} weak the reference is weak + * @param {false | null | GetConditionFn | undefined} condition condition for the connection + */ + constructor( + originModule, + dependency, + module, + explanation, + weak = false, + condition = undefined + ) { + this.originModule = originModule; + this.resolvedOriginModule = originModule; + this.dependency = dependency; + this.resolvedModule = module; + this.module = module; + this.weak = weak; + this.conditional = Boolean(condition); + this._active = condition !== false; + this.condition = condition || undefined; + /** @type {Set | undefined} */ + this.explanations = undefined; + if (explanation) { + this.explanations = new Set(); + this.explanations.add(explanation); + } + } + + clone() { + const clone = new ModuleGraphConnection( + this.resolvedOriginModule, + this.dependency, + this.resolvedModule, + undefined, + this.weak, + this.condition + ); + clone.originModule = this.originModule; + clone.module = this.module; + clone.conditional = this.conditional; + clone._active = this._active; + if (this.explanations) clone.explanations = new Set(this.explanations); + return clone; + } + + /** + * @param {GetConditionFn} condition condition for the connection + * @returns {void} + */ + addCondition(condition) { + if (this.conditional) { + const old = + /** @type {GetConditionFn} */ + (this.condition); + /** @type {GetConditionFn} */ + (this.condition) = (c, r) => + intersectConnectionStates(old(c, r), condition(c, r)); + } else if (this._active) { + this.conditional = true; + this.condition = condition; + } + } + + /** + * @param {string} explanation the explanation to add + * @returns {void} + */ + addExplanation(explanation) { + if (this.explanations === undefined) { + this.explanations = new Set(); + } + this.explanations.add(explanation); + } + + get explanation() { + if (this.explanations === undefined) return ""; + return [...this.explanations].join(" "); + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, if the connection is active + */ + isActive(runtime) { + if (!this.conditional) return this._active; + + return ( + /** @type {GetConditionFn} */ (this.condition)(this, runtime) !== false + ); + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, if the connection is active + */ + isTargetActive(runtime) { + if (!this.conditional) return this._active; + return ( + /** @type {GetConditionFn} */ (this.condition)(this, runtime) === true + ); + } + + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {ConnectionState} true: fully active, false: inactive, TRANSITIVE: direct module inactive, but transitive connection maybe active + */ + getActiveState(runtime) { + if (!this.conditional) return this._active; + return /** @type {GetConditionFn} */ (this.condition)(this, runtime); + } + + /** + * @param {boolean} value active or not + * @returns {void} + */ + setActive(value) { + this.conditional = false; + this._active = value; + } + + // TODO webpack 5 remove + get active() { + throw new Error("Use getActiveState instead"); + } + + set active(value) { + throw new Error("Use setActive instead"); + } +} + +/** @typedef {typeof TRANSITIVE_ONLY} TRANSITIVE_ONLY */ +/** @typedef {typeof CIRCULAR_CONNECTION} CIRCULAR_CONNECTION */ + +module.exports = ModuleGraphConnection; +module.exports.CIRCULAR_CONNECTION = /** @type {typeof CIRCULAR_CONNECTION} */ ( + CIRCULAR_CONNECTION +); +module.exports.TRANSITIVE_ONLY = /** @type {typeof TRANSITIVE_ONLY} */ ( + TRANSITIVE_ONLY +); +module.exports.addConnectionStates = addConnectionStates; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleHashingError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleHashingError.js new file mode 100644 index 0000000000000000000000000000000000000000..77c8f415aff7dad093b7f36bcf7c1b3914360878 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleHashingError.js @@ -0,0 +1,29 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Module")} Module */ + +class ModuleHashingError extends WebpackError { + /** + * Create a new ModuleHashingError + * @param {Module} module related module + * @param {Error} error Original error + */ + constructor(module, error) { + super(); + + this.name = "ModuleHashingError"; + this.error = error; + this.message = error.message; + this.details = error.stack; + this.module = module; + } +} + +module.exports = ModuleHashingError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleInfoHeaderPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleInfoHeaderPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..5aecdb2ca62795ce0076a7c6e3343a046a0bbcc4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleInfoHeaderPlugin.js @@ -0,0 +1,314 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { CachedSource, ConcatSource, RawSource } = require("webpack-sources"); +const { UsageState } = require("./ExportsInfo"); +const Template = require("./Template"); +const CssModulesPlugin = require("./css/CssModulesPlugin"); +const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./ExportsInfo")} ExportsInfo */ +/** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./RequestShortener")} RequestShortener */ + +/** + * @template T + * @param {Iterable} iterable iterable + * @returns {string} joined with comma + */ +const joinIterableWithComma = (iterable) => { + // This is more performant than Array.from().join(", ") + // as it doesn't create an array + let str = ""; + let first = true; + for (const item of iterable) { + if (first) { + first = false; + } else { + str += ", "; + } + str += item; + } + return str; +}; + +/** + * @param {ConcatSource} source output + * @param {string} indent spacing + * @param {ExportsInfo} exportsInfo data + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {RequestShortener} requestShortener requestShortener + * @param {Set} alreadyPrinted deduplication set + * @returns {void} + */ +const printExportsInfoToSource = ( + source, + indent, + exportsInfo, + moduleGraph, + requestShortener, + alreadyPrinted = new Set() +) => { + const otherExportsInfo = exportsInfo.otherExportsInfo; + + let alreadyPrintedExports = 0; + + // determine exports to print + const printedExports = []; + for (const exportInfo of exportsInfo.orderedExports) { + if (!alreadyPrinted.has(exportInfo)) { + alreadyPrinted.add(exportInfo); + printedExports.push(exportInfo); + } else { + alreadyPrintedExports++; + } + } + let showOtherExports = false; + if (!alreadyPrinted.has(otherExportsInfo)) { + alreadyPrinted.add(otherExportsInfo); + showOtherExports = true; + } else { + alreadyPrintedExports++; + } + + // print the exports + for (const exportInfo of printedExports) { + const target = exportInfo.getTarget(moduleGraph); + source.add( + `${Template.toComment( + `${indent}export ${JSON.stringify(exportInfo.name).slice( + 1, + -1 + )} [${exportInfo.getProvidedInfo()}] [${exportInfo.getUsedInfo()}] [${exportInfo.getRenameInfo()}]${ + target + ? ` -> ${target.module.readableIdentifier(requestShortener)}${ + target.export + ? ` .${target.export + .map((e) => JSON.stringify(e).slice(1, -1)) + .join(".")}` + : "" + }` + : "" + }` + )}\n` + ); + if (exportInfo.exportsInfo) { + printExportsInfoToSource( + source, + `${indent} `, + exportInfo.exportsInfo, + moduleGraph, + requestShortener, + alreadyPrinted + ); + } + } + + if (alreadyPrintedExports) { + source.add( + `${Template.toComment( + `${indent}... (${alreadyPrintedExports} already listed exports)` + )}\n` + ); + } + + if (showOtherExports) { + const target = otherExportsInfo.getTarget(moduleGraph); + if ( + target || + otherExportsInfo.provided !== false || + otherExportsInfo.getUsed(undefined) !== UsageState.Unused + ) { + const title = + printedExports.length > 0 || alreadyPrintedExports > 0 + ? "other exports" + : "exports"; + source.add( + `${Template.toComment( + `${indent}${title} [${otherExportsInfo.getProvidedInfo()}] [${otherExportsInfo.getUsedInfo()}]${ + target + ? ` -> ${target.module.readableIdentifier(requestShortener)}` + : "" + }` + )}\n` + ); + } + } +}; + +/** @type {WeakMap }>>} */ +const caches = new WeakMap(); + +const PLUGIN_NAME = "ModuleInfoHeaderPlugin"; + +class ModuleInfoHeaderPlugin { + /** + * @param {boolean=} verbose add more information like exports, runtime requirements and bailouts + */ + constructor(verbose = true) { + this._verbose = verbose; + } + + /** + * @param {Compiler} compiler the compiler + * @returns {void} + */ + apply(compiler) { + const { _verbose: verbose } = this; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const javascriptHooks = + JavascriptModulesPlugin.getCompilationHooks(compilation); + javascriptHooks.renderModulePackage.tap( + PLUGIN_NAME, + ( + moduleSource, + module, + { chunk, chunkGraph, moduleGraph, runtimeTemplate } + ) => { + const { requestShortener } = runtimeTemplate; + let cacheEntry; + let cache = caches.get(requestShortener); + if (cache === undefined) { + caches.set(requestShortener, (cache = new WeakMap())); + cache.set( + module, + (cacheEntry = { header: undefined, full: new WeakMap() }) + ); + } else { + cacheEntry = cache.get(module); + if (cacheEntry === undefined) { + cache.set( + module, + (cacheEntry = { header: undefined, full: new WeakMap() }) + ); + } else if (!verbose) { + const cachedSource = cacheEntry.full.get(moduleSource); + if (cachedSource !== undefined) return cachedSource; + } + } + const source = new ConcatSource(); + let header = cacheEntry.header; + if (header === undefined) { + header = this.generateHeader(module, requestShortener); + cacheEntry.header = header; + } + source.add(header); + if (verbose) { + const exportsType = /** @type {BuildMeta} */ (module.buildMeta) + .exportsType; + source.add( + `${Template.toComment( + exportsType + ? `${exportsType} exports` + : "unknown exports (runtime-defined)" + )}\n` + ); + if (exportsType) { + const exportsInfo = moduleGraph.getExportsInfo(module); + printExportsInfoToSource( + source, + "", + exportsInfo, + moduleGraph, + requestShortener + ); + } + source.add( + `${Template.toComment( + `runtime requirements: ${joinIterableWithComma( + chunkGraph.getModuleRuntimeRequirements(module, chunk.runtime) + )}` + )}\n` + ); + const optimizationBailout = + moduleGraph.getOptimizationBailout(module); + if (optimizationBailout) { + for (const text of optimizationBailout) { + const code = + typeof text === "function" ? text(requestShortener) : text; + source.add(`${Template.toComment(`${code}`)}\n`); + } + } + source.add(moduleSource); + return source; + } + source.add(moduleSource); + const cachedSource = new CachedSource(source); + cacheEntry.full.set(moduleSource, cachedSource); + return cachedSource; + } + ); + javascriptHooks.chunkHash.tap(PLUGIN_NAME, (_chunk, hash) => { + hash.update(PLUGIN_NAME); + hash.update("1"); + }); + const cssHooks = CssModulesPlugin.getCompilationHooks(compilation); + cssHooks.renderModulePackage.tap( + PLUGIN_NAME, + (moduleSource, module, { runtimeTemplate }) => { + const { requestShortener } = runtimeTemplate; + let cacheEntry; + let cache = caches.get(requestShortener); + if (cache === undefined) { + caches.set(requestShortener, (cache = new WeakMap())); + cache.set( + module, + (cacheEntry = { header: undefined, full: new WeakMap() }) + ); + } else { + cacheEntry = cache.get(module); + if (cacheEntry === undefined) { + cache.set( + module, + (cacheEntry = { header: undefined, full: new WeakMap() }) + ); + } else if (!verbose) { + const cachedSource = cacheEntry.full.get(moduleSource); + if (cachedSource !== undefined) return cachedSource; + } + } + const source = new ConcatSource(); + let header = cacheEntry.header; + if (header === undefined) { + header = this.generateHeader(module, requestShortener); + cacheEntry.header = header; + } + source.add(header); + source.add(moduleSource); + const cachedSource = new CachedSource(source); + cacheEntry.full.set(moduleSource, cachedSource); + return cachedSource; + } + ); + cssHooks.chunkHash.tap(PLUGIN_NAME, (_chunk, hash) => { + hash.update(PLUGIN_NAME); + hash.update("1"); + }); + }); + } + + /** + * @param {Module} module the module + * @param {RequestShortener} requestShortener request shortener + * @returns {RawSource} the header + */ + generateHeader(module, requestShortener) { + const req = module.readableIdentifier(requestShortener); + const reqStr = req.replace(/\*\//g, "*_/"); + const reqStrStar = "*".repeat(reqStr.length); + const headerStr = `/*!****${reqStrStar}****!*\\\n !*** ${reqStr} ***!\n \\****${reqStrStar}****/\n`; + return new RawSource(headerStr); + } +} + +module.exports = ModuleInfoHeaderPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleNotFoundError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleNotFoundError.js new file mode 100644 index 0000000000000000000000000000000000000000..6f86b76f17af31c8a22124b52d1535b47cbc8ee5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleNotFoundError.js @@ -0,0 +1,89 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ + +const previouslyPolyfilledBuiltinModules = { + assert: "assert/", + buffer: "buffer/", + console: "console-browserify", + constants: "constants-browserify", + crypto: "crypto-browserify", + domain: "domain-browser", + events: "events/", + http: "stream-http", + https: "https-browserify", + os: "os-browserify/browser", + path: "path-browserify", + punycode: "punycode/", + process: "process/browser", + querystring: "querystring-es3", + stream: "stream-browserify", + _stream_duplex: "readable-stream/duplex", + _stream_passthrough: "readable-stream/passthrough", + _stream_readable: "readable-stream/readable", + _stream_transform: "readable-stream/transform", + _stream_writable: "readable-stream/writable", + string_decoder: "string_decoder/", + sys: "util/", + timers: "timers-browserify", + tty: "tty-browserify", + url: "url/", + util: "util/", + vm: "vm-browserify", + zlib: "browserify-zlib" +}; + +class ModuleNotFoundError extends WebpackError { + /** + * @param {Module | null} module module tied to dependency + * @param {Error & { details?: string }} err error thrown + * @param {DependencyLocation} loc location of dependency + */ + constructor(module, err, loc) { + let message = `Module not found: ${err.toString()}`; + + // TODO remove in webpack 6 + const match = err.message.match(/Can't resolve '([^']+)'/); + if (match) { + const request = match[1]; + const alias = + previouslyPolyfilledBuiltinModules[ + /** @type {keyof previouslyPolyfilledBuiltinModules} */ (request) + ]; + if (alias) { + const pathIndex = alias.indexOf("/"); + const dependency = pathIndex > 0 ? alias.slice(0, pathIndex) : alias; + message += + "\n\n" + + "BREAKING CHANGE: " + + "webpack < 5 used to include polyfills for node.js core modules by default.\n" + + "This is no longer the case. Verify if you need this module and configure a polyfill for it.\n\n"; + message += + "If you want to include a polyfill, you need to:\n" + + `\t- add a fallback 'resolve.fallback: { "${request}": require.resolve("${alias}") }'\n` + + `\t- install '${dependency}'\n`; + message += + "If you don't want to include a polyfill, you can use an empty module like this:\n" + + `\tresolve.fallback: { "${request}": false }`; + } + } + + super(message); + + this.name = "ModuleNotFoundError"; + this.details = err.details; + this.module = module; + this.error = err; + this.loc = loc; + } +} + +module.exports = ModuleNotFoundError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleParseError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleParseError.js new file mode 100644 index 0000000000000000000000000000000000000000..54774bb579abc715031956288392b2fe7e020975 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleParseError.js @@ -0,0 +1,121 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +const WASM_HEADER = Buffer.from([0x00, 0x61, 0x73, 0x6d]); + +class ModuleParseError extends WebpackError { + /** + * @param {string | Buffer} source source code + * @param {Error & { loc?: SourcePosition }} err the parse error + * @param {string[]} loaders the loaders used + * @param {string} type module type + */ + constructor(source, err, loaders, type) { + let message = `Module parse failed: ${err && err.message}`; + let loc; + + if ( + ((Buffer.isBuffer(source) && source.slice(0, 4).equals(WASM_HEADER)) || + (typeof source === "string" && /^\0asm/.test(source))) && + !type.startsWith("webassembly") + ) { + message += + "\nThe module seem to be a WebAssembly module, but module is not flagged as WebAssembly module for webpack."; + message += + "\nBREAKING CHANGE: Since webpack 5 WebAssembly is not enabled by default and flagged as experimental feature."; + message += + "\nYou need to enable one of the WebAssembly experiments via 'experiments.asyncWebAssembly: true' (based on async modules) or 'experiments.syncWebAssembly: true' (like webpack 4, deprecated)."; + message += + "\nFor files that transpile to WebAssembly, make sure to set the module type in the 'module.rules' section of the config (e. g. 'type: \"webassembly/async\"')."; + } else if (!loaders) { + message += + "\nYou may need an appropriate loader to handle this file type."; + } else if (loaders.length >= 1) { + message += `\nFile was processed with these loaders:${loaders + .map((loader) => `\n * ${loader}`) + .join("")}`; + message += + "\nYou may need an additional loader to handle the result of these loaders."; + } else { + message += + "\nYou may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders"; + } + + if ( + err && + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + const lineNumber = err.loc.line; + + if ( + Buffer.isBuffer(source) || + // eslint-disable-next-line no-control-regex + /[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source) + ) { + // binary file + message += "\n(Source code omitted for this binary file)"; + } else { + const sourceLines = source.split(/\r?\n/); + const start = Math.max(0, lineNumber - 3); + const linesBefore = sourceLines.slice(start, lineNumber - 1); + const theLine = sourceLines[lineNumber - 1]; + const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2); + + message += `${linesBefore + .map((l) => `\n| ${l}`) + .join( + "" + )}\n> ${theLine}${linesAfter.map((l) => `\n| ${l}`).join("")}`; + } + + loc = { start: err.loc }; + } else if (err && err.stack) { + message += `\n${err.stack}`; + } + + super(message); + + this.name = "ModuleParseError"; + this.loc = loc; + this.error = err; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.error); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.error = read(); + + super.deserialize(context); + } +} + +makeSerializable(ModuleParseError, "webpack/lib/ModuleParseError"); + +module.exports = ModuleParseError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleProfile.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleProfile.js new file mode 100644 index 0000000000000000000000000000000000000000..360991ab0051cf6b3ce74931aa628da91c2c4d59 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleProfile.js @@ -0,0 +1,108 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +class ModuleProfile { + constructor() { + this.startTime = Date.now(); + + this.factoryStartTime = 0; + this.factoryEndTime = 0; + this.factory = 0; + this.factoryParallelismFactor = 0; + + this.restoringStartTime = 0; + this.restoringEndTime = 0; + this.restoring = 0; + this.restoringParallelismFactor = 0; + + this.integrationStartTime = 0; + this.integrationEndTime = 0; + this.integration = 0; + this.integrationParallelismFactor = 0; + + this.buildingStartTime = 0; + this.buildingEndTime = 0; + this.building = 0; + this.buildingParallelismFactor = 0; + + this.storingStartTime = 0; + this.storingEndTime = 0; + this.storing = 0; + this.storingParallelismFactor = 0; + + /** @type {{ start: number, end: number }[] | undefined } */ + this.additionalFactoryTimes = undefined; + this.additionalFactories = 0; + this.additionalFactoriesParallelismFactor = 0; + + /** @deprecated */ + this.additionalIntegration = 0; + } + + markFactoryStart() { + this.factoryStartTime = Date.now(); + } + + markFactoryEnd() { + this.factoryEndTime = Date.now(); + this.factory = this.factoryEndTime - this.factoryStartTime; + } + + markRestoringStart() { + this.restoringStartTime = Date.now(); + } + + markRestoringEnd() { + this.restoringEndTime = Date.now(); + this.restoring = this.restoringEndTime - this.restoringStartTime; + } + + markIntegrationStart() { + this.integrationStartTime = Date.now(); + } + + markIntegrationEnd() { + this.integrationEndTime = Date.now(); + this.integration = this.integrationEndTime - this.integrationStartTime; + } + + markBuildingStart() { + this.buildingStartTime = Date.now(); + } + + markBuildingEnd() { + this.buildingEndTime = Date.now(); + this.building = this.buildingEndTime - this.buildingStartTime; + } + + markStoringStart() { + this.storingStartTime = Date.now(); + } + + markStoringEnd() { + this.storingEndTime = Date.now(); + this.storing = this.storingEndTime - this.storingStartTime; + } + + // This depends on timing so we ignore it for coverage + /* istanbul ignore next */ + /** + * Merge this profile into another one + * @param {ModuleProfile} realProfile the profile to merge into + * @returns {void} + */ + mergeInto(realProfile) { + realProfile.additionalFactories = this.factory; + (realProfile.additionalFactoryTimes = + realProfile.additionalFactoryTimes || []).push({ + start: this.factoryStartTime, + end: this.factoryEndTime + }); + } +} + +module.exports = ModuleProfile; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleRestoreError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleRestoreError.js new file mode 100644 index 0000000000000000000000000000000000000000..2570862d42118c9787963dc66dfbb13044cd99d1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleRestoreError.js @@ -0,0 +1,44 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Module")} Module */ + +class ModuleRestoreError extends WebpackError { + /** + * @param {Module} module module tied to dependency + * @param {string | Error} err error thrown + */ + constructor(module, err) { + let message = "Module restore failed: "; + /** @type {string | undefined} */ + const details = undefined; + if (err !== null && typeof err === "object") { + if (typeof err.stack === "string" && err.stack) { + const stack = err.stack; + message += stack; + } else if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; + } + } else { + message += String(err); + } + + super(message); + + this.name = "ModuleRestoreError"; + /** @type {string | undefined} */ + this.details = details; + this.module = module; + this.error = err; + } +} + +module.exports = ModuleRestoreError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleSourceTypesConstants.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleSourceTypesConstants.js new file mode 100644 index 0000000000000000000000000000000000000000..d81fc8aa066a41b154a5770961f5c6597903fd44 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleSourceTypesConstants.js @@ -0,0 +1,123 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Alexander Akait @alexander-akait +*/ + +"use strict"; + +/** + * @type {ReadonlySet} + */ +const NO_TYPES = new Set(); + +/** + * @type {ReadonlySet<"asset">} + */ +const ASSET_TYPES = new Set(["asset"]); + +/** + * @type {ReadonlySet<"asset" | "javascript" | "asset">} + */ +const ASSET_AND_JS_TYPES = new Set(["asset", "javascript"]); + +/** + * @type {ReadonlySet<"css-url" | "asset">} + */ +const ASSET_AND_CSS_URL_TYPES = new Set(["asset", "css-url"]); + +/** + * @type {ReadonlySet<"javascript" | "css-url" | "asset">} + */ +const ASSET_AND_JS_AND_CSS_URL_TYPES = new Set([ + "asset", + "javascript", + "css-url" +]); + +/** + * @type {"javascript"} + */ +const JS_TYPE = "javascript"; + +/** + * @type {ReadonlySet<"javascript">} + */ +const JS_TYPES = new Set(["javascript"]); + +/** + * @type {ReadonlySet<"javascript" | "css-export">} + */ +const JS_AND_CSS_EXPORT_TYPES = new Set(["javascript", "css-export"]); + +/** + * @type {ReadonlySet<"javascript" | "css-url">} + */ +const JS_AND_CSS_URL_TYPES = new Set(["javascript", "css-url"]); + +/** + * @type {ReadonlySet<"javascript" | "css">} + */ +const JS_AND_CSS_TYPES = new Set(["javascript", "css"]); + +/** + * @type {"css"} + */ +const CSS_TYPE = "css"; +/** + * @type {ReadonlySet<"css">} + */ +const CSS_TYPES = new Set(["css"]); + +/** + * @type {ReadonlySet<"css-url">} + */ +const CSS_URL_TYPES = new Set(["css-url"]); +/** + * @type {ReadonlySet<"css-import">} + */ +const CSS_IMPORT_TYPES = new Set(["css-import"]); + +/** + * @type {ReadonlySet<"webassembly">} + */ +const WEBASSEMBLY_TYPES = new Set(["webassembly"]); + +/** + * @type {ReadonlySet<"runtime">} + */ +const RUNTIME_TYPES = new Set(["runtime"]); + +/** + * @type {ReadonlySet<"remote" | "share-init">} + */ +const REMOTE_AND_SHARE_INIT_TYPES = new Set(["remote", "share-init"]); + +/** + * @type {ReadonlySet<"consume-shared">} + */ +const CONSUME_SHARED_TYPES = new Set(["consume-shared"]); + +/** + * @type {ReadonlySet<"share-init">} + */ +const SHARED_INIT_TYPES = new Set(["share-init"]); + +module.exports.ASSET_AND_CSS_URL_TYPES = ASSET_AND_CSS_URL_TYPES; +module.exports.ASSET_AND_JS_AND_CSS_URL_TYPES = ASSET_AND_JS_AND_CSS_URL_TYPES; +module.exports.ASSET_AND_JS_TYPES = ASSET_AND_JS_TYPES; +module.exports.ASSET_TYPES = ASSET_TYPES; +module.exports.CONSUME_SHARED_TYPES = CONSUME_SHARED_TYPES; +module.exports.CSS_IMPORT_TYPES = CSS_IMPORT_TYPES; +module.exports.CSS_TYPE = CSS_TYPE; +module.exports.CSS_TYPES = CSS_TYPES; +module.exports.CSS_URL_TYPES = CSS_URL_TYPES; +module.exports.JS_AND_CSS_EXPORT_TYPES = JS_AND_CSS_EXPORT_TYPES; +module.exports.JS_AND_CSS_TYPES = JS_AND_CSS_TYPES; +module.exports.JS_AND_CSS_URL_TYPES = JS_AND_CSS_URL_TYPES; +module.exports.JS_TYPE = JS_TYPE; +module.exports.JS_TYPES = JS_TYPES; +module.exports.NO_TYPES = NO_TYPES; +module.exports.REMOTE_AND_SHARE_INIT_TYPES = REMOTE_AND_SHARE_INIT_TYPES; +module.exports.RUNTIME_TYPES = RUNTIME_TYPES; +module.exports.SHARED_INIT_TYPES = SHARED_INIT_TYPES; +module.exports.WEBASSEMBLY_TYPES = WEBASSEMBLY_TYPES; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleStoreError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleStoreError.js new file mode 100644 index 0000000000000000000000000000000000000000..26ca0c8b5d73ecae8d41610b716508d75f96bfee --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleStoreError.js @@ -0,0 +1,43 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Module")} Module */ + +class ModuleStoreError extends WebpackError { + /** + * @param {Module} module module tied to dependency + * @param {string | Error} err error thrown + */ + constructor(module, err) { + let message = "Module storing failed: "; + /** @type {string | undefined} */ + const details = undefined; + if (err !== null && typeof err === "object") { + if (typeof err.stack === "string" && err.stack) { + const stack = err.stack; + message += stack; + } else if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; + } + } else { + message += String(err); + } + + super(message); + + this.name = "ModuleStoreError"; + this.details = /** @type {string | undefined} */ (details); + this.module = module; + this.error = err; + } +} + +module.exports = ModuleStoreError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleTemplate.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleTemplate.js new file mode 100644 index 0000000000000000000000000000000000000000..4d2809307b11defac1c57c88c79cdf126415d00a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleTemplate.js @@ -0,0 +1,175 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const memoize = require("./util/memoize"); + +/** @typedef {import("tapable").Tap} Tap */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").ModuleRenderContext} ModuleRenderContext */ +/** @typedef {import("./util/Hash")} Hash */ + +/** + * @template T + * @typedef {import("tapable").IfSet} IfSet + */ + +const getJavascriptModulesPlugin = memoize(() => + require("./javascript/JavascriptModulesPlugin") +); + +// TODO webpack 6: remove this class +class ModuleTemplate { + /** + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Compilation} compilation the compilation + */ + constructor(runtimeTemplate, compilation) { + this._runtimeTemplate = runtimeTemplate; + this.type = "javascript"; + this.hooks = Object.freeze({ + content: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(source: Source, module: Module, moduleRenderContext: ModuleRenderContext, dependencyTemplates: DependencyTemplates) => Source} fn fn + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .renderModuleContent.tap( + options, + (source, module, renderContext) => + fn( + source, + module, + renderContext, + renderContext.dependencyTemplates + ) + ); + }, + "ModuleTemplate.hooks.content is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)", + "DEP_MODULE_TEMPLATE_CONTENT" + ) + }, + module: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(source: Source, module: Module, moduleRenderContext: ModuleRenderContext, dependencyTemplates: DependencyTemplates) => Source} fn fn + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .renderModuleContent.tap( + options, + (source, module, renderContext) => + fn( + source, + module, + renderContext, + renderContext.dependencyTemplates + ) + ); + }, + "ModuleTemplate.hooks.module is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)", + "DEP_MODULE_TEMPLATE_MODULE" + ) + }, + render: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(source: Source, module: Module, chunkRenderContext: ChunkRenderContext, dependencyTemplates: DependencyTemplates) => Source} fn fn + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .renderModuleContainer.tap( + options, + (source, module, renderContext) => + fn( + source, + module, + renderContext, + renderContext.dependencyTemplates + ) + ); + }, + "ModuleTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer instead)", + "DEP_MODULE_TEMPLATE_RENDER" + ) + }, + package: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(source: Source, module: Module, chunkRenderContext: ChunkRenderContext, dependencyTemplates: DependencyTemplates) => Source} fn fn + */ + (options, fn) => { + getJavascriptModulesPlugin() + .getCompilationHooks(compilation) + .renderModulePackage.tap( + options, + (source, module, renderContext) => + fn( + source, + module, + renderContext, + renderContext.dependencyTemplates + ) + ); + }, + "ModuleTemplate.hooks.package is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModulePackage instead)", + "DEP_MODULE_TEMPLATE_PACKAGE" + ) + }, + hash: { + tap: util.deprecate( + /** + * @template AdditionalOptions + * @param {string | Tap & IfSet} options options + * @param {(hash: Hash) => void} fn fn + */ + (options, fn) => { + compilation.hooks.fullHash.tap(options, fn); + }, + "ModuleTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)", + "DEP_MODULE_TEMPLATE_HASH" + ) + } + }); + } +} + +Object.defineProperty(ModuleTemplate.prototype, "runtimeTemplate", { + get: util.deprecate( + /** + * @this {ModuleTemplate} + * @returns {RuntimeTemplate} output options + */ + function runtimeTemplate() { + return this._runtimeTemplate; + }, + "ModuleTemplate.runtimeTemplate is deprecated (use Compilation.runtimeTemplate instead)", + "DEP_WEBPACK_CHUNK_TEMPLATE_OUTPUT_OPTIONS" + ) +}); + +module.exports = ModuleTemplate; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleTypeConstants.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleTypeConstants.js new file mode 100644 index 0000000000000000000000000000000000000000..484d6d86efbb4ec5c13c9ed4bdd35c7bfda91ec2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleTypeConstants.js @@ -0,0 +1,183 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @TheLarkInn +*/ + +"use strict"; + +/** + * @type {Readonly<"javascript/auto">} + */ +const JAVASCRIPT_MODULE_TYPE_AUTO = "javascript/auto"; + +/** + * @type {Readonly<"javascript/dynamic">} + */ +const JAVASCRIPT_MODULE_TYPE_DYNAMIC = "javascript/dynamic"; + +/** + * @type {Readonly<"javascript/esm">} + * This is the module type used for _strict_ ES Module syntax. This means that all legacy formats + * that webpack supports (CommonJS, AMD, SystemJS) are not supported. + */ +const JAVASCRIPT_MODULE_TYPE_ESM = "javascript/esm"; + +/** + * @type {Readonly<"json">} + * This is the module type used for JSON files. JSON files are always parsed as ES Module. + */ +const JSON_MODULE_TYPE = "json"; + +/** + * @type {Readonly<"webassembly/async">} + * This is the module type used for WebAssembly modules. In webpack 5 they are always treated as async modules. + */ +const WEBASSEMBLY_MODULE_TYPE_ASYNC = "webassembly/async"; + +/** + * @type {Readonly<"webassembly/sync">} + * This is the module type used for WebAssembly modules. In webpack 4 they are always treated as sync modules. + * There is a legacy option to support this usage in webpack 5 and up. + */ +const WEBASSEMBLY_MODULE_TYPE_SYNC = "webassembly/sync"; + +/** + * @type {Readonly<"css">} + * This is the module type used for CSS files. + */ +const CSS_MODULE_TYPE = "css"; + +/** + * @type {Readonly<"css/global">} + * This is the module type used for CSS modules files where you need to use `:local` in selector list to hash classes. + */ +const CSS_MODULE_TYPE_GLOBAL = "css/global"; + +/** + * @type {Readonly<"css/module">} + * This is the module type used for CSS modules files, by default all classes are hashed. + */ +const CSS_MODULE_TYPE_MODULE = "css/module"; + +/** + * @type {Readonly<"css/auto">} + * This is the module type used for CSS files, the module will be parsed as CSS modules if it's filename contains `.module.` or `.modules.`. + */ +const CSS_MODULE_TYPE_AUTO = "css/auto"; + +/** + * @type {Readonly<"asset">} + * This is the module type used for automatically choosing between `asset/inline`, `asset/resource` based on asset size limit (8096). + */ +const ASSET_MODULE_TYPE = "asset"; + +/** + * @type {Readonly<"asset/inline">} + * This is the module type used for assets that are inlined as a data URI. This is the equivalent of `url-loader`. + */ +const ASSET_MODULE_TYPE_INLINE = "asset/inline"; + +/** + * @type {Readonly<"asset/resource">} + * This is the module type used for assets that are copied to the output directory. This is the equivalent of `file-loader`. + */ +const ASSET_MODULE_TYPE_RESOURCE = "asset/resource"; + +/** + * @type {Readonly<"asset/source">} + * This is the module type used for assets that are imported as source code. This is the equivalent of `raw-loader`. + */ +const ASSET_MODULE_TYPE_SOURCE = "asset/source"; + +/** + * @type {Readonly<"asset/raw-data-url">} + * TODO: Document what this asset type is for. See css-loader tests for its usage. + */ +const ASSET_MODULE_TYPE_RAW_DATA_URL = "asset/raw-data-url"; + +/** + * @type {Readonly<"runtime">} + * This is the module type used for the webpack runtime abstractions. + */ +const WEBPACK_MODULE_TYPE_RUNTIME = "runtime"; + +/** + * @type {Readonly<"fallback-module">} + * This is the module type used for the ModuleFederation feature's FallbackModule class. + * TODO: Document this better. + */ +const WEBPACK_MODULE_TYPE_FALLBACK = "fallback-module"; + +/** + * @type {Readonly<"remote-module">} + * This is the module type used for the ModuleFederation feature's RemoteModule class. + * TODO: Document this better. + */ +const WEBPACK_MODULE_TYPE_REMOTE = "remote-module"; + +/** + * @type {Readonly<"provide-module">} + * This is the module type used for the ModuleFederation feature's ProvideModule class. + * TODO: Document this better. + */ +const WEBPACK_MODULE_TYPE_PROVIDE = "provide-module"; + +/** + * @type {Readonly<"consume-shared-module">} + * This is the module type used for the ModuleFederation feature's ConsumeSharedModule class. + */ +const WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE = "consume-shared-module"; + +/** + * @type {Readonly<"lazy-compilation-proxy">} + * Module type used for `experiments.lazyCompilation` feature. See `LazyCompilationPlugin` for more information. + */ +const WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY = "lazy-compilation-proxy"; + +/** @typedef {"javascript/auto" | "javascript/dynamic" | "javascript/esm"} JavaScriptModuleTypes */ +/** @typedef {"json"} JSONModuleType */ +/** @typedef {"webassembly/async" | "webassembly/sync"} WebAssemblyModuleTypes */ +/** @typedef {"css" | "css/global" | "css/module"} CSSModuleTypes */ +/** @typedef {"asset" | "asset/inline" | "asset/resource" | "asset/source" | "asset/raw-data-url"} AssetModuleTypes */ +/** @typedef {"runtime" | "fallback-module" | "remote-module" | "provide-module" | "consume-shared-module" | "lazy-compilation-proxy"} WebpackModuleTypes */ +/** @typedef {string} UnknownModuleTypes */ +/** @typedef {JavaScriptModuleTypes | JSONModuleType | WebAssemblyModuleTypes | CSSModuleTypes | AssetModuleTypes | WebpackModuleTypes | UnknownModuleTypes} ModuleTypes */ + +module.exports.ASSET_MODULE_TYPE = ASSET_MODULE_TYPE; +module.exports.ASSET_MODULE_TYPE_INLINE = ASSET_MODULE_TYPE_INLINE; +module.exports.ASSET_MODULE_TYPE_RAW_DATA_URL = ASSET_MODULE_TYPE_RAW_DATA_URL; +module.exports.ASSET_MODULE_TYPE_RESOURCE = ASSET_MODULE_TYPE_RESOURCE; +module.exports.ASSET_MODULE_TYPE_SOURCE = ASSET_MODULE_TYPE_SOURCE; +module.exports.CSS_MODULES = [ + CSS_MODULE_TYPE, + CSS_MODULE_TYPE_GLOBAL, + CSS_MODULE_TYPE_MODULE, + CSS_MODULE_TYPE_AUTO +]; +module.exports.CSS_MODULE_TYPE = CSS_MODULE_TYPE; +module.exports.CSS_MODULE_TYPE_AUTO = CSS_MODULE_TYPE_AUTO; +module.exports.CSS_MODULE_TYPE_GLOBAL = CSS_MODULE_TYPE_GLOBAL; +module.exports.CSS_MODULE_TYPE_MODULE = CSS_MODULE_TYPE_MODULE; +module.exports.JAVASCRIPT_MODULES = [ + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +]; +module.exports.JAVASCRIPT_MODULE_TYPE_AUTO = JAVASCRIPT_MODULE_TYPE_AUTO; +module.exports.JAVASCRIPT_MODULE_TYPE_DYNAMIC = JAVASCRIPT_MODULE_TYPE_DYNAMIC; +module.exports.JAVASCRIPT_MODULE_TYPE_ESM = JAVASCRIPT_MODULE_TYPE_ESM; +module.exports.JSON_MODULE_TYPE = JSON_MODULE_TYPE; +module.exports.WEBASSEMBLY_MODULES = [ + WEBASSEMBLY_MODULE_TYPE_SYNC, + WEBASSEMBLY_MODULE_TYPE_SYNC +]; +module.exports.WEBASSEMBLY_MODULE_TYPE_ASYNC = WEBASSEMBLY_MODULE_TYPE_ASYNC; +module.exports.WEBASSEMBLY_MODULE_TYPE_SYNC = WEBASSEMBLY_MODULE_TYPE_SYNC; +module.exports.WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE = + WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE; +module.exports.WEBPACK_MODULE_TYPE_FALLBACK = WEBPACK_MODULE_TYPE_FALLBACK; +module.exports.WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY = + WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY; +module.exports.WEBPACK_MODULE_TYPE_PROVIDE = WEBPACK_MODULE_TYPE_PROVIDE; +module.exports.WEBPACK_MODULE_TYPE_REMOTE = WEBPACK_MODULE_TYPE_REMOTE; +module.exports.WEBPACK_MODULE_TYPE_RUNTIME = WEBPACK_MODULE_TYPE_RUNTIME; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..9b45a9afdd071239ac9c167018e6253b765c5753 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ModuleWarning.js @@ -0,0 +1,66 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { cleanUp } = require("./ErrorHelpers"); +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class ModuleWarning extends WebpackError { + /** + * @param {Error} warning error thrown + * @param {{from?: string|null}} info additional info + */ + constructor(warning, { from = null } = {}) { + let message = "Module Warning"; + + message += from ? ` (from ${from}):\n` : ": "; + + if (warning && typeof warning === "object" && warning.message) { + message += warning.message; + } else if (warning) { + message += String(warning); + } + + super(message); + + this.name = "ModuleWarning"; + this.warning = warning; + this.details = + warning && typeof warning === "object" && warning.stack + ? cleanUp(warning.stack, this.message) + : undefined; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.warning); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.warning = read(); + + super.deserialize(context); + } +} + +makeSerializable(ModuleWarning, "webpack/lib/ModuleWarning"); + +module.exports = ModuleWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MultiCompiler.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MultiCompiler.js new file mode 100644 index 0000000000000000000000000000000000000000..3ab64e4affcc4dbec9ba86ab810dfc43788d17c4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MultiCompiler.js @@ -0,0 +1,666 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const asyncLib = require("neo-async"); +const { MultiHook, SyncHook } = require("tapable"); + +const ConcurrentCompilationError = require("./ConcurrentCompilationError"); +const MultiStats = require("./MultiStats"); +const MultiWatching = require("./MultiWatching"); +const WebpackError = require("./WebpackError"); +const ArrayQueue = require("./util/ArrayQueue"); + +/** @template T @typedef {import("tapable").AsyncSeriesHook} AsyncSeriesHook */ +/** @template T @template R @typedef {import("tapable").SyncBailHook} SyncBailHook */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Stats")} Stats */ +/** @typedef {import("./Watching")} Watching */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ +/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ + +/** + * @template T + * @callback Callback + * @param {Error | null} err + * @param {T=} result + */ + +/** + * @callback RunWithDependenciesHandler + * @param {Compiler} compiler + * @param {Callback} callback + */ + +/** + * @typedef {object} MultiCompilerOptions + * @property {number=} parallelism how many Compilers are allows to run at the same time in parallel + */ + +/** @typedef {ReadonlyArray & MultiCompilerOptions} MultiWebpackOptions */ + +const CLASS_NAME = "MultiCompiler"; + +module.exports = class MultiCompiler { + /** + * @param {Compiler[] | Record} compilers child compilers + * @param {MultiCompilerOptions} options options + */ + constructor(compilers, options) { + if (!Array.isArray(compilers)) { + /** @type {Compiler[]} */ + compilers = Object.keys(compilers).map((name) => { + /** @type {Record} */ + (compilers)[name].name = name; + return /** @type {Record} */ (compilers)[name]; + }); + } + + this.hooks = Object.freeze({ + /** @type {SyncHook<[MultiStats]>} */ + done: new SyncHook(["stats"]), + /** @type {MultiHook>} */ + invalid: new MultiHook(compilers.map((c) => c.hooks.invalid)), + /** @type {MultiHook>} */ + run: new MultiHook(compilers.map((c) => c.hooks.run)), + /** @type {SyncHook<[]>} */ + watchClose: new SyncHook([]), + /** @type {MultiHook>} */ + watchRun: new MultiHook(compilers.map((c) => c.hooks.watchRun)), + /** @type {MultiHook>} */ + infrastructureLog: new MultiHook( + compilers.map((c) => c.hooks.infrastructureLog) + ) + }); + this.compilers = compilers; + /** @type {MultiCompilerOptions} */ + this._options = { + parallelism: options.parallelism || Infinity + }; + /** @type {WeakMap} */ + this.dependencies = new WeakMap(); + this.running = false; + + /** @type {(Stats | null)[]} */ + const compilerStats = this.compilers.map(() => null); + let doneCompilers = 0; + for (let index = 0; index < this.compilers.length; index++) { + const compiler = this.compilers[index]; + const compilerIndex = index; + let compilerDone = false; + // eslint-disable-next-line no-loop-func + compiler.hooks.done.tap(CLASS_NAME, (stats) => { + if (!compilerDone) { + compilerDone = true; + doneCompilers++; + } + compilerStats[compilerIndex] = stats; + if (doneCompilers === this.compilers.length) { + this.hooks.done.call( + new MultiStats(/** @type {Stats[]} */ (compilerStats)) + ); + } + }); + // eslint-disable-next-line no-loop-func + compiler.hooks.invalid.tap(CLASS_NAME, () => { + if (compilerDone) { + compilerDone = false; + doneCompilers--; + } + }); + } + this._validateCompilersOptions(); + } + + _validateCompilersOptions() { + if (this.compilers.length < 2) return; + /** + * @param {Compiler} compiler compiler + * @param {WebpackError} warning warning + */ + const addWarning = (compiler, warning) => { + compiler.hooks.thisCompilation.tap(CLASS_NAME, (compilation) => { + compilation.warnings.push(warning); + }); + }; + const cacheNames = new Set(); + for (const compiler of this.compilers) { + if (compiler.options.cache && "name" in compiler.options.cache) { + const name = compiler.options.cache.name; + if (cacheNames.has(name)) { + addWarning( + compiler, + new WebpackError( + `${ + compiler.name + ? `Compiler with name "${compiler.name}" doesn't use unique cache name. ` + : "" + }Please set unique "cache.name" option. Name "${name}" already used.` + ) + ); + } else { + cacheNames.add(name); + } + } + } + } + + get options() { + return Object.assign( + this.compilers.map((c) => c.options), + this._options + ); + } + + get outputPath() { + let commonPath = this.compilers[0].outputPath; + for (const compiler of this.compilers) { + while ( + compiler.outputPath.indexOf(commonPath) !== 0 && + /[/\\]/.test(commonPath) + ) { + commonPath = commonPath.replace(/[/\\][^/\\]*$/, ""); + } + } + + if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/"; + return commonPath; + } + + get inputFileSystem() { + throw new Error("Cannot read inputFileSystem of a MultiCompiler"); + } + + /** + * @param {InputFileSystem} value the new input file system + */ + set inputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.inputFileSystem = value; + } + } + + get outputFileSystem() { + throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + } + + /** + * @param {OutputFileSystem} value the new output file system + */ + set outputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.outputFileSystem = value; + } + } + + get watchFileSystem() { + throw new Error("Cannot read watchFileSystem of a MultiCompiler"); + } + + /** + * @param {WatchFileSystem} value the new watch file system + */ + set watchFileSystem(value) { + for (const compiler of this.compilers) { + compiler.watchFileSystem = value; + } + } + + /** + * @param {IntermediateFileSystem} value the new intermediate file system + */ + set intermediateFileSystem(value) { + for (const compiler of this.compilers) { + compiler.intermediateFileSystem = value; + } + } + + get intermediateFileSystem() { + throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + } + + /** + * @param {string | (() => string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name + */ + getInfrastructureLogger(name) { + return this.compilers[0].getInfrastructureLogger(name); + } + + /** + * @param {Compiler} compiler the child compiler + * @param {string[]} dependencies its dependencies + * @returns {void} + */ + setDependencies(compiler, dependencies) { + this.dependencies.set(compiler, dependencies); + } + + /** + * @param {Callback} callback signals when the validation is complete + * @returns {boolean} true if the dependencies are valid + */ + validateDependencies(callback) { + /** @type {Set<{source: Compiler, target: Compiler}>} */ + const edges = new Set(); + /** @type {string[]} */ + const missing = []; + /** + * @param {Compiler} compiler compiler + * @returns {boolean} target was found + */ + const targetFound = (compiler) => { + for (const edge of edges) { + if (edge.target === compiler) { + return true; + } + } + return false; + }; + /** + * @param {{source: Compiler, target: Compiler}} e1 edge 1 + * @param {{source: Compiler, target: Compiler}} e2 edge 2 + * @returns {number} result + */ + const sortEdges = (e1, e2) => + /** @type {string} */ + (e1.source.name).localeCompare(/** @type {string} */ (e2.source.name)) || + /** @type {string} */ + (e1.target.name).localeCompare(/** @type {string} */ (e2.target.name)); + for (const source of this.compilers) { + const dependencies = this.dependencies.get(source); + if (dependencies) { + for (const dep of dependencies) { + const target = this.compilers.find((c) => c.name === dep); + if (!target) { + missing.push(dep); + } else { + edges.add({ + source, + target + }); + } + } + } + } + /** @type {string[]} */ + const errors = missing.map( + (m) => `Compiler dependency \`${m}\` not found.` + ); + const stack = this.compilers.filter((c) => !targetFound(c)); + while (stack.length > 0) { + const current = stack.pop(); + for (const edge of edges) { + if (edge.source === current) { + edges.delete(edge); + const target = edge.target; + if (!targetFound(target)) { + stack.push(target); + } + } + } + } + if (edges.size > 0) { + /** @type {string[]} */ + const lines = [...edges] + .sort(sortEdges) + .map((edge) => `${edge.source.name} -> ${edge.target.name}`); + lines.unshift("Circular dependency found in compiler dependencies."); + errors.unshift(lines.join("\n")); + } + if (errors.length > 0) { + const message = errors.join("\n"); + callback(new Error(message)); + return false; + } + return true; + } + + // TODO webpack 6 remove + /** + * @deprecated This method should have been private + * @param {Compiler[]} compilers the child compilers + * @param {RunWithDependenciesHandler} fn a handler to run for each compiler + * @param {Callback} callback the compiler's handler + * @returns {void} + */ + runWithDependencies(compilers, fn, callback) { + const fulfilledNames = new Set(); + let remainingCompilers = compilers; + /** + * @param {string} d dependency + * @returns {boolean} when dependency was fulfilled + */ + const isDependencyFulfilled = (d) => fulfilledNames.has(d); + /** + * @returns {Compiler[]} compilers + */ + const getReadyCompilers = () => { + const readyCompilers = []; + const list = remainingCompilers; + remainingCompilers = []; + for (const c of list) { + const dependencies = this.dependencies.get(c); + const ready = + !dependencies || dependencies.every(isDependencyFulfilled); + if (ready) { + readyCompilers.push(c); + } else { + remainingCompilers.push(c); + } + } + return readyCompilers; + }; + /** + * @param {Callback} callback callback + * @returns {void} + */ + const runCompilers = (callback) => { + if (remainingCompilers.length === 0) return callback(null); + asyncLib.map( + getReadyCompilers(), + (compiler, callback) => { + fn(compiler, (err) => { + if (err) return callback(err); + fulfilledNames.add(compiler.name); + runCompilers(callback); + }); + }, + (err, results) => { + callback(err, results); + } + ); + }; + runCompilers(callback); + } + + /** + * @template SetupResult + * @param {(compiler: Compiler, index: number, doneCallback: Callback, isBlocked: () => boolean, setChanged: () => void, setInvalid: () => void) => SetupResult} setup setup a single compiler + * @param {(compiler: Compiler, setupResult: SetupResult, callback: Callback) => void} run run/continue a single compiler + * @param {Callback} callback callback when all compilers are done, result includes Stats of all changed compilers + * @returns {SetupResult[]} result of setup + */ + _runGraph(setup, run, callback) { + /** @typedef {{ compiler: Compiler, setupResult: undefined | SetupResult, result: undefined | Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */ + + // State transitions for nodes: + // -> blocked (initial) + // blocked -> starting [running++] (when all parents done) + // queued -> starting [running++] (when processing the queue) + // starting -> running (when run has been called) + // running -> done [running--] (when compilation is done) + // done -> pending (when invalidated from file change) + // pending -> blocked [add to queue] (when invalidated from aggregated changes) + // done -> blocked [add to queue] (when invalidated, from parent invalidation) + // running -> running-outdated (when invalidated, either from change or parent invalidation) + // running-outdated -> blocked [running--] (when compilation is done) + + /** @type {Node[]} */ + const nodes = this.compilers.map((compiler) => ({ + compiler, + setupResult: undefined, + result: undefined, + state: "blocked", + children: [], + parents: [] + })); + /** @type {Map} */ + const compilerToNode = new Map(); + for (const node of nodes) { + compilerToNode.set(/** @type {string} */ (node.compiler.name), node); + } + for (const node of nodes) { + const dependencies = this.dependencies.get(node.compiler); + if (!dependencies) continue; + for (const dep of dependencies) { + const parent = /** @type {Node} */ (compilerToNode.get(dep)); + node.parents.push(parent); + parent.children.push(node); + } + } + /** @type {ArrayQueue} */ + const queue = new ArrayQueue(); + for (const node of nodes) { + if (node.parents.length === 0) { + node.state = "queued"; + queue.enqueue(node); + } + } + let errored = false; + let running = 0; + const parallelism = /** @type {number} */ (this._options.parallelism); + /** + * @param {Node} node node + * @param {(Error | null)=} err error + * @param {Stats=} stats result + * @returns {void} + */ + const nodeDone = (node, err, stats) => { + if (errored) return; + if (err) { + errored = true; + return asyncLib.each( + nodes, + (node, callback) => { + if (node.compiler.watching) { + node.compiler.watching.close(callback); + } else { + callback(); + } + }, + () => callback(err) + ); + } + node.result = stats; + running--; + if (node.state === "running") { + node.state = "done"; + for (const child of node.children) { + if (child.state === "blocked") queue.enqueue(child); + } + } else if (node.state === "running-outdated") { + node.state = "blocked"; + queue.enqueue(node); + } + processQueue(); + }; + /** + * @param {Node} node node + * @returns {void} + */ + const nodeInvalidFromParent = (node) => { + if (node.state === "done") { + node.state = "blocked"; + } else if (node.state === "running") { + node.state = "running-outdated"; + } + for (const child of node.children) { + nodeInvalidFromParent(child); + } + }; + /** + * @param {Node} node node + * @returns {void} + */ + const nodeInvalid = (node) => { + if (node.state === "done") { + node.state = "pending"; + } else if (node.state === "running") { + node.state = "running-outdated"; + } + for (const child of node.children) { + nodeInvalidFromParent(child); + } + }; + /** + * @param {Node} node node + * @returns {void} + */ + const nodeChange = (node) => { + nodeInvalid(node); + if (node.state === "pending") { + node.state = "blocked"; + } + if (node.state === "blocked") { + queue.enqueue(node); + processQueue(); + } + }; + + /** @type {SetupResult[]} */ + const setupResults = []; + for (const [i, node] of nodes.entries()) { + setupResults.push( + (node.setupResult = setup( + node.compiler, + i, + nodeDone.bind(null, node), + () => node.state !== "starting" && node.state !== "running", + () => nodeChange(node), + () => nodeInvalid(node) + )) + ); + } + let processing = true; + const processQueue = () => { + if (processing) return; + processing = true; + process.nextTick(processQueueWorker); + }; + const processQueueWorker = () => { + // eslint-disable-next-line no-unmodified-loop-condition + while (running < parallelism && queue.length > 0 && !errored) { + const node = /** @type {Node} */ (queue.dequeue()); + if ( + node.state === "queued" || + (node.state === "blocked" && + node.parents.every((p) => p.state === "done")) + ) { + running++; + node.state = "starting"; + run( + node.compiler, + /** @type {SetupResult} */ (node.setupResult), + nodeDone.bind(null, node) + ); + node.state = "running"; + } + } + processing = false; + if ( + !errored && + running === 0 && + nodes.every((node) => node.state === "done") + ) { + const stats = []; + for (const node of nodes) { + const result = node.result; + if (result) { + node.result = undefined; + stats.push(result); + } + } + if (stats.length > 0) { + callback(null, new MultiStats(stats)); + } + } + }; + processQueueWorker(); + return setupResults; + } + + /** + * @param {WatchOptions | WatchOptions[]} watchOptions the watcher's options + * @param {Callback} handler signals when the call finishes + * @returns {MultiWatching} a compiler watcher + */ + watch(watchOptions, handler) { + if (this.running) { + return handler(new ConcurrentCompilationError()); + } + this.running = true; + + if (this.validateDependencies(handler)) { + const watchings = this._runGraph( + (compiler, idx, callback, isBlocked, setChanged, setInvalid) => { + const watching = compiler.watch( + Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions, + callback + ); + if (watching) { + watching._onInvalid = setInvalid; + watching._onChange = setChanged; + watching._isBlocked = isBlocked; + } + return watching; + }, + (compiler, watching, _callback) => { + if (compiler.watching !== watching) return; + if (!watching.running) watching.invalidate(); + }, + handler + ); + return new MultiWatching(watchings, this); + } + + return new MultiWatching([], this); + } + + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); + } + this.running = true; + + if (this.validateDependencies(callback)) { + this._runGraph( + () => {}, + (compiler, setupResult, callback) => compiler.run(callback), + (err, stats) => { + this.running = false; + + if (callback !== undefined) { + return callback(err, stats); + } + } + ); + } + } + + purgeInputFileSystem() { + for (const compiler of this.compilers) { + if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { + compiler.inputFileSystem.purge(); + } + } + } + + /** + * @param {Callback} callback signals when the compiler closes + * @returns {void} + */ + close(callback) { + asyncLib.each( + this.compilers, + (compiler, callback) => { + compiler.close(callback); + }, + (error) => { + callback(error); + } + ); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MultiStats.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MultiStats.js new file mode 100644 index 0000000000000000000000000000000000000000..62504ab823459031ce08cc70f9956ded618b1fa8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MultiStats.js @@ -0,0 +1,213 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const identifierUtils = require("./util/identifier"); + +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("./Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */ +/** @typedef {import("./Compilation").NormalizedStatsOptions} NormalizedStatsOptions */ +/** @typedef {import("./Stats")} Stats */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").KnownStatsCompilation} KnownStatsCompilation */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ + +/** + * @param {string} str string + * @param {string} prefix pref + * @returns {string} indent + */ +const indent = (str, prefix) => { + const rem = str.replace(/\n([^\n])/g, `\n${prefix}$1`); + return prefix + rem; +}; + +/** @typedef {undefined | string | boolean | StatsOptions} ChildrenStatsOptions */ +/** @typedef {Omit & { children?: ChildrenStatsOptions | ChildrenStatsOptions[] }} MultiStatsOptions */ +/** @typedef {{ version: boolean, hash: boolean, errorsCount: boolean, warningsCount: boolean, errors: boolean, warnings: boolean, children: NormalizedStatsOptions[] }} ChildOptions */ + +class MultiStats { + /** + * @param {Stats[]} stats the child stats + */ + constructor(stats) { + this.stats = stats; + } + + get hash() { + return this.stats.map((stat) => stat.hash).join(""); + } + + /** + * @returns {boolean} true if a child compilation encountered an error + */ + hasErrors() { + return this.stats.some((stat) => stat.hasErrors()); + } + + /** + * @returns {boolean} true if a child compilation had a warning + */ + hasWarnings() { + return this.stats.some((stat) => stat.hasWarnings()); + } + + /** + * @param {undefined | string | boolean | MultiStatsOptions} options stats options + * @param {CreateStatsOptionsContext} context context + * @returns {ChildOptions} context context + */ + _createChildOptions(options, context) { + const getCreateStatsOptions = () => { + if (!options) { + options = {}; + } + + const { children: childrenOptions = undefined, ...baseOptions } = + typeof options === "string" + ? { preset: options } + : /** @type {StatsOptions} */ (options); + + return { childrenOptions, baseOptions }; + }; + + const children = this.stats.map((stat, idx) => { + if (typeof options === "boolean") { + return stat.compilation.createStatsOptions(options, context); + } + const { childrenOptions, baseOptions } = getCreateStatsOptions(); + const childOptions = Array.isArray(childrenOptions) + ? childrenOptions[idx] + : childrenOptions; + if (typeof childOptions === "boolean") { + return stat.compilation.createStatsOptions(childOptions, context); + } + return stat.compilation.createStatsOptions( + { + ...baseOptions, + ...(typeof childOptions === "string" + ? { preset: childOptions } + : childOptions && typeof childOptions === "object" + ? childOptions + : undefined) + }, + context + ); + }); + return { + version: children.every((o) => o.version), + hash: children.every((o) => o.hash), + errorsCount: children.every((o) => o.errorsCount), + warningsCount: children.every((o) => o.warningsCount), + errors: children.every((o) => o.errors), + warnings: children.every((o) => o.warnings), + children + }; + } + + /** + * @param {(string | boolean | MultiStatsOptions)=} options stats options + * @returns {StatsCompilation} json output + */ + toJson(options) { + const childOptions = this._createChildOptions(options, { + forToString: false + }); + /** @type {KnownStatsCompilation} */ + const obj = {}; + obj.children = this.stats.map((stat, idx) => { + const obj = stat.toJson(childOptions.children[idx]); + const compilationName = stat.compilation.name; + const name = + compilationName && + identifierUtils.makePathsRelative( + stat.compilation.compiler.context, + compilationName, + stat.compilation.compiler.root + ); + obj.name = name; + return obj; + }); + if (childOptions.version) { + obj.version = obj.children[0].version; + } + if (childOptions.hash) { + obj.hash = obj.children.map((j) => j.hash).join(""); + } + /** + * @param {StatsCompilation} j stats error + * @param {StatsError} obj Stats error + * @returns {StatsError} result + */ + const mapError = (j, obj) => ({ + ...obj, + compilerPath: obj.compilerPath ? `${j.name}.${obj.compilerPath}` : j.name + }); + if (childOptions.errors) { + obj.errors = []; + for (const j of obj.children) { + const errors = + /** @type {NonNullable} */ + (j.errors); + for (const i of errors) { + obj.errors.push(mapError(j, i)); + } + } + } + if (childOptions.warnings) { + obj.warnings = []; + for (const j of obj.children) { + const warnings = + /** @type {NonNullable} */ + (j.warnings); + for (const i of warnings) { + obj.warnings.push(mapError(j, i)); + } + } + } + if (childOptions.errorsCount) { + obj.errorsCount = 0; + for (const j of obj.children) { + obj.errorsCount += /** @type {number} */ (j.errorsCount); + } + } + if (childOptions.warningsCount) { + obj.warningsCount = 0; + for (const j of obj.children) { + obj.warningsCount += /** @type {number} */ (j.warningsCount); + } + } + return obj; + } + + /** + * @param {(string | boolean | MultiStatsOptions)=} options stats options + * @returns {string} string output + */ + toString(options) { + const childOptions = this._createChildOptions(options, { + forToString: true + }); + const results = this.stats.map((stat, idx) => { + const str = stat.toString(childOptions.children[idx]); + const compilationName = stat.compilation.name; + const name = + compilationName && + identifierUtils + .makePathsRelative( + stat.compilation.compiler.context, + compilationName, + stat.compilation.compiler.root + ) + .replace(/\|/g, " "); + if (!str) return str; + return name ? `${name}:\n${indent(str, " ")}` : str; + }); + return results.filter(Boolean).join("\n\n"); + } +} + +module.exports = MultiStats; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MultiWatching.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MultiWatching.js new file mode 100644 index 0000000000000000000000000000000000000000..448ac96206a6292b8ae7842ab04b1dd7c7d81e12 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/MultiWatching.js @@ -0,0 +1,81 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const asyncLib = require("neo-async"); + +/** @typedef {import("./MultiCompiler")} MultiCompiler */ +/** @typedef {import("./Watching")} Watching */ + +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result + */ + +class MultiWatching { + /** + * @param {Watching[]} watchings child compilers' watchers + * @param {MultiCompiler} compiler the compiler + */ + constructor(watchings, compiler) { + this.watchings = watchings; + this.compiler = compiler; + } + + /** + * @param {Callback=} callback signals when the build has completed again + * @returns {void} + */ + invalidate(callback) { + if (callback) { + asyncLib.each( + this.watchings, + (watching, callback) => watching.invalidate(callback), + callback + ); + } else { + for (const watching of this.watchings) { + watching.invalidate(); + } + } + } + + suspend() { + for (const watching of this.watchings) { + watching.suspend(); + } + } + + resume() { + for (const watching of this.watchings) { + watching.resume(); + } + } + + /** + * @param {Callback} callback signals when the watcher is closed + * @returns {void} + */ + close(callback) { + asyncLib.each( + this.watchings, + (watching, finishedCallback) => { + watching.close(finishedCallback); + }, + (err) => { + this.compiler.hooks.watchClose.call(); + if (typeof callback === "function") { + this.compiler.running = false; + callback(err); + } + } + ); + } +} + +module.exports = MultiWatching; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NoEmitOnErrorsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NoEmitOnErrorsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f0a7f00332fa0cb639577bfdf77a8c5b81fce2cf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NoEmitOnErrorsPlugin.js @@ -0,0 +1,30 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Compiler")} Compiler */ + +const PLUGIN_NAME = "NoEmitOnErrorsPlugin"; + +class NoEmitOnErrorsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.shouldEmit.tap(PLUGIN_NAME, (compilation) => { + if (compilation.getStats().hasErrors()) return false; + }); + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.shouldRecord.tap(PLUGIN_NAME, () => { + if (compilation.getStats().hasErrors()) return false; + }); + }); + } +} + +module.exports = NoEmitOnErrorsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NoModeWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NoModeWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..fdd3fadf9c6de4dc704cc408931b2ccd8437ffef --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NoModeWarning.js @@ -0,0 +1,22 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +module.exports = class NoModeWarning extends WebpackError { + constructor() { + super(); + + this.name = "NoModeWarning"; + this.message = + "configuration\n" + + "The 'mode' option has not been set, webpack will fallback to 'production' for this value.\n" + + "Set 'mode' option to 'development' or 'production' to enable defaults for each environment.\n" + + "You can also set it to 'none' to disable any default behavior. " + + "Learn more: https://webpack.js.org/configuration/mode/"; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NodeStuffInWebError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NodeStuffInWebError.js new file mode 100644 index 0000000000000000000000000000000000000000..02b048ec4fd8a58b36d19ce11ac6f9ca63c04140 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NodeStuffInWebError.js @@ -0,0 +1,34 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + +class NodeStuffInWebError extends WebpackError { + /** + * @param {DependencyLocation} loc loc + * @param {string} expression expression + * @param {string} description description + */ + constructor(loc, expression, description) { + super( + `${JSON.stringify( + expression + )} has been used, it will be undefined in next major version. +${description}` + ); + + this.name = "NodeStuffInWebError"; + this.loc = loc; + } +} + +makeSerializable(NodeStuffInWebError, "webpack/lib/NodeStuffInWebError"); + +module.exports = NodeStuffInWebError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NodeStuffPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NodeStuffPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..6cd44b8d53f5303bf5b09560e28c2a03f5b0d5aa --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NodeStuffPlugin.js @@ -0,0 +1,287 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC +} = require("./ModuleTypeConstants"); +const NodeStuffInWebError = require("./NodeStuffInWebError"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const CachedConstDependency = require("./dependencies/CachedConstDependency"); +const ConstDependency = require("./dependencies/ConstDependency"); +const ExternalModuleDependency = require("./dependencies/ExternalModuleDependency"); +const { + evaluateToString, + expressionIsUnsupported +} = require("./javascript/JavascriptParserHelpers"); +const { relative } = require("./util/fs"); +const { parseResource } = require("./util/identifier"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../declarations/WebpackOptions").NodeOptions} NodeOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./NormalModule")} NormalModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +const PLUGIN_NAME = "NodeStuffPlugin"; + +class NodeStuffPlugin { + /** + * @param {NodeOptions} options options + */ + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ExternalModuleDependency, + new ExternalModuleDependency.Template() + ); + + /** + * @param {JavascriptParser} parser the parser + * @param {JavascriptParserOptions} parserOptions options + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; + + let localOptions = options; + if (parserOptions.node) { + localOptions = { ...localOptions, ...parserOptions.node }; + } + + if (localOptions.global !== false) { + const withWarning = localOptions.global === "warn"; + parser.hooks.expression.for("global").tap(PLUGIN_NAME, (expr) => { + const dep = new ConstDependency( + RuntimeGlobals.global, + /** @type {Range} */ (expr.range), + [RuntimeGlobals.global] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + + // TODO webpack 6 remove + if (withWarning) { + parser.state.module.addWarning( + new NodeStuffInWebError( + dep.loc, + "global", + "The global namespace object is a Node.js feature and isn't available in browsers." + ) + ); + } + }); + parser.hooks.rename.for("global").tap(PLUGIN_NAME, (expr) => { + const dep = new ConstDependency( + RuntimeGlobals.global, + /** @type {Range} */ (expr.range), + [RuntimeGlobals.global] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return false; + }); + } + + /** + * @param {string} expressionName expression name + * @param {(module: NormalModule) => string} fn function + * @param {string=} warning warning + * @returns {void} + */ + const setModuleConstant = (expressionName, fn, warning) => { + parser.hooks.expression + .for(expressionName) + .tap(PLUGIN_NAME, (expr) => { + const dep = new CachedConstDependency( + JSON.stringify(fn(parser.state.module)), + /** @type {Range} */ + (expr.range), + expressionName + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + + // TODO webpack 6 remove + if (warning) { + parser.state.module.addWarning( + new NodeStuffInWebError(dep.loc, expressionName, warning) + ); + } + + return true; + }); + }; + + /** + * @param {string} expressionName expression name + * @param {(value: string) => string} fn function + * @returns {void} + */ + const setUrlModuleConstant = (expressionName, fn) => { + parser.hooks.expression + .for(expressionName) + .tap(PLUGIN_NAME, (expr) => { + const dep = new ExternalModuleDependency( + "url", + [ + { + name: "fileURLToPath", + value: "__webpack_fileURLToPath__" + } + ], + undefined, + fn("__webpack_fileURLToPath__"), + /** @type {Range} */ (expr.range), + expressionName + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + + return true; + }); + }; + + /** + * @param {string} expressionName expression name + * @param {string} value value + * @param {string=} warning warning + * @returns {void} + */ + const setConstant = (expressionName, value, warning) => + setModuleConstant(expressionName, () => value, warning); + + const context = compiler.context; + if (localOptions.__filename) { + switch (localOptions.__filename) { + case "mock": + setConstant("__filename", "/index.js"); + break; + case "warn-mock": + setConstant( + "__filename", + "/index.js", + "__filename is a Node.js feature and isn't available in browsers." + ); + break; + case "node-module": { + const importMetaName = + /** @type {string} */ + (compilation.outputOptions.importMetaName); + + setUrlModuleConstant( + "__filename", + (functionName) => `${functionName}(${importMetaName}.url)` + ); + break; + } + case true: + setModuleConstant("__filename", (module) => + relative( + /** @type {InputFileSystem} */ (compiler.inputFileSystem), + context, + module.resource + ) + ); + break; + } + + parser.hooks.evaluateIdentifier + .for("__filename") + .tap(PLUGIN_NAME, (expr) => { + if (!parser.state.module) return; + const resource = parseResource(parser.state.module.resource); + return evaluateToString(resource.path)(expr); + }); + } + if (localOptions.__dirname) { + switch (localOptions.__dirname) { + case "mock": + setConstant("__dirname", "/"); + break; + case "warn-mock": + setConstant( + "__dirname", + "/", + "__dirname is a Node.js feature and isn't available in browsers." + ); + break; + case "node-module": { + const importMetaName = + /** @type {string} */ + (compilation.outputOptions.importMetaName); + + setUrlModuleConstant( + "__dirname", + (functionName) => + `${functionName}(${importMetaName}.url + "/..").slice(0, -1)` + ); + break; + } + case true: + setModuleConstant("__dirname", (module) => + relative( + /** @type {InputFileSystem} */ (compiler.inputFileSystem), + context, + /** @type {string} */ (module.context) + ) + ); + break; + } + + parser.hooks.evaluateIdentifier + .for("__dirname") + .tap(PLUGIN_NAME, (expr) => { + if (!parser.state.module) return; + return evaluateToString( + /** @type {string} */ + (parser.state.module.context) + )(expr); + }); + } + parser.hooks.expression + .for("require.extensions") + .tap( + PLUGIN_NAME, + expressionIsUnsupported( + parser, + "require.extensions is not supported by webpack. Use a loader instead." + ) + ); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = NodeStuffPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NormalModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NormalModule.js new file mode 100644 index 0000000000000000000000000000000000000000..f9d4c2d95de67aaa0ecfa8c74036f279b90ad7a6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NormalModule.js @@ -0,0 +1,1715 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const querystring = require("querystring"); +const parseJson = require("json-parse-even-better-errors"); +const { getContext, runLoaders } = require("loader-runner"); +const { + AsyncSeriesBailHook, + HookMap, + SyncHook, + SyncWaterfallHook +} = require("tapable"); +const { + CachedSource, + OriginalSource, + RawSource, + SourceMapSource +} = require("webpack-sources"); +const Compilation = require("./Compilation"); +const HookWebpackError = require("./HookWebpackError"); +const Module = require("./Module"); +const ModuleBuildError = require("./ModuleBuildError"); +const ModuleError = require("./ModuleError"); +const ModuleGraphConnection = require("./ModuleGraphConnection"); +const ModuleParseError = require("./ModuleParseError"); +const { JAVASCRIPT_MODULE_TYPE_AUTO } = require("./ModuleTypeConstants"); +const ModuleWarning = require("./ModuleWarning"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const UnhandledSchemeError = require("./UnhandledSchemeError"); +const WebpackError = require("./WebpackError"); +const formatLocation = require("./formatLocation"); +const LazySet = require("./util/LazySet"); +const { isSubset } = require("./util/SetHelpers"); +const { getScheme } = require("./util/URLAbsoluteSpecifier"); +const { + compareLocations, + compareSelect, + concatComparators, + keepOriginalOrder, + sortWithSourceOrder +} = require("./util/comparators"); +const createHash = require("./util/createHash"); +const { createFakeHook } = require("./util/deprecation"); +const { join } = require("./util/fs"); +const { + absolutify, + contextify, + makePathsRelative +} = require("./util/identifier"); +const makeSerializable = require("./util/makeSerializable"); +const memoize = require("./util/memoize"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("webpack-sources").RawSourceMap} RawSourceMap */ +/** @typedef {import("../declarations/WebpackOptions").Mode} Mode */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../declarations/WebpackOptions").NoParse} NoParse */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator")} Generator */ +/** @typedef {import("./Generator").GenerateErrorFn} GenerateErrorFn */ +/** @typedef {import("./Generator").GenerateContextData} GenerateContextData */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ +/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("./Module").KnownBuildInfo} KnownBuildInfo */ +/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("./Module").BuildCallback} BuildCallback */ +/** @typedef {import("./Generator").SourceTypes} SourceTypes */ +/** @typedef {import("./Module").UnsafeCacheData} UnsafeCacheData */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./NormalModuleFactory").ResourceDataWithData} ResourceDataWithData */ +/** @typedef {import("./NormalModuleFactory").ResourceSchemeData} ResourceSchemeData */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {import("./Parser").PreparsedAst} PreparsedAst */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./ResolverFactory").ResolveRequest} ResolveRequest */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./logging/Logger").Logger} WebpackLogger */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ +/** @typedef {import("./dependencies/HarmonyImportSideEffectDependency")} HarmonyImportSideEffectDependency */ +/** @typedef {import("./dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */ +/** + * @template T + * @typedef {import("./util/deprecation").FakeHook} FakeHook + */ + +/** @typedef {{ [k: string]: EXPECTED_ANY }} ParserOptions */ +/** @typedef {{ [k: string]: EXPECTED_ANY }} GeneratorOptions */ + +/** + * @template T + * @typedef {import("../declarations/LoaderContext").LoaderContext} LoaderContext + */ + +/** + * @template T + * @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext} NormalModuleLoaderContext + */ + +const getInvalidDependenciesModuleWarning = memoize(() => + require("./InvalidDependenciesModuleWarning") +); +const getValidate = memoize(() => require("schema-utils").validate); + +const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/; + +/** + * @typedef {object} LoaderItem + * @property {string} loader + * @property {string | null | undefined | Record} options + * @property {string?} ident + * @property {string?} type + */ + +/** + * @param {string} context absolute context path + * @param {string} source a source path + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} new source path + */ +const contextifySourceUrl = (context, source, associatedObjectForCache) => { + if (source.startsWith("webpack://")) return source; + return `webpack://${makePathsRelative( + context, + source, + associatedObjectForCache + )}`; +}; + +/** + * @param {string} context absolute context path + * @param {string | RawSourceMap} sourceMap a source map + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached + * @returns {string | RawSourceMap} new source map + */ +const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => { + if (typeof sourceMap === "string" || !Array.isArray(sourceMap.sources)) { + return sourceMap; + } + const { sourceRoot } = sourceMap; + /** @type {(source: string) => string} */ + const mapper = !sourceRoot + ? (source) => source + : sourceRoot.endsWith("/") + ? (source) => + source.startsWith("/") + ? `${sourceRoot.slice(0, -1)}${source}` + : `${sourceRoot}${source}` + : (source) => + source.startsWith("/") + ? `${sourceRoot}${source}` + : `${sourceRoot}/${source}`; + const newSources = sourceMap.sources.map((source) => + contextifySourceUrl(context, mapper(source), associatedObjectForCache) + ); + return { + ...sourceMap, + file: "x", + sourceRoot: undefined, + sources: newSources + }; +}; + +/** + * @param {string | Buffer} input the input + * @returns {string} the converted string + */ +const asString = (input) => { + if (Buffer.isBuffer(input)) { + return input.toString("utf8"); + } + return input; +}; + +/** + * @param {string | Buffer} input the input + * @returns {Buffer} the converted buffer + */ +const asBuffer = (input) => { + if (!Buffer.isBuffer(input)) { + return Buffer.from(input, "utf8"); + } + return input; +}; + +class NonErrorEmittedError extends WebpackError { + /** + * @param {EXPECTED_ANY} error value which is not an instance of Error + */ + constructor(error) { + super(); + + this.name = "NonErrorEmittedError"; + this.message = `(Emitted value instead of an instance of Error) ${error}`; + } +} + +makeSerializable( + NonErrorEmittedError, + "webpack/lib/NormalModule", + "NonErrorEmittedError" +); + +/** @typedef {[string | Buffer, string | RawSourceMap | undefined, PreparsedAst | undefined]} Result */ + +/** + * @typedef {object} NormalModuleCompilationHooks + * @property {SyncHook<[LoaderContext, NormalModule]>} loader + * @property {SyncHook<[LoaderItem[], NormalModule, LoaderContext]>} beforeLoaders + * @property {SyncHook<[NormalModule]>} beforeParse + * @property {SyncHook<[NormalModule]>} beforeSnapshot + * @property {HookMap>>} readResourceForScheme + * @property {HookMap], string | Buffer | null>>} readResource + * @property {SyncWaterfallHook<[Result, NormalModule]>} processResult + * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild + */ + +/** + * @typedef {object} NormalModuleCreateData + * @property {string=} layer an optional layer in which the module is + * @property {ModuleTypes | ""} type module type. When deserializing, this is set to an empty string "". + * @property {string} request request string + * @property {string} userRequest request intended by user (without loaders from config) + * @property {string} rawRequest request without resolving + * @property {LoaderItem[]} loaders list of loaders + * @property {string} resource path + query of the real resource + * @property {(ResourceSchemeData & Partial)=} resourceResolveData resource resolve data + * @property {string} context context directory for resolving + * @property {string=} matchResource path + query of the matched resource (virtual) + * @property {Parser} parser the parser used + * @property {ParserOptions=} parserOptions the options of the parser used + * @property {Generator} generator the generator used + * @property {GeneratorOptions=} generatorOptions the options of the generator used + * @property {ResolveOptions=} resolveOptions options used for resolving requests from this module + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class NormalModule extends Module { + /** + * @param {Compilation} compilation the compilation + * @returns {NormalModuleCompilationHooks} the attached hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + loader: new SyncHook(["loaderContext", "module"]), + beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]), + beforeParse: new SyncHook(["module"]), + beforeSnapshot: new SyncHook(["module"]), + // TODO webpack 6 deprecate + readResourceForScheme: new HookMap((scheme) => { + const hook = + /** @type {NormalModuleCompilationHooks} */ + (hooks).readResource.for(scheme); + return createFakeHook( + /** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>} */ ({ + tap: (options, fn) => + hook.tap(options, (loaderContext) => + fn( + loaderContext.resource, + /** @type {NormalModule} */ (loaderContext._module) + ) + ), + tapAsync: (options, fn) => + hook.tapAsync(options, (loaderContext, callback) => + fn( + loaderContext.resource, + /** @type {NormalModule} */ (loaderContext._module), + callback + ) + ), + tapPromise: (options, fn) => + hook.tapPromise(options, (loaderContext) => + fn( + loaderContext.resource, + /** @type {NormalModule} */ (loaderContext._module) + ) + ) + }) + ); + }), + readResource: new HookMap( + () => new AsyncSeriesBailHook(["loaderContext"]) + ), + processResult: new SyncWaterfallHook(["result", "module"]), + needBuild: new AsyncSeriesBailHook(["module", "context"]) + }; + compilationHooksMap.set( + compilation, + /** @type {NormalModuleCompilationHooks} */ (hooks) + ); + } + return /** @type {NormalModuleCompilationHooks} */ (hooks); + } + + /** + * @param {NormalModuleCreateData} options options object + */ + constructor({ + layer, + type, + request, + userRequest, + rawRequest, + loaders, + resource, + resourceResolveData, + context, + matchResource, + parser, + parserOptions, + generator, + generatorOptions, + resolveOptions + }) { + super(type, context || getContext(resource), layer); + + // Info from Factory + /** @type {string} */ + this.request = request; + /** @type {string} */ + this.userRequest = userRequest; + /** @type {string} */ + this.rawRequest = rawRequest; + /** @type {boolean} */ + this.binary = /^(asset|webassembly)\b/.test(type); + /** @type {undefined | Parser} */ + this.parser = parser; + /** @type {undefined | ParserOptions} */ + this.parserOptions = parserOptions; + /** @type {undefined | Generator} */ + this.generator = generator; + /** @type {undefined | GeneratorOptions} */ + this.generatorOptions = generatorOptions; + /** @type {string} */ + this.resource = resource; + this.resourceResolveData = resourceResolveData; + /** @type {string | undefined} */ + this.matchResource = matchResource; + /** @type {LoaderItem[]} */ + this.loaders = loaders; + if (resolveOptions !== undefined) { + // already declared in super class + this.resolveOptions = resolveOptions; + } + + // Info from Build + /** @type {WebpackError | null} */ + this.error = null; + /** + * @private + * @type {Source | null} + */ + this._source = null; + /** + * @private + * @type {Map | undefined} + */ + this._sourceSizes = undefined; + /** + * @private + * @type {undefined | SourceTypes} + */ + this._sourceTypes = undefined; + + // Cache + this._lastSuccessfulBuildMeta = {}; + this._forceBuild = true; + this._isEvaluatingSideEffects = false; + /** @type {WeakSet | undefined} */ + this._addedSideEffectsBailout = undefined; + /** @type {GenerateContextData} */ + this._codeGeneratorData = new Map(); + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + if (this.layer === null) { + if (this.type === JAVASCRIPT_MODULE_TYPE_AUTO) { + return this.request; + } + return `${this.type}|${this.request}`; + } + return `${this.type}|${this.request}|${this.layer}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return /** @type {string} */ (requestShortener.shorten(this.userRequest)); + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + let ident = contextify( + options.context, + this.userRequest, + options.associatedObjectForCache + ); + if (this.layer) ident = `(${this.layer})/${ident}`; + return ident; + } + + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + const resource = this.matchResource || this.resource; + const idx = resource.indexOf("?"); + if (idx >= 0) return resource.slice(0, idx); + return resource; + } + + /** + * Assuming this module is in the cache. Update the (cached) module with + * the fresh module from the factory. Usually updates internal references + * and properties. + * @param {Module} module fresh module + * @returns {void} + */ + updateCacheModule(module) { + super.updateCacheModule(module); + const m = /** @type {NormalModule} */ (module); + this.binary = m.binary; + this.request = m.request; + this.userRequest = m.userRequest; + this.rawRequest = m.rawRequest; + this.parser = m.parser; + this.parserOptions = m.parserOptions; + this.generator = m.generator; + this.generatorOptions = m.generatorOptions; + this.resource = m.resource; + this.resourceResolveData = m.resourceResolveData; + this.context = m.context; + this.matchResource = m.matchResource; + this.loaders = m.loaders; + } + + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + // Make sure to cache types and sizes before cleanup when this module has been built + // They are accessed by the stats and we don't want them to crash after cleanup + // TODO reconsider this for webpack 6 + if (this.buildInfo) { + if (this._sourceTypes === undefined) this.getSourceTypes(); + for (const type of /** @type {SourceTypes} */ (this._sourceTypes)) { + this.size(type); + } + } + super.cleanupForCache(); + this.parser = undefined; + this.parserOptions = undefined; + this.generator = undefined; + this.generatorOptions = undefined; + } + + /** + * Module should be unsafe cached. Get data that's needed for that. + * This data will be passed to restoreFromUnsafeCache later. + * @returns {UnsafeCacheData} cached data + */ + getUnsafeCacheData() { + const data = super.getUnsafeCacheData(); + data.parserOptions = this.parserOptions; + data.generatorOptions = this.generatorOptions; + return data; + } + + /** + * restore unsafe cache data + * @param {UnsafeCacheData} unsafeCacheData data from getUnsafeCacheData + * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching + */ + restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); + } + + /** + * restore unsafe cache data + * @param {UnsafeCacheData} unsafeCacheData data from getUnsafeCacheData + * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching + */ + _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); + this.parserOptions = unsafeCacheData.parserOptions; + this.parser = normalModuleFactory.getParser(this.type, this.parserOptions); + this.generatorOptions = unsafeCacheData.generatorOptions; + this.generator = normalModuleFactory.getGenerator( + this.type, + this.generatorOptions + ); + // we assume the generator behaves identically and keep cached sourceTypes/Sizes + } + + /** + * @param {string} context the compilation context + * @param {string} name the asset name + * @param {string | Buffer} content the content + * @param {(string | RawSourceMap)=} sourceMap an optional source map + * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching + * @returns {Source} the created source + */ + createSourceForAsset( + context, + name, + content, + sourceMap, + associatedObjectForCache + ) { + if (sourceMap) { + if ( + typeof sourceMap === "string" && + (this.useSourceMap || this.useSimpleSourceMap) + ) { + return new OriginalSource( + content, + contextifySourceUrl(context, sourceMap, associatedObjectForCache) + ); + } + + if (this.useSourceMap) { + return new SourceMapSource( + content, + name, + contextifySourceMap( + context, + /** @type {RawSourceMap} */ + (sourceMap), + associatedObjectForCache + ) + ); + } + } + + return new RawSource(content); + } + + /** + * @private + * @template T + * @param {ResolverWithOptions} resolver a resolver + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {InputFileSystem} fs file system from reading + * @param {NormalModuleCompilationHooks} hooks the hooks + * @returns {import("../declarations/LoaderContext").LoaderContext} loader context + */ + _createLoaderContext(resolver, options, compilation, fs, hooks) { + const { requestShortener } = compilation.runtimeTemplate; + const getCurrentLoaderName = () => { + const currentLoader = this.getCurrentLoader( + /** @type {LoaderContext} */ (loaderContext) + ); + if (!currentLoader) return "(not in loader scope)"; + return requestShortener.shorten(currentLoader.loader); + }; + /** + * @returns {ResolveContext} resolve context + */ + const getResolveContext = () => ({ + fileDependencies: { + add: (d) => + /** @type {LoaderContext} */ ( + loaderContext + ).addDependency(d) + }, + contextDependencies: { + add: (d) => + /** @type {LoaderContext} */ ( + loaderContext + ).addContextDependency(d) + }, + missingDependencies: { + add: (d) => + /** @type {LoaderContext} */ ( + loaderContext + ).addMissingDependency(d) + } + }); + const getAbsolutify = memoize(() => + absolutify.bindCache(compilation.compiler.root) + ); + const getAbsolutifyInContext = memoize(() => + absolutify.bindContextCache( + /** @type {string} */ + (this.context), + compilation.compiler.root + ) + ); + const getContextify = memoize(() => + contextify.bindCache(compilation.compiler.root) + ); + const getContextifyInContext = memoize(() => + contextify.bindContextCache( + /** @type {string} */ + (this.context), + compilation.compiler.root + ) + ); + const utils = { + /** + * @param {string} context context + * @param {string} request request + * @returns {string} result + */ + absolutify: (context, request) => + context === this.context + ? getAbsolutifyInContext()(request) + : getAbsolutify()(context, request), + /** + * @param {string} context context + * @param {string} request request + * @returns {string} result + */ + contextify: (context, request) => + context === this.context + ? getContextifyInContext()(request) + : getContextify()(context, request), + /** + * @param {HashFunction=} type type + * @returns {Hash} hash + */ + createHash: (type) => + createHash( + type || + /** @type {HashFunction} */ + (compilation.outputOptions.hashFunction) + ) + }; + /** @type {import("../declarations/LoaderContext").NormalModuleLoaderContext} */ + const loaderContext = { + version: 2, + /** + * @param {import("../declarations/LoaderContext").Schema=} schema schema + * @returns {T} options + */ + getOptions: (schema) => { + const loader = this.getCurrentLoader( + /** @type {LoaderContext} */ (loaderContext) + ); + + let { options } = /** @type {LoaderItem} */ (loader); + + if (typeof options === "string") { + if (options.startsWith("{") && options.endsWith("}")) { + try { + options = parseJson(options); + } catch (err) { + throw new Error( + `Cannot parse string options: ${/** @type {Error} */ (err).message}` + ); + } + } else { + options = querystring.parse(options, "&", "=", { + maxKeys: 0 + }); + } + } + + if (options === null || options === undefined) { + options = {}; + } + + if (schema) { + let name = "Loader"; + let baseDataPath = "options"; + let match; + if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) { + [, name, baseDataPath] = match; + } + getValidate()(schema, /** @type {EXPECTED_OBJECT} */ (options), { + name, + baseDataPath + }); + } + + return /** @type {T} */ (options); + }, + emitWarning: (warning) => { + if (!(warning instanceof Error)) { + warning = new NonErrorEmittedError(warning); + } + this.addWarning( + new ModuleWarning(warning, { + from: getCurrentLoaderName() + }) + ); + }, + emitError: (error) => { + if (!(error instanceof Error)) { + error = new NonErrorEmittedError(error); + } + this.addError( + new ModuleError(error, { + from: getCurrentLoaderName() + }) + ); + }, + getLogger: (name) => { + const currentLoader = this.getCurrentLoader( + /** @type {LoaderContext} */ (loaderContext) + ); + return compilation.getLogger(() => + [currentLoader && currentLoader.loader, name, this.identifier()] + .filter(Boolean) + .join("|") + ); + }, + resolve(context, request, callback) { + resolver.resolve({}, context, request, getResolveContext(), callback); + }, + getResolve(options) { + const child = options ? resolver.withOptions(options) : resolver; + return /** @type {ReturnType["getResolve"]>} */ ( + (context, request, callback) => { + if (callback) { + child.resolve( + {}, + context, + request, + getResolveContext(), + callback + ); + } else { + return new Promise((resolve, reject) => { + child.resolve( + {}, + context, + request, + getResolveContext(), + (err, result) => { + if (err) reject(err); + else resolve(result); + } + ); + }); + } + } + ); + }, + emitFile: (name, content, sourceMap, assetInfo) => { + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + if (!buildInfo.assets) { + buildInfo.assets = Object.create(null); + buildInfo.assetsInfo = new Map(); + } + + const assets = + /** @type {NonNullable} */ + (buildInfo.assets); + const assetsInfo = + /** @type {NonNullable} */ + (buildInfo.assetsInfo); + + assets[name] = this.createSourceForAsset( + /** @type {string} */ (options.context), + name, + content, + sourceMap, + compilation.compiler.root + ); + assetsInfo.set(name, assetInfo); + }, + addBuildDependency: (dep) => { + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + if (buildInfo.buildDependencies === undefined) { + buildInfo.buildDependencies = new LazySet(); + } + buildInfo.buildDependencies.add(dep); + }, + utils, + rootContext: /** @type {string} */ (options.context), + webpack: true, + sourceMap: Boolean(this.useSourceMap), + mode: options.mode || "production", + hashFunction: /** @type {string} */ (options.output.hashFunction), + hashDigest: /** @type {string} */ (options.output.hashDigest), + hashDigestLength: /** @type {number} */ (options.output.hashDigestLength), + hashSalt: /** @type {string} */ (options.output.hashSalt), + _module: this, + _compilation: compilation, + _compiler: compilation.compiler, + fs + }; + + Object.assign(loaderContext, options.loader); + + // After `hooks.loader.call` is called, the loaderContext is typed as LoaderContext + hooks.loader.call( + /** @type {LoaderContext} */ + (loaderContext), + this + ); + + return /** @type {LoaderContext} */ (loaderContext); + } + + // TODO remove `loaderContext` in webpack@6 + /** + * @param {LoaderContext} loaderContext loader context + * @param {number} index index + * @returns {LoaderItem | null} loader + */ + getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { + if ( + this.loaders && + this.loaders.length && + index < this.loaders.length && + index >= 0 && + this.loaders[index] + ) { + return this.loaders[index]; + } + return null; + } + + /** + * @param {string} context the compilation context + * @param {string | Buffer} content the content + * @param {(string | RawSourceMap | null)=} sourceMap an optional source map + * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching + * @returns {Source} the created source + */ + createSource(context, content, sourceMap, associatedObjectForCache) { + if (Buffer.isBuffer(content)) { + return new RawSource(content); + } + + // if there is no identifier return raw source + if (!this.identifier) { + return new RawSource(content); + } + + // from here on we assume we have an identifier + const identifier = this.identifier(); + + if (this.useSourceMap && sourceMap) { + return new SourceMapSource( + content, + contextifySourceUrl(context, identifier, associatedObjectForCache), + contextifySourceMap(context, sourceMap, associatedObjectForCache) + ); + } + + if (this.useSourceMap || this.useSimpleSourceMap) { + return new OriginalSource( + content, + contextifySourceUrl(context, identifier, associatedObjectForCache) + ); + } + + return new RawSource(content); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {NormalModuleCompilationHooks} hooks the hooks + * @param {BuildCallback} callback callback function + * @returns {void} + */ + _doBuild(options, compilation, resolver, fs, hooks, callback) { + const loaderContext = this._createLoaderContext( + resolver, + options, + compilation, + fs, + hooks + ); + + /** + * @param {Error | null} err err + * @param {(Result | null)=} result_ result + * @returns {void} + */ + const processResult = (err, result_) => { + if (err) { + if (!(err instanceof Error)) { + err = new NonErrorEmittedError(err); + } + const currentLoader = this.getCurrentLoader(loaderContext); + const error = new ModuleBuildError(err, { + from: + currentLoader && + compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + }); + return callback(error); + } + const result = hooks.processResult.call( + /** @type {Result} */ + (result_), + this + ); + const source = result[0]; + const sourceMap = result.length >= 1 ? result[1] : null; + const extraInfo = result.length >= 2 ? result[2] : null; + + if (!Buffer.isBuffer(source) && typeof source !== "string") { + const currentLoader = this.getCurrentLoader(loaderContext, 0); + const err = new Error( + `Final loader (${ + currentLoader + ? compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + : "unknown" + }) didn't return a Buffer or String` + ); + const error = new ModuleBuildError(err); + return callback(error); + } + + const isBinaryModule = + this.generatorOptions && this.generatorOptions.binary !== undefined + ? this.generatorOptions.binary + : this.binary; + + this._source = this.createSource( + /** @type {string} */ (options.context), + isBinaryModule ? asBuffer(source) : asString(source), + sourceMap, + compilation.compiler.root + ); + if (this._sourceSizes !== undefined) this._sourceSizes.clear(); + this._ast = + typeof extraInfo === "object" && + extraInfo !== null && + extraInfo.webpackAST !== undefined + ? extraInfo.webpackAST + : null; + return callback(); + }; + + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + buildInfo.fileDependencies = new LazySet(); + buildInfo.contextDependencies = new LazySet(); + buildInfo.missingDependencies = new LazySet(); + buildInfo.cacheable = true; + + try { + hooks.beforeLoaders.call( + this.loaders, + this, + /** @type {LoaderContext} */ + (loaderContext) + ); + } catch (err) { + processResult(/** @type {Error} */ (err)); + return; + } + + if (this.loaders.length > 0) { + /** @type {BuildInfo} */ + (this.buildInfo).buildDependencies = new LazySet(); + } + + runLoaders( + { + resource: this.resource, + loaders: this.loaders, + context: loaderContext, + /** + * @param {LoaderContext} loaderContext the loader context + * @param {string} resourcePath the resource Path + * @param {(err: Error | null, result?: string | Buffer) => void} callback callback + */ + processResource: (loaderContext, resourcePath, callback) => { + const resource = loaderContext.resource; + const scheme = getScheme(resource); + hooks.readResource + .for(scheme) + .callAsync(loaderContext, (err, result) => { + if (err) return callback(err); + if (typeof result !== "string" && !result) { + return callback( + new UnhandledSchemeError( + /** @type {string} */ + (scheme), + resource + ) + ); + } + return callback(null, result); + }); + } + }, + (err, result) => { + // Cleanup loaderContext to avoid leaking memory in ICs + loaderContext._compilation = + loaderContext._compiler = + loaderContext._module = + loaderContext.fs = + /** @type {EXPECTED_ANY} */ + (undefined); + + if (!result) { + /** @type {BuildInfo} */ + (this.buildInfo).cacheable = false; + return processResult( + err || new Error("No result from loader-runner processing"), + null + ); + } + + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + const fileDependencies = + /** @type {NonNullable} */ + (buildInfo.fileDependencies); + const contextDependencies = + /** @type {NonNullable} */ + (buildInfo.contextDependencies); + const missingDependencies = + /** @type {NonNullable} */ + (buildInfo.missingDependencies); + + fileDependencies.addAll(result.fileDependencies); + contextDependencies.addAll(result.contextDependencies); + missingDependencies.addAll(result.missingDependencies); + for (const loader of this.loaders) { + const buildDependencies = + /** @type {NonNullable} */ + (buildInfo.buildDependencies); + + buildDependencies.add(loader.loader); + } + buildInfo.cacheable = buildInfo.cacheable && result.cacheable; + processResult(err, result.result); + } + ); + } + + /** + * @param {WebpackError} error the error + * @returns {void} + */ + markModuleAsErrored(error) { + // Restore build meta from successful build to keep importing state + this.buildMeta = { ...this._lastSuccessfulBuildMeta }; + this.error = error; + this.addError(error); + } + + /** + * @param {Exclude} rule rule + * @param {string} content content + * @returns {boolean} result + */ + applyNoParseRule(rule, content) { + // must start with "rule" if rule is a string + if (typeof rule === "string") { + return content.startsWith(rule); + } + + if (typeof rule === "function") { + return rule(content); + } + // we assume rule is a regexp + return rule.test(content); + } + + /** + * @param {undefined | NoParse} noParseRule no parse rule + * @param {string} request request + * @returns {boolean} check if module should not be parsed, returns "true" if the module should !not! be parsed, returns "false" if the module !must! be parsed + */ + shouldPreventParsing(noParseRule, request) { + // if no noParseRule exists, return false + // the module !must! be parsed. + if (!noParseRule) { + return false; + } + + // we only have one rule to check + if (!Array.isArray(noParseRule)) { + // returns "true" if the module is !not! to be parsed + return this.applyNoParseRule(noParseRule, request); + } + + for (let i = 0; i < noParseRule.length; i++) { + const rule = noParseRule[i]; + // early exit on first truthy match + // this module is !not! to be parsed + if (this.applyNoParseRule(rule, request)) { + return true; + } + } + // no match found, so this module !should! be parsed + return false; + } + + /** + * @param {Compilation} compilation compilation + * @private + */ + _initBuildHash(compilation) { + const hash = createHash( + /** @type {HashFunction} */ + (compilation.outputOptions.hashFunction) + ); + if (this._source) { + hash.update("source"); + this._source.updateHash(hash); + } + hash.update("meta"); + hash.update(JSON.stringify(this.buildMeta)); + /** @type {BuildInfo} */ + (this.buildInfo).hash = /** @type {string} */ (hash.digest("hex")); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this._forceBuild = false; + this._source = null; + if (this._sourceSizes !== undefined) this._sourceSizes.clear(); + this._sourceTypes = undefined; + this._ast = null; + this.error = null; + this.clearWarningsAndErrors(); + this.clearDependenciesAndBlocks(); + this.buildMeta = {}; + this.buildInfo = { + cacheable: false, + parsed: true, + fileDependencies: undefined, + contextDependencies: undefined, + missingDependencies: undefined, + buildDependencies: undefined, + valueDependencies: undefined, + hash: undefined, + assets: undefined, + assetsInfo: undefined + }; + + const startTime = compilation.compiler.fsStartTime || Date.now(); + + const hooks = NormalModule.getCompilationHooks(compilation); + + return this._doBuild(options, compilation, resolver, fs, hooks, (err) => { + // if we have an error mark module as failed and exit + if (err) { + this.markModuleAsErrored(err); + this._initBuildHash(compilation); + return callback(); + } + + /** + * @param {Error} e error + * @returns {void} + */ + const handleParseError = (e) => { + const source = /** @type {Source} */ (this._source).source(); + const loaders = this.loaders.map((item) => + contextify( + /** @type {string} */ (options.context), + item.loader, + compilation.compiler.root + ) + ); + const error = new ModuleParseError(source, e, loaders, this.type); + this.markModuleAsErrored(error); + this._initBuildHash(compilation); + return callback(); + }; + + const handleParseResult = () => { + this.dependencies.sort( + concatComparators( + compareSelect((a) => a.loc, compareLocations), + keepOriginalOrder(this.dependencies) + ) + ); + sortWithSourceOrder(this.dependencies, new WeakMap()); + this._initBuildHash(compilation); + this._lastSuccessfulBuildMeta = + /** @type {BuildMeta} */ + (this.buildMeta); + return handleBuildDone(); + }; + + const handleBuildDone = () => { + try { + hooks.beforeSnapshot.call(this); + } catch (err) { + this.markModuleAsErrored(/** @type {WebpackError} */ (err)); + return callback(); + } + + const snapshotOptions = compilation.options.snapshot.module; + const { cacheable } = /** @type {BuildInfo} */ (this.buildInfo); + if (!cacheable || !snapshotOptions) { + return callback(); + } + // add warning for all non-absolute paths in fileDependencies, etc + // This makes it easier to find problems with watching and/or caching + /** @type {undefined | Set} */ + let nonAbsoluteDependencies; + /** + * @param {LazySet} deps deps + */ + const checkDependencies = (deps) => { + for (const dep of deps) { + if (!ABSOLUTE_PATH_REGEX.test(dep)) { + if (nonAbsoluteDependencies === undefined) { + nonAbsoluteDependencies = new Set(); + } + nonAbsoluteDependencies.add(dep); + deps.delete(dep); + try { + const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, ""); + const absolute = join( + compilation.fileSystemInfo.fs, + /** @type {string} */ + (this.context), + depWithoutGlob + ); + if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) { + (depWithoutGlob !== dep + ? /** @type {NonNullable} */ + ( + /** @type {BuildInfo} */ + (this.buildInfo).contextDependencies + ) + : deps + ).add(absolute); + } + } catch (_err) { + // ignore + } + } + } + }; + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + const fileDependencies = + /** @type {NonNullable} */ + (buildInfo.fileDependencies); + const contextDependencies = + /** @type {NonNullable} */ + (buildInfo.contextDependencies); + const missingDependencies = + /** @type {NonNullable} */ + (buildInfo.missingDependencies); + checkDependencies(fileDependencies); + checkDependencies(missingDependencies); + checkDependencies(contextDependencies); + if (nonAbsoluteDependencies !== undefined) { + const InvalidDependenciesModuleWarning = + getInvalidDependenciesModuleWarning(); + this.addWarning( + new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies) + ); + } + // convert file/context/missingDependencies into filesystem snapshot + compilation.fileSystemInfo.createSnapshot( + startTime, + fileDependencies, + contextDependencies, + missingDependencies, + snapshotOptions, + (err, snapshot) => { + if (err) { + this.markModuleAsErrored(err); + return; + } + buildInfo.fileDependencies = undefined; + buildInfo.contextDependencies = undefined; + buildInfo.missingDependencies = undefined; + buildInfo.snapshot = snapshot; + return callback(); + } + ); + }; + + try { + hooks.beforeParse.call(this); + } catch (err) { + this.markModuleAsErrored(/** @type {WebpackError} */ (err)); + this._initBuildHash(compilation); + return callback(); + } + + // check if this module should !not! be parsed. + // if so, exit here; + const noParseRule = options.module && options.module.noParse; + if (this.shouldPreventParsing(noParseRule, this.request)) { + // We assume that we need module and exports + /** @type {BuildInfo} */ + (this.buildInfo).parsed = false; + this._initBuildHash(compilation); + return handleBuildDone(); + } + + try { + const source = /** @type {Source} */ (this._source).source(); + /** @type {Parser} */ + (this.parser).parse(this._ast || source, { + source, + current: this, + module: this, + compilation, + options + }); + } catch (parseErr) { + handleParseError(/** @type {Error} */ (parseErr)); + return; + } + handleParseResult(); + }); + } + + /** + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(context) { + return /** @type {Generator} */ ( + this.generator + ).getConcatenationBailoutReason(this, context); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + */ + getSideEffectsConnectionState(moduleGraph) { + if (this.factoryMeta !== undefined) { + if (this.factoryMeta.sideEffectFree) return false; + if (this.factoryMeta.sideEffectFree === false) return true; + } + if (this.buildMeta !== undefined && this.buildMeta.sideEffectFree) { + if (this._isEvaluatingSideEffects) { + return ModuleGraphConnection.CIRCULAR_CONNECTION; + } + this._isEvaluatingSideEffects = true; + /** @type {ConnectionState} */ + let current = false; + for (const dep of this.dependencies) { + const state = dep.getModuleEvaluationSideEffectsState(moduleGraph); + if (state === true) { + if ( + this._addedSideEffectsBailout === undefined + ? ((this._addedSideEffectsBailout = new WeakSet()), true) + : !this._addedSideEffectsBailout.has(moduleGraph) + ) { + this._addedSideEffectsBailout.add(moduleGraph); + moduleGraph + .getOptimizationBailout(this) + .push( + () => + `Dependency (${ + dep.type + }) with side effects at ${formatLocation(dep.loc)}` + ); + } + this._isEvaluatingSideEffects = false; + return true; + } else if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) { + current = ModuleGraphConnection.addConnectionStates(current, state); + } + } + this._isEvaluatingSideEffects = false; + // When caching is implemented here, make sure to not cache when + // at least one circular connection was in the loop above + return current; + } + return true; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + if (this._sourceTypes === undefined) { + this._sourceTypes = /** @type {Generator} */ (this.generator).getTypes( + this + ); + } + return this._sourceTypes; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + concatenationScope, + codeGenerationResults, + sourceTypes + }) { + /** @type {Set} */ + const runtimeRequirements = new Set(); + + const { parsed } = /** @type {BuildInfo} */ (this.buildInfo); + + if (!parsed) { + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + } + + const getData = () => this._codeGeneratorData; + + const sources = new Map(); + for (const type of sourceTypes || chunkGraph.getModuleSourceTypes(this)) { + // TODO webpack@6 make generateError required + const generator = + /** @type {Generator & { generateError?: GenerateErrorFn }} */ + (this.generator); + const source = this.error + ? generator.generateError + ? generator.generateError(this.error, this, { + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements, + runtime, + concatenationScope, + codeGenerationResults, + getData, + type + }) + : new RawSource( + `throw new Error(${JSON.stringify(this.error.message)});` + ) + : generator.generate(this, { + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements, + runtime, + concatenationScope, + codeGenerationResults, + getData, + type + }); + + if (source) { + sources.set(type, new CachedSource(source)); + } + } + + /** @type {CodeGenerationResult} */ + const resultEntry = { + sources, + runtimeRequirements, + data: this._codeGeneratorData + }; + return resultEntry; + } + + /** + * @returns {Source | null} the original source for the module before webpack transformation + */ + originalSource() { + return this._source; + } + + /** + * @returns {void} + */ + invalidateBuild() { + this._forceBuild = true; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + const { fileSystemInfo, compilation, valueCacheVersions } = context; + // build if enforced + if (this._forceBuild) return callback(null, true); + + // always try to build in case of an error + if (this.error) return callback(null, true); + + const { cacheable, snapshot, valueDependencies } = + /** @type {BuildInfo} */ (this.buildInfo); + + // always build when module is not cacheable + if (!cacheable) return callback(null, true); + + // build when there is no snapshot to check + if (!snapshot) return callback(null, true); + + // build when valueDependencies have changed + if (valueDependencies) { + if (!valueCacheVersions) return callback(null, true); + for (const [key, value] of valueDependencies) { + if (value === undefined) return callback(null, true); + const current = valueCacheVersions.get(key); + if ( + value !== current && + (typeof value === "string" || + typeof current === "string" || + current === undefined || + !isSubset(value, current)) + ) { + return callback(null, true); + } + } + } + + // check snapshot for validity + fileSystemInfo.checkSnapshotValid(snapshot, (err, valid) => { + if (err) return callback(err); + if (!valid) return callback(null, true); + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.needBuild.callAsync(this, context, (err, needBuild) => { + if (err) { + return callback( + HookWebpackError.makeWebpackError( + err, + "NormalModule.getCompilationHooks().needBuild" + ) + ); + } + callback(null, Boolean(needBuild)); + }); + }); + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + const cachedSize = + this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type); + if (cachedSize !== undefined) { + return cachedSize; + } + const size = Math.max( + 1, + /** @type {Generator} */ (this.generator).getSize(this, type) + ); + if (this._sourceSizes === undefined) { + this._sourceSizes = new Map(); + } + this._sourceSizes.set(type, size); + return size; + } + + /** + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to + */ + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) { + const { snapshot, buildDependencies: buildDeps } = + /** @type {BuildInfo} */ (this.buildInfo); + if (snapshot) { + fileDependencies.addAll(snapshot.getFileIterable()); + contextDependencies.addAll(snapshot.getContextIterable()); + missingDependencies.addAll(snapshot.getMissingIterable()); + } else { + const { + fileDependencies: fileDeps, + contextDependencies: contextDeps, + missingDependencies: missingDeps + } = /** @type {BuildInfo} */ (this.buildInfo); + if (fileDeps !== undefined) fileDependencies.addAll(fileDeps); + if (contextDeps !== undefined) contextDependencies.addAll(contextDeps); + if (missingDeps !== undefined) missingDependencies.addAll(missingDeps); + } + if (buildDeps !== undefined) { + buildDependencies.addAll(buildDeps); + } + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + hash.update( + /** @type {string} */ + (buildInfo.hash) + ); + /** @type {Generator} */ + (this.generator).updateHash(hash, { + module: this, + ...context + }); + super.updateHash(hash, context); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + // deserialize + write(this._source); + write(this.error); + write(this._lastSuccessfulBuildMeta); + write(this._forceBuild); + write(this._codeGeneratorData); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {NormalModule} module + */ + static deserialize(context) { + const obj = new NormalModule({ + // will be deserialized by Module + layer: /** @type {EXPECTED_ANY} */ (null), + type: "", + // will be filled by updateCacheModule + resource: "", + context: "", + request: /** @type {EXPECTED_ANY} */ (null), + userRequest: /** @type {EXPECTED_ANY} */ (null), + rawRequest: /** @type {EXPECTED_ANY} */ (null), + loaders: /** @type {EXPECTED_ANY} */ (null), + matchResource: /** @type {EXPECTED_ANY} */ (null), + parser: /** @type {EXPECTED_ANY} */ (null), + parserOptions: /** @type {EXPECTED_ANY} */ (null), + generator: /** @type {EXPECTED_ANY} */ (null), + generatorOptions: /** @type {EXPECTED_ANY} */ (null), + resolveOptions: /** @type {EXPECTED_ANY} */ (null) + }); + obj.deserialize(context); + return obj; + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this._source = read(); + this.error = read(); + this._lastSuccessfulBuildMeta = read(); + this._forceBuild = read(); + this._codeGeneratorData = read(); + super.deserialize(context); + } +} + +makeSerializable(NormalModule, "webpack/lib/NormalModule"); + +module.exports = NormalModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NormalModuleFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NormalModuleFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..93dc8129b58fc62f6ec0a7cccb93b5330a90dda9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NormalModuleFactory.js @@ -0,0 +1,1352 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { getContext } = require("loader-runner"); +const asyncLib = require("neo-async"); +const { + AsyncSeriesBailHook, + HookMap, + SyncBailHook, + SyncHook, + SyncWaterfallHook +} = require("tapable"); +const ChunkGraph = require("./ChunkGraph"); +const Module = require("./Module"); +const ModuleFactory = require("./ModuleFactory"); +const ModuleGraph = require("./ModuleGraph"); +const { JAVASCRIPT_MODULE_TYPE_AUTO } = require("./ModuleTypeConstants"); +const NormalModule = require("./NormalModule"); +const BasicEffectRulePlugin = require("./rules/BasicEffectRulePlugin"); +const BasicMatcherRulePlugin = require("./rules/BasicMatcherRulePlugin"); +const ObjectMatcherRulePlugin = require("./rules/ObjectMatcherRulePlugin"); +const RuleSetCompiler = require("./rules/RuleSetCompiler"); +const UseEffectRulePlugin = require("./rules/UseEffectRulePlugin"); +const LazySet = require("./util/LazySet"); +const { getScheme } = require("./util/URLAbsoluteSpecifier"); +const { cachedCleverMerge, cachedSetProperty } = require("./util/cleverMerge"); +const { join } = require("./util/fs"); +const { + parseResource, + parseResourceWithoutFragment +} = require("./util/identifier"); + +/** @typedef {import("../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ +/** @typedef {import("./Generator")} Generator */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./NormalModule").GeneratorOptions} GeneratorOptions */ +/** @typedef {import("./NormalModule").LoaderItem} LoaderItem */ +/** @typedef {import("./NormalModule").NormalModuleCreateData} NormalModuleCreateData */ +/** @typedef {import("./NormalModule").ParserOptions} ParserOptions */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {import("./ResolverFactory")} ResolverFactory */ +/** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */ +/** @typedef {import("./ResolverFactory").ResolveRequest} ResolveRequest */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ +/** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("./rules/RuleSetCompiler").RuleSetRules} RuleSetRules */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ + +/** @typedef {Pick} ModuleSettings */ +/** @typedef {Partial} CreateData */ + +/** + * @typedef {object} ResolveData + * @property {ModuleFactoryCreateData["contextInfo"]} contextInfo + * @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions + * @property {string} context + * @property {string} request + * @property {ImportAttributes | undefined} assertions + * @property {ModuleDependency[]} dependencies + * @property {string} dependencyType + * @property {CreateData} createData + * @property {LazySet} fileDependencies + * @property {LazySet} missingDependencies + * @property {LazySet} contextDependencies + * @property {Module=} ignoredModule + * @property {boolean} cacheable allow to use the unsafe cache + */ + +/** + * @typedef {object} ResourceData + * @property {string} resource + * @property {string=} path + * @property {string=} query + * @property {string=} fragment + * @property {string=} context + */ + +/** + * @typedef {object} ResourceSchemeData + * @property {string=} mimetype mime type of the resource + * @property {string=} parameters additional parameters for the resource + * @property {"base64" | false=} encoding encoding of the resource + * @property {string=} encodedContent encoded content of the resource + */ + +/** @typedef {ResourceData & { data: ResourceSchemeData & Partial }} ResourceDataWithData */ + +/** + * @typedef {object} ParsedLoaderRequest + * @property {string} loader loader + * @property {string|undefined} options options + */ + +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} stats + * @returns {void} + */ + +const EMPTY_RESOLVE_OPTIONS = {}; +/** @type {ParserOptions} */ +const EMPTY_PARSER_OPTIONS = {}; +/** @type {GeneratorOptions} */ +const EMPTY_GENERATOR_OPTIONS = {}; +/** @type {ParsedLoaderRequest[]} */ +const EMPTY_ELEMENTS = []; + +const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; +const LEADING_DOT_EXTENSION_REGEX = /^[^.]/; + +/** + * @param {LoaderItem} data data + * @returns {string} ident + */ +const loaderToIdent = (data) => { + if (!data.options) { + return data.loader; + } + if (typeof data.options === "string") { + return `${data.loader}?${data.options}`; + } + if (typeof data.options !== "object") { + throw new Error("loader options must be string or object"); + } + if (data.ident) { + return `${data.loader}??${data.ident}`; + } + return `${data.loader}?${JSON.stringify(data.options)}`; +}; + +/** + * @param {LoaderItem[]} loaders loaders + * @param {string} resource resource + * @returns {string} stringified loaders and resource + */ +const stringifyLoadersAndResource = (loaders, resource) => { + let str = ""; + for (const loader of loaders) { + str += `${loaderToIdent(loader)}!`; + } + return str + resource; +}; + +/** + * @param {number} times times + * @param {(err?: null | Error) => void} callback callback + * @returns {(err?: null | Error) => void} callback + */ +const needCalls = (times, callback) => (err) => { + if (--times === 0) { + return callback(err); + } + if (err && times > 0) { + times = Number.NaN; + return callback(err); + } +}; + +/** + * @template T + * @template O + * @param {T} globalOptions global options + * @param {string} type type + * @param {O} localOptions local options + * @returns {T & O | T | O} result + */ +const mergeGlobalOptions = (globalOptions, type, localOptions) => { + const parts = type.split("/"); + let result; + let current = ""; + for (const part of parts) { + current = current ? `${current}/${part}` : part; + const options = + /** @type {T} */ + (globalOptions[/** @type {keyof T} */ (current)]); + if (typeof options === "object") { + result = + result === undefined ? options : cachedCleverMerge(result, options); + } + } + if (result === undefined) { + return localOptions; + } + return cachedCleverMerge(result, localOptions); +}; + +// TODO webpack 6 remove +/** + * @template {import("tapable").Hook} T + * @param {string} name name + * @param {T} hook hook + * @returns {string} result + */ +const deprecationChangedHookMessage = (name, hook) => { + const names = hook.taps.map((tapped) => tapped.name).join(", "); + + return ( + `NormalModuleFactory.${name} (${names}) is no longer a waterfall hook, but a bailing hook instead. ` + + "Do not return the passed object, but modify it instead. " + + "Returning false will ignore the request and results in no module created." + ); +}; + +const ruleSetCompiler = new RuleSetCompiler([ + new BasicMatcherRulePlugin("test", "resource"), + new BasicMatcherRulePlugin("scheme"), + new BasicMatcherRulePlugin("mimetype"), + new BasicMatcherRulePlugin("dependency"), + new BasicMatcherRulePlugin("include", "resource"), + new BasicMatcherRulePlugin("exclude", "resource", true), + new BasicMatcherRulePlugin("resource"), + new BasicMatcherRulePlugin("resourceQuery"), + new BasicMatcherRulePlugin("resourceFragment"), + new BasicMatcherRulePlugin("realResource"), + new BasicMatcherRulePlugin("issuer"), + new BasicMatcherRulePlugin("compiler"), + new BasicMatcherRulePlugin("issuerLayer"), + new ObjectMatcherRulePlugin("assert", "assertions", (value) => { + if (value) { + return ( + /** @type {ImportAttributes} */ (value)._isLegacyAssert !== undefined + ); + } + + return false; + }), + new ObjectMatcherRulePlugin("with", "assertions", (value) => { + if (value) { + return !(/** @type {ImportAttributes} */ (value)._isLegacyAssert); + } + return false; + }), + new ObjectMatcherRulePlugin("descriptionData"), + new BasicEffectRulePlugin("type"), + new BasicEffectRulePlugin("sideEffects"), + new BasicEffectRulePlugin("parser"), + new BasicEffectRulePlugin("resolve"), + new BasicEffectRulePlugin("generator"), + new BasicEffectRulePlugin("layer"), + new UseEffectRulePlugin() +]); + +class NormalModuleFactory extends ModuleFactory { + /** + * @param {object} param params + * @param {string=} param.context context + * @param {InputFileSystem} param.fs file system + * @param {ResolverFactory} param.resolverFactory resolverFactory + * @param {ModuleOptions} param.options options + * @param {AssociatedObjectForCache} param.associatedObjectForCache an object to which the cache will be attached + * @param {boolean=} param.layers enable layers + */ + constructor({ + context, + fs, + resolverFactory, + options, + associatedObjectForCache, + layers = false + }) { + super(); + this.hooks = Object.freeze({ + /** @type {AsyncSeriesBailHook<[ResolveData], Module | false | void>} */ + resolve: new AsyncSeriesBailHook(["resolveData"]), + /** @type {HookMap>} */ + resolveForScheme: new HookMap( + () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) + ), + /** @type {HookMap>} */ + resolveInScheme: new HookMap( + () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) + ), + /** @type {AsyncSeriesBailHook<[ResolveData], Module | undefined>} */ + factorize: new AsyncSeriesBailHook(["resolveData"]), + /** @type {AsyncSeriesBailHook<[ResolveData], false | void>} */ + beforeResolve: new AsyncSeriesBailHook(["resolveData"]), + /** @type {AsyncSeriesBailHook<[ResolveData], false | void>} */ + afterResolve: new AsyncSeriesBailHook(["resolveData"]), + /** @type {AsyncSeriesBailHook<[CreateData, ResolveData], Module | void>} */ + createModule: new AsyncSeriesBailHook(["createData", "resolveData"]), + /** @type {SyncWaterfallHook<[Module, CreateData, ResolveData]>} */ + module: new SyncWaterfallHook(["module", "createData", "resolveData"]), + /** @type {HookMap>} */ + createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), + /** @type {HookMap>} */ + parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), + /** @type {HookMap>} */ + createGenerator: new HookMap( + () => new SyncBailHook(["generatorOptions"]) + ), + /** @type {HookMap>} */ + generator: new HookMap( + () => new SyncHook(["generator", "generatorOptions"]) + ), + /** @type {HookMap>} */ + createModuleClass: new HookMap( + () => new SyncBailHook(["createData", "resolveData"]) + ) + }); + this.resolverFactory = resolverFactory; + this.ruleSet = ruleSetCompiler.compile([ + { + rules: /** @type {RuleSetRules} */ (options.defaultRules) + }, + { + rules: /** @type {RuleSetRules} */ (options.rules) + } + ]); + this.context = context || ""; + this.fs = fs; + this._globalParserOptions = options.parser; + this._globalGeneratorOptions = options.generator; + /** @type {Map>} */ + this.parserCache = new Map(); + /** @type {Map>} */ + this.generatorCache = new Map(); + /** @type {Set} */ + this._restoredUnsafeCacheEntries = new Set(); + + /** @type {(resource: string) => import("./util/identifier").ParsedResource} */ + const cacheParseResource = parseResource.bindCache( + associatedObjectForCache + ); + const cachedParseResourceWithoutFragment = + parseResourceWithoutFragment.bindCache(associatedObjectForCache); + this._parseResourceWithoutFragment = cachedParseResourceWithoutFragment; + + this.hooks.factorize.tapAsync( + { + name: "NormalModuleFactory", + stage: 100 + }, + (resolveData, callback) => { + this.hooks.resolve.callAsync(resolveData, (err, result) => { + if (err) return callback(err); + + // Ignored + if (result === false) return callback(); + + // direct module + if (result instanceof Module) return callback(null, result); + + if (typeof result === "object") { + throw new Error( + `${deprecationChangedHookMessage( + "resolve", + this.hooks.resolve + )} Returning a Module object will result in this module used as result.` + ); + } + + this.hooks.afterResolve.callAsync(resolveData, (err, result) => { + if (err) return callback(err); + + if (typeof result === "object") { + throw new Error( + deprecationChangedHookMessage( + "afterResolve", + this.hooks.afterResolve + ) + ); + } + + // Ignored + if (result === false) return callback(); + + const createData = resolveData.createData; + + this.hooks.createModule.callAsync( + createData, + resolveData, + (err, createdModule) => { + if (!createdModule) { + if (!resolveData.request) { + return callback(new Error("Empty dependency (no request)")); + } + + // TODO webpack 6 make it required and move javascript/wasm/asset properties to own module + createdModule = this.hooks.createModuleClass + .for( + /** @type {ModuleSettings} */ + (createData.settings).type + ) + .call(createData, resolveData); + + if (!createdModule) { + createdModule = /** @type {Module} */ ( + new NormalModule( + /** @type {NormalModuleCreateData} */ + (createData) + ) + ); + } + } + + createdModule = this.hooks.module.call( + createdModule, + createData, + resolveData + ); + + return callback(null, createdModule); + } + ); + }); + }); + } + ); + this.hooks.resolve.tapAsync( + { + name: "NormalModuleFactory", + stage: 100 + }, + (data, callback) => { + const { + contextInfo, + context, + dependencies, + dependencyType, + request, + assertions, + resolveOptions, + fileDependencies, + missingDependencies, + contextDependencies + } = data; + const loaderResolver = this.getResolver("loader"); + + /** @type {ResourceData | undefined} */ + let matchResourceData; + /** @type {string} */ + let unresolvedResource; + /** @type {ParsedLoaderRequest[]} */ + let elements; + let noPreAutoLoaders = false; + let noAutoLoaders = false; + let noPrePostAutoLoaders = false; + + const contextScheme = getScheme(context); + /** @type {string | undefined} */ + let scheme = getScheme(request); + + if (!scheme) { + /** @type {string} */ + let requestWithoutMatchResource = request; + const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); + if (matchResourceMatch) { + let matchResource = matchResourceMatch[1]; + // Check if matchResource starts with ./ or ../ + if (matchResource.charCodeAt(0) === 46) { + // 46 is "." + const secondChar = matchResource.charCodeAt(1); + if ( + secondChar === 47 || // 47 is "/" + (secondChar === 46 && matchResource.charCodeAt(2) === 47) // "../" + ) { + // Resolve relative path against context + matchResource = join(this.fs, context, matchResource); + } + } + + matchResourceData = { + ...cacheParseResource(matchResource), + resource: matchResource + }; + requestWithoutMatchResource = request.slice( + matchResourceMatch[0].length + ); + } + + scheme = getScheme(requestWithoutMatchResource); + + if (!scheme && !contextScheme) { + const firstChar = requestWithoutMatchResource.charCodeAt(0); + const secondChar = requestWithoutMatchResource.charCodeAt(1); + noPreAutoLoaders = firstChar === 45 && secondChar === 33; // startsWith "-!" + noAutoLoaders = noPreAutoLoaders || firstChar === 33; // startsWith "!" + noPrePostAutoLoaders = firstChar === 33 && secondChar === 33; // startsWith "!!"; + const rawElements = requestWithoutMatchResource + .slice( + noPreAutoLoaders || noPrePostAutoLoaders + ? 2 + : noAutoLoaders + ? 1 + : 0 + ) + .split(/!+/); + unresolvedResource = /** @type {string} */ (rawElements.pop()); + elements = rawElements.map((el) => { + const { path, query } = cachedParseResourceWithoutFragment(el); + return { + loader: path, + options: query ? query.slice(1) : undefined + }; + }); + scheme = getScheme(unresolvedResource); + } else { + unresolvedResource = requestWithoutMatchResource; + elements = EMPTY_ELEMENTS; + } + } else { + unresolvedResource = request; + elements = EMPTY_ELEMENTS; + } + + /** @type {ResolveContext} */ + const resolveContext = { + fileDependencies, + missingDependencies, + contextDependencies + }; + + /** @type {ResourceDataWithData} */ + let resourceData; + + /** @type {undefined | LoaderItem[]} */ + let loaders; + + const continueCallback = needCalls(2, (err) => { + if (err) return callback(err); + + // translate option idents + try { + for (const item of /** @type {LoaderItem[]} */ (loaders)) { + if (typeof item.options === "string" && item.options[0] === "?") { + const ident = item.options.slice(1); + if (ident === "[[missing ident]]") { + throw new Error( + "No ident is provided by referenced loader. " + + "When using a function for Rule.use in config you need to " + + "provide an 'ident' property for referenced loader options." + ); + } + item.options = this.ruleSet.references.get(ident); + if (item.options === undefined) { + throw new Error( + "Invalid ident is provided by referenced loader" + ); + } + item.ident = ident; + } + } + } catch (identErr) { + return callback(/** @type {Error} */ (identErr)); + } + + if (!resourceData) { + // ignored + return callback(null, dependencies[0].createIgnoredModule(context)); + } + + const userRequest = + (matchResourceData !== undefined + ? `${matchResourceData.resource}!=!` + : "") + + stringifyLoadersAndResource( + /** @type {LoaderItem[]} */ (loaders), + resourceData.resource + ); + + /** @type {ModuleSettings} */ + const settings = {}; + /** @type {LoaderItem[]} */ + const useLoadersPost = []; + /** @type {LoaderItem[]} */ + const useLoaders = []; + /** @type {LoaderItem[]} */ + const useLoadersPre = []; + + // handle .webpack[] suffix + let resource; + let match; + if ( + matchResourceData && + typeof (resource = matchResourceData.resource) === "string" && + (match = /\.webpack\[([^\]]+)\]$/.exec(resource)) + ) { + settings.type = match[1]; + matchResourceData.resource = matchResourceData.resource.slice( + 0, + -settings.type.length - 10 + ); + } else { + settings.type = JAVASCRIPT_MODULE_TYPE_AUTO; + const resourceDataForRules = matchResourceData || resourceData; + const result = this.ruleSet.exec({ + resource: resourceDataForRules.path, + realResource: resourceData.path, + resourceQuery: resourceDataForRules.query, + resourceFragment: resourceDataForRules.fragment, + scheme, + assertions, + mimetype: matchResourceData + ? "" + : resourceData.data.mimetype || "", + dependency: dependencyType, + descriptionData: matchResourceData + ? undefined + : resourceData.data.descriptionFileData, + issuer: contextInfo.issuer, + compiler: contextInfo.compiler, + issuerLayer: contextInfo.issuerLayer || "" + }); + for (const r of result) { + // https://github.com/webpack/webpack/issues/16466 + // if a request exists PrePostAutoLoaders, should disable modifying Rule.type + if (r.type === "type" && noPrePostAutoLoaders) { + continue; + } + if (r.type === "use") { + if (!noAutoLoaders && !noPrePostAutoLoaders) { + useLoaders.push(r.value); + } + } else if (r.type === "use-post") { + if (!noPrePostAutoLoaders) { + useLoadersPost.push(r.value); + } + } else if (r.type === "use-pre") { + if (!noPreAutoLoaders && !noPrePostAutoLoaders) { + useLoadersPre.push(r.value); + } + } else if ( + typeof r.value === "object" && + r.value !== null && + typeof settings[ + /** @type {keyof ModuleSettings} */ + (r.type) + ] === "object" && + settings[/** @type {keyof ModuleSettings} */ (r.type)] !== null + ) { + const type = /** @type {keyof ModuleSettings} */ (r.type); + settings[type] = cachedCleverMerge(settings[type], r.value); + } else { + const type = /** @type {keyof ModuleSettings} */ (r.type); + settings[type] = r.value; + } + } + } + + /** @type {undefined | LoaderItem[]} */ + let postLoaders; + /** @type {undefined | LoaderItem[]} */ + let normalLoaders; + /** @type {undefined | LoaderItem[]} */ + let preLoaders; + + const continueCallback = needCalls(3, (err) => { + if (err) { + return callback(err); + } + const allLoaders = /** @type {LoaderItem[]} */ (postLoaders); + if (matchResourceData === undefined) { + for (const loader of /** @type {LoaderItem[]} */ (loaders)) { + allLoaders.push(loader); + } + for (const loader of /** @type {LoaderItem[]} */ ( + normalLoaders + )) { + allLoaders.push(loader); + } + } else { + for (const loader of /** @type {LoaderItem[]} */ ( + normalLoaders + )) { + allLoaders.push(loader); + } + for (const loader of /** @type {LoaderItem[]} */ (loaders)) { + allLoaders.push(loader); + } + } + for (const loader of /** @type {LoaderItem[]} */ (preLoaders)) { + allLoaders.push(loader); + } + const type = /** @type {string} */ (settings.type); + const resolveOptions = settings.resolve; + const layer = settings.layer; + if (layer !== undefined && !layers) { + return callback( + new Error( + "'Rule.layer' is only allowed when 'experiments.layers' is enabled" + ) + ); + } + try { + Object.assign(data.createData, { + layer: + layer === undefined ? contextInfo.issuerLayer || null : layer, + request: stringifyLoadersAndResource( + allLoaders, + resourceData.resource + ), + userRequest, + rawRequest: request, + loaders: allLoaders, + resource: resourceData.resource, + context: + resourceData.context || getContext(resourceData.resource), + matchResource: matchResourceData + ? matchResourceData.resource + : undefined, + resourceResolveData: resourceData.data, + settings, + type, + parser: this.getParser(type, settings.parser), + parserOptions: settings.parser, + generator: this.getGenerator(type, settings.generator), + generatorOptions: settings.generator, + resolveOptions + }); + } catch (createDataErr) { + return callback(/** @type {Error} */ (createDataErr)); + } + callback(); + }); + this.resolveRequestArray( + contextInfo, + this.context, + useLoadersPost, + loaderResolver, + resolveContext, + (err, result) => { + postLoaders = result; + continueCallback(err); + } + ); + this.resolveRequestArray( + contextInfo, + this.context, + useLoaders, + loaderResolver, + resolveContext, + (err, result) => { + normalLoaders = result; + continueCallback(err); + } + ); + this.resolveRequestArray( + contextInfo, + this.context, + useLoadersPre, + loaderResolver, + resolveContext, + (err, result) => { + preLoaders = result; + continueCallback(err); + } + ); + }); + + this.resolveRequestArray( + contextInfo, + contextScheme ? this.context : context, + /** @type {LoaderItem[]} */ (elements), + loaderResolver, + resolveContext, + (err, result) => { + if (err) return continueCallback(err); + loaders = result; + continueCallback(); + } + ); + + /** + * @param {string} context context + */ + const defaultResolve = (context) => { + if (/^($|\?)/.test(unresolvedResource)) { + resourceData = { + ...cacheParseResource(unresolvedResource), + resource: unresolvedResource, + data: {} + }; + continueCallback(); + } + + // resource without scheme and with path + else { + const normalResolver = this.getResolver( + "normal", + dependencyType + ? cachedSetProperty( + resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + dependencyType + ) + : resolveOptions + ); + this.resolveResource( + contextInfo, + context, + unresolvedResource, + normalResolver, + resolveContext, + (err, _resolvedResource, resolvedResourceResolveData) => { + if (err) return continueCallback(err); + if (_resolvedResource !== false) { + const resolvedResource = + /** @type {string} */ + (_resolvedResource); + resourceData = { + ...cacheParseResource(resolvedResource), + resource: resolvedResource, + data: + /** @type {ResolveRequest} */ + (resolvedResourceResolveData) + }; + } + continueCallback(); + } + ); + } + }; + + // resource with scheme + if (scheme) { + resourceData = { + resource: unresolvedResource, + data: {}, + path: undefined, + query: undefined, + fragment: undefined, + context: undefined + }; + this.hooks.resolveForScheme + .for(scheme) + .callAsync(resourceData, data, (err) => { + if (err) return continueCallback(err); + continueCallback(); + }); + } + + // resource within scheme + else if (contextScheme) { + resourceData = { + resource: unresolvedResource, + data: {}, + path: undefined, + query: undefined, + fragment: undefined, + context: undefined + }; + this.hooks.resolveInScheme + .for(contextScheme) + .callAsync(resourceData, data, (err, handled) => { + if (err) return continueCallback(err); + if (!handled) return defaultResolve(this.context); + continueCallback(); + }); + } + + // resource without scheme and without path + else { + defaultResolve(context); + } + } + ); + } + + cleanupForCache() { + for (const module of this._restoredUnsafeCacheEntries) { + ChunkGraph.clearChunkGraphForModule(module); + ModuleGraph.clearModuleGraphForModule(module); + module.cleanupForCache(); + } + } + + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create(data, callback) { + const dependencies = /** @type {ModuleDependency[]} */ (data.dependencies); + const context = data.context || this.context; + const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; + const dependency = dependencies[0]; + const request = dependency.request; + const assertions = dependency.assertions; + const dependencyType = dependency.category || ""; + const contextInfo = data.contextInfo; + const fileDependencies = new LazySet(); + const missingDependencies = new LazySet(); + const contextDependencies = new LazySet(); + /** @type {ResolveData} */ + const resolveData = { + contextInfo, + resolveOptions, + context, + request, + assertions, + dependencies, + dependencyType, + fileDependencies, + missingDependencies, + contextDependencies, + createData: {}, + cacheable: true + }; + this.hooks.beforeResolve.callAsync(resolveData, (err, result) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: false + }); + } + + // Ignored + if (result === false) { + /** @type {ModuleFactoryResult} * */ + const factoryResult = { + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: resolveData.cacheable + }; + + if (resolveData.ignoredModule) { + factoryResult.module = resolveData.ignoredModule; + } + + return callback(null, factoryResult); + } + + if (typeof result === "object") { + throw new Error( + deprecationChangedHookMessage( + "beforeResolve", + this.hooks.beforeResolve + ) + ); + } + + this.hooks.factorize.callAsync(resolveData, (err, module) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: false + }); + } + + /** @type {ModuleFactoryResult} * */ + const factoryResult = { + module, + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: resolveData.cacheable + }; + + callback(null, factoryResult); + }); + }); + } + + /** + * @param {ModuleFactoryCreateDataContextInfo} contextInfo context info + * @param {string} context context + * @param {string} unresolvedResource unresolved resource + * @param {ResolverWithOptions} resolver resolver + * @param {ResolveContext} resolveContext resolver context + * @param {(err: null | Error, res?: string | false, req?: ResolveRequest) => void} callback callback + */ + resolveResource( + contextInfo, + context, + unresolvedResource, + resolver, + resolveContext, + callback + ) { + resolver.resolve( + contextInfo, + context, + unresolvedResource, + resolveContext, + (err, resolvedResource, resolvedResourceResolveData) => { + if (err) { + return this._resolveResourceErrorHints( + err, + contextInfo, + context, + unresolvedResource, + resolver, + resolveContext, + (err2, hints) => { + if (err2) { + err.message += ` +A fatal error happened during resolving additional hints for this error: ${err2.message}`; + err.stack += ` + +A fatal error happened during resolving additional hints for this error: +${err2.stack}`; + return callback(err); + } + if (hints && hints.length > 0) { + err.message += ` +${hints.join("\n\n")}`; + } + + // Check if the extension is missing a leading dot (e.g. "js" instead of ".js") + let appendResolveExtensionsHint = false; + const specifiedExtensions = [...resolver.options.extensions]; + const expectedExtensions = specifiedExtensions.map( + (extension) => { + if (LEADING_DOT_EXTENSION_REGEX.test(extension)) { + appendResolveExtensionsHint = true; + return `.${extension}`; + } + return extension; + } + ); + if (appendResolveExtensionsHint) { + err.message += `\nDid you miss the leading dot in 'resolve.extensions'? Did you mean '${JSON.stringify( + expectedExtensions + )}' instead of '${JSON.stringify(specifiedExtensions)}'?`; + } + + callback(err); + } + ); + } + callback(err, resolvedResource, resolvedResourceResolveData); + } + ); + } + + /** + * @param {Error} error error + * @param {ModuleFactoryCreateDataContextInfo} contextInfo context info + * @param {string} context context + * @param {string} unresolvedResource unresolved resource + * @param {ResolverWithOptions} resolver resolver + * @param {ResolveContext} resolveContext resolver context + * @param {Callback} callback callback + * @private + */ + _resolveResourceErrorHints( + error, + contextInfo, + context, + unresolvedResource, + resolver, + resolveContext, + callback + ) { + asyncLib.parallel( + [ + (callback) => { + if (!resolver.options.fullySpecified) return callback(); + resolver + .withOptions({ + fullySpecified: false + }) + .resolve( + contextInfo, + context, + unresolvedResource, + resolveContext, + (err, resolvedResource) => { + if (!err && resolvedResource) { + const resource = parseResource(resolvedResource).path.replace( + /^.*[\\/]/, + "" + ); + return callback( + null, + `Did you mean '${resource}'? +BREAKING CHANGE: The request '${unresolvedResource}' failed to resolve only because it was resolved as fully specified +(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"'). +The extension in the request is mandatory for it to be fully specified. +Add the extension to the request.` + ); + } + callback(); + } + ); + }, + (callback) => { + if (!resolver.options.enforceExtension) return callback(); + resolver + .withOptions({ + enforceExtension: false, + extensions: [] + }) + .resolve( + contextInfo, + context, + unresolvedResource, + resolveContext, + (err, resolvedResource) => { + if (!err && resolvedResource) { + let hint = ""; + const match = /(\.[^.]+)(\?|$)/.exec(unresolvedResource); + if (match) { + const fixedRequest = unresolvedResource.replace( + /(\.[^.]+)(\?|$)/, + "$2" + ); + hint = resolver.options.extensions.has(match[1]) + ? `Did you mean '${fixedRequest}'?` + : `Did you mean '${fixedRequest}'? Also note that '${match[1]}' is not in 'resolve.extensions' yet and need to be added for this to work?`; + } else { + hint = + "Did you mean to omit the extension or to remove 'resolve.enforceExtension'?"; + } + return callback( + null, + `The request '${unresolvedResource}' failed to resolve only because 'resolve.enforceExtension' was specified. +${hint} +Including the extension in the request is no longer possible. Did you mean to enforce including the extension in requests with 'resolve.extensions: []' instead?` + ); + } + callback(); + } + ); + }, + (callback) => { + if ( + /^\.\.?\//.test(unresolvedResource) || + resolver.options.preferRelative + ) { + return callback(); + } + resolver.resolve( + contextInfo, + context, + `./${unresolvedResource}`, + resolveContext, + (err, resolvedResource) => { + if (err || !resolvedResource) return callback(); + const moduleDirectories = resolver.options.modules + .map((m) => (Array.isArray(m) ? m.join(", ") : m)) + .join(", "); + callback( + null, + `Did you mean './${unresolvedResource}'? +Requests that should resolve in the current directory need to start with './'. +Requests that start with a name are treated as module requests and resolve within module directories (${moduleDirectories}). +If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.` + ); + } + ); + } + ], + (err, hints) => { + if (err) return callback(err); + callback(null, /** @type {string[]} */ (hints).filter(Boolean)); + } + ); + } + + /** + * @param {ModuleFactoryCreateDataContextInfo} contextInfo context info + * @param {string} context context + * @param {LoaderItem[]} array array + * @param {ResolverWithOptions} resolver resolver + * @param {ResolveContext} resolveContext resolve context + * @param {Callback} callback callback + * @returns {void} result + */ + resolveRequestArray( + contextInfo, + context, + array, + resolver, + resolveContext, + callback + ) { + // LoaderItem + if (array.length === 0) return callback(null, array); + asyncLib.map( + array, + (item, callback) => { + resolver.resolve( + contextInfo, + context, + item.loader, + resolveContext, + (err, result, resolveRequest) => { + if ( + err && + /^[^/]*$/.test(item.loader) && + !item.loader.endsWith("-loader") + ) { + return resolver.resolve( + contextInfo, + context, + `${item.loader}-loader`, + resolveContext, + (err2) => { + if (!err2) { + err.message = + `${err.message}\n` + + "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + + ` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` + + " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; + } + callback(err); + } + ); + } + if (err) return callback(err); + + const parsedResult = this._parseResourceWithoutFragment( + /** @type {string} */ (result) + ); + + const type = /\.mjs$/i.test(parsedResult.path) + ? "module" + : /\.cjs$/i.test(parsedResult.path) + ? "commonjs" + : /** @type {ResolveRequest} */ + (resolveRequest).descriptionFileData === undefined + ? undefined + : /** @type {ResolveRequest} */ + (resolveRequest).descriptionFileData.type; + const resolved = { + loader: parsedResult.path, + type, + options: + item.options === undefined + ? parsedResult.query + ? parsedResult.query.slice(1) + : undefined + : item.options, + ident: + item.options === undefined + ? undefined + : /** @type {string} */ (item.ident) + }; + + return callback(null, /** @type {LoaderItem} */ (resolved)); + } + ); + }, + /** @type {Callback<(LoaderItem | undefined)[]>} */ (callback) + ); + } + + /** + * @param {string} type type + * @param {ParserOptions} parserOptions parser options + * @returns {Parser} parser + */ + getParser(type, parserOptions = EMPTY_PARSER_OPTIONS) { + let cache = this.parserCache.get(type); + + if (cache === undefined) { + cache = new WeakMap(); + this.parserCache.set(type, cache); + } + + let parser = cache.get(parserOptions); + + if (parser === undefined) { + parser = this.createParser(type, parserOptions); + cache.set(parserOptions, parser); + } + + return parser; + } + + /** + * @param {string} type type + * @param {ParserOptions} parserOptions parser options + * @returns {Parser} parser + */ + createParser(type, parserOptions = {}) { + parserOptions = mergeGlobalOptions( + this._globalParserOptions, + type, + parserOptions + ); + const parser = this.hooks.createParser.for(type).call(parserOptions); + if (!parser) { + throw new Error(`No parser registered for ${type}`); + } + this.hooks.parser.for(type).call(parser, parserOptions); + return parser; + } + + /** + * @param {string} type type of generator + * @param {GeneratorOptions} generatorOptions generator options + * @returns {Generator} generator + */ + getGenerator(type, generatorOptions = EMPTY_GENERATOR_OPTIONS) { + let cache = this.generatorCache.get(type); + + if (cache === undefined) { + cache = new WeakMap(); + this.generatorCache.set(type, cache); + } + + let generator = cache.get(generatorOptions); + + if (generator === undefined) { + generator = this.createGenerator(type, generatorOptions); + cache.set(generatorOptions, generator); + } + + return generator; + } + + /** + * @param {string} type type of generator + * @param {GeneratorOptions} generatorOptions generator options + * @returns {Generator} generator + */ + createGenerator(type, generatorOptions = {}) { + generatorOptions = mergeGlobalOptions( + this._globalGeneratorOptions, + type, + generatorOptions + ); + const generator = this.hooks.createGenerator + .for(type) + .call(generatorOptions); + if (!generator) { + throw new Error(`No generator registered for ${type}`); + } + this.hooks.generator.for(type).call(generator, generatorOptions); + return generator; + } + + /** + * @param {Parameters[0]} type type of resolver + * @param {Parameters[1]=} resolveOptions options + * @returns {ReturnType} the resolver + */ + getResolver(type, resolveOptions) { + return this.resolverFactory.get(type, resolveOptions); + } +} + +module.exports = NormalModuleFactory; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NormalModuleReplacementPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NormalModuleReplacementPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..aa7eea7d6a21b0415c29b4b611145067611c6d8c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NormalModuleReplacementPlugin.js @@ -0,0 +1,75 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { dirname, join } = require("./util/fs"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +/** @typedef {(resolveData: ResolveData) => void} ModuleReplacer */ + +const PLUGIN_NAME = "NormalModuleReplacementPlugin"; + +class NormalModuleReplacementPlugin { + /** + * Create an instance of the plugin + * @param {RegExp} resourceRegExp the resource matcher + * @param {string | ModuleReplacer} newResource the resource replacement + */ + constructor(resourceRegExp, newResource) { + this.resourceRegExp = resourceRegExp; + this.newResource = newResource; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const resourceRegExp = this.resourceRegExp; + const newResource = this.newResource; + compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (nmf) => { + nmf.hooks.beforeResolve.tap(PLUGIN_NAME, (result) => { + if (resourceRegExp.test(result.request)) { + if (typeof newResource === "function") { + newResource(result); + } else { + result.request = newResource; + } + } + }); + nmf.hooks.afterResolve.tap(PLUGIN_NAME, (result) => { + const createData = result.createData; + if (resourceRegExp.test(/** @type {string} */ (createData.resource))) { + if (typeof newResource === "function") { + newResource(result); + } else { + const fs = + /** @type {InputFileSystem} */ + (compiler.inputFileSystem); + if ( + newResource.startsWith("/") || + (newResource.length > 1 && newResource[1] === ":") + ) { + createData.resource = newResource; + } else { + createData.resource = join( + fs, + dirname(fs, /** @type {string} */ (createData.resource)), + newResource + ); + } + } + } + }); + }); + } +} + +module.exports = NormalModuleReplacementPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NullFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NullFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..f420508ca7d746149ecbc407abb8c7117c4bbac2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/NullFactory.js @@ -0,0 +1,24 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleFactory = require("./ModuleFactory"); + +/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ + +class NullFactory extends ModuleFactory { + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create(data, callback) { + return callback(); + } +} + +module.exports = NullFactory; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/OptimizationStages.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/OptimizationStages.js new file mode 100644 index 0000000000000000000000000000000000000000..c464b8abef35a38aa529cc11f3250dbc46e0f7df --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/OptimizationStages.js @@ -0,0 +1,10 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +module.exports.STAGE_ADVANCED = 10; +module.exports.STAGE_BASIC = -10; +module.exports.STAGE_DEFAULT = 0; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/OptionsApply.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/OptionsApply.js new file mode 100644 index 0000000000000000000000000000000000000000..b7a3941543be5cd61cd6a012ce4ea7c5373e631f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/OptionsApply.js @@ -0,0 +1,22 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Compiler")} Compiler */ + +class OptionsApply { + /** + * @param {WebpackOptions} options options object + * @param {Compiler} compiler compiler object + * @returns {WebpackOptions} options object + */ + process(options, compiler) { + return options; + } +} + +module.exports = OptionsApply; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Parser.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Parser.js new file mode 100644 index 0000000000000000000000000000000000000000..8a5c4fdf704eba267954f8501faf4cdfe2587748 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Parser.js @@ -0,0 +1,40 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./NormalModule")} NormalModule */ + +/** @typedef {Record} PreparsedAst */ + +/** + * @typedef {object} ParserStateBase + * @property {string | Buffer} source + * @property {NormalModule} current + * @property {NormalModule} module + * @property {Compilation} compilation + * @property {WebpackOptions} options + */ + +/** @typedef {Record & ParserStateBase} ParserState */ + +class Parser { + /* istanbul ignore next */ + /** + * @abstract + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } +} + +module.exports = Parser; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/PlatformPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/PlatformPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..57a8808cedaa7e365a80b1879e23051a1e89aab9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/PlatformPlugin.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Authors Ivan Kopeykin @vankop +*/ + +"use strict"; + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./config/target").PlatformTargetProperties} PlatformTargetProperties */ + +const PLUGIN_NAME = "PlatformPlugin"; + +/** + * Should be used only for "target === false" or + * when you want to overwrite platform target properties + */ +class PlatformPlugin { + /** + * @param {Partial} platform target properties + */ + constructor(platform) { + /** @type {Partial} */ + this.platform = platform; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.environment.tap(PLUGIN_NAME, () => { + compiler.platform = { + ...compiler.platform, + ...this.platform + }; + }); + } +} + +module.exports = PlatformPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/PrefetchPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/PrefetchPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..52cf9647bb1719702f714fca562c088f4612f214 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/PrefetchPlugin.js @@ -0,0 +1,56 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const PrefetchDependency = require("./dependencies/PrefetchDependency"); + +/** @typedef {import("./Compiler")} Compiler */ + +const PLUGIN_NAME = "PrefetchPlugin"; + +class PrefetchPlugin { + /** + * @param {string} context context or request if context is not set + * @param {string=} request request + */ + constructor(context, request) { + if (request) { + this.context = context; + this.request = request; + } else { + this.context = null; + this.request = context; + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory + ); + } + ); + compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { + compilation.addModuleChain( + this.context || compiler.context, + new PrefetchDependency(this.request), + (err) => { + callback(err); + } + ); + }); + } +} + +module.exports = PrefetchPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ProgressPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ProgressPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9577f93a81f1b93abc0215e123c078a04bc23423 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ProgressPlugin.js @@ -0,0 +1,712 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Compiler = require("./Compiler"); +const MultiCompiler = require("./MultiCompiler"); +const NormalModule = require("./NormalModule"); +const createSchemaValidation = require("./util/create-schema-validation"); +const { contextify } = require("./util/identifier"); + +/** @typedef {import("tapable").Tap} Tap */ +/** + * @template T, R, AdditionalOptions + * @typedef {import("tapable").Hook} Hook + */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ +/** @typedef {import("./Compilation").FactorizeModuleOptions} FactorizeModuleOptions */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./logging/Logger").Logger} Logger */ + +/** + * @template T, K, R + * @typedef {import("./util/AsyncQueue")} AsyncQueue + */ + +/** + * @typedef {object} CountsData + * @property {number} modulesCount modules count + * @property {number} dependenciesCount dependencies count + */ + +const validate = createSchemaValidation( + require("../schemas/plugins/ProgressPlugin.check"), + () => require("../schemas/plugins/ProgressPlugin.json"), + { + name: "Progress Plugin", + baseDataPath: "options" + } +); + +/** + * @param {number} a a + * @param {number} b b + * @param {number} c c + * @returns {number} median + */ +const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c); + +/** + * @param {boolean | null | undefined} profile need profile + * @param {Logger} logger logger + * @returns {defaultHandler} default handler + */ +const createDefaultHandler = (profile, logger) => { + /** @type {{ value: string | undefined, time: number }[]} */ + const lastStateInfo = []; + + /** + * @param {number} percentage percentage + * @param {string} msg message + * @param {...string} args additional arguments + */ + const defaultHandler = (percentage, msg, ...args) => { + if (profile) { + if (percentage === 0) { + lastStateInfo.length = 0; + } + const fullState = [msg, ...args]; + const state = fullState.map((s) => s.replace(/\d+\/\d+ /g, "")); + const now = Date.now(); + const len = Math.max(state.length, lastStateInfo.length); + for (let i = len; i >= 0; i--) { + const stateItem = i < state.length ? state[i] : undefined; + const lastStateItem = + i < lastStateInfo.length ? lastStateInfo[i] : undefined; + if (lastStateItem) { + if (stateItem !== lastStateItem.value) { + const diff = now - lastStateItem.time; + if (lastStateItem.value) { + let reportState = lastStateItem.value; + if (i > 0) { + reportState = `${lastStateInfo[i - 1].value} > ${reportState}`; + } + const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`; + const d = diff; + // This depends on timing so we ignore it for coverage + /* eslint-disable no-lone-blocks */ + /* istanbul ignore next */ + { + if (d > 10000) { + logger.error(stateMsg); + } else if (d > 1000) { + logger.warn(stateMsg); + } else if (d > 10) { + logger.info(stateMsg); + } else if (d > 5) { + logger.log(stateMsg); + } else { + logger.debug(stateMsg); + } + } + /* eslint-enable no-lone-blocks */ + } + if (stateItem === undefined) { + lastStateInfo.length = i; + } else { + lastStateItem.value = stateItem; + lastStateItem.time = now; + lastStateInfo.length = i + 1; + } + } + } else { + lastStateInfo[i] = { + value: stateItem, + time: now + }; + } + } + } + logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); + if (percentage === 1 || (!msg && args.length === 0)) logger.status(); + }; + + return defaultHandler; +}; + +const SKIPPED_QUEUE_CONTEXTS = ["import-module", "load-module"]; + +/** + * @callback ReportProgress + * @param {number} p percentage + * @param {...string} args additional arguments + * @returns {void} + */ + +/** @type {WeakMap} */ +const progressReporters = new WeakMap(); + +const PLUGIN_NAME = "ProgressPlugin"; + +class ProgressPlugin { + /** + * @param {Compiler} compiler the current compiler + * @returns {ReportProgress | undefined} a progress reporter, if any + */ + static getReporter(compiler) { + return progressReporters.get(compiler); + } + + /** + * @param {ProgressPluginArgument} options options + */ + constructor(options = {}) { + if (typeof options === "function") { + options = { + handler: options + }; + } + + validate(options); + options = { ...ProgressPlugin.defaultOptions, ...options }; + + this.profile = options.profile; + this.handler = options.handler; + this.modulesCount = options.modulesCount; + this.dependenciesCount = options.dependenciesCount; + this.showEntries = options.entries; + this.showModules = options.modules; + this.showDependencies = options.dependencies; + this.showActiveModules = options.activeModules; + this.percentBy = options.percentBy; + } + + /** + * @param {Compiler | MultiCompiler} compiler webpack compiler + * @returns {void} + */ + apply(compiler) { + const handler = + this.handler || + createDefaultHandler( + this.profile, + compiler.getInfrastructureLogger("webpack.Progress") + ); + if (compiler instanceof MultiCompiler) { + this._applyOnMultiCompiler(compiler, handler); + } else if (compiler instanceof Compiler) { + this._applyOnCompiler(compiler, handler); + } + } + + /** + * @param {MultiCompiler} compiler webpack multi-compiler + * @param {HandlerFunction} handler function that executes for every progress step + * @returns {void} + */ + _applyOnMultiCompiler(compiler, handler) { + const states = compiler.compilers.map( + () => /** @type {[number, ...string[]]} */ ([0]) + ); + for (const [idx, item] of compiler.compilers.entries()) { + new ProgressPlugin((p, msg, ...args) => { + states[idx] = [p, msg, ...args]; + let sum = 0; + for (const [p] of states) sum += p; + handler(sum / states.length, `[${idx}] ${msg}`, ...args); + }).apply(item); + } + } + + /** + * @param {Compiler} compiler webpack compiler + * @param {HandlerFunction} handler function that executes for every progress step + * @returns {void} + */ + _applyOnCompiler(compiler, handler) { + const showEntries = this.showEntries; + const showModules = this.showModules; + const showDependencies = this.showDependencies; + const showActiveModules = this.showActiveModules; + let lastActiveModule = ""; + let currentLoader = ""; + let lastModulesCount = 0; + let lastDependenciesCount = 0; + let lastEntriesCount = 0; + let modulesCount = 0; + let skippedModulesCount = 0; + let dependenciesCount = 0; + let skippedDependenciesCount = 0; + let entriesCount = 1; + let doneModules = 0; + let doneDependencies = 0; + let doneEntries = 0; + const activeModules = new Set(); + let lastUpdate = 0; + + const updateThrottled = () => { + if (lastUpdate + 500 < Date.now()) update(); + }; + + const update = () => { + /** @type {string[]} */ + const items = []; + const percentByModules = + doneModules / + Math.max(lastModulesCount || this.modulesCount || 1, modulesCount); + const percentByEntries = + doneEntries / + Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount); + const percentByDependencies = + doneDependencies / + Math.max(lastDependenciesCount || 1, dependenciesCount); + let percentageFactor; + + switch (this.percentBy) { + case "entries": + percentageFactor = percentByEntries; + break; + case "dependencies": + percentageFactor = percentByDependencies; + break; + case "modules": + percentageFactor = percentByModules; + break; + default: + percentageFactor = median3( + percentByModules, + percentByEntries, + percentByDependencies + ); + } + + const percentage = 0.1 + percentageFactor * 0.55; + + if (currentLoader) { + items.push( + `import loader ${contextify( + compiler.context, + currentLoader, + compiler.root + )}` + ); + } else { + const statItems = []; + if (showEntries) { + statItems.push(`${doneEntries}/${entriesCount} entries`); + } + if (showDependencies) { + statItems.push( + `${doneDependencies}/${dependenciesCount} dependencies` + ); + } + if (showModules) { + statItems.push(`${doneModules}/${modulesCount} modules`); + } + if (showActiveModules) { + statItems.push(`${activeModules.size} active`); + } + if (statItems.length > 0) { + items.push(statItems.join(" ")); + } + if (showActiveModules) { + items.push(lastActiveModule); + } + } + handler(percentage, "building", ...items); + lastUpdate = Date.now(); + }; + + /** + * @template T + * @param {AsyncQueue} factorizeQueue async queue + * @param {T} _item item + */ + const factorizeAdd = (factorizeQueue, _item) => { + if (SKIPPED_QUEUE_CONTEXTS.includes(factorizeQueue.getContext())) { + skippedDependenciesCount++; + } + dependenciesCount++; + if (dependenciesCount < 50 || dependenciesCount % 100 === 0) { + updateThrottled(); + } + }; + + const factorizeDone = () => { + doneDependencies++; + if (doneDependencies < 50 || doneDependencies % 100 === 0) { + updateThrottled(); + } + }; + + /** + * @template T + * @param {AsyncQueue} addModuleQueue async queue + * @param {T} _item item + */ + const moduleAdd = (addModuleQueue, _item) => { + if (SKIPPED_QUEUE_CONTEXTS.includes(addModuleQueue.getContext())) { + skippedModulesCount++; + } + modulesCount++; + if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled(); + }; + + // only used when showActiveModules is set + /** + * @param {Module} module the module + */ + const moduleBuild = (module) => { + const ident = module.identifier(); + if (ident) { + activeModules.add(ident); + lastActiveModule = ident; + update(); + } + }; + + /** + * @param {Dependency} entry entry dependency + * @param {EntryOptions} options options object + */ + const entryAdd = (entry, options) => { + entriesCount++; + if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled(); + }; + + /** + * @param {Module} module the module + */ + const moduleDone = (module) => { + doneModules++; + if (showActiveModules) { + const ident = module.identifier(); + if (ident) { + activeModules.delete(ident); + if (lastActiveModule === ident) { + lastActiveModule = ""; + for (const m of activeModules) { + lastActiveModule = m; + } + update(); + return; + } + } + } + if (doneModules < 50 || doneModules % 100 === 0) updateThrottled(); + }; + + /** + * @param {Dependency} entry entry dependency + * @param {EntryOptions} options options object + */ + const entryDone = (entry, options) => { + doneEntries++; + update(); + }; + + const cache = compiler.getCache(PLUGIN_NAME).getItemCache("counts", null); + + /** @type {Promise | undefined} */ + let cacheGetPromise; + + compiler.hooks.beforeCompile.tap(PLUGIN_NAME, () => { + if (!cacheGetPromise) { + cacheGetPromise = cache.getPromise().then( + (data) => { + if (data) { + lastModulesCount = lastModulesCount || data.modulesCount; + lastDependenciesCount = + lastDependenciesCount || data.dependenciesCount; + } + return data; + }, + (_err) => { + // Ignore error + } + ); + } + }); + + compiler.hooks.afterCompile.tapPromise(PLUGIN_NAME, (compilation) => { + if (compilation.compiler.isChild()) return Promise.resolve(); + return /** @type {Promise} */ (cacheGetPromise).then( + async (oldData) => { + const realModulesCount = modulesCount - skippedModulesCount; + const realDependenciesCount = + dependenciesCount - skippedDependenciesCount; + + if ( + !oldData || + oldData.modulesCount !== realModulesCount || + oldData.dependenciesCount !== realDependenciesCount + ) { + await cache.storePromise({ + modulesCount: realModulesCount, + dependenciesCount: realDependenciesCount + }); + } + } + ); + }); + + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + if (compilation.compiler.isChild()) return; + lastModulesCount = modulesCount; + lastEntriesCount = entriesCount; + lastDependenciesCount = dependenciesCount; + modulesCount = + skippedModulesCount = + dependenciesCount = + skippedDependenciesCount = + entriesCount = + 0; + doneModules = doneDependencies = doneEntries = 0; + + compilation.factorizeQueue.hooks.added.tap(PLUGIN_NAME, (item) => + factorizeAdd(compilation.factorizeQueue, item) + ); + compilation.factorizeQueue.hooks.result.tap(PLUGIN_NAME, factorizeDone); + + compilation.addModuleQueue.hooks.added.tap(PLUGIN_NAME, (item) => + moduleAdd(compilation.addModuleQueue, item) + ); + compilation.processDependenciesQueue.hooks.result.tap( + PLUGIN_NAME, + moduleDone + ); + + if (showActiveModules) { + compilation.hooks.buildModule.tap(PLUGIN_NAME, moduleBuild); + } + + compilation.hooks.addEntry.tap(PLUGIN_NAME, entryAdd); + compilation.hooks.failedEntry.tap(PLUGIN_NAME, entryDone); + compilation.hooks.succeedEntry.tap(PLUGIN_NAME, entryDone); + + // @ts-expect-error avoid dynamic require if bundled with webpack + if (typeof __webpack_require__ !== "function") { + const requiredLoaders = new Set(); + NormalModule.getCompilationHooks(compilation).beforeLoaders.tap( + PLUGIN_NAME, + (loaders) => { + for (const loader of loaders) { + if ( + loader.type !== "module" && + !requiredLoaders.has(loader.loader) + ) { + requiredLoaders.add(loader.loader); + currentLoader = loader.loader; + update(); + require(loader.loader); + } + } + if (currentLoader) { + currentLoader = ""; + update(); + } + } + ); + } + + const hooks = { + finishModules: "finish module graph", + seal: "plugins", + optimizeDependencies: "dependencies optimization", + afterOptimizeDependencies: "after dependencies optimization", + beforeChunks: "chunk graph", + afterChunks: "after chunk graph", + optimize: "optimizing", + optimizeModules: "module optimization", + afterOptimizeModules: "after module optimization", + optimizeChunks: "chunk optimization", + afterOptimizeChunks: "after chunk optimization", + optimizeTree: "module and chunk tree optimization", + afterOptimizeTree: "after module and chunk tree optimization", + optimizeChunkModules: "chunk modules optimization", + afterOptimizeChunkModules: "after chunk modules optimization", + reviveModules: "module reviving", + beforeModuleIds: "before module ids", + moduleIds: "module ids", + optimizeModuleIds: "module id optimization", + afterOptimizeModuleIds: "module id optimization", + reviveChunks: "chunk reviving", + beforeChunkIds: "before chunk ids", + chunkIds: "chunk ids", + optimizeChunkIds: "chunk id optimization", + afterOptimizeChunkIds: "after chunk id optimization", + recordModules: "record modules", + recordChunks: "record chunks", + beforeModuleHash: "module hashing", + beforeCodeGeneration: "code generation", + beforeRuntimeRequirements: "runtime requirements", + beforeHash: "hashing", + afterHash: "after hashing", + recordHash: "record hash", + beforeModuleAssets: "module assets processing", + beforeChunkAssets: "chunk assets processing", + processAssets: "asset processing", + afterProcessAssets: "after asset optimization", + record: "recording", + afterSeal: "after seal" + }; + const numberOfHooks = Object.keys(hooks).length; + for (const [idx, name] of Object.keys(hooks).entries()) { + const title = hooks[/** @type {keyof typeof hooks} */ (name)]; + const percentage = (idx / numberOfHooks) * 0.25 + 0.7; + compilation.hooks[/** @type {keyof typeof hooks} */ (name)].intercept({ + name: PLUGIN_NAME, + call() { + handler(percentage, "sealing", title); + }, + done() { + progressReporters.set(compiler, undefined); + handler(percentage, "sealing", title); + }, + result() { + handler(percentage, "sealing", title); + }, + error() { + handler(percentage, "sealing", title); + }, + tap(tap) { + // p is percentage from 0 to 1 + // args is any number of messages in a hierarchical matter + progressReporters.set(compilation.compiler, (p, ...args) => { + handler(percentage, "sealing", title, tap.name, ...args); + }); + handler(percentage, "sealing", title, tap.name); + } + }); + } + }); + compiler.hooks.make.intercept({ + name: PLUGIN_NAME, + call() { + handler(0.1, "building"); + }, + done() { + handler(0.65, "building"); + } + }); + /** + * @template {Hook} T + * @param {T} hook hook + * @param {number} progress progress from 0 to 1 + * @param {string} category category + * @param {string} name name + */ + const interceptHook = (hook, progress, category, name) => { + hook.intercept({ + name: PLUGIN_NAME, + call() { + handler(progress, category, name); + }, + done() { + progressReporters.set(compiler, undefined); + handler(progress, category, name); + }, + result() { + handler(progress, category, name); + }, + error() { + handler(progress, category, name); + }, + /** + * @param {Tap} tap tap + */ + tap(tap) { + progressReporters.set(compiler, (p, ...args) => { + handler(progress, category, name, tap.name, ...args); + }); + handler(progress, category, name, tap.name); + } + }); + }; + compiler.cache.hooks.endIdle.intercept({ + name: PLUGIN_NAME, + call() { + handler(0, ""); + } + }); + interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle"); + compiler.hooks.beforeRun.intercept({ + name: PLUGIN_NAME, + call() { + handler(0, ""); + } + }); + interceptHook(compiler.hooks.beforeRun, 0.01, "setup", "before run"); + interceptHook(compiler.hooks.run, 0.02, "setup", "run"); + interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run"); + interceptHook( + compiler.hooks.normalModuleFactory, + 0.04, + "setup", + "normal module factory" + ); + interceptHook( + compiler.hooks.contextModuleFactory, + 0.05, + "setup", + "context module factory" + ); + interceptHook( + compiler.hooks.beforeCompile, + 0.06, + "setup", + "before compile" + ); + interceptHook(compiler.hooks.compile, 0.07, "setup", "compile"); + interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation"); + interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation"); + interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish"); + interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit"); + interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit"); + interceptHook(compiler.hooks.done, 0.99, "done", "plugins"); + compiler.hooks.done.intercept({ + name: PLUGIN_NAME, + done() { + handler(0.99, ""); + } + }); + interceptHook( + compiler.cache.hooks.storeBuildDependencies, + 0.99, + "cache", + "store build dependencies" + ); + interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown"); + interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle"); + interceptHook( + compiler.hooks.watchClose, + 0.99, + "end", + "closing watch compilation" + ); + compiler.cache.hooks.beginIdle.intercept({ + name: PLUGIN_NAME, + done() { + handler(1, ""); + } + }); + compiler.cache.hooks.shutdown.intercept({ + name: PLUGIN_NAME, + done() { + handler(1, ""); + } + }); + } +} + +ProgressPlugin.defaultOptions = { + profile: false, + modulesCount: 5000, + dependenciesCount: 10000, + modules: true, + dependencies: true, + activeModules: false, + entries: true +}; + +ProgressPlugin.createDefaultHandler = createDefaultHandler; + +module.exports = ProgressPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ProvidePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ProvidePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..898bd0d08470916a02fa997405f09298adf56447 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ProvidePlugin.js @@ -0,0 +1,123 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("./ModuleTypeConstants"); +const ConstDependency = require("./dependencies/ConstDependency"); +const ProvidedDependency = require("./dependencies/ProvidedDependency"); +const { approve } = require("./javascript/JavascriptParserHelpers"); + +/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "ProvidePlugin"; + +class ProvidePlugin { + /** + * @param {Record} definitions the provided identifiers + */ + constructor(definitions) { + this.definitions = definitions; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + compilation.dependencyFactories.set( + ProvidedDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ProvidedDependency, + new ProvidedDependency.Template() + ); + /** + * @param {JavascriptParser} parser the parser + * @param {JavascriptParserOptions} parserOptions options + * @returns {void} + */ + const handler = (parser, parserOptions) => { + for (const name of Object.keys(definitions)) { + const request = + /** @type {string[]} */ + ([ + ...(Array.isArray(definitions[name]) + ? definitions[name] + : [definitions[name]]) + ]); + const splittedName = name.split("."); + if (splittedName.length > 0) { + for (const [i, _] of splittedName.slice(1).entries()) { + const name = splittedName.slice(0, i + 1).join("."); + parser.hooks.canRename.for(name).tap(PLUGIN_NAME, approve); + } + } + + parser.hooks.expression.for(name).tap(PLUGIN_NAME, (expr) => { + const nameIdentifier = name.includes(".") + ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` + : name; + const dep = new ProvidedDependency( + request[0], + nameIdentifier, + request.slice(1), + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + return true; + }); + + parser.hooks.call.for(name).tap(PLUGIN_NAME, (expr) => { + const nameIdentifier = name.includes(".") + ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` + : name; + const dep = new ProvidedDependency( + request[0], + nameIdentifier, + request.slice(1), + /** @type {Range} */ (expr.callee.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.callee.loc); + parser.state.module.addDependency(dep); + parser.walkExpressions(expr.arguments); + return true; + }); + } + }; + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = ProvidePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RawModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RawModule.js new file mode 100644 index 0000000000000000000000000000000000000000..a04222520ba6add57fb2129608a97983159a7c2f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RawModule.js @@ -0,0 +1,180 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { OriginalSource, RawSource } = require("webpack-sources"); +const Module = require("./Module"); +const { JS_TYPES } = require("./ModuleSourceTypesConstants"); +const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator").SourceTypes} SourceTypes */ +/** @typedef {import("./Module").BuildCallback} BuildCallback */ +/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +class RawModule extends Module { + /** + * @param {string} source source code + * @param {string} identifier unique identifier + * @param {string=} readableIdentifier readable identifier + * @param {ReadOnlyRuntimeRequirements=} runtimeRequirements runtime requirements needed for the source code + */ + constructor(source, identifier, readableIdentifier, runtimeRequirements) { + super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null); + this.sourceStr = source; + this.identifierStr = identifier || this.sourceStr; + this.readableIdentifierStr = readableIdentifier || this.identifierStr; + this.runtimeRequirements = runtimeRequirements || null; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return JS_TYPES; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this.identifierStr; + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return Math.max(1, this.sourceStr.length); + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return /** @type {string} */ ( + requestShortener.shorten(this.readableIdentifierStr) + ); + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + cacheable: true + }; + callback(); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + */ + getSideEffectsConnectionState(moduleGraph) { + if (this.factoryMeta !== undefined) { + if (this.factoryMeta.sideEffectFree) return false; + if (this.factoryMeta.sideEffectFree === false) return true; + } + return true; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + const sources = new Map(); + if (this.useSourceMap || this.useSimpleSourceMap) { + sources.set( + "javascript", + new OriginalSource(this.sourceStr, this.identifier()) + ); + } else { + sources.set("javascript", new RawSource(this.sourceStr)); + } + return { sources, runtimeRequirements: this.runtimeRequirements }; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(this.sourceStr); + super.updateHash(hash, context); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.sourceStr); + write(this.identifierStr); + write(this.readableIdentifierStr); + write(this.runtimeRequirements); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.sourceStr = read(); + this.identifierStr = read(); + this.readableIdentifierStr = read(); + this.runtimeRequirements = read(); + + super.deserialize(context); + } +} + +makeSerializable(RawModule, "webpack/lib/RawModule"); + +module.exports = RawModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RecordIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RecordIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..fa7cb8ce2dbcebdfea16b4df97277abf1c7ac3e7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RecordIdsPlugin.js @@ -0,0 +1,212 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { compareNumbers } = require("./util/comparators"); +const identifierUtils = require("./util/identifier"); + +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ + +/** + * @typedef {object} RecordsChunks + * @property {Record=} byName + * @property {Record=} bySource + * @property {number[]=} usedIds + */ + +/** + * @typedef {object} RecordsModules + * @property {Record=} byIdentifier + * @property {number[]=} usedIds + */ + +/** + * @typedef {object} Records + * @property {RecordsChunks=} chunks + * @property {RecordsModules=} modules + */ + +/** + * @typedef {object} RecordIdsPluginOptions + * @property {boolean=} portableIds true, when ids need to be portable + */ + +const PLUGIN_NAME = "RecordIdsPlugin"; + +class RecordIdsPlugin { + /** + * @param {RecordIdsPluginOptions=} options object + */ + constructor(options) { + this.options = options || {}; + } + + /** + * @param {Compiler} compiler the Compiler + * @returns {void} + */ + apply(compiler) { + const portableIds = this.options.portableIds; + + const makePathsRelative = + identifierUtils.makePathsRelative.bindContextCache( + compiler.context, + compiler.root + ); + + /** + * @param {Module} module the module + * @returns {string} the (portable) identifier + */ + const getModuleIdentifier = (module) => { + if (portableIds) { + return makePathsRelative(module.identifier()); + } + return module.identifier(); + }; + + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.recordModules.tap(PLUGIN_NAME, (modules, records) => { + const chunkGraph = compilation.chunkGraph; + if (!records.modules) records.modules = {}; + if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; + /** @type {Set} */ + const usedIds = new Set(); + for (const module of modules) { + const moduleId = chunkGraph.getModuleId(module); + if (typeof moduleId !== "number") continue; + const identifier = getModuleIdentifier(module); + records.modules.byIdentifier[identifier] = moduleId; + usedIds.add(moduleId); + } + records.modules.usedIds = [...usedIds].sort(compareNumbers); + }); + compilation.hooks.reviveModules.tap(PLUGIN_NAME, (modules, records) => { + if (!records.modules) return; + if (records.modules.byIdentifier) { + const chunkGraph = compilation.chunkGraph; + /** @type {Set} */ + const usedIds = new Set(); + for (const module of modules) { + const moduleId = chunkGraph.getModuleId(module); + if (moduleId !== null) continue; + const identifier = getModuleIdentifier(module); + const id = records.modules.byIdentifier[identifier]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunkGraph.setModuleId(module, id); + } + } + if (Array.isArray(records.modules.usedIds)) { + compilation.usedModuleIds = new Set(records.modules.usedIds); + } + }); + + /** + * @param {Chunk} chunk the chunk + * @returns {string[]} sources of the chunk + */ + const getChunkSources = (chunk) => { + /** @type {string[]} */ + const sources = []; + for (const chunkGroup of chunk.groupsIterable) { + const index = chunkGroup.chunks.indexOf(chunk); + if (chunkGroup.name) { + sources.push(`${index} ${chunkGroup.name}`); + } else { + for (const origin of chunkGroup.origins) { + if (origin.module) { + if (origin.request) { + sources.push( + `${index} ${getModuleIdentifier(origin.module)} ${ + origin.request + }` + ); + } else if (typeof origin.loc === "string") { + sources.push( + `${index} ${getModuleIdentifier(origin.module)} ${ + origin.loc + }` + ); + } else if ( + origin.loc && + typeof origin.loc === "object" && + "start" in origin.loc + ) { + sources.push( + `${index} ${getModuleIdentifier( + origin.module + )} ${JSON.stringify(origin.loc.start)}` + ); + } + } + } + } + } + return sources; + }; + + compilation.hooks.recordChunks.tap(PLUGIN_NAME, (chunks, records) => { + if (!records.chunks) records.chunks = {}; + if (!records.chunks.byName) records.chunks.byName = {}; + if (!records.chunks.bySource) records.chunks.bySource = {}; + /** @type {Set} */ + const usedIds = new Set(); + for (const chunk of chunks) { + if (typeof chunk.id !== "number") continue; + const name = chunk.name; + if (name) records.chunks.byName[name] = chunk.id; + const sources = getChunkSources(chunk); + for (const source of sources) { + records.chunks.bySource[source] = chunk.id; + } + usedIds.add(chunk.id); + } + records.chunks.usedIds = [...usedIds].sort(compareNumbers); + }); + compilation.hooks.reviveChunks.tap(PLUGIN_NAME, (chunks, records) => { + if (!records.chunks) return; + /** @type {Set} */ + const usedIds = new Set(); + if (records.chunks.byName) { + for (const chunk of chunks) { + if (chunk.id !== null) continue; + if (!chunk.name) continue; + const id = records.chunks.byName[chunk.name]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + chunk.ids = [id]; + } + } + if (records.chunks.bySource) { + for (const chunk of chunks) { + if (chunk.id !== null) continue; + const sources = getChunkSources(chunk); + for (const source of sources) { + const id = records.chunks.bySource[source]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + chunk.ids = [id]; + break; + } + } + } + if (Array.isArray(records.chunks.usedIds)) { + compilation.usedChunkIds = new Set(records.chunks.usedIds); + } + }); + }); + } +} + +module.exports = RecordIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RequestShortener.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RequestShortener.js new file mode 100644 index 0000000000000000000000000000000000000000..b39bc2e738499d2cfdfaaccbceb34bb1e89623d8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RequestShortener.js @@ -0,0 +1,36 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { contextify } = require("./util/identifier"); + +/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ + +class RequestShortener { + /** + * @param {string} dir the directory + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached + */ + constructor(dir, associatedObjectForCache) { + this.contextify = contextify.bindContextCache( + dir, + associatedObjectForCache + ); + } + + /** + * @param {string | undefined | null} request the request to shorten + * @returns {string | undefined | null} the shortened request + */ + shorten(request) { + if (!request) { + return request; + } + return this.contextify(request); + } +} + +module.exports = RequestShortener; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RequireJsStuffPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RequireJsStuffPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..c9acc6643dda9b341f2d0870a2741352f196d73d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RequireJsStuffPlugin.js @@ -0,0 +1,84 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC +} = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const ConstDependency = require("./dependencies/ConstDependency"); +const { + toConstantDependency +} = require("./javascript/JavascriptParserHelpers"); + +/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + +const PLUGIN_NAME = "RequireJsStuffPlugin"; + +module.exports = class RequireJsStuffPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + /** + * @param {JavascriptParser} parser the parser + * @param {JavascriptParserOptions} parserOptions options + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireJs === undefined || + !parserOptions.requireJs + ) { + return; + } + + parser.hooks.call + .for("require.config") + .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined")); + parser.hooks.call + .for("requirejs.config") + .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined")); + + parser.hooks.expression + .for("require.version") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("0.0.0")) + ); + parser.hooks.expression + .for("requirejs.onError") + .tap( + PLUGIN_NAME, + toConstantDependency( + parser, + RuntimeGlobals.uncaughtErrorHandler, + [RuntimeGlobals.uncaughtErrorHandler] + ) + ); + }; + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + } + ); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ResolverFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ResolverFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..697fdee5c16677a4543bc78d933be10fc21edb52 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ResolverFactory.js @@ -0,0 +1,158 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Factory = require("enhanced-resolve").ResolverFactory; +const { HookMap, SyncHook, SyncWaterfallHook } = require("tapable"); +const { + cachedCleverMerge, + removeOperations, + resolveByProperty +} = require("./util/cleverMerge"); + +/** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */ +/** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */ +/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */ +/** @typedef {import("enhanced-resolve").Resolver} Resolver */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */ + +/** @typedef {WebpackResolveOptions & { dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */ +/** + * @typedef {object} WithOptions + * @property {(options: Partial) => ResolverWithOptions} withOptions create a resolver with additional/different options + */ + +/** @typedef {Resolver & WithOptions} ResolverWithOptions */ + +// need to be hoisted on module level for caching identity +/** @type {ResolveOptionsWithDependencyType} */ +const EMPTY_RESOLVE_OPTIONS = {}; + +/** + * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType enhanced options + * @returns {ResolveOptions} merged options + */ +const convertToResolveOptions = (resolveOptionsWithDepType) => { + const { dependencyType, plugins, ...remaining } = resolveOptionsWithDepType; + + // check type compat + /** @type {Partial} */ + const partialOptions = { + ...remaining, + plugins: + plugins && + /** @type {ResolvePluginInstance[]} */ ( + plugins.filter((item) => item !== "...") + ) + }; + + if (!partialOptions.fileSystem) { + throw new Error( + "fileSystem is missing in resolveOptions, but it's required for enhanced-resolve" + ); + } + // These weird types validate that we checked all non-optional properties + const options = + /** @type {Partial & Pick} */ ( + partialOptions + ); + + return /** @type {ResolveOptions} */ ( + removeOperations( + resolveByProperty(options, "byDependency", dependencyType), + // Keep the `unsafeCache` because it can be a `Proxy` + ["unsafeCache"] + ) + ); +}; + +/** + * @typedef {object} ResolverCache + * @property {WeakMap} direct + * @property {Map} stringified + */ + +module.exports = class ResolverFactory { + constructor() { + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + resolveOptions: new HookMap( + () => new SyncWaterfallHook(["resolveOptions"]) + ), + /** @type {HookMap>} */ + resolver: new HookMap( + () => new SyncHook(["resolver", "resolveOptions", "userResolveOptions"]) + ) + }); + /** @type {Map} */ + this.cache = new Map(); + } + + /** + * @param {string} type type of resolver + * @param {ResolveOptionsWithDependencyType=} resolveOptions options + * @returns {ResolverWithOptions} the resolver + */ + get(type, resolveOptions = EMPTY_RESOLVE_OPTIONS) { + let typedCaches = this.cache.get(type); + if (!typedCaches) { + typedCaches = { + direct: new WeakMap(), + stringified: new Map() + }; + this.cache.set(type, typedCaches); + } + const cachedResolver = typedCaches.direct.get(resolveOptions); + if (cachedResolver) { + return cachedResolver; + } + const ident = JSON.stringify(resolveOptions); + const resolver = typedCaches.stringified.get(ident); + if (resolver) { + typedCaches.direct.set(resolveOptions, resolver); + return resolver; + } + const newResolver = this._create(type, resolveOptions); + typedCaches.direct.set(resolveOptions, newResolver); + typedCaches.stringified.set(ident, newResolver); + return newResolver; + } + + /** + * @param {string} type type of resolver + * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType options + * @returns {ResolverWithOptions} the resolver + */ + _create(type, resolveOptionsWithDepType) { + /** @type {ResolveOptionsWithDependencyType} */ + const originalResolveOptions = { ...resolveOptionsWithDepType }; + + const resolveOptions = convertToResolveOptions( + this.hooks.resolveOptions.for(type).call(resolveOptionsWithDepType) + ); + const resolver = /** @type {ResolverWithOptions} */ ( + Factory.createResolver(resolveOptions) + ); + if (!resolver) { + throw new Error("No resolver created"); + } + /** @type {WeakMap, ResolverWithOptions>} */ + const childCache = new WeakMap(); + resolver.withOptions = (options) => { + const cacheEntry = childCache.get(options); + if (cacheEntry !== undefined) return cacheEntry; + const mergedOptions = cachedCleverMerge(originalResolveOptions, options); + const resolver = this.get(type, mergedOptions); + childCache.set(options, resolver); + return resolver; + }; + this.hooks.resolver + .for(type) + .call(resolver, resolveOptions, originalResolveOptions); + return resolver; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimeGlobals.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimeGlobals.js new file mode 100644 index 0000000000000000000000000000000000000000..26178a0e5df20d7ad53ba9f082629b980ffea01c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimeGlobals.js @@ -0,0 +1,427 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * the AMD define function + */ +module.exports.amdDefine = "__webpack_require__.amdD"; + +/** + * the AMD options + */ +module.exports.amdOptions = "__webpack_require__.amdO"; + +/** + * Creates an async module. The body function must be a async function. + * "module.exports" will be decorated with an AsyncModulePromise. + * The body function will be called. + * To handle async dependencies correctly do this: "([a, b, c] = await handleDependencies([a, b, c]));". + * If "hasAwaitAfterDependencies" is truthy, "handleDependencies()" must be called at the end of the body function. + * Signature: function( + * module: Module, + * body: (handleDependencies: (deps: AsyncModulePromise[]) => Promise & () => void, + * hasAwaitAfterDependencies?: boolean + * ) => void + */ +module.exports.asyncModule = "__webpack_require__.a"; + +/** + * The internal symbol that asyncModule is using. + */ +module.exports.asyncModuleDoneSymbol = "__webpack_require__.aD"; + +/** + * The internal symbol that asyncModule is using. + */ +module.exports.asyncModuleExportSymbol = "__webpack_require__.aE"; + +/** + * the baseURI of current document + */ +module.exports.baseURI = "__webpack_require__.b"; + +/** + * global callback functions for installing chunks + */ +module.exports.chunkCallback = "webpackChunk"; + +/** + * the chunk name of the chunk with the runtime + */ +module.exports.chunkName = "__webpack_require__.cn"; + +/** + * compatibility get default export + */ +module.exports.compatGetDefaultExport = "__webpack_require__.n"; + +/** + * create a fake namespace object + */ +module.exports.createFakeNamespaceObject = "__webpack_require__.t"; + +/** + * function to promote a string to a TrustedScript using webpack's Trusted + * Types policy + * Arguments: (script: string) => TrustedScript + */ +module.exports.createScript = "__webpack_require__.ts"; + +/** + * function to promote a string to a TrustedScriptURL using webpack's Trusted + * Types policy + * Arguments: (url: string) => TrustedScriptURL + */ +module.exports.createScriptUrl = "__webpack_require__.tu"; + +/** + * The current scope when getting a module from a remote + */ +module.exports.currentRemoteGetScope = "__webpack_require__.R"; + +/** + * the exported property define getters function + */ +module.exports.definePropertyGetters = "__webpack_require__.d"; + +/** + * the chunk ensure function + */ +module.exports.ensureChunk = "__webpack_require__.e"; + +/** + * an object with handlers to ensure a chunk + */ +module.exports.ensureChunkHandlers = "__webpack_require__.f"; + +/** + * a runtime requirement if ensureChunkHandlers should include loading of chunk needed for entries + */ +module.exports.ensureChunkIncludeEntries = + "__webpack_require__.f (include entries)"; + +/** + * the module id of the entry point + */ +module.exports.entryModuleId = "__webpack_require__.s"; + +/** + * esm module id + */ +module.exports.esmId = "__webpack_esm_id__"; + +/** + * esm module ids + */ +module.exports.esmIds = "__webpack_esm_ids__"; + +/** + * esm modules + */ +module.exports.esmModules = "__webpack_esm_modules__"; + +/** + * esm runtime + */ +module.exports.esmRuntime = "__webpack_esm_runtime__"; + +/** + * the internal exports object + */ +module.exports.exports = "__webpack_exports__"; + +/** + * method to install a chunk that was loaded somehow + * Signature: ({ id, ids, modules, runtime }) => void + */ +module.exports.externalInstallChunk = "__webpack_require__.C"; + +/** + * the filename of the css part of the chunk + */ +module.exports.getChunkCssFilename = "__webpack_require__.k"; + +/** + * the filename of the script part of the chunk + */ +module.exports.getChunkScriptFilename = "__webpack_require__.u"; + +/** + * the filename of the css part of the hot update chunk + */ +module.exports.getChunkUpdateCssFilename = "__webpack_require__.hk"; + +/** + * the filename of the script part of the hot update chunk + */ +module.exports.getChunkUpdateScriptFilename = "__webpack_require__.hu"; + +/** + * the webpack hash + */ +module.exports.getFullHash = "__webpack_require__.h"; + +/** + * function to return webpack's Trusted Types policy + * Arguments: () => TrustedTypePolicy + */ +module.exports.getTrustedTypesPolicy = "__webpack_require__.tt"; + +/** + * the filename of the HMR manifest + */ +module.exports.getUpdateManifestFilename = "__webpack_require__.hmrF"; + +/** + * the global object + */ +module.exports.global = "__webpack_require__.g"; + +/** + * harmony module decorator + */ +module.exports.harmonyModuleDecorator = "__webpack_require__.hmd"; + +/** + * a flag when a module/chunk/tree has css modules + */ +module.exports.hasCssModules = "has css modules"; + +/** + * a flag when a chunk has a fetch priority + */ +module.exports.hasFetchPriority = "has fetch priority"; + +/** + * the shorthand for Object.prototype.hasOwnProperty + * using of it decreases the compiled bundle size + */ +module.exports.hasOwnProperty = "__webpack_require__.o"; + +/** + * function downloading the update manifest + */ +module.exports.hmrDownloadManifest = "__webpack_require__.hmrM"; + +/** + * array with handler functions to download chunk updates + */ +module.exports.hmrDownloadUpdateHandlers = "__webpack_require__.hmrC"; + +/** + * array with handler functions when a module should be invalidated + */ +module.exports.hmrInvalidateModuleHandlers = "__webpack_require__.hmrI"; + +/** + * object with all hmr module data for all modules + */ +module.exports.hmrModuleData = "__webpack_require__.hmrD"; + +/** + * the prefix for storing state of runtime modules when hmr is enabled + */ +module.exports.hmrRuntimeStatePrefix = "__webpack_require__.hmrS"; + +/** + * The sharing init sequence function (only runs once per share scope). + * Has one argument, the name of the share scope. + * Creates a share scope if not existing + */ +module.exports.initializeSharing = "__webpack_require__.I"; + +/** + * instantiate a wasm instance from module exports object, id, hash and importsObject + */ +module.exports.instantiateWasm = "__webpack_require__.v"; + +/** + * interceptor for module executions + */ +module.exports.interceptModuleExecution = "__webpack_require__.i"; + +/** + * function to load a script tag. + * Arguments: (url: string, done: (event) => void), key?: string | number, chunkId?: string | number) => void + * done function is called when loading has finished or timeout occurred. + * It will attach to existing script tags with data-webpack == uniqueName + ":" + key or src == url. + */ +module.exports.loadScript = "__webpack_require__.l"; + +/** + * make a deferred namespace object + */ +module.exports.makeDeferredNamespaceObject = "__webpack_require__.z"; + +/** + * the internal symbol that makeDeferredNamespaceObject is using. + */ +module.exports.makeDeferredNamespaceObjectSymbol = "__webpack_require__.zS"; + +/** + * define compatibility on export + */ +module.exports.makeNamespaceObject = "__webpack_require__.r"; + +/** + * the internal module object + */ +module.exports.module = "module"; + +/** + * the module cache + */ +module.exports.moduleCache = "__webpack_require__.c"; + +/** + * the module functions + */ +module.exports.moduleFactories = "__webpack_require__.m"; + +/** + * the module functions, with only write access + */ +module.exports.moduleFactoriesAddOnly = "__webpack_require__.m (add only)"; + +/** + * the internal module object + */ +module.exports.moduleId = "module.id"; + +/** + * the internal module object + */ +module.exports.moduleLoaded = "module.loaded"; + +/** + * node.js module decorator + */ +module.exports.nodeModuleDecorator = "__webpack_require__.nmd"; + +/** + * register deferred code, which will run when certain + * chunks are loaded. + * Signature: (chunkIds: Id[], fn: () => any, priority: int >= 0 = 0) => any + * Returned value will be returned directly when all chunks are already loaded + * When (priority & 1) it will wait for all other handlers with lower priority to + * be executed before itself is executed + */ +module.exports.onChunksLoaded = "__webpack_require__.O"; + +/** + * the chunk prefetch function + */ +module.exports.prefetchChunk = "__webpack_require__.E"; + +/** + * an object with handlers to prefetch a chunk + */ +module.exports.prefetchChunkHandlers = "__webpack_require__.F"; + +/** + * the chunk preload function + */ +module.exports.preloadChunk = "__webpack_require__.G"; + +/** + * an object with handlers to preload a chunk + */ +module.exports.preloadChunkHandlers = "__webpack_require__.H"; + +/** + * the bundle public path + */ +module.exports.publicPath = "__webpack_require__.p"; + +/** + * a RelativeURL class when relative URLs are used + */ +module.exports.relativeUrl = "__webpack_require__.U"; + +/** + * the internal require function + */ +module.exports.require = "__webpack_require__"; + +/** + * access to properties of the internal require function/object + */ +module.exports.requireScope = "__webpack_require__.*"; + +/** + * runtime need to return the exports of the last entry module + */ +module.exports.returnExportsFromRuntime = "return-exports-from-runtime"; + +/** + * the runtime id of the current runtime + */ +module.exports.runtimeId = "__webpack_require__.j"; + +/** + * the script nonce + */ +module.exports.scriptNonce = "__webpack_require__.nc"; + +/** + * an object with all share scopes + */ +module.exports.shareScopeMap = "__webpack_require__.S"; + +/** + * startup signal from runtime + * This will be called when the runtime chunk has been loaded. + */ +module.exports.startup = "__webpack_require__.x"; + +/** + * method to startup an entrypoint with needed chunks. + * Signature: (moduleId: Id, chunkIds: Id[]) => any. + * Returns the exports of the module or a Promise + */ +module.exports.startupEntrypoint = "__webpack_require__.X"; + +/** + * @deprecated + * creating a default startup function with the entry modules + */ +module.exports.startupNoDefault = "__webpack_require__.x (no default handler)"; + +/** + * startup signal from runtime but only used to add logic after the startup + */ +module.exports.startupOnlyAfter = "__webpack_require__.x (only after)"; + +/** + * startup signal from runtime but only used to add sync logic before the startup + */ +module.exports.startupOnlyBefore = "__webpack_require__.x (only before)"; + +/** + * the System polyfill object + */ +module.exports.system = "__webpack_require__.System"; + +/** + * the System.register context object + */ +module.exports.systemContext = "__webpack_require__.y"; + +/** + * top-level this need to be the exports object + */ +module.exports.thisAsExports = "top-level-this-exports"; + +/** + * the uncaught error handler for the webpack runtime + */ +module.exports.uncaughtErrorHandler = "__webpack_require__.oe"; + +/** + * an object containing all installed WebAssembly.Instance export objects keyed by module id + */ +module.exports.wasmInstances = "__webpack_require__.w"; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..d063ff0efe04b1eef730fb993479cd3a906a0e5b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimeModule.js @@ -0,0 +1,217 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const OriginalSource = require("webpack-sources").OriginalSource; +const Module = require("./Module"); +const { RUNTIME_TYPES } = require("./ModuleSourceTypesConstants"); +const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./Generator").SourceTypes} SourceTypes */ +/** @typedef {import("./Module").BuildCallback} BuildCallback */ +/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +class RuntimeModule extends Module { + /** + * @param {string} name a readable name + * @param {number=} stage an optional stage + */ + constructor(name, stage = 0) { + super(WEBPACK_MODULE_TYPE_RUNTIME); + this.name = name; + this.stage = stage; + this.buildMeta = {}; + this.buildInfo = {}; + /** @type {Compilation | undefined} */ + this.compilation = undefined; + /** @type {Chunk | undefined} */ + this.chunk = undefined; + /** @type {ChunkGraph | undefined} */ + this.chunkGraph = undefined; + this.fullHash = false; + this.dependentHash = false; + /** @type {string | undefined | null} */ + this._cachedGeneratedCode = undefined; + } + + /** + * @param {Compilation} compilation the compilation + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + attach(compilation, chunk, chunkGraph = compilation.chunkGraph) { + this.compilation = compilation; + this.chunk = chunk; + this.chunkGraph = chunkGraph; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `webpack/runtime/${this.name}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `webpack/runtime/${this.name}`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, false); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + // do nothing + // should not be called as runtime modules are added later to the compilation + callback(); + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(this.name); + hash.update(`${this.stage}`); + try { + if (this.fullHash || this.dependentHash) { + // Do not use getGeneratedCode here, because i. e. compilation hash might be not + // ready at this point. We will cache it later instead. + hash.update(/** @type {string} */ (this.generate())); + } else { + hash.update(/** @type {string} */ (this.getGeneratedCode())); + } + } catch (err) { + hash.update(/** @type {Error} */ (err).message); + } + super.updateHash(hash, context); + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return RUNTIME_TYPES; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + const sources = new Map(); + const generatedCode = this.getGeneratedCode(); + if (generatedCode) { + sources.set( + WEBPACK_MODULE_TYPE_RUNTIME, + this.useSourceMap || this.useSimpleSourceMap + ? new OriginalSource(generatedCode, this.identifier()) + : new RawSource(generatedCode) + ); + } + return { + sources, + runtimeRequirements: null + }; + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + try { + const source = this.getGeneratedCode(); + return source ? source.length : 0; + } catch (_err) { + return 0; + } + } + + /* istanbul ignore next */ + /** + * @abstract + * @returns {string | null} runtime code + */ + generate() { + const AbstractMethodError = require("./AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /** + * @returns {string | null} runtime code + */ + getGeneratedCode() { + if (this._cachedGeneratedCode) { + return this._cachedGeneratedCode; + } + return (this._cachedGeneratedCode = this.generate()); + } + + /** + * @returns {boolean} true, if the runtime module should get it's own scope + */ + shouldIsolate() { + return true; + } +} + +/** + * Runtime modules without any dependencies to other runtime modules + */ +RuntimeModule.STAGE_NORMAL = 0; + +/** + * Runtime modules with simple dependencies on other runtime modules + */ +RuntimeModule.STAGE_BASIC = 5; + +/** + * Runtime modules which attach to handlers of other runtime modules + */ +RuntimeModule.STAGE_ATTACH = 10; + +/** + * Runtime modules which trigger actions on bootstrap + */ +RuntimeModule.STAGE_TRIGGER = 20; + +module.exports = RuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..6e9e30959bb1df5b9544c9563985776cb502418f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimePlugin.js @@ -0,0 +1,524 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("./RuntimeGlobals"); +const { getChunkFilenameTemplate } = require("./css/CssModulesPlugin"); +const RuntimeRequirementsDependency = require("./dependencies/RuntimeRequirementsDependency"); +const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); +const AsyncModuleRuntimeModule = require("./runtime/AsyncModuleRuntimeModule"); +const AutoPublicPathRuntimeModule = require("./runtime/AutoPublicPathRuntimeModule"); +const BaseUriRuntimeModule = require("./runtime/BaseUriRuntimeModule"); +const CompatGetDefaultExportRuntimeModule = require("./runtime/CompatGetDefaultExportRuntimeModule"); +const CompatRuntimeModule = require("./runtime/CompatRuntimeModule"); +const CreateFakeNamespaceObjectRuntimeModule = require("./runtime/CreateFakeNamespaceObjectRuntimeModule"); +const CreateScriptRuntimeModule = require("./runtime/CreateScriptRuntimeModule"); +const CreateScriptUrlRuntimeModule = require("./runtime/CreateScriptUrlRuntimeModule"); +const DefinePropertyGettersRuntimeModule = require("./runtime/DefinePropertyGettersRuntimeModule"); +const EnsureChunkRuntimeModule = require("./runtime/EnsureChunkRuntimeModule"); +const GetChunkFilenameRuntimeModule = require("./runtime/GetChunkFilenameRuntimeModule"); +const GetMainFilenameRuntimeModule = require("./runtime/GetMainFilenameRuntimeModule"); +const GetTrustedTypesPolicyRuntimeModule = require("./runtime/GetTrustedTypesPolicyRuntimeModule"); +const GlobalRuntimeModule = require("./runtime/GlobalRuntimeModule"); +const HasOwnPropertyRuntimeModule = require("./runtime/HasOwnPropertyRuntimeModule"); +const LoadScriptRuntimeModule = require("./runtime/LoadScriptRuntimeModule"); +const MakeDeferredNamespaceObjectRuntime = require("./runtime/MakeDeferredNamespaceObjectRuntime"); +const MakeNamespaceObjectRuntimeModule = require("./runtime/MakeNamespaceObjectRuntimeModule"); +const NonceRuntimeModule = require("./runtime/NonceRuntimeModule"); +const OnChunksLoadedRuntimeModule = require("./runtime/OnChunksLoadedRuntimeModule"); +const PublicPathRuntimeModule = require("./runtime/PublicPathRuntimeModule"); +const RelativeUrlRuntimeModule = require("./runtime/RelativeUrlRuntimeModule"); +const RuntimeIdRuntimeModule = require("./runtime/RuntimeIdRuntimeModule"); +const SystemContextRuntimeModule = require("./runtime/SystemContextRuntimeModule"); +const ShareRuntimeModule = require("./sharing/ShareRuntimeModule"); +const StringXor = require("./util/StringXor"); +const memoize = require("./util/memoize"); + +/** @typedef {import("../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputNormalized */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */ + +const getJavascriptModulesPlugin = memoize(() => + require("./javascript/JavascriptModulesPlugin") +); +const getCssModulesPlugin = memoize(() => require("./css/CssModulesPlugin")); + +const GLOBALS_ON_REQUIRE = [ + RuntimeGlobals.chunkName, + RuntimeGlobals.runtimeId, + RuntimeGlobals.compatGetDefaultExport, + RuntimeGlobals.createFakeNamespaceObject, + RuntimeGlobals.createScript, + RuntimeGlobals.createScriptUrl, + RuntimeGlobals.getTrustedTypesPolicy, + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.ensureChunk, + RuntimeGlobals.entryModuleId, + RuntimeGlobals.getFullHash, + RuntimeGlobals.global, + RuntimeGlobals.makeNamespaceObject, + RuntimeGlobals.moduleCache, + RuntimeGlobals.moduleFactories, + RuntimeGlobals.moduleFactoriesAddOnly, + RuntimeGlobals.interceptModuleExecution, + RuntimeGlobals.publicPath, + RuntimeGlobals.baseURI, + RuntimeGlobals.relativeUrl, + // TODO webpack 6 - rename to nonce, because we use it for CSS too + RuntimeGlobals.scriptNonce, + RuntimeGlobals.uncaughtErrorHandler, + RuntimeGlobals.asyncModule, + RuntimeGlobals.wasmInstances, + RuntimeGlobals.instantiateWasm, + RuntimeGlobals.shareScopeMap, + RuntimeGlobals.initializeSharing, + RuntimeGlobals.loadScript, + RuntimeGlobals.systemContext, + RuntimeGlobals.onChunksLoaded, + RuntimeGlobals.makeDeferredNamespaceObject +]; + +const MODULE_DEPENDENCIES = { + [RuntimeGlobals.moduleLoaded]: [RuntimeGlobals.module], + [RuntimeGlobals.moduleId]: [RuntimeGlobals.module] +}; + +const TREE_DEPENDENCIES = { + [RuntimeGlobals.definePropertyGetters]: [RuntimeGlobals.hasOwnProperty], + [RuntimeGlobals.compatGetDefaultExport]: [ + RuntimeGlobals.definePropertyGetters + ], + [RuntimeGlobals.createFakeNamespaceObject]: [ + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.makeNamespaceObject, + RuntimeGlobals.require + ], + [RuntimeGlobals.makeDeferredNamespaceObject]: [ + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.makeNamespaceObject, + RuntimeGlobals.createFakeNamespaceObject, + RuntimeGlobals.hasOwnProperty, + RuntimeGlobals.require + ], + [RuntimeGlobals.initializeSharing]: [RuntimeGlobals.shareScopeMap], + [RuntimeGlobals.shareScopeMap]: [RuntimeGlobals.hasOwnProperty] +}; + +const PLUGIN_NAME = "RuntimePlugin"; + +class RuntimePlugin { + /** + * @param {Compiler} compiler the Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + /** + * @param {Chunk} chunk chunk + * @returns {boolean} true, when chunk loading is disabled for the chunk + */ + const isChunkLoadingDisabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === false; + }; + compilation.dependencyTemplates.set( + RuntimeRequirementsDependency, + new RuntimeRequirementsDependency.Template() + ); + for (const req of GLOBALS_ON_REQUIRE) { + compilation.hooks.runtimeRequirementInModule + .for(req) + .tap(PLUGIN_NAME, (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); + compilation.hooks.runtimeRequirementInTree + .for(req) + .tap(PLUGIN_NAME, (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); + } + for (const req of Object.keys(TREE_DEPENDENCIES)) { + const deps = + TREE_DEPENDENCIES[/** @type {keyof TREE_DEPENDENCIES} */ (req)]; + compilation.hooks.runtimeRequirementInTree + .for(req) + .tap(PLUGIN_NAME, (chunk, set) => { + for (const dep of deps) set.add(dep); + }); + } + for (const req of Object.keys(MODULE_DEPENDENCIES)) { + const deps = + MODULE_DEPENDENCIES[/** @type {keyof MODULE_DEPENDENCIES} */ (req)]; + compilation.hooks.runtimeRequirementInModule + .for(req) + .tap(PLUGIN_NAME, (chunk, set) => { + for (const dep of deps) set.add(dep); + }); + } + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.definePropertyGetters) + .tap(PLUGIN_NAME, (chunk) => { + compilation.addRuntimeModule( + chunk, + new DefinePropertyGettersRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.makeNamespaceObject) + .tap(PLUGIN_NAME, (chunk) => { + compilation.addRuntimeModule( + chunk, + new MakeNamespaceObjectRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.createFakeNamespaceObject) + .tap(PLUGIN_NAME, (chunk) => { + compilation.addRuntimeModule( + chunk, + new CreateFakeNamespaceObjectRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.makeDeferredNamespaceObject) + .tap("RuntimePlugin", (chunk, runtimeRequirement) => { + compilation.addRuntimeModule( + chunk, + new MakeDeferredNamespaceObjectRuntime( + runtimeRequirement.has(RuntimeGlobals.asyncModule) + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hasOwnProperty) + .tap(PLUGIN_NAME, (chunk) => { + compilation.addRuntimeModule( + chunk, + new HasOwnPropertyRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.compatGetDefaultExport) + .tap(PLUGIN_NAME, (chunk) => { + compilation.addRuntimeModule( + chunk, + new CompatGetDefaultExportRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.runtimeId) + .tap(PLUGIN_NAME, (chunk) => { + compilation.addRuntimeModule(chunk, new RuntimeIdRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.publicPath) + .tap(PLUGIN_NAME, (chunk, set) => { + const { outputOptions } = compilation; + const { publicPath: globalPublicPath, scriptType } = outputOptions; + const entryOptions = chunk.getEntryOptions(); + const publicPath = + entryOptions && entryOptions.publicPath !== undefined + ? entryOptions.publicPath + : globalPublicPath; + + if (publicPath === "auto") { + const module = new AutoPublicPathRuntimeModule(); + if (scriptType !== "module") set.add(RuntimeGlobals.global); + compilation.addRuntimeModule(chunk, module); + } else { + const module = new PublicPathRuntimeModule(publicPath); + + if ( + typeof publicPath !== "string" || + /\[(full)?hash\]/.test(publicPath) + ) { + module.fullHash = true; + } + + compilation.addRuntimeModule(chunk, module); + } + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.global) + .tap(PLUGIN_NAME, (chunk) => { + compilation.addRuntimeModule(chunk, new GlobalRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.asyncModule) + .tap(PLUGIN_NAME, (chunk) => { + const experiments = compilation.options.experiments; + compilation.addRuntimeModule( + chunk, + new AsyncModuleRuntimeModule(experiments.deferImport) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.systemContext) + .tap(PLUGIN_NAME, (chunk) => { + const entryOptions = chunk.getEntryOptions(); + const libraryType = + entryOptions && entryOptions.library !== undefined + ? entryOptions.library.type + : /** @type {LibraryOptions} */ + (compilation.outputOptions.library).type; + + if (libraryType === "system") { + compilation.addRuntimeModule( + chunk, + new SystemContextRuntimeModule() + ); + } + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getChunkScriptFilename) + .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => { + if ( + typeof compilation.outputOptions.chunkFilename === "string" && + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.chunkFilename + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetChunkFilenameRuntimeModule( + "javascript", + "javascript", + RuntimeGlobals.getChunkScriptFilename, + (chunk) => + getJavascriptModulesPlugin().chunkHasJs(chunk, chunkGraph) && + /** @type {TemplatePath} */ ( + chunk.filenameTemplate || + (chunk.canBeInitial() + ? compilation.outputOptions.filename + : compilation.outputOptions.chunkFilename) + ), + set.has(RuntimeGlobals.hmrDownloadUpdateHandlers) + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getChunkCssFilename) + .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => { + if ( + typeof compilation.outputOptions.cssChunkFilename === "string" && + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.cssChunkFilename + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetChunkFilenameRuntimeModule( + "css", + "css", + RuntimeGlobals.getChunkCssFilename, + (chunk) => + getCssModulesPlugin().chunkHasCss(chunk, chunkGraph) && + getChunkFilenameTemplate(chunk, compilation.outputOptions), + set.has(RuntimeGlobals.hmrDownloadUpdateHandlers) + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getChunkUpdateScriptFilename) + .tap(PLUGIN_NAME, (chunk, set) => { + if ( + /\[(full)?hash(:\d+)?\]/.test( + /** @type {NonNullable} */ + (compilation.outputOptions.hotUpdateChunkFilename) + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetChunkFilenameRuntimeModule( + "javascript", + "javascript update", + RuntimeGlobals.getChunkUpdateScriptFilename, + (_chunk) => + /** @type {NonNullable} */ + (compilation.outputOptions.hotUpdateChunkFilename), + true + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getUpdateManifestFilename) + .tap(PLUGIN_NAME, (chunk, set) => { + if ( + /\[(full)?hash(:\d+)?\]/.test( + /** @type {NonNullable} */ + (compilation.outputOptions.hotUpdateMainFilename) + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetMainFilenameRuntimeModule( + "update manifest", + RuntimeGlobals.getUpdateManifestFilename, + /** @type {NonNullable} */ + (compilation.outputOptions.hotUpdateMainFilename) + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunk) + .tap(PLUGIN_NAME, (chunk, set) => { + const hasAsyncChunks = chunk.hasAsyncChunks(); + if (hasAsyncChunks) { + set.add(RuntimeGlobals.ensureChunkHandlers); + } + compilation.addRuntimeModule( + chunk, + new EnsureChunkRuntimeModule(set) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkIncludeEntries) + .tap(PLUGIN_NAME, (chunk, set) => { + set.add(RuntimeGlobals.ensureChunkHandlers); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.shareScopeMap) + .tap(PLUGIN_NAME, (chunk, set) => { + compilation.addRuntimeModule(chunk, new ShareRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.loadScript) + .tap(PLUGIN_NAME, (chunk, set) => { + const withCreateScriptUrl = Boolean( + compilation.outputOptions.trustedTypes + ); + if (withCreateScriptUrl) { + set.add(RuntimeGlobals.createScriptUrl); + } + const withFetchPriority = set.has(RuntimeGlobals.hasFetchPriority); + compilation.addRuntimeModule( + chunk, + new LoadScriptRuntimeModule(withCreateScriptUrl, withFetchPriority) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.createScript) + .tap(PLUGIN_NAME, (chunk, set) => { + if (compilation.outputOptions.trustedTypes) { + set.add(RuntimeGlobals.getTrustedTypesPolicy); + } + compilation.addRuntimeModule(chunk, new CreateScriptRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.createScriptUrl) + .tap(PLUGIN_NAME, (chunk, set) => { + if (compilation.outputOptions.trustedTypes) { + set.add(RuntimeGlobals.getTrustedTypesPolicy); + } + compilation.addRuntimeModule( + chunk, + new CreateScriptUrlRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getTrustedTypesPolicy) + .tap(PLUGIN_NAME, (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new GetTrustedTypesPolicyRuntimeModule(set) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.relativeUrl) + .tap(PLUGIN_NAME, (chunk, _set) => { + compilation.addRuntimeModule(chunk, new RelativeUrlRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap(PLUGIN_NAME, (chunk, _set) => { + compilation.addRuntimeModule( + chunk, + new OnChunksLoadedRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap(PLUGIN_NAME, (chunk) => { + if (isChunkLoadingDisabledForChunk(chunk)) { + compilation.addRuntimeModule(chunk, new BaseUriRuntimeModule()); + return true; + } + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.scriptNonce) + .tap(PLUGIN_NAME, (chunk) => { + compilation.addRuntimeModule(chunk, new NonceRuntimeModule()); + return true; + }); + // TODO webpack 6: remove CompatRuntimeModule + compilation.hooks.additionalTreeRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, _set) => { + const { mainTemplate } = compilation; + if ( + mainTemplate.hooks.bootstrap.isUsed() || + mainTemplate.hooks.localVars.isUsed() || + mainTemplate.hooks.requireEnsure.isUsed() || + mainTemplate.hooks.requireExtensions.isUsed() + ) { + compilation.addRuntimeModule(chunk, new CompatRuntimeModule()); + } + } + ); + JavascriptModulesPlugin.getCompilationHooks(compilation).chunkHash.tap( + PLUGIN_NAME, + (chunk, hash, { chunkGraph }) => { + const xor = new StringXor(); + for (const m of chunkGraph.getChunkRuntimeModulesIterable(chunk)) { + xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); + } + xor.updateHash(hash); + } + ); + }); + } +} + +module.exports = RuntimePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimeTemplate.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimeTemplate.js new file mode 100644 index 0000000000000000000000000000000000000000..bc5c4cf901530e6e91a903a1288c6f326a6afc85 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/RuntimeTemplate.js @@ -0,0 +1,1208 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const InitFragment = require("./InitFragment"); +const RuntimeGlobals = require("./RuntimeGlobals"); +const Template = require("./Template"); +const { + getOutgoingAsyncModules +} = require("./async-modules/AsyncModuleHelpers"); +const { + getMakeDeferredNamespaceModeFromExportsType, + getOptimizedDeferredModule +} = require("./runtime/MakeDeferredNamespaceObjectRuntime"); +const { equals } = require("./util/ArrayHelpers"); +const compileBooleanMatcher = require("./util/compileBooleanMatcher"); +const propertyAccess = require("./util/propertyAccess"); +const { forEachRuntime, subtractRuntime } = require("./util/runtime"); + +/** @typedef {import("../declarations/WebpackOptions").Environment} Environment */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./CodeGenerationResults").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ +/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @param {Module} module the module + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {string} error message + */ +const noModuleIdErrorMessage = ( + module, + chunkGraph +) => `Module ${module.identifier()} has no id assigned. +This should not happen. +It's in these chunks: ${ + Array.from( + chunkGraph.getModuleChunksIterable(module), + (c) => c.name || c.id || c.debugId + ).join(", ") || "none" +} (If module is in no chunk this indicates a bug in some chunk/module optimization logic) +Module has these incoming connections: ${Array.from( + chunkGraph.moduleGraph.getIncomingConnections(module), + (connection) => + `\n - ${ + connection.originModule && connection.originModule.identifier() + } ${connection.dependency && connection.dependency.type} ${ + (connection.explanations && [...connection.explanations].join(", ")) || "" + }` +).join("")}`; + +/** + * @param {string | undefined} definition global object definition + * @returns {string | undefined} save to use global object + */ +function getGlobalObject(definition) { + if (!definition) return definition; + const trimmed = definition.trim(); + + if ( + // identifier, we do not need real identifier regarding ECMAScript/Unicode + /^[_\p{L}][_0-9\p{L}]*$/iu.test(trimmed) || + // iife + // call expression + // expression in parentheses + /^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu.test(trimmed) + ) { + return trimmed; + } + + return `Object(${trimmed})`; +} + +class RuntimeTemplate { + /** + * @param {Compilation} compilation the compilation + * @param {OutputOptions} outputOptions the compilation output options + * @param {RequestShortener} requestShortener the request shortener + */ + constructor(compilation, outputOptions, requestShortener) { + this.compilation = compilation; + this.outputOptions = /** @type {OutputOptions} */ (outputOptions || {}); + this.requestShortener = requestShortener; + this.globalObject = + /** @type {string} */ + (getGlobalObject(outputOptions.globalObject)); + this.contentHashReplacement = "X".repeat( + /** @type {NonNullable} */ + (outputOptions.hashDigestLength) + ); + } + + isIIFE() { + return this.outputOptions.iife; + } + + isModule() { + return this.outputOptions.module; + } + + isNeutralPlatform() { + return ( + !this.outputOptions.environment.document && + !this.compilation.compiler.platform.node + ); + } + + supportsConst() { + return this.outputOptions.environment.const; + } + + supportsArrowFunction() { + return this.outputOptions.environment.arrowFunction; + } + + supportsAsyncFunction() { + return this.outputOptions.environment.asyncFunction; + } + + supportsOptionalChaining() { + return this.outputOptions.environment.optionalChaining; + } + + supportsForOf() { + return this.outputOptions.environment.forOf; + } + + supportsDestructuring() { + return this.outputOptions.environment.destructuring; + } + + supportsBigIntLiteral() { + return this.outputOptions.environment.bigIntLiteral; + } + + supportsDynamicImport() { + return this.outputOptions.environment.dynamicImport; + } + + supportsEcmaScriptModuleSyntax() { + return this.outputOptions.environment.module; + } + + supportTemplateLiteral() { + return this.outputOptions.environment.templateLiteral; + } + + supportNodePrefixForCoreModules() { + return this.outputOptions.environment.nodePrefixForCoreModules; + } + + /** + * @param {string} mod a module + * @returns {string} a module with `node:` prefix when supported, otherwise an original name + */ + renderNodePrefixForCoreModule(mod) { + return this.outputOptions.environment.nodePrefixForCoreModules + ? `"node:${mod}"` + : `"${mod}"`; + } + + /** + * @param {string} returnValue return value + * @param {string} args arguments + * @returns {string} returning function + */ + returningFunction(returnValue, args = "") { + return this.supportsArrowFunction() + ? `(${args}) => (${returnValue})` + : `function(${args}) { return ${returnValue}; }`; + } + + /** + * @param {string} args arguments + * @param {string | string[]} body body + * @returns {string} basic function + */ + basicFunction(args, body) { + return this.supportsArrowFunction() + ? `(${args}) => {\n${Template.indent(body)}\n}` + : `function(${args}) {\n${Template.indent(body)}\n}`; + } + + /** + * @param {Array} args args + * @returns {string} result expression + */ + concatenation(...args) { + const len = args.length; + + if (len === 2) return this._es5Concatenation(args); + if (len === 0) return '""'; + if (len === 1) { + return typeof args[0] === "string" + ? JSON.stringify(args[0]) + : `"" + ${args[0].expr}`; + } + if (!this.supportTemplateLiteral()) return this._es5Concatenation(args); + + // cost comparison between template literal and concatenation: + // both need equal surroundings: `xxx` vs "xxx" + // template literal has constant cost of 3 chars for each expression + // es5 concatenation has cost of 3 + n chars for n expressions in row + // when a es5 concatenation ends with an expression it reduces cost by 3 + // when a es5 concatenation starts with an single expression it reduces cost by 3 + // e. g. `${a}${b}${c}` (3*3 = 9) is longer than ""+a+b+c ((3+3)-3 = 3) + // e. g. `x${a}x${b}x${c}x` (3*3 = 9) is shorter than "x"+a+"x"+b+"x"+c+"x" (4+4+4 = 12) + + let templateCost = 0; + let concatenationCost = 0; + + let lastWasExpr = false; + for (const arg of args) { + const isExpr = typeof arg !== "string"; + if (isExpr) { + templateCost += 3; + concatenationCost += lastWasExpr ? 1 : 4; + } + lastWasExpr = isExpr; + } + if (lastWasExpr) concatenationCost -= 3; + if (typeof args[0] !== "string" && typeof args[1] === "string") { + concatenationCost -= 3; + } + + if (concatenationCost <= templateCost) return this._es5Concatenation(args); + + return `\`${args + .map((arg) => (typeof arg === "string" ? arg : `\${${arg.expr}}`)) + .join("")}\``; + } + + /** + * @param {Array} args args (len >= 2) + * @returns {string} result expression + * @private + */ + _es5Concatenation(args) { + const str = args + .map((arg) => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr)) + .join(" + "); + + // when the first two args are expression, we need to prepend "" + to force string + // concatenation instead of number addition. + return typeof args[0] !== "string" && typeof args[1] !== "string" + ? `"" + ${str}` + : str; + } + + /** + * @param {string} expression expression + * @param {string} args arguments + * @returns {string} expression function code + */ + expressionFunction(expression, args = "") { + return this.supportsArrowFunction() + ? `(${args}) => (${expression})` + : `function(${args}) { ${expression}; }`; + } + + /** + * @returns {string} empty function code + */ + emptyFunction() { + return this.supportsArrowFunction() ? "x => {}" : "function() {}"; + } + + /** + * @param {string[]} items items + * @param {string} value value + * @returns {string} destructure array code + */ + destructureArray(items, value) { + return this.supportsDestructuring() + ? `var [${items.join(", ")}] = ${value};` + : Template.asString( + items.map((item, i) => `var ${item} = ${value}[${i}];`) + ); + } + + /** + * @param {string[]} items items + * @param {string} value value + * @returns {string} destructure object code + */ + destructureObject(items, value) { + return this.supportsDestructuring() + ? `var {${items.join(", ")}} = ${value};` + : Template.asString( + items.map( + (item) => `var ${item} = ${value}${propertyAccess([item])};` + ) + ); + } + + /** + * @param {string} args arguments + * @param {string} body body + * @returns {string} IIFE code + */ + iife(args, body) { + return `(${this.basicFunction(args, body)})()`; + } + + /** + * @param {string} variable variable + * @param {string} array array + * @param {string | string[]} body body + * @returns {string} for each code + */ + forEach(variable, array, body) { + return this.supportsForOf() + ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}` + : `${array}.forEach(function(${variable}) {\n${Template.indent( + body + )}\n});`; + } + + /** + * Add a comment + * @param {object} options Information content of the comment + * @param {string=} options.request request string used originally + * @param {(string | null)=} options.chunkName name of the chunk referenced + * @param {string=} options.chunkReason reason information of the chunk + * @param {string=} options.message additional message + * @param {string=} options.exportName name of the export + * @returns {string} comment + */ + comment({ request, chunkName, chunkReason, message, exportName }) { + let content; + if (this.outputOptions.pathinfo) { + content = [message, request, chunkName, chunkReason] + .filter(Boolean) + .map((item) => this.requestShortener.shorten(item)) + .join(" | "); + } else { + content = [message, chunkName, chunkReason] + .filter(Boolean) + .map((item) => this.requestShortener.shorten(item)) + .join(" | "); + } + if (!content) return ""; + if (this.outputOptions.pathinfo) { + return `${Template.toComment(content)} `; + } + return `${Template.toNormalComment(content)} `; + } + + /** + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error block + */ + throwMissingModuleErrorBlock({ request }) { + const err = `Cannot find module '${request}'`; + return `var e = new Error(${JSON.stringify( + err + )}); e.code = 'MODULE_NOT_FOUND'; throw e;`; + } + + /** + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error function + */ + throwMissingModuleErrorFunction({ request }) { + return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock( + { request } + )} }`; + } + + /** + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error IIFE + */ + missingModule({ request }) { + return `Object(${this.throwMissingModuleErrorFunction({ request })}())`; + } + + /** + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error statement + */ + missingModuleStatement({ request }) { + return `${this.missingModule({ request })};\n`; + } + + /** + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error code + */ + missingModulePromise({ request }) { + return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ + request + })})`; + } + + /** + * @param {object} options options object + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Module} options.module the module + * @param {string=} options.request the request that should be printed as comment + * @param {string=} options.idExpr expression to use as id expression + * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned + * @returns {string} the code + */ + weakError({ module, chunkGraph, request, idExpr, type }) { + const moduleId = chunkGraph.getModuleId(module); + const errorMessage = + moduleId === null + ? JSON.stringify("Module is not available (weak dependency)") + : idExpr + ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"` + : JSON.stringify( + `Module '${moduleId}' is not available (weak dependency)` + ); + const comment = request ? `${Template.toNormalComment(request)} ` : ""; + const errorStatements = `var e = new Error(${errorMessage}); ${ + comment + }e.code = 'MODULE_NOT_FOUND'; throw e;`; + switch (type) { + case "statements": + return errorStatements; + case "promise": + return `Promise.resolve().then(${this.basicFunction( + "", + errorStatements + )})`; + case "expression": + return this.iife("", errorStatements); + } + } + + /** + * @param {object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string=} options.request the request that should be printed as comment + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @returns {string} the expression + */ + moduleId({ module, chunkGraph, request, weak }) { + if (!module) { + return this.missingModule({ + request + }); + } + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) { + if (weak) { + return "null /* weak dependency, without id */"; + } + throw new Error( + `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + return `${this.comment({ request })}${JSON.stringify(moduleId)}`; + } + + /** + * @param {object} options options object + * @param {Module | null} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string=} options.request the request that should be printed as comment + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the expression + */ + moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) { + if (!module) { + return this.missingModule({ + request + }); + } + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return this.weakError({ + module, + chunkGraph, + request, + type: "expression" + }); + } + throw new Error( + `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + runtimeRequirements.add(RuntimeGlobals.require); + return `${RuntimeGlobals.require}(${this.moduleId({ + module, + chunkGraph, + request, + weak + })})`; + } + + /** + * @param {object} options options object + * @param {Module | null} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the expression + */ + moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) { + return this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + } + + /** + * @param {object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.strict if the current module is in strict esm mode + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the expression + */ + moduleNamespace({ + module, + chunkGraph, + request, + strict, + weak, + runtimeRequirements + }) { + if (!module) { + return this.missingModule({ + request + }); + } + if (chunkGraph.getModuleId(module) === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return this.weakError({ + module, + chunkGraph, + request, + type: "expression" + }); + } + throw new Error( + `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + const moduleId = this.moduleId({ + module, + chunkGraph, + request, + weak + }); + const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); + switch (exportsType) { + case "namespace": + return this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + case "default-with-named": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`; + case "default-only": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`; + case "dynamic": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`; + } + } + + /** + * @param {object} options options object + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {AsyncDependenciesBlock=} options.block the current dependencies block + * @param {Module} options.module the module + * @param {string} options.request the request that should be printed as comment + * @param {string} options.message a message for the comment + * @param {boolean=} options.strict if the current module is in strict esm mode + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the promise expression + */ + moduleNamespacePromise({ + chunkGraph, + block, + module, + request, + message, + strict, + weak, + runtimeRequirements + }) { + if (!module) { + return this.missingModulePromise({ + request + }); + } + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return this.weakError({ + module, + chunkGraph, + request, + type: "promise" + }); + } + throw new Error( + `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + const promise = this.blockPromise({ + chunkGraph, + block, + message, + runtimeRequirements + }); + + let appending; + let idExpr = JSON.stringify(chunkGraph.getModuleId(module)); + const comment = this.comment({ + request + }); + let header = ""; + if (weak) { + if (idExpr.length > 8) { + // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"' + header += `var id = ${idExpr}; `; + idExpr = "id"; + } + runtimeRequirements.add(RuntimeGlobals.moduleFactories); + header += `if(!${ + RuntimeGlobals.moduleFactories + }[${idExpr}]) { ${this.weakError({ + module, + chunkGraph, + request, + idExpr, + type: "statements" + })} } `; + } + const moduleIdExpr = this.moduleId({ + module, + chunkGraph, + request, + weak + }); + const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); + let fakeType = 16; + switch (exportsType) { + case "namespace": + if (header) { + const rawModule = this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + appending = `.then(${this.basicFunction( + "", + `${header}return ${rawModule};` + )})`; + } else { + runtimeRequirements.add(RuntimeGlobals.require); + appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`; + } + break; + case "dynamic": + fakeType |= 4; + /* fall through */ + case "default-with-named": + fakeType |= 2; + /* fall through */ + case "default-only": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + if (chunkGraph.moduleGraph.isAsync(module)) { + if (header) { + const rawModule = this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + appending = `.then(${this.basicFunction( + "", + `${header}return ${rawModule};` + )})`; + } else { + runtimeRequirements.add(RuntimeGlobals.require); + appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`; + } + appending += `.then(${this.returningFunction( + `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`, + "m" + )})`; + } else { + fakeType |= 1; + if (header) { + const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`; + appending = `.then(${this.basicFunction( + "", + `${header}return ${returnExpression};` + )})`; + } else { + appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${fakeType}))`; + } + } + break; + } + + return `${promise || "Promise.resolve()"}${appending}`; + } + + /** + * @param {object} options options object + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated + * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} expression + */ + runtimeConditionExpression({ + chunkGraph, + runtimeCondition, + runtime, + runtimeRequirements + }) { + if (runtimeCondition === undefined) return "true"; + if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`; + /** @type {Set} */ + const positiveRuntimeIds = new Set(); + forEachRuntime(runtimeCondition, (runtime) => + positiveRuntimeIds.add( + `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}` + ) + ); + /** @type {Set} */ + const negativeRuntimeIds = new Set(); + forEachRuntime(subtractRuntime(runtime, runtimeCondition), (runtime) => + negativeRuntimeIds.add( + `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}` + ) + ); + runtimeRequirements.add(RuntimeGlobals.runtimeId); + return compileBooleanMatcher.fromLists( + [...positiveRuntimeIds], + [...negativeRuntimeIds] + )(RuntimeGlobals.runtimeId); + } + + /** + * @param {object} options options object + * @param {boolean=} options.update whether a new variable should be created or the existing one updated + * @param {Module} options.module the module + * @param {ModuleGraph} options.moduleGraph the module graph + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {string} options.importVar name of the import variable + * @param {Module} options.originModule module in which the statement is emitted + * @param {boolean=} options.weak true, if this is a weak dependency + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @param {boolean=} options.defer if set, the module will be deferred + * @returns {[string, string]} the import statement and the compat statement + */ + importStatement({ + update, + module, + moduleGraph, + chunkGraph, + request, + importVar, + originModule, + weak, + defer, + runtimeRequirements + }) { + if (!module) { + return [ + this.missingModuleStatement({ + request + }), + "" + ]; + } + + if (chunkGraph.getModuleId(module) === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return [ + this.weakError({ + module, + chunkGraph, + request, + type: "statements" + }), + "" + ]; + } + throw new Error( + `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + const moduleId = this.moduleId({ + module, + chunkGraph, + request, + weak + }); + const optDeclaration = update ? "" : "var "; + + const exportsType = module.getExportsType( + chunkGraph.moduleGraph, + /** @type {BuildMeta} */ + (originModule.buildMeta).strictHarmonyModule + ); + runtimeRequirements.add(RuntimeGlobals.require); + let importContent; + if (defer && !(/** @type {BuildMeta} */ (module.buildMeta).async)) { + /** @type {Set} */ + const outgoingAsyncModules = getOutgoingAsyncModules(moduleGraph, module); + + importContent = `/* deferred harmony import */ ${optDeclaration}${importVar} = ${getOptimizedDeferredModule( + this, + exportsType, + moduleId, + Array.from(outgoingAsyncModules, (mod) => chunkGraph.getModuleId(mod)) + )};\n`; + + return [importContent, ""]; + } + importContent = `/* harmony import */ ${optDeclaration}${importVar} = ${RuntimeGlobals.require}(${moduleId});\n`; + + if (exportsType === "dynamic") { + runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); + return [ + importContent, + `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n` + ]; + } + return [importContent, ""]; + } + + /** + * @template GenerateContext + * @param {object} options options + * @param {ModuleGraph} options.moduleGraph the module graph + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Module} options.module the module + * @param {string} options.request the request + * @param {string | string[]} options.exportName the export name + * @param {Module} options.originModule the origin module + * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted + * @param {boolean} options.isCall true, if expression will be called + * @param {boolean | null} options.callContext when false, call context will not be preserved + * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated + * @param {string} options.importVar the identifier name of the import variable + * @param {InitFragment[]} options.initFragments init fragments will be added here + * @param {RuntimeSpec} options.runtime runtime for which this code will be generated + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @param {boolean=} options.defer if true, the module will be deferred. + * @returns {string} expression + */ + exportFromImport({ + moduleGraph, + chunkGraph, + module, + request, + exportName, + originModule, + asiSafe, + isCall, + callContext, + defaultInterop, + importVar, + initFragments, + runtime, + runtimeRequirements, + defer + }) { + if (!module) { + return this.missingModule({ + request + }); + } + if (!Array.isArray(exportName)) { + exportName = exportName ? [exportName] : []; + } + const exportsType = module.getExportsType( + moduleGraph, + /** @type {BuildMeta} */ + (originModule.buildMeta).strictHarmonyModule + ); + + const isDeferred = + defer && !(/** @type {BuildMeta} */ (module.buildMeta).async); + + if (defaultInterop) { + // when the defaultInterop is used (when a ESM imports a CJS module), + if (exportName.length > 0 && exportName[0] === "default") { + if (isDeferred && exportsType !== "namespace") { + const access = `${importVar}.a${propertyAccess(exportName, 1)}`; + if (isCall || asiSafe === undefined) { + return access; + } + return asiSafe ? `(${access})` : `;(${access})`; + } + // accessing the .default property is same thing as `require()` the module. + + // For example: + // import mod from "cjs"; mod.default.x; + // is translated to + // var mod = require("cjs"); mod.x; + switch (exportsType) { + case "dynamic": + if (isCall) { + return `${importVar}_default()${propertyAccess(exportName, 1)}`; + } + return asiSafe + ? `(${importVar}_default()${propertyAccess(exportName, 1)})` + : asiSafe === false + ? `;(${importVar}_default()${propertyAccess(exportName, 1)})` + : `${importVar}_default.a${propertyAccess(exportName, 1)}`; + + case "default-only": + case "default-with-named": + exportName = exportName.slice(1); + break; + } + } else if (exportName.length > 0) { + // the property used is not .default. + // For example: + // import * as ns from "cjs"; cjs.prop; + if (exportsType === "default-only") { + // in the strictest case, it is a runtime error (e.g. NodeJS behavior of CJS-ESM interop). + return `/* non-default import from non-esm module */undefined${propertyAccess( + exportName, + 1 + )}`; + } else if ( + exportsType !== "namespace" && + exportName[0] === "__esModule" + ) { + return "/* __esModule */true"; + } + } else if (isDeferred) { + // now exportName.length is 0 + // fall through to the end of this function, create the namespace there. + } else if ( + exportsType === "default-only" || + exportsType === "default-with-named" + ) { + // now exportName.length is 0, which means the namespace object is used in an unknown way + // for example: + // import * as ns from "cjs"; console.log(ns); + // we will need to createFakeNamespaceObject that simulates ES Module namespace object + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + initFragments.push( + new InitFragment( + `var ${importVar}_namespace_cache;\n`, + InitFragment.STAGE_CONSTANTS, + -1, + `${importVar}_namespace_cache` + ) + ); + return `/*#__PURE__*/ ${ + asiSafe ? "" : asiSafe === false ? ";" : "Object" + }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${ + RuntimeGlobals.createFakeNamespaceObject + }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`; + } + } + + if (exportName.length > 0) { + const exportsInfo = moduleGraph.getExportsInfo(module); + // in some case the exported item is renamed (get this by getUsedName). for example, + // x.default might be emitted as x.Z (default is renamed to Z) + const used = exportsInfo.getUsedName(exportName, runtime); + if (!used) { + const comment = Template.toNormalComment( + `unused export ${propertyAccess(exportName)}` + ); + return `${comment} undefined`; + } + const comment = equals(used, exportName) + ? "" + : `${Template.toNormalComment(propertyAccess(exportName))} `; + const access = `${importVar}${ + isDeferred ? ".a" : "" + }${comment}${propertyAccess(used)}`; + if (isCall && callContext === false) { + return asiSafe + ? `(0,${access})` + : asiSafe === false + ? `;(0,${access})` + : `/*#__PURE__*/Object(${access})`; + } + return access; + } + if (isDeferred) { + initFragments.push( + new InitFragment( + `var ${importVar}_deferred_namespace_cache;\n`, + InitFragment.STAGE_CONSTANTS, + -1, + `${importVar}_deferred_namespace_cache` + ) + ); + + runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject); + const id = chunkGraph.getModuleId(module); + const type = getMakeDeferredNamespaceModeFromExportsType(exportsType); + const init = `${ + RuntimeGlobals.makeDeferredNamespaceObject + }(${JSON.stringify(id)}, ${type})`; + + return `/*#__PURE__*/ ${ + asiSafe ? "" : asiSafe === false ? ";" : "Object" + }(${importVar}_deferred_namespace_cache || (${importVar}_deferred_namespace_cache = ${init}))`; + } + // if we hit here, the importVar is either + // - already a ES module namespace object + // - or imported by a way that does not need interop. + return importVar; + } + + /** + * @param {object} options options + * @param {AsyncDependenciesBlock | undefined} options.block the async block + * @param {string} options.message the message + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} expression + */ + blockPromise({ block, message, chunkGraph, runtimeRequirements }) { + if (!block) { + const comment = this.comment({ + message + }); + return `Promise.resolve(${comment.trim()})`; + } + const chunkGroup = chunkGraph.getBlockChunkGroup(block); + if (!chunkGroup || chunkGroup.chunks.length === 0) { + const comment = this.comment({ + message + }); + return `Promise.resolve(${comment.trim()})`; + } + const chunks = chunkGroup.chunks.filter( + (chunk) => !chunk.hasRuntime() && chunk.id !== null + ); + const comment = this.comment({ + message, + chunkName: block.chunkName + }); + if (chunks.length === 1) { + const chunkId = JSON.stringify(chunks[0].id); + runtimeRequirements.add(RuntimeGlobals.ensureChunk); + + const fetchPriority = chunkGroup.options.fetchPriority; + + if (fetchPriority) { + runtimeRequirements.add(RuntimeGlobals.hasFetchPriority); + } + + return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId}${ + fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : "" + })`; + } else if (chunks.length > 0) { + runtimeRequirements.add(RuntimeGlobals.ensureChunk); + + const fetchPriority = chunkGroup.options.fetchPriority; + + if (fetchPriority) { + runtimeRequirements.add(RuntimeGlobals.hasFetchPriority); + } + + /** + * @param {Chunk} chunk chunk + * @returns {string} require chunk id code + */ + const requireChunkId = (chunk) => + `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)}${ + fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : "" + })`; + return `Promise.all(${comment.trim()}[${chunks + .map(requireChunkId) + .join(", ")}])`; + } + return `Promise.resolve(${comment.trim()})`; + } + + /** + * @param {object} options options + * @param {AsyncDependenciesBlock} options.block the async block + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @param {string=} options.request request string used originally + * @returns {string} expression + */ + asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) { + const dep = block.dependencies[0]; + const module = chunkGraph.moduleGraph.getModule(dep); + const ensureChunk = this.blockPromise({ + block, + message: "", + chunkGraph, + runtimeRequirements + }); + const factory = this.returningFunction( + this.moduleRaw({ + module, + chunkGraph, + request, + runtimeRequirements + }) + ); + return this.returningFunction( + ensureChunk.startsWith("Promise.resolve(") + ? `${factory}` + : `${ensureChunk}.then(${this.returningFunction(factory)})` + ); + } + + /** + * @param {object} options options + * @param {Dependency} options.dependency the dependency + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @param {string=} options.request request string used originally + * @returns {string} expression + */ + syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) { + const module = chunkGraph.moduleGraph.getModule(dependency); + const factory = this.returningFunction( + this.moduleRaw({ + module, + chunkGraph, + request, + runtimeRequirements + }) + ); + return this.returningFunction(factory); + } + + /** + * @param {object} options options + * @param {string} options.exportsArgument the name of the exports object + * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} statement + */ + defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); + runtimeRequirements.add(RuntimeGlobals.exports); + return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`; + } +} + +module.exports = RuntimeTemplate; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SelfModuleFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SelfModuleFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..97562b280c9d4aef06116792252a53b6ce2120d4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SelfModuleFactory.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ + +class SelfModuleFactory { + /** + * @param {ModuleGraph} moduleGraph module graph + */ + constructor(moduleGraph) { + this.moduleGraph = moduleGraph; + } + + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create(data, callback) { + const module = this.moduleGraph.getParentModule(data.dependencies[0]); + callback(null, { + module + }); + } +} + +module.exports = SelfModuleFactory; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SingleEntryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SingleEntryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..65791735c792058cad6d82108065a1182627796e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SingleEntryPlugin.js @@ -0,0 +1,8 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + +"use strict"; + +module.exports = require("./EntryPlugin"); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SizeFormatHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SizeFormatHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..e233d5fa6302d336f9b7097ae91e3a6aca63a768 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SizeFormatHelpers.js @@ -0,0 +1,25 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + +"use strict"; + +/** + * @param {number} size the size in bytes + * @returns {string} the formatted size + */ +module.exports.formatSize = (size) => { + if (typeof size !== "number" || Number.isNaN(size) === true) { + return "unknown size"; + } + + if (size <= 0) { + return "0 bytes"; + } + + const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; + const index = Math.floor(Math.log(size) / Math.log(1024)); + + return `${Number((size / 1024 ** index).toPrecision(3))} ${abbreviations[index]}`; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SourceMapDevToolModuleOptionsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SourceMapDevToolModuleOptionsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..c024125bd7ab7af58357992e7c81369e189f6f16 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SourceMapDevToolModuleOptionsPlugin.js @@ -0,0 +1,51 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); + +/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ +/** @typedef {import("./Compilation")} Compilation */ + +const PLUGIN_NAME = "SourceMapDevToolModuleOptionsPlugin"; + +class SourceMapDevToolModuleOptionsPlugin { + /** + * @param {SourceMapDevToolPluginOptions} options options + */ + constructor(options) { + this.options = options; + } + + /** + * @param {Compilation} compilation the compiler instance + * @returns {void} + */ + apply(compilation) { + const options = this.options; + if (options.module !== false) { + compilation.hooks.buildModule.tap(PLUGIN_NAME, (module) => { + module.useSourceMap = true; + }); + compilation.hooks.runtimeModule.tap(PLUGIN_NAME, (module) => { + module.useSourceMap = true; + }); + } else { + compilation.hooks.buildModule.tap(PLUGIN_NAME, (module) => { + module.useSimpleSourceMap = true; + }); + compilation.hooks.runtimeModule.tap(PLUGIN_NAME, (module) => { + module.useSimpleSourceMap = true; + }); + } + JavascriptModulesPlugin.getCompilationHooks(compilation).useSourceMap.tap( + PLUGIN_NAME, + () => true + ); + } +} + +module.exports = SourceMapDevToolModuleOptionsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SourceMapDevToolPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SourceMapDevToolPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..913dad027306ad8e2f5aca51b14bce649369a0d6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/SourceMapDevToolPlugin.js @@ -0,0 +1,613 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const asyncLib = require("neo-async"); +const { ConcatSource, RawSource } = require("webpack-sources"); +const Compilation = require("./Compilation"); +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); +const ProgressPlugin = require("./ProgressPlugin"); +const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin"); +const createSchemaValidation = require("./util/create-schema-validation"); +const createHash = require("./util/createHash"); +const { dirname, relative } = require("./util/fs"); +const generateDebugId = require("./util/generateDebugId"); +const { makePathsAbsolute } = require("./util/identifier"); + +/** @typedef {import("webpack-sources").MapOptions} MapOptions */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ +/** @typedef {import("./Cache").Etag} Etag */ +/** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compilation").Asset} Asset */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./NormalModule").RawSourceMap} RawSourceMap */ +/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ + +const validate = createSchemaValidation( + require("../schemas/plugins/SourceMapDevToolPlugin.check"), + () => require("../schemas/plugins/SourceMapDevToolPlugin.json"), + { + name: "SourceMap DevTool Plugin", + baseDataPath: "options" + } +); +/** + * @typedef {object} SourceMapTask + * @property {Source} asset + * @property {AssetInfo} assetInfo + * @property {(string | Module)[]} modules + * @property {string} source + * @property {string} file + * @property {RawSourceMap} sourceMap + * @property {ItemCacheFacade} cacheItem cache item + */ + +const METACHARACTERS_REGEXP = /[-[\]\\/{}()*+?.^$|]/g; +const CONTENT_HASH_DETECT_REGEXP = /\[contenthash(:\w+)?\]/; +const CSS_AND_JS_MODULE_EXTENSIONS_REGEXP = /\.((c|m)?js|css)($|\?)/i; +const CSS_EXTENSION_DETECT_REGEXP = /\.css($|\?)/i; +const MAP_URL_COMMENT_REGEXP = /\[map\]/g; +const URL_COMMENT_REGEXP = /\[url\]/g; +const URL_FORMATTING_REGEXP = /^\n\/\/(.*)$/; + +/** + * Reset's .lastIndex of stateful Regular Expressions + * For when `test` or `exec` is called on them + * @param {RegExp} regexp Stateful Regular Expression to be reset + * @returns {void} + */ +const resetRegexpState = (regexp) => { + regexp.lastIndex = -1; +}; + +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quoteMeta = (str) => str.replace(METACHARACTERS_REGEXP, "\\$&"); + +/** + * Creating {@link SourceMapTask} for given file + * @param {string} file current compiled file + * @param {Source} asset the asset + * @param {AssetInfo} assetInfo the asset info + * @param {MapOptions} options source map options + * @param {Compilation} compilation compilation instance + * @param {ItemCacheFacade} cacheItem cache item + * @returns {SourceMapTask | undefined} created task instance or `undefined` + */ +const getTaskForFile = ( + file, + asset, + assetInfo, + options, + compilation, + cacheItem +) => { + let source; + /** @type {RawSourceMap} */ + let sourceMap; + /** + * Check if asset can build source map + */ + if (asset.sourceAndMap) { + const sourceAndMap = asset.sourceAndMap(options); + sourceMap = /** @type {RawSourceMap} */ (sourceAndMap.map); + source = sourceAndMap.source; + } else { + sourceMap = /** @type {RawSourceMap} */ (asset.map(options)); + source = asset.source(); + } + if (!sourceMap || typeof source !== "string") return; + const context = /** @type {string} */ (compilation.options.context); + const root = compilation.compiler.root; + const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root); + const modules = sourceMap.sources.map((source) => { + if (!source.startsWith("webpack://")) return source; + source = cachedAbsolutify(source.slice(10)); + const module = compilation.findModule(source); + return module || source; + }); + + return { + file, + asset, + source, + assetInfo, + sourceMap, + modules, + cacheItem + }; +}; + +const PLUGIN_NAME = "SourceMapDevToolPlugin"; + +class SourceMapDevToolPlugin { + /** + * @param {SourceMapDevToolPluginOptions=} options options object + * @throws {Error} throws error, if got more than 1 arguments + */ + constructor(options = {}) { + validate(options); + + this.sourceMapFilename = /** @type {string | false} */ (options.filename); + /** @type {false | TemplatePath}} */ + this.sourceMappingURLComment = + options.append === false + ? false + : // eslint-disable-next-line no-useless-concat + options.append || "\n//# source" + "MappingURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; + this.fallbackModuleFilenameTemplate = + options.fallbackModuleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[hash]"; + this.namespace = options.namespace || ""; + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler compiler instance + * @returns {void} + */ + apply(compiler) { + const outputFs = /** @type {OutputFileSystem} */ ( + compiler.outputFileSystem + ); + const sourceMapFilename = this.sourceMapFilename; + const sourceMappingURLComment = this.sourceMappingURLComment; + const moduleFilenameTemplate = this.moduleFilenameTemplate; + const namespace = this.namespace; + const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; + const requestShortener = compiler.requestShortener; + const options = this.options; + options.test = options.test || CSS_AND_JS_MODULE_EXTENSIONS_REGEXP; + + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); + + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); + + compilation.hooks.processAssets.tapAsync( + { + name: PLUGIN_NAME, + stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING, + additionalAssets: true + }, + (assets, callback) => { + const chunkGraph = compilation.chunkGraph; + const cache = compilation.getCache(PLUGIN_NAME); + /** @type {Map} */ + const moduleToSourceNameMapping = new Map(); + const reportProgress = + ProgressPlugin.getReporter(compilation.compiler) || (() => {}); + + /** @type {Map} */ + const fileToChunk = new Map(); + for (const chunk of compilation.chunks) { + for (const file of chunk.files) { + fileToChunk.set(file, chunk); + } + for (const file of chunk.auxiliaryFiles) { + fileToChunk.set(file, chunk); + } + } + + /** @type {string[]} */ + const files = []; + for (const file of Object.keys(assets)) { + if (matchObject(file)) { + files.push(file); + } + } + + reportProgress(0); + /** @type {SourceMapTask[]} */ + const tasks = []; + let fileIndex = 0; + + asyncLib.each( + files, + (file, callback) => { + const asset = + /** @type {Readonly} */ + (compilation.getAsset(file)); + if (asset.info.related && asset.info.related.sourceMap) { + fileIndex++; + return callback(); + } + + const chunk = fileToChunk.get(file); + const sourceMapNamespace = compilation.getPath(this.namespace, { + chunk + }); + + const cacheItem = cache.getItemCache( + file, + cache.mergeEtags( + cache.getLazyHashedEtag(asset.source), + sourceMapNamespace + ) + ); + + cacheItem.get((err, cacheEntry) => { + if (err) { + return callback(err); + } + /** + * If presented in cache, reassigns assets. Cache assets already have source maps. + */ + if (cacheEntry) { + const { assets, assetsInfo } = cacheEntry; + for (const cachedFile of Object.keys(assets)) { + if (cachedFile === file) { + compilation.updateAsset( + cachedFile, + assets[cachedFile], + assetsInfo[cachedFile] + ); + } else { + compilation.emitAsset( + cachedFile, + assets[cachedFile], + assetsInfo[cachedFile] + ); + } + /** + * Add file to chunk, if not presented there + */ + if (cachedFile !== file && chunk !== undefined) { + chunk.auxiliaryFiles.add(cachedFile); + } + } + + reportProgress( + (0.5 * ++fileIndex) / files.length, + file, + "restored cached SourceMap" + ); + + return callback(); + } + + reportProgress( + (0.5 * fileIndex) / files.length, + file, + "generate SourceMap" + ); + + /** @type {SourceMapTask | undefined} */ + const task = getTaskForFile( + file, + asset.source, + asset.info, + { + module: options.module, + columns: options.columns + }, + compilation, + cacheItem + ); + + if (task) { + const modules = task.modules; + + for (let idx = 0; idx < modules.length; idx++) { + const module = modules[idx]; + + if ( + typeof module === "string" && + /^(data|https?):/.test(module) + ) { + moduleToSourceNameMapping.set(module, module); + continue; + } + + if (!moduleToSourceNameMapping.get(module)) { + moduleToSourceNameMapping.set( + module, + ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate, + namespace: sourceMapNamespace + }, + { + requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction + } + ) + ); + } + } + + tasks.push(task); + } + + reportProgress( + (0.5 * ++fileIndex) / files.length, + file, + "generated SourceMap" + ); + + callback(); + }); + }, + (err) => { + if (err) { + return callback(err); + } + + reportProgress(0.5, "resolve sources"); + /** @type {Set} */ + const usedNamesSet = new Set(moduleToSourceNameMapping.values()); + /** @type {Set} */ + const conflictDetectionSet = new Set(); + + /** + * all modules in defined order (longest identifier first) + * @type {Array} + */ + const allModules = [...moduleToSourceNameMapping.keys()].sort( + (a, b) => { + const ai = typeof a === "string" ? a : a.identifier(); + const bi = typeof b === "string" ? b : b.identifier(); + return ai.length - bi.length; + } + ); + + // find modules with conflicting source names + for (let idx = 0; idx < allModules.length; idx++) { + const module = allModules[idx]; + let sourceName = + /** @type {string} */ + (moduleToSourceNameMapping.get(module)); + let hasName = conflictDetectionSet.has(sourceName); + if (!hasName) { + conflictDetectionSet.add(sourceName); + continue; + } + + // try the fallback name first + sourceName = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: fallbackModuleFilenameTemplate, + namespace + }, + { + requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction + } + ); + hasName = usedNamesSet.has(sourceName); + if (!hasName) { + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + continue; + } + + // otherwise just append stars until we have a valid name + while (hasName) { + sourceName += "*"; + hasName = usedNamesSet.has(sourceName); + } + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + } + + let taskIndex = 0; + + asyncLib.each( + tasks, + (task, callback) => { + const assets = Object.create(null); + const assetsInfo = Object.create(null); + const file = task.file; + const chunk = fileToChunk.get(file); + const sourceMap = task.sourceMap; + const source = task.source; + const modules = task.modules; + + reportProgress( + 0.5 + (0.5 * taskIndex) / tasks.length, + file, + "attach SourceMap" + ); + + const moduleFilenames = modules.map((m) => + moduleToSourceNameMapping.get(m) + ); + sourceMap.sources = /** @type {string[]} */ (moduleFilenames); + if (options.noSources) { + sourceMap.sourcesContent = undefined; + } + sourceMap.sourceRoot = options.sourceRoot || ""; + sourceMap.file = file; + const usesContentHash = + sourceMapFilename && + CONTENT_HASH_DETECT_REGEXP.test(sourceMapFilename); + + resetRegexpState(CONTENT_HASH_DETECT_REGEXP); + + // If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file` + if (usesContentHash && task.assetInfo.contenthash) { + const contenthash = task.assetInfo.contenthash; + const pattern = Array.isArray(contenthash) + ? contenthash.map(quoteMeta).join("|") + : quoteMeta(contenthash); + sourceMap.file = sourceMap.file.replace( + new RegExp(pattern, "g"), + (m) => "x".repeat(m.length) + ); + } + + /** @type {false | TemplatePath} */ + let currentSourceMappingURLComment = sourceMappingURLComment; + const cssExtensionDetected = + CSS_EXTENSION_DETECT_REGEXP.test(file); + resetRegexpState(CSS_EXTENSION_DETECT_REGEXP); + if ( + currentSourceMappingURLComment !== false && + typeof currentSourceMappingURLComment !== "function" && + cssExtensionDetected + ) { + currentSourceMappingURLComment = + currentSourceMappingURLComment.replace( + URL_FORMATTING_REGEXP, + "\n/*$1*/" + ); + } + + if (options.debugIds) { + const debugId = generateDebugId(source, sourceMap.file); + sourceMap.debugId = debugId; + currentSourceMappingURLComment = `\n//# debugId=${debugId}${currentSourceMappingURLComment}`; + } + + const sourceMapString = JSON.stringify(sourceMap); + if (sourceMapFilename) { + const filename = file; + const sourceMapContentHash = + /** @type {string} */ + ( + usesContentHash && + createHash( + /** @type {HashFunction} */ + (compilation.outputOptions.hashFunction) + ) + .update(sourceMapString) + .digest("hex") + ); + const pathParams = { + chunk, + filename: options.fileContext + ? relative( + outputFs, + `/${options.fileContext}`, + `/${filename}` + ) + : filename, + contentHash: sourceMapContentHash + }; + const { path: sourceMapFile, info: sourceMapInfo } = + compilation.getPathWithInfo( + sourceMapFilename, + pathParams + ); + const sourceMapUrl = options.publicPath + ? options.publicPath + sourceMapFile + : relative( + outputFs, + dirname(outputFs, `/${file}`), + `/${sourceMapFile}` + ); + /** @type {Source} */ + let asset = new RawSource(source); + if (currentSourceMappingURLComment !== false) { + // Add source map url to compilation asset, if currentSourceMappingURLComment is set + asset = new ConcatSource( + asset, + compilation.getPath(currentSourceMappingURLComment, { + url: sourceMapUrl, + ...pathParams + }) + ); + } + const assetInfo = { + related: { sourceMap: sourceMapFile } + }; + assets[file] = asset; + assetsInfo[file] = assetInfo; + compilation.updateAsset(file, asset, assetInfo); + // Add source map file to compilation assets and chunk files + const sourceMapAsset = new RawSource(sourceMapString); + const sourceMapAssetInfo = { + ...sourceMapInfo, + development: true + }; + assets[sourceMapFile] = sourceMapAsset; + assetsInfo[sourceMapFile] = sourceMapAssetInfo; + compilation.emitAsset( + sourceMapFile, + sourceMapAsset, + sourceMapAssetInfo + ); + if (chunk !== undefined) { + chunk.auxiliaryFiles.add(sourceMapFile); + } + } else { + if (currentSourceMappingURLComment === false) { + throw new Error( + `${PLUGIN_NAME}: append can't be false when no filename is provided` + ); + } + if (typeof currentSourceMappingURLComment === "function") { + throw new Error( + `${PLUGIN_NAME}: append can't be a function when no filename is provided` + ); + } + /** + * Add source map as data url to asset + */ + const asset = new ConcatSource( + new RawSource(source), + currentSourceMappingURLComment + .replace(MAP_URL_COMMENT_REGEXP, () => sourceMapString) + .replace( + URL_COMMENT_REGEXP, + () => + `data:application/json;charset=utf-8;base64,${Buffer.from( + sourceMapString, + "utf8" + ).toString("base64")}` + ) + ); + assets[file] = asset; + assetsInfo[file] = undefined; + compilation.updateAsset(file, asset); + } + + task.cacheItem.store({ assets, assetsInfo }, (err) => { + reportProgress( + 0.5 + (0.5 * ++taskIndex) / tasks.length, + task.file, + "attached SourceMap" + ); + + if (err) { + return callback(err); + } + callback(); + }); + }, + (err) => { + reportProgress(1); + callback(err); + } + ); + } + ); + } + ); + }); + } +} + +module.exports = SourceMapDevToolPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Stats.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Stats.js new file mode 100644 index 0000000000000000000000000000000000000000..2a88379626943815da197e26e41a7e7b0ae975cb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Stats.js @@ -0,0 +1,89 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compilation").NormalizedStatsOptions} NormalizedStatsOptions */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ + +class Stats { + /** + * @param {Compilation} compilation webpack compilation + */ + constructor(compilation) { + this.compilation = compilation; + } + + get hash() { + return this.compilation.hash; + } + + get startTime() { + return this.compilation.startTime; + } + + get endTime() { + return this.compilation.endTime; + } + + /** + * @returns {boolean} true if the compilation had a warning + */ + hasWarnings() { + return ( + this.compilation.getWarnings().length > 0 || + this.compilation.children.some((child) => child.getStats().hasWarnings()) + ); + } + + /** + * @returns {boolean} true if the compilation encountered an error + */ + hasErrors() { + return ( + this.compilation.errors.length > 0 || + this.compilation.children.some((child) => child.getStats().hasErrors()) + ); + } + + /** + * @param {(string | boolean | StatsOptions)=} options stats options + * @returns {StatsCompilation} json output + */ + toJson(options) { + const normalizedOptions = this.compilation.createStatsOptions(options, { + forToString: false + }); + + const statsFactory = this.compilation.createStatsFactory(normalizedOptions); + + return statsFactory.create("compilation", this.compilation, { + compilation: this.compilation + }); + } + + /** + * @param {(string | boolean | StatsOptions)=} options stats options + * @returns {string} string output + */ + toString(options) { + const normalizedOptions = this.compilation.createStatsOptions(options, { + forToString: true + }); + + const statsFactory = this.compilation.createStatsFactory(normalizedOptions); + const statsPrinter = this.compilation.createStatsPrinter(normalizedOptions); + + const data = statsFactory.create("compilation", this.compilation, { + compilation: this.compilation + }); + const result = statsPrinter.print("compilation", data); + return result === undefined ? "" : result; + } +} + +module.exports = Stats; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Template.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Template.js new file mode 100644 index 0000000000000000000000000000000000000000..f8b60e3becbebd811943a1898b017d4fba758d56 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Template.js @@ -0,0 +1,416 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource, PrefixSource } = require("webpack-sources"); +const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants"); +const RuntimeGlobals = require("./RuntimeGlobals"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").PathData} PathData */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ + +const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); +const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); +const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; +const NUMBER_OF_IDENTIFIER_START_CHARS = DELTA_A_TO_Z * 2 + 2; // a-z A-Z _ $ +const NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = + NUMBER_OF_IDENTIFIER_START_CHARS + 10; // a-z A-Z _ $ 0-9 +const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; +const INDENT_MULTILINE_REGEX = /^\t/gm; +const LINE_SEPARATOR_REGEX = /\r?\n/g; +const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; +const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; +const COMMENT_END_REGEX = /\*\//g; +const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; +const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; + +/** + * @typedef {object} RenderManifestOptions + * @property {Chunk} chunk the chunk used to render + * @property {string} hash + * @property {string} fullHash + * @property {OutputOptions} outputOptions + * @property {CodeGenerationResults} codeGenerationResults + * @property {{javascript: ModuleTemplate}} moduleTemplates + * @property {DependencyTemplates} dependencyTemplates + * @property {RuntimeTemplate} runtimeTemplate + * @property {ModuleGraph} moduleGraph + * @property {ChunkGraph} chunkGraph + */ + +/** @typedef {RenderManifestEntryTemplated | RenderManifestEntryStatic} RenderManifestEntry */ + +/** + * @typedef {object} RenderManifestEntryTemplated + * @property {() => Source} render + * @property {TemplatePath} filenameTemplate + * @property {PathData=} pathOptions + * @property {AssetInfo=} info + * @property {string} identifier + * @property {string=} hash + * @property {boolean=} auxiliary + */ + +/** + * @typedef {object} RenderManifestEntryStatic + * @property {() => Source} render + * @property {string} filename + * @property {AssetInfo} info + * @property {string} identifier + * @property {string=} hash + * @property {boolean=} auxiliary + */ + +/** + * @typedef {object} HasId + * @property {number | string} id + */ + +/** + * @typedef {(module: Module) => boolean} ModuleFilterPredicate + */ + +class Template { + /** + * @template {EXPECTED_FUNCTION} T + * @param {T} fn a runtime function (.runtime.js) "template" + * @returns {string} the updated and normalized function string + */ + static getFunctionContent(fn) { + return fn + .toString() + .replace(FUNCTION_CONTENT_REGEX, "") + .replace(INDENT_MULTILINE_REGEX, "") + .replace(LINE_SEPARATOR_REGEX, "\n"); + } + + /** + * @param {string} str the string converted to identifier + * @returns {string} created identifier + */ + static toIdentifier(str) { + if (typeof str !== "string") return ""; + return str + .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") + .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); + } + + /** + * @param {string} str string to be converted to commented in bundle code + * @returns {string} returns a commented version of string + */ + static toComment(str) { + if (!str) return ""; + return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; + } + + /** + * @param {string} str string to be converted to "normal comment" + * @returns {string} returns a commented version of string + */ + static toNormalComment(str) { + if (!str) return ""; + return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; + } + + /** + * @param {string} str string path to be normalized + * @returns {string} normalized bundle-safe path + */ + static toPath(str) { + if (typeof str !== "string") return ""; + return str + .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") + .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); + } + + // map number to a single character a-z, A-Z or multiple characters if number is too big + /** + * @param {number} n number to convert to ident + * @returns {string} returns single character ident + */ + static numberToIdentifier(n) { + if (n >= NUMBER_OF_IDENTIFIER_START_CHARS) { + // use multiple letters + return ( + Template.numberToIdentifier(n % NUMBER_OF_IDENTIFIER_START_CHARS) + + Template.numberToIdentifierContinuation( + Math.floor(n / NUMBER_OF_IDENTIFIER_START_CHARS) + ) + ); + } + + // lower case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } + n -= DELTA_A_TO_Z; + + // upper case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); + } + + if (n === DELTA_A_TO_Z) return "_"; + return "$"; + } + + /** + * @param {number} n number to convert to ident + * @returns {string} returns single character ident + */ + static numberToIdentifierContinuation(n) { + if (n >= NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) { + // use multiple letters + return ( + Template.numberToIdentifierContinuation( + n % NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS + ) + + Template.numberToIdentifierContinuation( + Math.floor(n / NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) + ) + ); + } + + // lower case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } + n -= DELTA_A_TO_Z; + + // upper case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); + } + n -= DELTA_A_TO_Z; + + // numbers + if (n < 10) { + return `${n}`; + } + + if (n === 10) return "_"; + return "$"; + } + + /** + * @param {string | string[]} s string to convert to identity + * @returns {string} converted identity + */ + static indent(s) { + if (Array.isArray(s)) { + return s.map(Template.indent).join("\n"); + } + const str = s.trimEnd(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : "\t"; + return ind + str.replace(/\n([^\n])/g, "\n\t$1"); + } + + /** + * @param {string|string[]} s string to create prefix for + * @param {string} prefix prefix to compose + * @returns {string} returns new prefix string + */ + static prefix(s, prefix) { + const str = Template.asString(s).trim(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : prefix; + return ind + str.replace(/\n([^\n])/g, `\n${prefix}$1`); + } + + /** + * @param {string|string[]} str string or string collection + * @returns {string} returns a single string from array + */ + static asString(str) { + if (Array.isArray(str)) { + return str.join("\n"); + } + return str; + } + + /** + * @typedef {object} WithId + * @property {string | number} id + */ + + /** + * @param {WithId[]} modules a collection of modules to get array bounds for + * @returns {[number, number] | false} returns the upper and lower array bounds + * or false if not every module has a number based id + */ + static getModulesArrayBounds(modules) { + let maxId = -Infinity; + let minId = Infinity; + for (const module of modules) { + const moduleId = module.id; + if (typeof moduleId !== "number") return false; + if (maxId < moduleId) maxId = moduleId; + if (minId > moduleId) minId = moduleId; + } + if (minId < 16 + String(minId).length) { + // add minId x ',' instead of 'Array(minId).concat(…)' + minId = 0; + } + // start with -1 because the first module needs no comma + let objectOverhead = -1; + for (const module of modules) { + // module id + colon + comma + objectOverhead += `${module.id}`.length + 2; + } + // number of commas, or when starting non-zero the length of Array(minId).concat() + const arrayOverhead = minId === 0 ? maxId : 16 + `${minId}`.length + maxId; + return arrayOverhead < objectOverhead ? [minId, maxId] : false; + } + + /** + * @param {ChunkRenderContext} renderContext render context + * @param {Module[]} modules modules to render (should be ordered by identifier) + * @param {(module: Module) => Source | null} renderModule function to render a module + * @param {string=} prefix applying prefix strings + * @returns {Source | null} rendered chunk modules in a Source object or null if no modules + */ + static renderChunkModules(renderContext, modules, renderModule, prefix = "") { + const { chunkGraph } = renderContext; + const source = new ConcatSource(); + if (modules.length === 0) { + return null; + } + /** @type {{id: string|number, source: Source|string}[]} */ + const allModules = modules.map((module) => ({ + id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)), + source: renderModule(module) || "false" + })); + const bounds = Template.getModulesArrayBounds(allModules); + if (bounds) { + // Render a spare array + const minId = bounds[0]; + const maxId = bounds[1]; + if (minId !== 0) { + source.add(`Array(${minId}).concat(`); + } + source.add("[\n"); + /** @type {Map} */ + const modules = new Map(); + for (const module of allModules) { + modules.set(module.id, module); + } + for (let idx = minId; idx <= maxId; idx++) { + const module = modules.get(idx); + if (idx !== minId) { + source.add(",\n"); + } + source.add(`/* ${idx} */`); + if (module) { + source.add("\n"); + source.add(module.source); + } + } + source.add(`\n${prefix}]`); + if (minId !== 0) { + source.add(")"); + } + } else { + // Render an object + source.add("{\n"); + for (let i = 0; i < allModules.length; i++) { + const module = allModules[i]; + if (i !== 0) { + source.add(",\n"); + } + source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); + source.add(module.source); + } + source.add(`\n\n${prefix}}`); + } + return source; + } + + /** + * @param {RuntimeModule[]} runtimeModules array of runtime modules in order + * @param {RenderContext & { codeGenerationResults?: CodeGenerationResults }} renderContext render context + * @returns {Source} rendered runtime modules in a Source object + */ + static renderRuntimeModules(runtimeModules, renderContext) { + const source = new ConcatSource(); + for (const module of runtimeModules) { + const codeGenerationResults = renderContext.codeGenerationResults; + let runtimeSource; + if (codeGenerationResults) { + runtimeSource = codeGenerationResults.getSource( + module, + renderContext.chunk.runtime, + WEBPACK_MODULE_TYPE_RUNTIME + ); + } else { + const codeGenResult = module.codeGeneration({ + chunkGraph: renderContext.chunkGraph, + dependencyTemplates: renderContext.dependencyTemplates, + moduleGraph: renderContext.moduleGraph, + runtimeTemplate: renderContext.runtimeTemplate, + runtime: renderContext.chunk.runtime, + codeGenerationResults + }); + if (!codeGenResult) continue; + runtimeSource = codeGenResult.sources.get("runtime"); + } + if (runtimeSource) { + source.add(`${Template.toNormalComment(module.identifier())}\n`); + if (!module.shouldIsolate()) { + source.add(runtimeSource); + source.add("\n\n"); + } else if (renderContext.runtimeTemplate.supportsArrowFunction()) { + source.add("(() => {\n"); + source.add(new PrefixSource("\t", runtimeSource)); + source.add("\n})();\n\n"); + } else { + source.add("!function() {\n"); + source.add(new PrefixSource("\t", runtimeSource)); + source.add("\n}();\n\n"); + } + } + } + return source; + } + + /** + * @param {RuntimeModule[]} runtimeModules array of runtime modules in order + * @param {RenderContext} renderContext render context + * @returns {Source} rendered chunk runtime modules in a Source object + */ + static renderChunkRuntimeModules(runtimeModules, renderContext) { + return new PrefixSource( + "/******/ ", + new ConcatSource( + `function(${RuntimeGlobals.require}) { // webpackRuntimeModules\n`, + this.renderRuntimeModules(runtimeModules, renderContext), + "}\n" + ) + ); + } +} + +module.exports = Template; +module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS; +module.exports.NUMBER_OF_IDENTIFIER_START_CHARS = + NUMBER_OF_IDENTIFIER_START_CHARS; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/TemplatedPathPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/TemplatedPathPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..0afb5aff26a002a922e30e20fa86fd110bc68e80 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/TemplatedPathPlugin.js @@ -0,0 +1,398 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Jason Anderson @diurnalist +*/ + +"use strict"; + +const { basename, extname } = require("path"); +const util = require("util"); +const mime = require("mime-types"); +const Chunk = require("./Chunk"); +const Module = require("./Module"); +const { parseResource } = require("./util/identifier"); + +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").PathData} PathData */ +/** @typedef {import("./Compiler")} Compiler */ + +const REGEXP = /\[\\*([\w:]+)\\*\]/gi; + +/** + * @param {string | number} id id + * @returns {string | number} result + */ +const prepareId = (id) => { + if (typeof id !== "string") return id; + + if (/^"\s\+*.*\+\s*"$/.test(id)) { + const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id); + + return `" + (${ + /** @type {string[]} */ (match)[1] + } + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`; + } + + return id.replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); +}; + +/** + * @callback ReplacerFunction + * @param {string} match + * @param {string | undefined} arg + * @param {string} input + */ + +/** + * @param {ReplacerFunction} replacer replacer + * @param {((arg0: number) => string) | undefined} handler handler + * @param {AssetInfo | undefined} assetInfo asset info + * @param {string} hashName hash name + * @returns {Replacer} hash replacer function + */ +const hashLength = (replacer, handler, assetInfo, hashName) => { + /** @type {Replacer} */ + const fn = (match, arg, input) => { + let result; + const length = arg && Number.parseInt(arg, 10); + + if (length && handler) { + result = handler(length); + } else { + const hash = replacer(match, arg, input); + + result = length ? hash.slice(0, length) : hash; + } + if (assetInfo) { + assetInfo.immutable = true; + if (Array.isArray(assetInfo[hashName])) { + assetInfo[hashName] = [...assetInfo[hashName], result]; + } else if (assetInfo[hashName]) { + assetInfo[hashName] = [assetInfo[hashName], result]; + } else { + assetInfo[hashName] = result; + } + } + return result; + }; + + return fn; +}; + +/** @typedef {(match: string, arg: string | undefined, input: string) => string} Replacer */ + +/** + * @param {string | number | null | undefined | (() => string | number | null | undefined)} value value + * @param {boolean=} allowEmpty allow empty + * @returns {Replacer} replacer + */ +const replacer = (value, allowEmpty) => { + /** @type {Replacer} */ + const fn = (match, arg, input) => { + if (typeof value === "function") { + value = value(); + } + if (value === null || value === undefined) { + if (!allowEmpty) { + throw new Error( + `Path variable ${match} not implemented in this context: ${input}` + ); + } + + return ""; + } + + return `${value}`; + }; + + return fn; +}; + +const deprecationCache = new Map(); +const deprecatedFunction = (() => () => {})(); +/** + * @template {(...args: EXPECTED_ANY[]) => EXPECTED_ANY} T + * @param {T} fn function + * @param {string} message message + * @param {string} code code + * @returns {T} function with deprecation output + */ +const deprecated = (fn, message, code) => { + let d = deprecationCache.get(message); + if (d === undefined) { + d = util.deprecate(deprecatedFunction, message, code); + deprecationCache.set(message, d); + } + return /** @type {T} */ ( + (...args) => { + d(); + return fn(...args); + } + ); +}; + +/** @typedef {string | ((pathData: PathData, assetInfo?: AssetInfo) => string)} TemplatePath */ + +/** + * @param {TemplatePath} path the raw path + * @param {PathData} data context data + * @param {AssetInfo | undefined} assetInfo extra info about the asset (will be written to) + * @returns {string} the interpolated path + */ +const replacePathVariables = (path, data, assetInfo) => { + const chunkGraph = data.chunkGraph; + + /** @type {Map} */ + const replacements = new Map(); + + // Filename context + // + // Placeholders + // + // for /some/path/file.js?query#fragment: + // [file] - /some/path/file.js + // [query] - ?query + // [fragment] - #fragment + // [base] - file.js + // [path] - /some/path/ + // [name] - file + // [ext] - .js + if (typeof data.filename === "string") { + // check that filename is data uri + const match = data.filename.match(/^data:([^;,]+)/); + if (match) { + const ext = mime.extension(match[1]); + const emptyReplacer = replacer("", true); + // "XXXX" used for `updateHash`, so we don't need it here + const contentHash = + data.contentHash && !/X+/.test(data.contentHash) + ? data.contentHash + : false; + const baseReplacer = contentHash ? replacer(contentHash) : emptyReplacer; + + replacements.set("file", emptyReplacer); + replacements.set("query", emptyReplacer); + replacements.set("fragment", emptyReplacer); + replacements.set("path", emptyReplacer); + replacements.set("base", baseReplacer); + replacements.set("name", baseReplacer); + replacements.set("ext", replacer(ext ? `.${ext}` : "", true)); + // Legacy + replacements.set( + "filebase", + deprecated( + baseReplacer, + "[filebase] is now [base]", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME" + ) + ); + } else { + const { path: file, query, fragment } = parseResource(data.filename); + + const ext = extname(file); + const base = basename(file); + const name = base.slice(0, base.length - ext.length); + const path = file.slice(0, file.length - base.length); + + replacements.set("file", replacer(file)); + replacements.set("query", replacer(query, true)); + replacements.set("fragment", replacer(fragment, true)); + replacements.set("path", replacer(path, true)); + replacements.set("base", replacer(base)); + replacements.set("name", replacer(name)); + replacements.set("ext", replacer(ext, true)); + // Legacy + replacements.set( + "filebase", + deprecated( + replacer(base), + "[filebase] is now [base]", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME" + ) + ); + } + } + + // Compilation context + // + // Placeholders + // + // [fullhash] - data.hash (3a4b5c6e7f) + // + // Legacy Placeholders + // + // [hash] - data.hash (3a4b5c6e7f) + if (data.hash) { + const hashReplacer = hashLength( + replacer(data.hash), + data.hashWithLength, + assetInfo, + "fullhash" + ); + + replacements.set("fullhash", hashReplacer); + + // Legacy + replacements.set( + "hash", + deprecated( + hashReplacer, + "[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH" + ) + ); + } + + // Chunk Context + // + // Placeholders + // + // [id] - chunk.id (0.js) + // [name] - chunk.name (app.js) + // [chunkhash] - chunk.hash (7823t4t4.js) + // [contenthash] - chunk.contentHash[type] (3256u3zg.js) + if (data.chunk) { + const chunk = data.chunk; + + const contentHashType = data.contentHashType; + + const idReplacer = replacer(chunk.id); + const nameReplacer = replacer(chunk.name || chunk.id); + const chunkhashReplacer = hashLength( + replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash), + "hashWithLength" in chunk ? chunk.hashWithLength : undefined, + assetInfo, + "chunkhash" + ); + const contenthashReplacer = hashLength( + replacer( + data.contentHash || + (contentHashType && + chunk.contentHash && + chunk.contentHash[contentHashType]) + ), + data.contentHashWithLength || + ("contentHashWithLength" in chunk && chunk.contentHashWithLength + ? chunk.contentHashWithLength[/** @type {string} */ (contentHashType)] + : undefined), + assetInfo, + "contenthash" + ); + + replacements.set("id", idReplacer); + replacements.set("name", nameReplacer); + replacements.set("chunkhash", chunkhashReplacer); + replacements.set("contenthash", contenthashReplacer); + } + + // Module Context + // + // Placeholders + // + // [id] - module.id (2.png) + // [hash] - module.hash (6237543873.png) + // + // Legacy Placeholders + // + // [moduleid] - module.id (2.png) + // [modulehash] - module.hash (6237543873.png) + if (data.module) { + const module = data.module; + + const idReplacer = replacer(() => + prepareId( + module instanceof Module + ? /** @type {ModuleId} */ + (/** @type {ChunkGraph} */ (chunkGraph).getModuleId(module)) + : module.id + ) + ); + const moduleHashReplacer = hashLength( + replacer(() => + module instanceof Module + ? /** @type {ChunkGraph} */ + (chunkGraph).getRenderedModuleHash(module, data.runtime) + : module.hash + ), + "hashWithLength" in module ? module.hashWithLength : undefined, + assetInfo, + "modulehash" + ); + const contentHashReplacer = hashLength( + replacer(/** @type {string} */ (data.contentHash)), + undefined, + assetInfo, + "contenthash" + ); + + replacements.set("id", idReplacer); + replacements.set("modulehash", moduleHashReplacer); + replacements.set("contenthash", contentHashReplacer); + replacements.set( + "hash", + data.contentHash ? contentHashReplacer : moduleHashReplacer + ); + // Legacy + replacements.set( + "moduleid", + deprecated( + idReplacer, + "[moduleid] is now [id]", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID" + ) + ); + } + + // Other things + if (data.url) { + replacements.set("url", replacer(data.url)); + } + if (typeof data.runtime === "string") { + replacements.set( + "runtime", + replacer(() => prepareId(/** @type {string} */ (data.runtime))) + ); + } else { + replacements.set("runtime", replacer("_")); + } + + if (typeof path === "function") { + path = path(data, assetInfo); + } + + path = path.replace(REGEXP, (match, content) => { + if (content.length + 2 === match.length) { + const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content); + if (!contentMatch) return match; + const [, kind, arg] = contentMatch; + const replacer = replacements.get(kind); + if (replacer !== undefined) { + return replacer(match, arg, /** @type {string} */ (path)); + } + } else if (match.startsWith("[\\") && match.endsWith("\\]")) { + return `[${match.slice(2, -2)}]`; + } + return match; + }); + + return path; +}; + +const plugin = "TemplatedPathPlugin"; + +class TemplatedPathPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(plugin, (compilation) => { + compilation.hooks.assetPath.tap(plugin, replacePathVariables); + }); + } +} + +module.exports = TemplatedPathPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/UnhandledSchemeError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/UnhandledSchemeError.js new file mode 100644 index 0000000000000000000000000000000000000000..80fa07af1884531f8a65c23226a001cca62952b9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/UnhandledSchemeError.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +class UnhandledSchemeError extends WebpackError { + /** + * @param {string} scheme scheme + * @param {string} resource resource + */ + constructor(scheme, resource) { + super( + `Reading from "${resource}" is not handled by plugins (Unhandled scheme).` + + '\nWebpack supports "data:" and "file:" URIs by default.' + + `\nYou may need an additional plugin to handle "${scheme}:" URIs.` + ); + this.file = resource; + this.name = "UnhandledSchemeError"; + } +} + +makeSerializable( + UnhandledSchemeError, + "webpack/lib/UnhandledSchemeError", + "UnhandledSchemeError" +); + +module.exports = UnhandledSchemeError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/UnsupportedFeatureWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/UnsupportedFeatureWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..2c59f4a80a8e820146290645fda6aabfe01823b1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/UnsupportedFeatureWarning.js @@ -0,0 +1,32 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + +class UnsupportedFeatureWarning extends WebpackError { + /** + * @param {string} message description of warning + * @param {DependencyLocation} loc location start and end positions of the module + */ + constructor(message, loc) { + super(message); + + this.name = "UnsupportedFeatureWarning"; + this.loc = loc; + this.hideStack = true; + } +} + +makeSerializable( + UnsupportedFeatureWarning, + "webpack/lib/UnsupportedFeatureWarning" +); + +module.exports = UnsupportedFeatureWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/UseStrictPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/UseStrictPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..ea1d87fbebb27b249dacfda2c1e7e4020116f2d4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/UseStrictPlugin.js @@ -0,0 +1,81 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("./ModuleTypeConstants"); +const ConstDependency = require("./dependencies/ConstDependency"); + +/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module").BuildInfo} BuildInfo */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "UseStrictPlugin"; + +class UseStrictPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + /** + * @param {JavascriptParser} parser the parser + * @param {JavascriptParserOptions} parserOptions the javascript parser options + */ + const handler = (parser, parserOptions) => { + parser.hooks.program.tap(PLUGIN_NAME, (ast) => { + const firstNode = ast.body[0]; + if ( + firstNode && + firstNode.type === "ExpressionStatement" && + firstNode.expression.type === "Literal" && + firstNode.expression.value === "use strict" + ) { + // Remove "use strict" expression. It will be added later by the renderer again. + // This is necessary in order to not break the strict mode when webpack prepends code. + // @see https://github.com/webpack/webpack/issues/1970 + const dep = new ConstDependency( + "", + /** @type {Range} */ (firstNode.range) + ); + dep.loc = /** @type {DependencyLocation} */ (firstNode.loc); + parser.state.module.addPresentationalDependency(dep); + /** @type {BuildInfo} */ + (parser.state.module.buildInfo).strict = true; + } + if (parserOptions.overrideStrict) { + /** @type {BuildInfo} */ + (parser.state.module.buildInfo).strict = + parserOptions.overrideStrict === "strict"; + } + }); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = UseStrictPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WarnCaseSensitiveModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WarnCaseSensitiveModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..a272cff05034fcfc7e01bc6ecfef55fea9dbbc4f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WarnCaseSensitiveModulesPlugin.js @@ -0,0 +1,64 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const CaseSensitiveModulesWarning = require("./CaseSensitiveModulesWarning"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./NormalModule")} NormalModule */ + +const PLUGIN_NAME = "WarnCaseSensitiveModulesPlugin"; + +class WarnCaseSensitiveModulesPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.seal.tap(PLUGIN_NAME, () => { + /** @type {Map>} */ + const moduleWithoutCase = new Map(); + for (const module of compilation.modules) { + const identifier = module.identifier(); + + // Ignore `data:` URLs, because it's not a real path + if ( + /** @type {NormalModule} */ + (module).resourceResolveData !== undefined && + /** @type {NormalModule} */ + (module).resourceResolveData.encodedContent !== undefined + ) { + continue; + } + + const lowerIdentifier = identifier.toLowerCase(); + let map = moduleWithoutCase.get(lowerIdentifier); + if (map === undefined) { + map = new Map(); + moduleWithoutCase.set(lowerIdentifier, map); + } + map.set(identifier, module); + } + for (const pair of moduleWithoutCase) { + const map = pair[1]; + if (map.size > 1) { + compilation.warnings.push( + new CaseSensitiveModulesWarning( + map.values(), + compilation.moduleGraph + ) + ); + } + } + }); + }); + } +} + +module.exports = WarnCaseSensitiveModulesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WarnDeprecatedOptionPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WarnDeprecatedOptionPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..5afe80e9c19f7a29c2de2dfb736ff64daed8779e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WarnDeprecatedOptionPlugin.js @@ -0,0 +1,59 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Compiler")} Compiler */ + +const PLUGIN_NAME = "WarnDeprecatedOptionPlugin"; + +class WarnDeprecatedOptionPlugin { + /** + * Create an instance of the plugin + * @param {string} option the target option + * @param {string | number} value the deprecated option value + * @param {string} suggestion the suggestion replacement + */ + constructor(option, value, suggestion) { + this.option = option; + this.value = value; + this.suggestion = suggestion; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilation.warnings.push( + new DeprecatedOptionWarning(this.option, this.value, this.suggestion) + ); + }); + } +} + +class DeprecatedOptionWarning extends WebpackError { + /** + * Create an instance deprecated option warning + * @param {string} option the target option + * @param {string | number} value the deprecated option value + * @param {string} suggestion the suggestion replacement + */ + constructor(option, value, suggestion) { + super(); + + this.name = "DeprecatedOptionWarning"; + this.message = + "configuration\n" + + `The value '${value}' for option '${option}' is deprecated. ` + + `Use '${suggestion}' instead.`; + } +} + +module.exports = WarnDeprecatedOptionPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WarnNoModeSetPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WarnNoModeSetPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..3eaae89bc34d07078b6c0fafd79bc34b58d9b966 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WarnNoModeSetPlugin.js @@ -0,0 +1,27 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const NoModeWarning = require("./NoModeWarning"); + +/** @typedef {import("./Compiler")} Compiler */ + +const PLUGIN_NAME = "WarnNoModeSetPlugin"; + +class WarnNoModeSetPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilation.warnings.push(new NoModeWarning()); + }); + } +} + +module.exports = WarnNoModeSetPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WatchIgnorePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WatchIgnorePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b47b1cdefd690c26ca45b07789b3c70459f89fe3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WatchIgnorePlugin.js @@ -0,0 +1,156 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { groupBy } = require("./util/ArrayHelpers"); +const createSchemaValidation = require("./util/create-schema-validation"); + +/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ +/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./util/fs").TimeInfoEntries} TimeInfoEntries */ +/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ +/** @typedef {import("./util/fs").WatchMethod} WatchMethod */ +/** @typedef {import("./util/fs").Watcher} Watcher */ + +const validate = createSchemaValidation( + require("../schemas/plugins/WatchIgnorePlugin.check"), + () => require("../schemas/plugins/WatchIgnorePlugin.json"), + { + name: "Watch Ignore Plugin", + baseDataPath: "options" + } +); + +const IGNORE_TIME_ENTRY = "ignore"; + +class IgnoringWatchFileSystem { + /** + * @param {WatchFileSystem} wfs original file system + * @param {WatchIgnorePluginOptions["paths"]} paths ignored paths + */ + constructor(wfs, paths) { + this.wfs = wfs; + this.paths = paths; + } + + /** @type {WatchMethod} */ + watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { + files = [...files]; + dirs = [...dirs]; + /** + * @param {string} path path to check + * @returns {boolean} true, if path is ignored + */ + const ignored = (path) => + this.paths.some((p) => + p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0 + ); + + const [ignoredFiles, notIgnoredFiles] = groupBy( + /** @type {Array} */ + (files), + ignored + ); + const [ignoredDirs, notIgnoredDirs] = groupBy( + /** @type {Array} */ + (dirs), + ignored + ); + + const watcher = this.wfs.watch( + notIgnoredFiles, + notIgnoredDirs, + missing, + startTime, + options, + (err, fileTimestamps, dirTimestamps, changedFiles, removedFiles) => { + if (err) return callback(err); + for (const path of ignoredFiles) { + /** @type {TimeInfoEntries} */ + (fileTimestamps).set(path, IGNORE_TIME_ENTRY); + } + + for (const path of ignoredDirs) { + /** @type {TimeInfoEntries} */ + (dirTimestamps).set(path, IGNORE_TIME_ENTRY); + } + + callback( + null, + fileTimestamps, + dirTimestamps, + changedFiles, + removedFiles + ); + }, + callbackUndelayed + ); + + return { + close: () => watcher.close(), + pause: () => watcher.pause(), + getContextTimeInfoEntries: () => { + const dirTimestamps = watcher.getContextTimeInfoEntries(); + for (const path of ignoredDirs) { + dirTimestamps.set(path, IGNORE_TIME_ENTRY); + } + return dirTimestamps; + }, + getFileTimeInfoEntries: () => { + const fileTimestamps = watcher.getFileTimeInfoEntries(); + for (const path of ignoredFiles) { + fileTimestamps.set(path, IGNORE_TIME_ENTRY); + } + return fileTimestamps; + }, + getInfo: + watcher.getInfo && + (() => { + const info = + /** @type {NonNullable} */ + (watcher.getInfo)(); + const { fileTimeInfoEntries, contextTimeInfoEntries } = info; + for (const path of ignoredFiles) { + fileTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + } + for (const path of ignoredDirs) { + contextTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + } + return info; + }) + }; + } +} + +const PLUGIN_NAME = "WatchIgnorePlugin"; + +class WatchIgnorePlugin { + /** + * @param {WatchIgnorePluginOptions} options options + */ + constructor(options) { + validate(options); + this.paths = options.paths; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.afterEnvironment.tap(PLUGIN_NAME, () => { + compiler.watchFileSystem = new IgnoringWatchFileSystem( + /** @type {WatchFileSystem} */ + (compiler.watchFileSystem), + this.paths + ); + }); + } +} + +module.exports = WatchIgnorePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Watching.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Watching.js new file mode 100644 index 0000000000000000000000000000000000000000..2ecbc199231a14d7c57aaa5cc77f44b6b2c94c27 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/Watching.js @@ -0,0 +1,526 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Stats = require("./Stats"); + +/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./util/fs").TimeInfoEntries} TimeInfoEntries */ +/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ +/** @typedef {import("./util/fs").Watcher} Watcher */ + +/** + * @template T + * @callback Callback + * @param {Error | null} err + * @param {T=} result + */ + +class Watching { + /** + * @param {Compiler} compiler the compiler + * @param {WatchOptions} watchOptions options + * @param {Callback} handler completion handler + */ + constructor(compiler, watchOptions, handler) { + this.startTime = null; + this.invalid = false; + this.handler = handler; + /** @type {Callback[]} */ + this.callbacks = []; + /** @type {Callback[] | undefined} */ + this._closeCallbacks = undefined; + this.closed = false; + this.suspended = false; + this.blocked = false; + this._isBlocked = () => false; + this._onChange = () => {}; + this._onInvalid = () => {}; + if (typeof watchOptions === "number") { + /** @type {WatchOptions} */ + this.watchOptions = { + aggregateTimeout: watchOptions + }; + } else if (watchOptions && typeof watchOptions === "object") { + /** @type {WatchOptions} */ + this.watchOptions = { ...watchOptions }; + } else { + /** @type {WatchOptions} */ + this.watchOptions = {}; + } + if (typeof this.watchOptions.aggregateTimeout !== "number") { + this.watchOptions.aggregateTimeout = 20; + } + this.compiler = compiler; + this.running = false; + this._initial = true; + this._invalidReported = true; + this._needRecords = true; + this.watcher = undefined; + this.pausedWatcher = undefined; + /** @type {Set | undefined} */ + this._collectedChangedFiles = undefined; + /** @type {Set | undefined} */ + this._collectedRemovedFiles = undefined; + this._done = this._done.bind(this); + process.nextTick(() => { + if (this._initial) this._invalidate(); + }); + } + + /** + * @param {ReadonlySet | undefined | null} changedFiles changed files + * @param {ReadonlySet | undefined | null} removedFiles removed files + */ + _mergeWithCollected(changedFiles, removedFiles) { + if (!changedFiles) return; + if (!this._collectedChangedFiles) { + this._collectedChangedFiles = new Set(changedFiles); + this._collectedRemovedFiles = new Set(removedFiles); + } else { + for (const file of changedFiles) { + this._collectedChangedFiles.add(file); + /** @type {Set} */ + (this._collectedRemovedFiles).delete(file); + } + for (const file of /** @type {ReadonlySet} */ (removedFiles)) { + this._collectedChangedFiles.delete(file); + /** @type {Set} */ + (this._collectedRemovedFiles).add(file); + } + } + } + + /** + * @param {TimeInfoEntries=} fileTimeInfoEntries info for files + * @param {TimeInfoEntries=} contextTimeInfoEntries info for directories + * @param {ReadonlySet=} changedFiles changed files + * @param {ReadonlySet=} removedFiles removed files + * @returns {void} + */ + _go(fileTimeInfoEntries, contextTimeInfoEntries, changedFiles, removedFiles) { + this._initial = false; + if (this.startTime === null) this.startTime = Date.now(); + this.running = true; + if (this.watcher) { + this.pausedWatcher = this.watcher; + this.lastWatcherStartTime = Date.now(); + this.watcher.pause(); + this.watcher = null; + } else if (!this.lastWatcherStartTime) { + this.lastWatcherStartTime = Date.now(); + } + this.compiler.fsStartTime = Date.now(); + if ( + changedFiles && + removedFiles && + fileTimeInfoEntries && + contextTimeInfoEntries + ) { + this._mergeWithCollected(changedFiles, removedFiles); + this.compiler.fileTimestamps = fileTimeInfoEntries; + this.compiler.contextTimestamps = contextTimeInfoEntries; + } else if (this.pausedWatcher) { + if (this.pausedWatcher.getInfo) { + const { + changes, + removals, + fileTimeInfoEntries, + contextTimeInfoEntries + } = this.pausedWatcher.getInfo(); + this._mergeWithCollected(changes, removals); + this.compiler.fileTimestamps = fileTimeInfoEntries; + this.compiler.contextTimestamps = contextTimeInfoEntries; + } else { + this._mergeWithCollected( + this.pausedWatcher.getAggregatedChanges && + this.pausedWatcher.getAggregatedChanges(), + this.pausedWatcher.getAggregatedRemovals && + this.pausedWatcher.getAggregatedRemovals() + ); + this.compiler.fileTimestamps = + this.pausedWatcher.getFileTimeInfoEntries(); + this.compiler.contextTimestamps = + this.pausedWatcher.getContextTimeInfoEntries(); + } + } + this.compiler.modifiedFiles = this._collectedChangedFiles; + this._collectedChangedFiles = undefined; + this.compiler.removedFiles = this._collectedRemovedFiles; + this._collectedRemovedFiles = undefined; + + const run = () => { + if (this.compiler.idle) { + return this.compiler.cache.endIdle((err) => { + if (err) return this._done(err); + this.compiler.idle = false; + run(); + }); + } + if (this._needRecords) { + return this.compiler.readRecords((err) => { + if (err) return this._done(err); + + this._needRecords = false; + run(); + }); + } + this.invalid = false; + this._invalidReported = false; + this.compiler.hooks.watchRun.callAsync(this.compiler, (err) => { + if (err) return this._done(err); + /** + * @param {Error | null} err error + * @param {Compilation=} _compilation compilation + * @returns {void} + */ + const onCompiled = (err, _compilation) => { + if (err) return this._done(err, _compilation); + + const compilation = /** @type {Compilation} */ (_compilation); + + if (this.compiler.hooks.shouldEmit.call(compilation) === false) { + return this._done(null, compilation); + } + + process.nextTick(() => { + const logger = compilation.getLogger("webpack.Compiler"); + logger.time("emitAssets"); + this.compiler.emitAssets(compilation, (err) => { + logger.timeEnd("emitAssets"); + if (err) return this._done(err, compilation); + if (this.invalid) return this._done(null, compilation); + + logger.time("emitRecords"); + this.compiler.emitRecords((err) => { + logger.timeEnd("emitRecords"); + if (err) return this._done(err, compilation); + + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; + + compilation.startTime = /** @type {number} */ ( + this.startTime + ); + compilation.endTime = Date.now(); + logger.time("done hook"); + const stats = new Stats(compilation); + this.compiler.hooks.done.callAsync(stats, (err) => { + logger.timeEnd("done hook"); + if (err) return this._done(err, compilation); + + this.compiler.hooks.additionalPass.callAsync((err) => { + if (err) return this._done(err, compilation); + this.compiler.compile(onCompiled); + }); + }); + return; + } + return this._done(null, compilation); + }); + }); + }); + }; + this.compiler.compile(onCompiled); + }); + }; + + run(); + } + + /** + * @param {Compilation} compilation the compilation + * @returns {Stats} the compilation stats + */ + _getStats(compilation) { + const stats = new Stats(compilation); + return stats; + } + + /** + * @param {(Error | null)=} err an optional error + * @param {Compilation=} compilation the compilation + * @returns {void} + */ + _done(err, compilation) { + this.running = false; + + const logger = + /** @type {Logger} */ + (compilation && compilation.getLogger("webpack.Watching")); + + /** @type {Stats | undefined} */ + let stats; + + /** + * @param {Error} err error + * @param {Callback[]=} cbs callbacks + */ + const handleError = (err, cbs) => { + this.compiler.hooks.failed.call(err); + this.compiler.cache.beginIdle(); + this.compiler.idle = true; + this.handler(err, /** @type {Stats} */ (stats)); + if (!cbs) { + cbs = this.callbacks; + this.callbacks = []; + } + for (const cb of cbs) cb(err); + }; + + if ( + this.invalid && + !this.suspended && + !this.blocked && + !(this._isBlocked() && (this.blocked = true)) + ) { + if (compilation) { + logger.time("storeBuildDependencies"); + this.compiler.cache.storeBuildDependencies( + compilation.buildDependencies, + (err) => { + logger.timeEnd("storeBuildDependencies"); + if (err) return handleError(err); + this._go(); + } + ); + } else { + this._go(); + } + return; + } + + if (compilation) { + compilation.startTime = /** @type {number} */ (this.startTime); + compilation.endTime = Date.now(); + stats = new Stats(compilation); + } + this.startTime = null; + if (err) return handleError(err); + + const cbs = this.callbacks; + this.callbacks = []; + logger.time("done hook"); + this.compiler.hooks.done.callAsync(/** @type {Stats} */ (stats), (err) => { + logger.timeEnd("done hook"); + if (err) return handleError(err, cbs); + this.handler(null, stats); + logger.time("storeBuildDependencies"); + this.compiler.cache.storeBuildDependencies( + /** @type {Compilation} */ + (compilation).buildDependencies, + (err) => { + logger.timeEnd("storeBuildDependencies"); + if (err) return handleError(err, cbs); + logger.time("beginIdle"); + this.compiler.cache.beginIdle(); + this.compiler.idle = true; + logger.timeEnd("beginIdle"); + process.nextTick(() => { + if (!this.closed) { + this.watch( + /** @type {Compilation} */ + (compilation).fileDependencies, + /** @type {Compilation} */ + (compilation).contextDependencies, + /** @type {Compilation} */ + (compilation).missingDependencies + ); + } + }); + for (const cb of cbs) cb(null); + this.compiler.hooks.afterDone.call(/** @type {Stats} */ (stats)); + } + ); + }); + } + + /** + * @param {Iterable} files watched files + * @param {Iterable} dirs watched directories + * @param {Iterable} missing watched existence entries + * @returns {void} + */ + watch(files, dirs, missing) { + this.pausedWatcher = null; + this.watcher = + /** @type {WatchFileSystem} */ + (this.compiler.watchFileSystem).watch( + files, + dirs, + missing, + /** @type {number} */ (this.lastWatcherStartTime), + this.watchOptions, + ( + err, + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ) => { + if (err) { + this.compiler.modifiedFiles = undefined; + this.compiler.removedFiles = undefined; + this.compiler.fileTimestamps = undefined; + this.compiler.contextTimestamps = undefined; + this.compiler.fsStartTime = undefined; + return this.handler(err); + } + this._invalidate( + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ); + this._onChange(); + }, + (fileName, changeTime) => { + if (!this._invalidReported) { + this._invalidReported = true; + this.compiler.hooks.invalid.call(fileName, changeTime); + } + this._onInvalid(); + } + ); + } + + /** + * @param {Callback=} callback signals when the build has completed again + * @returns {void} + */ + invalidate(callback) { + if (callback) { + this.callbacks.push(callback); + } + if (!this._invalidReported) { + this._invalidReported = true; + this.compiler.hooks.invalid.call(null, Date.now()); + } + this._onChange(); + this._invalidate(); + } + + /** + * @param {TimeInfoEntries=} fileTimeInfoEntries info for files + * @param {TimeInfoEntries=} contextTimeInfoEntries info for directories + * @param {ReadonlySet=} changedFiles changed files + * @param {ReadonlySet=} removedFiles removed files + * @returns {void} + */ + _invalidate( + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ) { + if (this.suspended || (this._isBlocked() && (this.blocked = true))) { + this._mergeWithCollected(changedFiles, removedFiles); + return; + } + + if (this.running) { + this._mergeWithCollected(changedFiles, removedFiles); + this.invalid = true; + } else { + this._go( + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ); + } + } + + suspend() { + this.suspended = true; + } + + resume() { + if (this.suspended) { + this.suspended = false; + this._invalidate(); + } + } + + /** + * @param {Callback} callback signals when the watcher is closed + * @returns {void} + */ + close(callback) { + if (this._closeCallbacks) { + if (callback) { + this._closeCallbacks.push(callback); + } + return; + } + /** + * @param {WebpackError | null} err error if any + * @param {Compilation=} compilation compilation if any + */ + const finalCallback = (err, compilation) => { + this.running = false; + this.compiler.running = false; + this.compiler.watching = undefined; + this.compiler.watchMode = false; + this.compiler.modifiedFiles = undefined; + this.compiler.removedFiles = undefined; + this.compiler.fileTimestamps = undefined; + this.compiler.contextTimestamps = undefined; + this.compiler.fsStartTime = undefined; + /** + * @param {WebpackError | null} err error if any + */ + const shutdown = (err) => { + this.compiler.hooks.watchClose.call(); + const closeCallbacks = + /** @type {Callback[]} */ + (this._closeCallbacks); + this._closeCallbacks = undefined; + for (const cb of closeCallbacks) cb(err); + }; + if (compilation) { + const logger = compilation.getLogger("webpack.Watching"); + logger.time("storeBuildDependencies"); + this.compiler.cache.storeBuildDependencies( + compilation.buildDependencies, + (err2) => { + logger.timeEnd("storeBuildDependencies"); + shutdown(err || err2); + } + ); + } else { + shutdown(err); + } + }; + + this.closed = true; + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + if (this.pausedWatcher) { + this.pausedWatcher.close(); + this.pausedWatcher = null; + } + this._closeCallbacks = []; + if (callback) { + this._closeCallbacks.push(callback); + } + if (this.running) { + this.invalid = true; + this._done = finalCallback; + } else { + finalCallback(null); + } + } +} + +module.exports = Watching; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackError.js new file mode 100644 index 0000000000000000000000000000000000000000..02a7e4aba24722f04f5b6fe86143ea6f4b3c1644 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackError.js @@ -0,0 +1,78 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Jarid Margolin @jaridmargolin +*/ + +"use strict"; + +const inspect = require("util").inspect.custom; +const makeSerializable = require("./util/makeSerializable"); + +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class WebpackError extends Error { + /** + * Creates an instance of WebpackError. + * @param {string=} message error message + * @param {{ cause?: unknown }} options error options + */ + constructor(message, options = {}) { + // @ts-expect-error ES2018 doesn't `Error.cause`, but it can be used by developers + super(message, options); + + /** @type {string=} */ + this.details = undefined; + /** @type {(Module | null)=} */ + this.module = undefined; + /** @type {DependencyLocation=} */ + this.loc = undefined; + /** @type {boolean=} */ + this.hideStack = undefined; + /** @type {Chunk=} */ + this.chunk = undefined; + /** @type {string=} */ + this.file = undefined; + } + + [inspect]() { + return ( + this.stack + + (this.details ? `\n${this.details}` : "") + + (this.cause ? `\n${this.cause}` : "") + ); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize({ write }) { + write(this.name); + write(this.message); + write(this.stack); + write(this.cause); + write(this.details); + write(this.loc); + write(this.hideStack); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize({ read }) { + this.name = read(); + this.message = read(); + this.stack = read(); + this.cause = read(); + this.details = read(); + this.loc = read(); + this.hideStack = read(); + } +} + +makeSerializable(WebpackError, "webpack/lib/WebpackError"); + +module.exports = WebpackError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackIsIncludedPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackIsIncludedPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..3625901147d5aeb5fdd6ca70e1f76b83d1be3e64 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackIsIncludedPlugin.js @@ -0,0 +1,95 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const IgnoreErrorModuleFactory = require("./IgnoreErrorModuleFactory"); +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("./ModuleTypeConstants"); +const WebpackIsIncludedDependency = require("./dependencies/WebpackIsIncludedDependency"); +const { + toConstantDependency +} = require("./javascript/JavascriptParserHelpers"); + +/** @typedef {import("enhanced-resolve").Resolver} Resolver */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "WebpackIsIncludedPlugin"; + +class WebpackIsIncludedPlugin { + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WebpackIsIncludedDependency, + new IgnoreErrorModuleFactory(normalModuleFactory) + ); + compilation.dependencyTemplates.set( + WebpackIsIncludedDependency, + new WebpackIsIncludedDependency.Template() + ); + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const handler = (parser) => { + parser.hooks.call + .for("__webpack_is_included__") + .tap(PLUGIN_NAME, (expr) => { + if ( + expr.type !== "CallExpression" || + expr.arguments.length !== 1 || + expr.arguments[0].type === "SpreadElement" + ) { + return; + } + + const request = parser.evaluateExpression(expr.arguments[0]); + + if (!request.isString()) return; + + const dep = new WebpackIsIncludedDependency( + /** @type {string} */ (request.string), + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + return true; + }); + parser.hooks.typeof + .for("__webpack_is_included__") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("function")) + ); + }; + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = WebpackIsIncludedPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackOptionsApply.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackOptionsApply.js new file mode 100644 index 0000000000000000000000000000000000000000..906451d35ca4432e3fe385f9950785c0ff87f31f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackOptionsApply.js @@ -0,0 +1,892 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const APIPlugin = require("./APIPlugin"); + +const CompatibilityPlugin = require("./CompatibilityPlugin"); + +const ConstPlugin = require("./ConstPlugin"); + +const EntryOptionPlugin = require("./EntryOptionPlugin"); + +const ExportsInfoApiPlugin = require("./ExportsInfoApiPlugin"); +const FlagDependencyExportsPlugin = require("./FlagDependencyExportsPlugin"); + +const JavascriptMetaInfoPlugin = require("./JavascriptMetaInfoPlugin"); + +const OptionsApply = require("./OptionsApply"); + +const RecordIdsPlugin = require("./RecordIdsPlugin"); + +const RuntimePlugin = require("./RuntimePlugin"); + +const TemplatedPathPlugin = require("./TemplatedPathPlugin"); + +const UseStrictPlugin = require("./UseStrictPlugin"); + +const WarnCaseSensitiveModulesPlugin = require("./WarnCaseSensitiveModulesPlugin"); + +const WebpackIsIncludedPlugin = require("./WebpackIsIncludedPlugin"); + +const AssetModulesPlugin = require("./asset/AssetModulesPlugin"); + +const InferAsyncModulesPlugin = require("./async-modules/InferAsyncModulesPlugin"); + +const ResolverCachePlugin = require("./cache/ResolverCachePlugin"); + +const CommonJsPlugin = require("./dependencies/CommonJsPlugin"); + +const HarmonyModulesPlugin = require("./dependencies/HarmonyModulesPlugin"); + +const ImportMetaContextPlugin = require("./dependencies/ImportMetaContextPlugin"); +const ImportMetaPlugin = require("./dependencies/ImportMetaPlugin"); + +const ImportPlugin = require("./dependencies/ImportPlugin"); +const LoaderPlugin = require("./dependencies/LoaderPlugin"); + +const RequireContextPlugin = require("./dependencies/RequireContextPlugin"); +const RequireEnsurePlugin = require("./dependencies/RequireEnsurePlugin"); +const RequireIncludePlugin = require("./dependencies/RequireIncludePlugin"); + +const SystemPlugin = require("./dependencies/SystemPlugin"); + +const URLPlugin = require("./dependencies/URLPlugin"); + +const WorkerPlugin = require("./dependencies/WorkerPlugin"); + +const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); + +const JsonModulesPlugin = require("./json/JsonModulesPlugin"); + +const ChunkPrefetchPreloadPlugin = require("./prefetch/ChunkPrefetchPreloadPlugin"); + +const DataUriPlugin = require("./schemes/DataUriPlugin"); +const FileUriPlugin = require("./schemes/FileUriPlugin"); + +const DefaultStatsFactoryPlugin = require("./stats/DefaultStatsFactoryPlugin"); +const DefaultStatsPresetPlugin = require("./stats/DefaultStatsPresetPlugin"); +const DefaultStatsPrinterPlugin = require("./stats/DefaultStatsPrinterPlugin"); + +const { cleverMerge } = require("./util/cleverMerge"); + +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */ + +const CLASS_NAME = "WebpackOptionsApply"; + +class WebpackOptionsApply extends OptionsApply { + constructor() { + super(); + } + + /** + * @param {WebpackOptions} options options object + * @param {Compiler} compiler compiler object + * @returns {WebpackOptions} options object + */ + process(options, compiler) { + compiler.outputPath = /** @type {string} */ (options.output.path); + compiler.recordsInputPath = options.recordsInputPath || null; + compiler.recordsOutputPath = options.recordsOutputPath || null; + compiler.name = options.name; + + if (options.externals) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = require("./ExternalsPlugin"); + + new ExternalsPlugin(options.externalsType, options.externals).apply( + compiler + ); + } + + if (options.externalsPresets.node) { + const NodeTargetPlugin = require("./node/NodeTargetPlugin"); + + new NodeTargetPlugin().apply(compiler); + } + if (options.externalsPresets.electronMain) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin"); + + new ElectronTargetPlugin("main").apply(compiler); + } + if (options.externalsPresets.electronPreload) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin"); + + new ElectronTargetPlugin("preload").apply(compiler); + } + if (options.externalsPresets.electronRenderer) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin"); + + new ElectronTargetPlugin("renderer").apply(compiler); + } + if ( + options.externalsPresets.electron && + !options.externalsPresets.electronMain && + !options.externalsPresets.electronPreload && + !options.externalsPresets.electronRenderer + ) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin"); + + new ElectronTargetPlugin().apply(compiler); + } + if (options.externalsPresets.nwjs) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = require("./ExternalsPlugin"); + + new ExternalsPlugin("node-commonjs", "nw.gui").apply(compiler); + } + if (options.externalsPresets.webAsync) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = require("./ExternalsPlugin"); + + new ExternalsPlugin("import", ({ request, dependencyType }, callback) => { + if (dependencyType === "url") { + if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) { + return callback(null, `asset ${request}`); + } + } else if (options.experiments.css && dependencyType === "css-import") { + if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) { + return callback(null, `css-import ${request}`); + } + } else if ( + options.experiments.css && + /^(\/\/|https?:\/\/|std:)/.test(/** @type {string} */ (request)) + ) { + if (/^\.css(\?|$)/.test(/** @type {string} */ (request))) { + return callback(null, `css-import ${request}`); + } + return callback(null, `import ${request}`); + } + callback(); + }).apply(compiler); + } else if (options.externalsPresets.web) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = require("./ExternalsPlugin"); + + new ExternalsPlugin("module", ({ request, dependencyType }, callback) => { + if (dependencyType === "url") { + if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) { + return callback(null, `asset ${request}`); + } + } else if (options.experiments.css && dependencyType === "css-import") { + if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) { + return callback(null, `css-import ${request}`); + } + } else if ( + /^(\/\/|https?:\/\/|std:)/.test(/** @type {string} */ (request)) + ) { + if ( + options.experiments.css && + /^\.css((\?)|$)/.test(/** @type {string} */ (request)) + ) { + return callback(null, `css-import ${request}`); + } + return callback(null, `module ${request}`); + } + callback(); + }).apply(compiler); + } else if (options.externalsPresets.node && options.experiments.css) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = require("./ExternalsPlugin"); + + new ExternalsPlugin("module", ({ request, dependencyType }, callback) => { + if (dependencyType === "url") { + if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) { + return callback(null, `asset ${request}`); + } + } else if (dependencyType === "css-import") { + if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) { + return callback(null, `css-import ${request}`); + } + } else if ( + /^(\/\/|https?:\/\/|std:)/.test(/** @type {string} */ (request)) + ) { + if (/^\.css(\?|$)/.test(/** @type {string} */ (request))) { + return callback(null, `css-import ${request}`); + } + return callback(null, `module ${request}`); + } + callback(); + }).apply(compiler); + } + + new ChunkPrefetchPreloadPlugin().apply(compiler); + + if (typeof options.output.chunkFormat === "string") { + switch (options.output.chunkFormat) { + case "array-push": { + const ArrayPushCallbackChunkFormatPlugin = require("./javascript/ArrayPushCallbackChunkFormatPlugin"); + + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + break; + } + case "commonjs": { + const CommonJsChunkFormatPlugin = require("./javascript/CommonJsChunkFormatPlugin"); + + new CommonJsChunkFormatPlugin().apply(compiler); + break; + } + case "module": { + const ModuleChunkFormatPlugin = require("./esm/ModuleChunkFormatPlugin"); + + new ModuleChunkFormatPlugin().apply(compiler); + break; + } + default: + throw new Error( + `Unsupported chunk format '${options.output.chunkFormat}'.` + ); + } + } + + const enabledChunkLoadingTypes = + /** @type {NonNullable} */ + (options.output.enabledChunkLoadingTypes); + + if (enabledChunkLoadingTypes.length > 0) { + for (const type of enabledChunkLoadingTypes) { + const EnableChunkLoadingPlugin = require("./javascript/EnableChunkLoadingPlugin"); + + new EnableChunkLoadingPlugin(type).apply(compiler); + } + } + + const enabledWasmLoadingTypes = + /** @type {NonNullable} */ + (options.output.enabledWasmLoadingTypes); + + if (enabledWasmLoadingTypes.length > 0) { + for (const type of enabledWasmLoadingTypes) { + const EnableWasmLoadingPlugin = require("./wasm/EnableWasmLoadingPlugin"); + + new EnableWasmLoadingPlugin(type).apply(compiler); + } + } + + const enabledLibraryTypes = + /** @type {NonNullable} */ + (options.output.enabledLibraryTypes); + + if (enabledLibraryTypes.length > 0) { + let once = true; + for (const type of enabledLibraryTypes) { + const EnableLibraryPlugin = require("./library/EnableLibraryPlugin"); + + new EnableLibraryPlugin(type, { + // eslint-disable-next-line no-loop-func + additionalApply: () => { + if (!once) return; + once = false; + // We rely on `exportInfo` to generate the `export statement` in certain library bundles. + // Therefore, we ignore the disabling of `optimization.providedExport` and continue to apply `FlagDependencyExportsPlugin`. + if ( + ["module", "commonjs-static", "modern-module"].includes(type) && + !options.optimization.providedExports + ) { + new FlagDependencyExportsPlugin().apply(compiler); + } + } + }).apply(compiler); + } + } + + if (options.output.pathinfo) { + const ModuleInfoHeaderPlugin = require("./ModuleInfoHeaderPlugin"); + + new ModuleInfoHeaderPlugin(options.output.pathinfo !== true).apply( + compiler + ); + } + + if (options.output.clean) { + const CleanPlugin = require("./CleanPlugin"); + + new CleanPlugin( + options.output.clean === true ? {} : options.output.clean + ).apply(compiler); + } + + if (options.devtool) { + if (options.devtool.includes("source-map")) { + const hidden = options.devtool.includes("hidden"); + const inline = options.devtool.includes("inline"); + const evalWrapped = options.devtool.includes("eval"); + const cheap = options.devtool.includes("cheap"); + const moduleMaps = options.devtool.includes("module"); + const noSources = options.devtool.includes("nosources"); + const debugIds = options.devtool.includes("debugids"); + const Plugin = evalWrapped + ? require("./EvalSourceMapDevToolPlugin") + : require("./SourceMapDevToolPlugin"); + new Plugin({ + filename: inline ? null : options.output.sourceMapFilename, + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + fallbackModuleFilenameTemplate: + options.output.devtoolFallbackModuleFilenameTemplate, + append: hidden ? false : undefined, + module: moduleMaps ? true : !cheap, + columns: !cheap, + noSources, + namespace: options.output.devtoolNamespace, + debugIds + }).apply(compiler); + } else if (options.devtool.includes("eval")) { + const EvalDevToolModulePlugin = require("./EvalDevToolModulePlugin"); + + new EvalDevToolModulePlugin({ + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } + } + + new JavascriptModulesPlugin().apply(compiler); + new JsonModulesPlugin().apply(compiler); + new AssetModulesPlugin().apply(compiler); + + if (!options.experiments.outputModule) { + if (options.output.module) { + throw new Error( + "'output.module: true' is only allowed when 'experiments.outputModule' is enabled" + ); + } + if (options.output.enabledLibraryTypes.includes("module")) { + throw new Error( + "library type \"module\" is only allowed when 'experiments.outputModule' is enabled" + ); + } + if (options.output.enabledLibraryTypes.includes("modern-module")) { + throw new Error( + "library type \"modern-module\" is only allowed when 'experiments.outputModule' is enabled" + ); + } + if ( + options.externalsType === "module" || + options.externalsType === "module-import" + ) { + throw new Error( + "'externalsType: \"module\"' is only allowed when 'experiments.outputModule' is enabled" + ); + } + } + + if (options.experiments.syncWebAssembly) { + const WebAssemblyModulesPlugin = require("./wasm-sync/WebAssemblyModulesPlugin"); + + new WebAssemblyModulesPlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + } + + if (options.experiments.asyncWebAssembly) { + const AsyncWebAssemblyModulesPlugin = require("./wasm-async/AsyncWebAssemblyModulesPlugin"); + + new AsyncWebAssemblyModulesPlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + } + + if (options.experiments.css) { + const CssModulesPlugin = require("./css/CssModulesPlugin"); + + new CssModulesPlugin().apply(compiler); + } + + if (options.experiments.lazyCompilation) { + const LazyCompilationPlugin = require("./hmr/LazyCompilationPlugin"); + + const lazyOptions = + typeof options.experiments.lazyCompilation === "object" + ? options.experiments.lazyCompilation + : {}; + new LazyCompilationPlugin({ + backend: + typeof lazyOptions.backend === "function" + ? lazyOptions.backend + : require("./hmr/lazyCompilationBackend")({ + ...lazyOptions.backend, + client: + (lazyOptions.backend && lazyOptions.backend.client) || + require.resolve( + `../hot/lazy-compilation-${ + options.externalsPresets.node ? "node" : "web" + }.js` + ) + }), + entries: !lazyOptions || lazyOptions.entries !== false, + imports: !lazyOptions || lazyOptions.imports !== false, + test: (lazyOptions && lazyOptions.test) || undefined + }).apply(compiler); + } + + if (options.experiments.buildHttp) { + const HttpUriPlugin = require("./schemes/HttpUriPlugin"); + + const httpOptions = options.experiments.buildHttp; + new HttpUriPlugin(httpOptions).apply(compiler); + } + + if (options.experiments.deferImport) { + const JavascriptParser = require("./javascript/JavascriptParser"); + const importPhases = require("acorn-import-phases"); + + JavascriptParser.extend(importPhases({ source: false })); + } + + new EntryOptionPlugin().apply(compiler); + compiler.hooks.entryOption.call( + /** @type {string} */ + (options.context), + options.entry + ); + + new RuntimePlugin().apply(compiler); + + new InferAsyncModulesPlugin().apply(compiler); + + new DataUriPlugin().apply(compiler); + new FileUriPlugin().apply(compiler); + + new CompatibilityPlugin().apply(compiler); + new HarmonyModulesPlugin({ + topLevelAwait: options.experiments.topLevelAwait, + deferImport: options.experiments.deferImport + }).apply(compiler); + if (options.amd !== false) { + const AMDPlugin = require("./dependencies/AMDPlugin"); + const RequireJsStuffPlugin = require("./RequireJsStuffPlugin"); + + new AMDPlugin(options.amd || {}).apply(compiler); + new RequireJsStuffPlugin().apply(compiler); + } + new CommonJsPlugin().apply(compiler); + new LoaderPlugin().apply(compiler); + if (options.node !== false) { + const NodeStuffPlugin = require("./NodeStuffPlugin"); + + new NodeStuffPlugin(options.node).apply(compiler); + } + new APIPlugin({ + module: options.output.module + }).apply(compiler); + new ExportsInfoApiPlugin().apply(compiler); + new WebpackIsIncludedPlugin().apply(compiler); + new ConstPlugin().apply(compiler); + new UseStrictPlugin().apply(compiler); + new RequireIncludePlugin().apply(compiler); + new RequireEnsurePlugin().apply(compiler); + new RequireContextPlugin().apply(compiler); + new ImportPlugin().apply(compiler); + new ImportMetaContextPlugin().apply(compiler); + new SystemPlugin().apply(compiler); + new ImportMetaPlugin().apply(compiler); + new URLPlugin().apply(compiler); + new WorkerPlugin( + options.output.workerChunkLoading, + options.output.workerWasmLoading, + options.output.module, + options.output.workerPublicPath + ).apply(compiler); + + new DefaultStatsFactoryPlugin().apply(compiler); + new DefaultStatsPresetPlugin().apply(compiler); + new DefaultStatsPrinterPlugin().apply(compiler); + + new JavascriptMetaInfoPlugin().apply(compiler); + + if (typeof options.mode !== "string") { + const WarnNoModeSetPlugin = require("./WarnNoModeSetPlugin"); + + new WarnNoModeSetPlugin().apply(compiler); + } + + const EnsureChunkConditionsPlugin = require("./optimize/EnsureChunkConditionsPlugin"); + + new EnsureChunkConditionsPlugin().apply(compiler); + if (options.optimization.removeAvailableModules) { + const RemoveParentModulesPlugin = require("./optimize/RemoveParentModulesPlugin"); + + new RemoveParentModulesPlugin().apply(compiler); + } + if (options.optimization.removeEmptyChunks) { + const RemoveEmptyChunksPlugin = require("./optimize/RemoveEmptyChunksPlugin"); + + new RemoveEmptyChunksPlugin().apply(compiler); + } + if (options.optimization.mergeDuplicateChunks) { + const MergeDuplicateChunksPlugin = require("./optimize/MergeDuplicateChunksPlugin"); + + new MergeDuplicateChunksPlugin().apply(compiler); + } + if (options.optimization.flagIncludedChunks) { + const FlagIncludedChunksPlugin = require("./optimize/FlagIncludedChunksPlugin"); + + new FlagIncludedChunksPlugin().apply(compiler); + } + if (options.optimization.sideEffects) { + const SideEffectsFlagPlugin = require("./optimize/SideEffectsFlagPlugin"); + + new SideEffectsFlagPlugin( + options.optimization.sideEffects === true + ).apply(compiler); + } + if (options.optimization.providedExports) { + new FlagDependencyExportsPlugin().apply(compiler); + } + if (options.optimization.usedExports) { + const FlagDependencyUsagePlugin = require("./FlagDependencyUsagePlugin"); + + new FlagDependencyUsagePlugin( + options.optimization.usedExports === "global" + ).apply(compiler); + } + if (options.optimization.innerGraph) { + const InnerGraphPlugin = require("./optimize/InnerGraphPlugin"); + + new InnerGraphPlugin().apply(compiler); + } + if (options.optimization.mangleExports) { + const MangleExportsPlugin = require("./optimize/MangleExportsPlugin"); + + new MangleExportsPlugin( + options.optimization.mangleExports !== "size" + ).apply(compiler); + } + if (options.optimization.concatenateModules) { + const ModuleConcatenationPlugin = require("./optimize/ModuleConcatenationPlugin"); + + new ModuleConcatenationPlugin().apply(compiler); + } + if (options.optimization.splitChunks) { + const SplitChunksPlugin = require("./optimize/SplitChunksPlugin"); + + new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); + } + if (options.optimization.runtimeChunk) { + const RuntimeChunkPlugin = require("./optimize/RuntimeChunkPlugin"); + + new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); + } + if (!options.optimization.emitOnErrors) { + const NoEmitOnErrorsPlugin = require("./NoEmitOnErrorsPlugin"); + + new NoEmitOnErrorsPlugin().apply(compiler); + } + if (options.optimization.realContentHash) { + const RealContentHashPlugin = require("./optimize/RealContentHashPlugin"); + + new RealContentHashPlugin({ + hashFunction: + /** @type {NonNullable} */ + (options.output.hashFunction), + hashDigest: + /** @type {NonNullable} */ + (options.output.hashDigest) + }).apply(compiler); + } + if (options.optimization.checkWasmTypes) { + const WasmFinalizeExportsPlugin = require("./wasm-sync/WasmFinalizeExportsPlugin"); + + new WasmFinalizeExportsPlugin().apply(compiler); + } + const moduleIds = options.optimization.moduleIds; + if (moduleIds) { + switch (moduleIds) { + case "natural": { + const NaturalModuleIdsPlugin = require("./ids/NaturalModuleIdsPlugin"); + + new NaturalModuleIdsPlugin().apply(compiler); + break; + } + case "named": { + const NamedModuleIdsPlugin = require("./ids/NamedModuleIdsPlugin"); + + new NamedModuleIdsPlugin().apply(compiler); + break; + } + case "hashed": { + const WarnDeprecatedOptionPlugin = require("./WarnDeprecatedOptionPlugin"); + const HashedModuleIdsPlugin = require("./ids/HashedModuleIdsPlugin"); + + new WarnDeprecatedOptionPlugin( + "optimization.moduleIds", + "hashed", + "deterministic" + ).apply(compiler); + new HashedModuleIdsPlugin({ + hashFunction: options.output.hashFunction + }).apply(compiler); + break; + } + case "deterministic": { + const DeterministicModuleIdsPlugin = require("./ids/DeterministicModuleIdsPlugin"); + + new DeterministicModuleIdsPlugin().apply(compiler); + break; + } + case "size": { + const OccurrenceModuleIdsPlugin = require("./ids/OccurrenceModuleIdsPlugin"); + + new OccurrenceModuleIdsPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + } + default: + throw new Error( + `webpack bug: moduleIds: ${moduleIds} is not implemented` + ); + } + } + const chunkIds = options.optimization.chunkIds; + if (chunkIds) { + switch (chunkIds) { + case "natural": { + const NaturalChunkIdsPlugin = require("./ids/NaturalChunkIdsPlugin"); + + new NaturalChunkIdsPlugin().apply(compiler); + break; + } + case "named": { + const NamedChunkIdsPlugin = require("./ids/NamedChunkIdsPlugin"); + + new NamedChunkIdsPlugin().apply(compiler); + break; + } + case "deterministic": { + const DeterministicChunkIdsPlugin = require("./ids/DeterministicChunkIdsPlugin"); + + new DeterministicChunkIdsPlugin().apply(compiler); + break; + } + case "size": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin"); + + new OccurrenceChunkIdsPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + } + case "total-size": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin"); + + new OccurrenceChunkIdsPlugin({ + prioritiseInitial: false + }).apply(compiler); + break; + } + default: + throw new Error( + `webpack bug: chunkIds: ${chunkIds} is not implemented` + ); + } + } + if (options.optimization.nodeEnv) { + const DefinePlugin = require("./DefinePlugin"); + + new DefinePlugin({ + "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) + }).apply(compiler); + } + if (options.optimization.minimize) { + for (const minimizer of /** @type {(WebpackPluginInstance | WebpackPluginFunction | "...")[]} */ ( + options.optimization.minimizer + )) { + if (typeof minimizer === "function") { + /** @type {WebpackPluginFunction} */ + (minimizer).call(compiler, compiler); + } else if (minimizer !== "..." && minimizer) { + minimizer.apply(compiler); + } + } + } + + if (options.performance) { + const SizeLimitsPlugin = require("./performance/SizeLimitsPlugin"); + + new SizeLimitsPlugin(options.performance).apply(compiler); + } + + new TemplatedPathPlugin().apply(compiler); + + new RecordIdsPlugin({ + portableIds: options.optimization.portableRecords + }).apply(compiler); + + new WarnCaseSensitiveModulesPlugin().apply(compiler); + + const AddManagedPathsPlugin = require("./cache/AddManagedPathsPlugin"); + + new AddManagedPathsPlugin( + /** @type {NonNullable} */ + (options.snapshot.managedPaths), + /** @type {NonNullable} */ + (options.snapshot.immutablePaths), + /** @type {NonNullable} */ + (options.snapshot.unmanagedPaths) + ).apply(compiler); + + if (options.cache && typeof options.cache === "object") { + const cacheOptions = options.cache; + switch (cacheOptions.type) { + case "memory": { + if (Number.isFinite(cacheOptions.maxGenerations)) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryWithGcCachePlugin = require("./cache/MemoryWithGcCachePlugin"); + + new MemoryWithGcCachePlugin({ + maxGenerations: + /** @type {number} */ + (cacheOptions.maxGenerations) + }).apply(compiler); + } else { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryCachePlugin = require("./cache/MemoryCachePlugin"); + + new MemoryCachePlugin().apply(compiler); + } + if (cacheOptions.cacheUnaffected) { + if (!options.experiments.cacheUnaffected) { + throw new Error( + "'cache.cacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" + ); + } + compiler.moduleMemCaches = new Map(); + } + break; + } + case "filesystem": { + const AddBuildDependenciesPlugin = require("./cache/AddBuildDependenciesPlugin"); + + for (const key in cacheOptions.buildDependencies) { + const list = cacheOptions.buildDependencies[key]; + new AddBuildDependenciesPlugin(list).apply(compiler); + } + if (!Number.isFinite(cacheOptions.maxMemoryGenerations)) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryCachePlugin = require("./cache/MemoryCachePlugin"); + + new MemoryCachePlugin().apply(compiler); + } else if (cacheOptions.maxMemoryGenerations !== 0) { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryWithGcCachePlugin = require("./cache/MemoryWithGcCachePlugin"); + + new MemoryWithGcCachePlugin({ + maxGenerations: + /** @type {number} */ + (cacheOptions.maxMemoryGenerations) + }).apply(compiler); + } + if (cacheOptions.memoryCacheUnaffected) { + if (!options.experiments.cacheUnaffected) { + throw new Error( + "'cache.memoryCacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" + ); + } + compiler.moduleMemCaches = new Map(); + } + switch (cacheOptions.store) { + case "pack": { + const IdleFileCachePlugin = require("./cache/IdleFileCachePlugin"); + const PackFileCacheStrategy = require("./cache/PackFileCacheStrategy"); + + new IdleFileCachePlugin( + new PackFileCacheStrategy({ + compiler, + fs: + /** @type {IntermediateFileSystem} */ + (compiler.intermediateFileSystem), + context: /** @type {string} */ (options.context), + cacheLocation: + /** @type {string} */ + (cacheOptions.cacheLocation), + version: /** @type {string} */ (cacheOptions.version), + logger: compiler.getInfrastructureLogger( + "webpack.cache.PackFileCacheStrategy" + ), + snapshot: options.snapshot, + maxAge: /** @type {number} */ (cacheOptions.maxAge), + profile: cacheOptions.profile, + allowCollectingMemory: cacheOptions.allowCollectingMemory, + compression: cacheOptions.compression, + readonly: cacheOptions.readonly + }), + /** @type {number} */ + (cacheOptions.idleTimeout), + /** @type {number} */ + (cacheOptions.idleTimeoutForInitialStore), + /** @type {number} */ + (cacheOptions.idleTimeoutAfterLargeChanges) + ).apply(compiler); + break; + } + default: + throw new Error("Unhandled value for cache.store"); + } + break; + } + default: + // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) + throw new Error(`Unknown cache type ${cacheOptions.type}`); + } + } + new ResolverCachePlugin().apply(compiler); + + if (options.ignoreWarnings && options.ignoreWarnings.length > 0) { + const IgnoreWarningsPlugin = require("./IgnoreWarningsPlugin"); + + new IgnoreWarningsPlugin(options.ignoreWarnings).apply(compiler); + } + + compiler.hooks.afterPlugins.call(compiler); + if (!compiler.inputFileSystem) { + throw new Error("No input filesystem provided"); + } + compiler.resolverFactory.hooks.resolveOptions + .for("normal") + .tap(CLASS_NAME, (resolveOptions) => { + resolveOptions = cleverMerge(options.resolve, resolveOptions); + resolveOptions.fileSystem = + /** @type {InputFileSystem} */ + (compiler.inputFileSystem); + return resolveOptions; + }); + compiler.resolverFactory.hooks.resolveOptions + .for("context") + .tap(CLASS_NAME, (resolveOptions) => { + resolveOptions = cleverMerge(options.resolve, resolveOptions); + resolveOptions.fileSystem = + /** @type {InputFileSystem} */ + (compiler.inputFileSystem); + resolveOptions.resolveToContext = true; + return resolveOptions; + }); + compiler.resolverFactory.hooks.resolveOptions + .for("loader") + .tap(CLASS_NAME, (resolveOptions) => { + resolveOptions = cleverMerge(options.resolveLoader, resolveOptions); + resolveOptions.fileSystem = + /** @type {InputFileSystem} */ + (compiler.inputFileSystem); + return resolveOptions; + }); + compiler.hooks.afterResolvers.call(compiler); + return options; + } +} + +module.exports = WebpackOptionsApply; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackOptionsDefaulter.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackOptionsDefaulter.js new file mode 100644 index 0000000000000000000000000000000000000000..12fbe698d9318b014e1842820dbdfe6e6b6ffc66 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/WebpackOptionsDefaulter.js @@ -0,0 +1,26 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { applyWebpackOptionsDefaults } = require("./config/defaults"); +const { getNormalizedWebpackOptions } = require("./config/normalization"); + +/** @typedef {import("./config/normalization").WebpackOptions} WebpackOptions */ +/** @typedef {import("./config/normalization").WebpackOptionsNormalized} WebpackOptionsNormalized */ + +class WebpackOptionsDefaulter { + /** + * @param {WebpackOptions} options webpack options + * @returns {WebpackOptionsNormalized} normalized webpack options + */ + process(options) { + const normalizedOptions = getNormalizedWebpackOptions(options); + applyWebpackOptionsDefaults(normalizedOptions); + return normalizedOptions; + } +} + +module.exports = WebpackOptionsDefaulter; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetGenerator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..f1e1c025045cf4bdead53d96d8d16ebb2454d0ba --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetGenerator.js @@ -0,0 +1,811 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + +"use strict"; + +const path = require("path"); +const mimeTypes = require("mime-types"); +const { RawSource } = require("webpack-sources"); +const ConcatenationScope = require("../ConcatenationScope"); +const Generator = require("../Generator"); +const { + ASSET_AND_CSS_URL_TYPES, + ASSET_AND_JS_AND_CSS_URL_TYPES, + ASSET_AND_JS_TYPES, + ASSET_TYPES, + CSS_URL_TYPES, + JS_AND_CSS_URL_TYPES, + JS_TYPES, + NO_TYPES +} = require("../ModuleSourceTypesConstants"); +const { ASSET_MODULE_TYPE } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const CssUrlDependency = require("../dependencies/CssUrlDependency"); +const createHash = require("../util/createHash"); +const { makePathsRelative } = require("../util/identifier"); +const nonNumericOnlyHash = require("../util/nonNumericOnlyHash"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorDataUrlOptions} AssetGeneratorDataUrlOptions */ +/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorOptions} AssetGeneratorOptions */ +/** @typedef {import("../../declarations/WebpackOptions").AssetModuleFilename} AssetModuleFilename */ +/** @typedef {import("../../declarations/WebpackOptions").AssetModuleOutputPath} AssetModuleOutputPath */ +/** @typedef {import("../../declarations/WebpackOptions").AssetResourceGeneratorOptions} AssetResourceGeneratorOptions */ +/** @typedef {import("../../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("../../declarations/WebpackOptions").RawPublicPath} RawPublicPath */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compilation").InterpolatedPathAndAssetInfo} InterpolatedPathAndAssetInfo */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @template T + * @template U + * @param {null | string | Array | Set | undefined} a a + * @param {null | string | Array | Set | undefined} b b + * @returns {Array & Array} array + */ +const mergeMaybeArrays = (a, b) => { + const set = new Set(); + if (Array.isArray(a)) for (const item of a) set.add(item); + else set.add(a); + if (Array.isArray(b)) for (const item of b) set.add(item); + else set.add(b); + return [...set]; +}; + +/** + * @param {AssetInfo} a a + * @param {AssetInfo} b b + * @returns {AssetInfo} object + */ +const mergeAssetInfo = (a, b) => { + /** @type {AssetInfo} */ + const result = { ...a, ...b }; + for (const key of Object.keys(a)) { + if (key in b) { + if (a[key] === b[key]) continue; + switch (key) { + case "fullhash": + case "chunkhash": + case "modulehash": + case "contenthash": + result[key] = mergeMaybeArrays(a[key], b[key]); + break; + case "immutable": + case "development": + case "hotModuleReplacement": + case "javascriptModule": + result[key] = a[key] || b[key]; + break; + case "related": + result[key] = mergeRelatedInfo( + /** @type {NonNullable} */ + (a[key]), + /** @type {NonNullable} */ + (b[key]) + ); + break; + default: + throw new Error(`Can't handle conflicting asset info for ${key}`); + } + } + } + return result; +}; + +/** + * @param {NonNullable} a a + * @param {NonNullable} b b + * @returns {NonNullable} object + */ +const mergeRelatedInfo = (a, b) => { + const result = { ...a, ...b }; + for (const key of Object.keys(a)) { + if (key in b) { + if (a[key] === b[key]) continue; + result[key] = mergeMaybeArrays(a[key], b[key]); + } + } + return result; +}; + +/** + * @param {"base64" | false} encoding encoding + * @param {Source} source source + * @returns {string} encoded data + */ +const encodeDataUri = (encoding, source) => { + /** @type {string | undefined} */ + let encodedContent; + + switch (encoding) { + case "base64": { + encodedContent = source.buffer().toString("base64"); + break; + } + case false: { + const content = source.source(); + + if (typeof content !== "string") { + encodedContent = content.toString("utf8"); + } + + encodedContent = encodeURIComponent( + /** @type {string} */ + (encodedContent) + ).replace( + /[!'()*]/g, + (character) => + `%${/** @type {number} */ (character.codePointAt(0)).toString(16)}` + ); + break; + } + default: + throw new Error(`Unsupported encoding '${encoding}'`); + } + + return encodedContent; +}; + +/** + * @param {"base64" | false} encoding encoding + * @param {string} content content + * @returns {Buffer} decoded content + */ +const decodeDataUriContent = (encoding, content) => { + const isBase64 = encoding === "base64"; + + if (isBase64) { + return Buffer.from(content, "base64"); + } + + // If we can't decode return the original body + try { + return Buffer.from(decodeURIComponent(content), "ascii"); + } catch (_) { + return Buffer.from(content, "ascii"); + } +}; + +const DEFAULT_ENCODING = "base64"; + +class AssetGenerator extends Generator { + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {AssetGeneratorOptions["dataUrl"]=} dataUrlOptions the options for the data url + * @param {AssetModuleFilename=} filename override for output.assetModuleFilename + * @param {RawPublicPath=} publicPath override for output.assetModulePublicPath + * @param {AssetModuleOutputPath=} outputPath the output path for the emitted file which is not included in the runtime import + * @param {boolean=} emit generate output asset + */ + constructor( + moduleGraph, + dataUrlOptions, + filename, + publicPath, + outputPath, + emit + ) { + super(); + this.dataUrlOptions = dataUrlOptions; + this.filename = filename; + this.publicPath = publicPath; + this.outputPath = outputPath; + this.emit = emit; + this._moduleGraph = moduleGraph; + } + + /** + * @param {NormalModule} module module + * @param {RuntimeTemplate} runtimeTemplate runtime template + * @returns {string} source file name + */ + static getSourceFileName(module, runtimeTemplate) { + return makePathsRelative( + runtimeTemplate.compilation.compiler.context, + module.matchResource || module.resource, + runtimeTemplate.compilation.compiler.root + ).replace(/^\.\//, ""); + } + + /** + * @param {NormalModule} module module + * @param {RuntimeTemplate} runtimeTemplate runtime template + * @returns {[string, string]} return full hash and non-numeric full hash + */ + static getFullContentHash(module, runtimeTemplate) { + const hash = createHash( + /** @type {HashFunction} */ + (runtimeTemplate.outputOptions.hashFunction) + ); + + if (runtimeTemplate.outputOptions.hashSalt) { + hash.update(runtimeTemplate.outputOptions.hashSalt); + } + + const source = module.originalSource(); + + if (source) { + hash.update(source.buffer()); + } + + if (module.error) { + hash.update(module.error.toString()); + } + + const fullContentHash = /** @type {string} */ ( + hash.digest(runtimeTemplate.outputOptions.hashDigest) + ); + + /** @type {string} */ + const contentHash = nonNumericOnlyHash( + fullContentHash, + /** @type {number} */ + (runtimeTemplate.outputOptions.hashDigestLength) + ); + + return [fullContentHash, contentHash]; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {Pick} generatorOptions generator options + * @param {{ runtime: RuntimeSpec, runtimeTemplate: RuntimeTemplate, chunkGraph: ChunkGraph }} generateContext context for generate + * @param {string} contentHash the content hash + * @returns {{ filename: string, originalFilename: string, assetInfo: AssetInfo }} info + */ + static getFilenameWithInfo( + module, + generatorOptions, + { runtime, runtimeTemplate, chunkGraph }, + contentHash + ) { + const assetModuleFilename = + generatorOptions.filename || + /** @type {AssetModuleFilename} */ + (runtimeTemplate.outputOptions.assetModuleFilename); + + const sourceFilename = AssetGenerator.getSourceFileName( + module, + runtimeTemplate + ); + let { path: filename, info: assetInfo } = + runtimeTemplate.compilation.getAssetPathWithInfo(assetModuleFilename, { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + }); + + const originalFilename = filename; + + if (generatorOptions.outputPath) { + const { path: outputPath, info } = + runtimeTemplate.compilation.getAssetPathWithInfo( + generatorOptions.outputPath, + { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + } + ); + filename = path.posix.join(outputPath, filename); + assetInfo = mergeAssetInfo(assetInfo, info); + } + + return { originalFilename, filename, assetInfo }; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {Pick} generatorOptions generator options + * @param {GenerateContext} generateContext context for generate + * @param {string} filename the filename + * @param {AssetInfo} assetInfo the asset info + * @param {string} contentHash the content hash + * @returns {{ assetPath: string, assetInfo: AssetInfo }} asset path and info + */ + static getAssetPathWithInfo( + module, + generatorOptions, + { runtime, runtimeTemplate, type, chunkGraph, runtimeRequirements }, + filename, + assetInfo, + contentHash + ) { + const sourceFilename = AssetGenerator.getSourceFileName( + module, + runtimeTemplate + ); + + let assetPath; + + if (generatorOptions.publicPath !== undefined && type === "javascript") { + const { path, info } = runtimeTemplate.compilation.getAssetPathWithInfo( + generatorOptions.publicPath, + { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + } + ); + assetInfo = mergeAssetInfo(assetInfo, info); + assetPath = JSON.stringify(path + filename); + } else if ( + generatorOptions.publicPath !== undefined && + type === "css-url" + ) { + const { path, info } = runtimeTemplate.compilation.getAssetPathWithInfo( + generatorOptions.publicPath, + { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + } + ); + assetInfo = mergeAssetInfo(assetInfo, info); + assetPath = path + filename; + } else if (type === "javascript") { + // add __webpack_require__.p + runtimeRequirements.add(RuntimeGlobals.publicPath); + assetPath = runtimeTemplate.concatenation( + { expr: RuntimeGlobals.publicPath }, + filename + ); + } else if (type === "css-url") { + const compilation = runtimeTemplate.compilation; + const path = + compilation.outputOptions.publicPath === "auto" + ? CssUrlDependency.PUBLIC_PATH_AUTO + : compilation.getAssetPath( + /** @type {TemplatePath} */ + (compilation.outputOptions.publicPath), + { + hash: compilation.hash + } + ); + + assetPath = path + filename; + } + + return { + // eslint-disable-next-line object-shorthand + assetPath: /** @type {string} */ (assetPath), + assetInfo: { sourceFilename, ...assetInfo } + }; + } + + /** + * @param {NormalModule} module module for which the bailout reason should be determined + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(module, context) { + return undefined; + } + + /** + * @param {NormalModule} module module + * @returns {string} mime type + */ + getMimeType(module) { + if (typeof this.dataUrlOptions === "function") { + throw new Error( + "This method must not be called when dataUrlOptions is a function" + ); + } + + /** @type {string | boolean | undefined} */ + let mimeType = + /** @type {AssetGeneratorDataUrlOptions} */ + (this.dataUrlOptions).mimetype; + if (mimeType === undefined) { + const ext = path.extname( + /** @type {string} */ + (module.nameForCondition()) + ); + if ( + module.resourceResolveData && + module.resourceResolveData.mimetype !== undefined + ) { + mimeType = + module.resourceResolveData.mimetype + + module.resourceResolveData.parameters; + } else if (ext) { + mimeType = mimeTypes.lookup(ext); + + if (typeof mimeType !== "string") { + throw new Error( + "DataUrl can't be generated automatically, " + + `because there is no mimetype for "${ext}" in mimetype database. ` + + 'Either pass a mimetype via "generator.mimetype" or ' + + 'use type: "asset/resource" to create a resource file instead of a DataUrl' + ); + } + } + } + + if (typeof mimeType !== "string") { + throw new Error( + "DataUrl can't be generated automatically. " + + 'Either pass a mimetype via "generator.mimetype" or ' + + 'use type: "asset/resource" to create a resource file instead of a DataUrl' + ); + } + + return /** @type {string} */ (mimeType); + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @returns {string} DataURI + */ + generateDataUri(module) { + const source = /** @type {Source} */ (module.originalSource()); + + let encodedSource; + + if (typeof this.dataUrlOptions === "function") { + encodedSource = this.dataUrlOptions.call(null, source.source(), { + filename: module.matchResource || module.resource, + module + }); + } else { + let encoding = + /** @type {AssetGeneratorDataUrlOptions} */ + (this.dataUrlOptions).encoding; + if ( + encoding === undefined && + module.resourceResolveData && + module.resourceResolveData.encoding !== undefined + ) { + encoding = module.resourceResolveData.encoding; + } + if (encoding === undefined) { + encoding = DEFAULT_ENCODING; + } + const mimeType = this.getMimeType(module); + + let encodedContent; + + if ( + module.resourceResolveData && + module.resourceResolveData.encoding === encoding && + decodeDataUriContent( + module.resourceResolveData.encoding, + /** @type {string} */ (module.resourceResolveData.encodedContent) + ).equals(source.buffer()) + ) { + encodedContent = module.resourceResolveData.encodedContent; + } else { + encodedContent = encodeDataUri( + /** @type {"base64" | false} */ (encoding), + source + ); + } + + encodedSource = `data:${mimeType}${ + encoding ? `;${encoding}` : "" + },${encodedContent}`; + } + + return encodedSource; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate(module, generateContext) { + const { + type, + getData, + runtimeTemplate, + runtimeRequirements, + concatenationScope + } = generateContext; + + let content; + + const needContent = type === "javascript" || type === "css-url"; + + const data = getData ? getData() : undefined; + + if ( + /** @type {BuildInfo} */ + (module.buildInfo).dataUrl && + needContent + ) { + const encodedSource = this.generateDataUri(module); + content = + type === "javascript" ? JSON.stringify(encodedSource) : encodedSource; + + if (data) { + data.set("url", { [type]: content, ...data.get("url") }); + } + } else { + const [fullContentHash, contentHash] = AssetGenerator.getFullContentHash( + module, + runtimeTemplate + ); + + if (data) { + data.set("fullContentHash", fullContentHash); + data.set("contentHash", contentHash); + } + + /** @type {BuildInfo} */ + (module.buildInfo).fullContentHash = fullContentHash; + + const { originalFilename, filename, assetInfo } = + AssetGenerator.getFilenameWithInfo( + module, + { filename: this.filename, outputPath: this.outputPath }, + generateContext, + contentHash + ); + + if (data) { + data.set("filename", filename); + } + + let { assetPath, assetInfo: newAssetInfo } = + AssetGenerator.getAssetPathWithInfo( + module, + { publicPath: this.publicPath }, + generateContext, + originalFilename, + assetInfo, + contentHash + ); + + if (data && (type === "javascript" || type === "css-url")) { + data.set("url", { [type]: assetPath, ...data.get("url") }); + } + + if (data) { + const oldAssetInfo = data.get("assetInfo"); + + if (oldAssetInfo) { + newAssetInfo = mergeAssetInfo(oldAssetInfo, newAssetInfo); + } + } + + if (data) { + data.set("assetInfo", newAssetInfo); + } + + // Due to code generation caching module.buildInfo.XXX can't used to store such information + // It need to be stored in the code generation results instead, where it's cached too + // TODO webpack 6 For back-compat reasons we also store in on module.buildInfo + /** @type {BuildInfo} */ + (module.buildInfo).filename = filename; + + /** @type {BuildInfo} */ + (module.buildInfo).assetInfo = newAssetInfo; + + content = assetPath; + } + + if (type === "javascript") { + if (concatenationScope) { + concatenationScope.registerNamespaceExport( + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + ); + + return new RawSource( + `${runtimeTemplate.supportsConst() ? "const" : "var"} ${ + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + } = ${content};` + ); + } + + runtimeRequirements.add(RuntimeGlobals.module); + + return new RawSource(`${RuntimeGlobals.module}.exports = ${content};`); + } else if (type === "css-url") { + return null; + } + + return /** @type {Source} */ (module.originalSource()); + } + + /** + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generateError(error, module, generateContext) { + switch (generateContext.type) { + case "asset": { + return new RawSource(error.message); + } + case "javascript": { + return new RawSource( + `throw new Error(${JSON.stringify(error.message)});` + ); + } + default: + return null; + } + } + + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + /** @type {Set} */ + const sourceTypes = new Set(); + const connections = this._moduleGraph.getIncomingConnections(module); + + for (const connection of connections) { + if (!connection.originModule) { + continue; + } + + sourceTypes.add(connection.originModule.type.split("/")[0]); + } + + if ((module.buildInfo && module.buildInfo.dataUrl) || this.emit === false) { + if (sourceTypes.size > 0) { + if (sourceTypes.has("javascript") && sourceTypes.has("css")) { + return JS_AND_CSS_URL_TYPES; + } else if (sourceTypes.has("css")) { + return CSS_URL_TYPES; + } + return JS_TYPES; + } + + return NO_TYPES; + } + + if (sourceTypes.size > 0) { + if (sourceTypes.has("javascript") && sourceTypes.has("css")) { + return ASSET_AND_JS_AND_CSS_URL_TYPES; + } else if (sourceTypes.has("css")) { + return ASSET_AND_CSS_URL_TYPES; + } + return ASSET_AND_JS_TYPES; + } + + return ASSET_TYPES; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + switch (type) { + case ASSET_MODULE_TYPE: { + const originalSource = module.originalSource(); + + if (!originalSource) { + return 0; + } + + return originalSource.size(); + } + default: + if (module.buildInfo && module.buildInfo.dataUrl) { + const originalSource = module.originalSource(); + + if (!originalSource) { + return 0; + } + + // roughly for data url + // Example: m.exports="data:image/png;base64,ag82/f+2==" + // 4/3 = base64 encoding + // 34 = ~ data url header + footer + rounding + return originalSource.size() * 1.34 + 36; + } + // it's only estimated so this number is probably fine + // Example: m.exports=r.p+"0123456789012345678901.ext" + return 42; + } + } + + /** + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash + */ + updateHash(hash, updateHashContext) { + const { module } = updateHashContext; + + if ( + /** @type {BuildInfo} */ + (module.buildInfo).dataUrl + ) { + hash.update("data-url"); + // this.dataUrlOptions as function should be pure and only depend on input source and filename + // therefore it doesn't need to be hashed + if (typeof this.dataUrlOptions === "function") { + const ident = /** @type {{ ident?: string }} */ (this.dataUrlOptions) + .ident; + if (ident) hash.update(ident); + } else { + const dataUrlOptions = + /** @type {AssetGeneratorDataUrlOptions} */ + (this.dataUrlOptions); + if ( + dataUrlOptions.encoding && + dataUrlOptions.encoding !== DEFAULT_ENCODING + ) { + hash.update(dataUrlOptions.encoding); + } + if (dataUrlOptions.mimetype) hash.update(dataUrlOptions.mimetype); + // computed mimetype depends only on module filename which is already part of the hash + } + } else { + hash.update("resource"); + + const { module, chunkGraph, runtime } = updateHashContext; + const runtimeTemplate = + /** @type {NonNullable} */ + (updateHashContext.runtimeTemplate); + + const pathData = { + module, + runtime, + filename: AssetGenerator.getSourceFileName(module, runtimeTemplate), + chunkGraph, + contentHash: runtimeTemplate.contentHashReplacement + }; + + if (typeof this.publicPath === "function") { + hash.update("path"); + const assetInfo = {}; + hash.update(this.publicPath(pathData, assetInfo)); + hash.update(JSON.stringify(assetInfo)); + } else if (this.publicPath) { + hash.update("path"); + hash.update(this.publicPath); + } else { + hash.update("no-path"); + } + + const assetModuleFilename = + this.filename || + /** @type {AssetModuleFilename} */ + (runtimeTemplate.outputOptions.assetModuleFilename); + const { path: filename, info } = + runtimeTemplate.compilation.getAssetPathWithInfo( + assetModuleFilename, + pathData + ); + hash.update(filename); + hash.update(JSON.stringify(info)); + } + } +} + +module.exports = AssetGenerator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7b317cf5523fe4ef2eae593a0d6059526c8d5e1d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetModulesPlugin.js @@ -0,0 +1,294 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Yuta Hiroto @hiroppy +*/ + +"use strict"; + +const { + ASSET_MODULE_TYPE, + ASSET_MODULE_TYPE_INLINE, + ASSET_MODULE_TYPE_RESOURCE, + ASSET_MODULE_TYPE_SOURCE +} = require("../ModuleTypeConstants"); +const { cleverMerge } = require("../util/cleverMerge"); +const { compareModulesByIdOrIdentifier } = require("../util/comparators"); +const createSchemaValidation = require("../util/create-schema-validation"); +const memoize = require("../util/memoize"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */ +/** @typedef {import("schema-utils").Schema} Schema */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../NormalModule")} NormalModule */ + +/** + * @param {string} name name of definitions + * @returns {Schema} definition + */ +const getSchema = (name) => { + const { definitions } = require("../../schemas/WebpackOptions.json"); + + return { + definitions, + oneOf: [{ $ref: `#/definitions/${name}` }] + }; +}; + +const generatorValidationOptions = { + name: "Asset Modules Plugin", + baseDataPath: "generator" +}; +const validateGeneratorOptions = { + asset: createSchemaValidation( + require("../../schemas/plugins/asset/AssetGeneratorOptions.check"), + () => getSchema("AssetGeneratorOptions"), + generatorValidationOptions + ), + "asset/resource": createSchemaValidation( + require("../../schemas/plugins/asset/AssetResourceGeneratorOptions.check"), + () => getSchema("AssetResourceGeneratorOptions"), + generatorValidationOptions + ), + "asset/inline": createSchemaValidation( + require("../../schemas/plugins/asset/AssetInlineGeneratorOptions.check"), + () => getSchema("AssetInlineGeneratorOptions"), + generatorValidationOptions + ) +}; + +const validateParserOptions = createSchemaValidation( + require("../../schemas/plugins/asset/AssetParserOptions.check"), + () => getSchema("AssetParserOptions"), + { + name: "Asset Modules Plugin", + baseDataPath: "parser" + } +); + +const getAssetGenerator = memoize(() => require("./AssetGenerator")); +const getAssetParser = memoize(() => require("./AssetParser")); +const getAssetSourceParser = memoize(() => require("./AssetSourceParser")); +const getAssetSourceGenerator = memoize(() => + require("./AssetSourceGenerator") +); + +const type = ASSET_MODULE_TYPE; +const PLUGIN_NAME = "AssetModulesPlugin"; + +class AssetModulesPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.createParser + .for(ASSET_MODULE_TYPE) + .tap(PLUGIN_NAME, (parserOptions) => { + validateParserOptions(parserOptions); + parserOptions = cleverMerge( + /** @type {AssetParserOptions} */ + (compiler.options.module.parser.asset), + parserOptions + ); + + let dataUrlCondition = parserOptions.dataUrlCondition; + if (!dataUrlCondition || typeof dataUrlCondition === "object") { + dataUrlCondition = { + maxSize: 8096, + ...dataUrlCondition + }; + } + + const AssetParser = getAssetParser(); + + return new AssetParser(dataUrlCondition); + }); + normalModuleFactory.hooks.createParser + .for(ASSET_MODULE_TYPE_INLINE) + .tap(PLUGIN_NAME, (_parserOptions) => { + const AssetParser = getAssetParser(); + + return new AssetParser(true); + }); + normalModuleFactory.hooks.createParser + .for(ASSET_MODULE_TYPE_RESOURCE) + .tap(PLUGIN_NAME, (_parserOptions) => { + const AssetParser = getAssetParser(); + + return new AssetParser(false); + }); + normalModuleFactory.hooks.createParser + .for(ASSET_MODULE_TYPE_SOURCE) + .tap(PLUGIN_NAME, (_parserOptions) => { + const AssetSourceParser = getAssetSourceParser(); + + return new AssetSourceParser(); + }); + + for (const type of [ + ASSET_MODULE_TYPE, + ASSET_MODULE_TYPE_INLINE, + ASSET_MODULE_TYPE_RESOURCE + ]) { + normalModuleFactory.hooks.createGenerator + .for(type) + .tap(PLUGIN_NAME, (generatorOptions) => { + validateGeneratorOptions[type](generatorOptions); + + let dataUrl; + if (type !== ASSET_MODULE_TYPE_RESOURCE) { + dataUrl = generatorOptions.dataUrl; + if (!dataUrl || typeof dataUrl === "object") { + dataUrl = { + encoding: undefined, + mimetype: undefined, + ...dataUrl + }; + } + } + + let filename; + let publicPath; + let outputPath; + if (type !== ASSET_MODULE_TYPE_INLINE) { + filename = generatorOptions.filename; + publicPath = generatorOptions.publicPath; + outputPath = generatorOptions.outputPath; + } + + const AssetGenerator = getAssetGenerator(); + + return new AssetGenerator( + compilation.moduleGraph, + dataUrl, + filename, + publicPath, + outputPath, + generatorOptions.emit !== false + ); + }); + } + normalModuleFactory.hooks.createGenerator + .for(ASSET_MODULE_TYPE_SOURCE) + .tap(PLUGIN_NAME, () => { + const AssetSourceGenerator = getAssetSourceGenerator(); + + return new AssetSourceGenerator(compilation.moduleGraph); + }); + + compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => { + const { chunkGraph } = compilation; + const { chunk, codeGenerationResults, runtimeTemplate } = options; + + const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + ASSET_MODULE_TYPE, + compareModulesByIdOrIdentifier(chunkGraph) + ); + if (modules) { + for (const module of modules) { + try { + const codeGenResult = codeGenerationResults.get( + module, + chunk.runtime + ); + const buildInfo = /** @type {BuildInfo} */ (module.buildInfo); + const data = + /** @type {NonNullable} */ + (codeGenResult.data); + const errored = module.getNumberOfErrors() > 0; + + /** @type {string} */ + let entryFilename; + /** @type {AssetInfo} */ + let entryInfo; + /** @type {string} */ + let entryHash; + + if (errored) { + const erroredModule = /** @type {NormalModule} */ (module); + const AssetGenerator = getAssetGenerator(); + const [fullContentHash, contentHash] = + AssetGenerator.getFullContentHash( + erroredModule, + runtimeTemplate + ); + const { filename, assetInfo } = + AssetGenerator.getFilenameWithInfo( + erroredModule, + { + filename: + erroredModule.generatorOptions && + erroredModule.generatorOptions.filename, + outputPath: + erroredModule.generatorOptions && + erroredModule.generatorOptions.outputPath + }, + { + runtime: chunk.runtime, + runtimeTemplate, + chunkGraph + }, + contentHash + ); + entryFilename = filename; + entryInfo = assetInfo; + entryHash = fullContentHash; + } else { + entryFilename = buildInfo.filename || data.get("filename"); + entryInfo = buildInfo.assetInfo || data.get("assetInfo"); + entryHash = + buildInfo.fullContentHash || data.get("fullContentHash"); + } + + result.push({ + render: () => + /** @type {Source} */ (codeGenResult.sources.get(type)), + filename: entryFilename, + info: entryInfo, + auxiliary: true, + identifier: `assetModule${chunkGraph.getModuleId(module)}`, + hash: entryHash + }); + } catch (err) { + /** @type {Error} */ (err).message += + `\nduring rendering of asset ${module.identifier()}`; + throw err; + } + } + } + + return result; + }); + + compilation.hooks.prepareModuleExecution.tap( + PLUGIN_NAME, + (options, context) => { + const { codeGenerationResult } = options; + const source = codeGenerationResult.sources.get(ASSET_MODULE_TYPE); + if (source === undefined) return; + const data = + /** @type {NonNullable} */ + (codeGenerationResult.data); + context.assets.set(data.get("filename"), { + source, + info: data.get("assetInfo") + }); + } + ); + } + ); + } +} + +module.exports = AssetModulesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetParser.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetParser.js new file mode 100644 index 0000000000000000000000000000000000000000..b4f1d534948d87c83b1e041987971e81dcb0eaac --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetParser.js @@ -0,0 +1,65 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Yuta Hiroto @hiroppy +*/ + +"use strict"; + +const Parser = require("../Parser"); + +/** @typedef {import("../../declarations/WebpackOptions").AssetParserDataUrlOptions} AssetParserDataUrlOptions */ +/** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +class AssetParser extends Parser { + /** + * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl + */ + constructor(dataUrlCondition) { + super(); + this.dataUrlCondition = dataUrlCondition; + } + + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (typeof source === "object" && !Buffer.isBuffer(source)) { + throw new Error("AssetParser doesn't accept preparsed AST"); + } + + const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo); + buildInfo.strict = true; + const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta); + buildMeta.exportsType = "default"; + buildMeta.defaultObject = false; + + if (typeof this.dataUrlCondition === "function") { + buildInfo.dataUrl = this.dataUrlCondition(source, { + filename: state.module.matchResource || state.module.resource, + module: state.module + }); + } else if (typeof this.dataUrlCondition === "boolean") { + buildInfo.dataUrl = this.dataUrlCondition; + } else if ( + this.dataUrlCondition && + typeof this.dataUrlCondition === "object" + ) { + buildInfo.dataUrl = + Buffer.byteLength(source) <= + /** @type {NonNullable} */ + (this.dataUrlCondition.maxSize); + } else { + throw new Error("Unexpected dataUrlCondition type"); + } + + return state; + } +} + +module.exports = AssetParser; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetSourceGenerator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetSourceGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..90b8145c2ac553037b0cbdd3df8d2ee64e7d9404 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetSourceGenerator.js @@ -0,0 +1,166 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const ConcatenationScope = require("../ConcatenationScope"); +const Generator = require("../Generator"); +const { + CSS_URL_TYPES, + JS_AND_CSS_URL_TYPES, + JS_TYPES, + NO_TYPES +} = require("../ModuleSourceTypesConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../NormalModule")} NormalModule */ + +class AssetSourceGenerator extends Generator { + /** + * @param {ModuleGraph} moduleGraph the module graph + */ + constructor(moduleGraph) { + super(); + + this._moduleGraph = moduleGraph; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate( + module, + { type, concatenationScope, getData, runtimeTemplate, runtimeRequirements } + ) { + const originalSource = module.originalSource(); + const data = getData ? getData() : undefined; + + switch (type) { + case "javascript": { + if (!originalSource) { + return new RawSource(""); + } + + const content = originalSource.source(); + const encodedSource = + typeof content === "string" ? content : content.toString("utf8"); + + let sourceContent; + if (concatenationScope) { + concatenationScope.registerNamespaceExport( + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + ); + sourceContent = `${runtimeTemplate.supportsConst() ? "const" : "var"} ${ + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + } = ${JSON.stringify(encodedSource)};`; + } else { + runtimeRequirements.add(RuntimeGlobals.module); + sourceContent = `${RuntimeGlobals.module}.exports = ${JSON.stringify( + encodedSource + )};`; + } + return new RawSource(sourceContent); + } + case "css-url": { + if (!originalSource) { + return null; + } + + const content = originalSource.source(); + const encodedSource = + typeof content === "string" ? content : content.toString("utf8"); + + if (data) { + data.set("url", { [type]: encodedSource }); + } + return null; + } + default: + return null; + } + } + + /** + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generateError(error, module, generateContext) { + switch (generateContext.type) { + case "javascript": { + return new RawSource( + `throw new Error(${JSON.stringify(error.message)});` + ); + } + default: + return null; + } + } + + /** + * @param {NormalModule} module module for which the bailout reason should be determined + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(module, context) { + return undefined; + } + + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + /** @type {Set} */ + const sourceTypes = new Set(); + const connections = this._moduleGraph.getIncomingConnections(module); + + for (const connection of connections) { + if (!connection.originModule) { + continue; + } + + sourceTypes.add(connection.originModule.type.split("/")[0]); + } + + if (sourceTypes.size > 0) { + if (sourceTypes.has("javascript") && sourceTypes.has("css")) { + return JS_AND_CSS_URL_TYPES; + } else if (sourceTypes.has("css")) { + return CSS_URL_TYPES; + } + return JS_TYPES; + } + + return NO_TYPES; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + const originalSource = module.originalSource(); + + if (!originalSource) { + return 0; + } + + // Example: m.exports="abcd" + return originalSource.size() + 12; + } +} + +module.exports = AssetSourceGenerator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetSourceParser.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetSourceParser.js new file mode 100644 index 0000000000000000000000000000000000000000..c122f0ea4e4d7b0e16b62be4bfa532b6a5e533e5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/AssetSourceParser.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Yuta Hiroto @hiroppy +*/ + +"use strict"; + +const Parser = require("../Parser"); + +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +class AssetSourceParser extends Parser { + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (typeof source === "object" && !Buffer.isBuffer(source)) { + throw new Error("AssetSourceParser doesn't accept preparsed AST"); + } + const { module } = state; + /** @type {BuildInfo} */ + (module.buildInfo).strict = true; + /** @type {BuildMeta} */ + (module.buildMeta).exportsType = "default"; + /** @type {BuildMeta} */ + (state.module.buildMeta).defaultObject = false; + + return state; + } +} + +module.exports = AssetSourceParser; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/RawDataUrlModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/RawDataUrlModule.js new file mode 100644 index 0000000000000000000000000000000000000000..b15973e2f4822a39d660edd4ef94151d815ed2e5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/asset/RawDataUrlModule.js @@ -0,0 +1,167 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const Module = require("../Module"); +const { JS_TYPES } = require("../ModuleSourceTypesConstants"); +const { ASSET_MODULE_TYPE_RAW_DATA_URL } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").BuildCallback} BuildCallback */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + +class RawDataUrlModule extends Module { + /** + * @param {string} url raw url + * @param {string} identifier unique identifier + * @param {string=} readableIdentifier readable identifier + */ + constructor(url, identifier, readableIdentifier) { + super(ASSET_MODULE_TYPE_RAW_DATA_URL, null); + this.url = url; + this.urlBuffer = url ? Buffer.from(url) : undefined; + this.identifierStr = identifier || this.url; + this.readableIdentifierStr = readableIdentifier || this.identifierStr; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return JS_TYPES; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this.identifierStr; + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + if (this.url === undefined) { + this.url = /** @type {Buffer} */ (this.urlBuffer).toString(); + } + return Math.max(1, this.url.length); + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return /** @type {string} */ ( + requestShortener.shorten(this.readableIdentifierStr) + ); + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + cacheable: true + }; + callback(); + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + if (this.url === undefined) { + this.url = /** @type {Buffer} */ (this.urlBuffer).toString(); + } + const sources = new Map(); + sources.set( + "javascript", + new RawSource(`module.exports = ${JSON.stringify(this.url)};`) + ); + const data = new Map(); + data.set("url", { + javascript: this.url + }); + const runtimeRequirements = new Set(); + runtimeRequirements.add(RuntimeGlobals.module); + return { sources, runtimeRequirements, data }; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(/** @type {Buffer} */ (this.urlBuffer)); + super.updateHash(hash, context); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.urlBuffer); + write(this.identifierStr); + write(this.readableIdentifierStr); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.urlBuffer = read(); + this.identifierStr = read(); + this.readableIdentifierStr = read(); + + super.deserialize(context); + } +} + +makeSerializable(RawDataUrlModule, "webpack/lib/asset/RawDataUrlModule"); + +module.exports = RawDataUrlModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/async-modules/AsyncModuleHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/async-modules/AsyncModuleHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..df45deca5034ea3334dfa96e52e68a996d973af0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/async-modules/AsyncModuleHelpers.js @@ -0,0 +1,50 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Haijie Xie @hai-x +*/ + +"use strict"; + +const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); + +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../Module")} Module */ + +/** + * @param {ModuleGraph} moduleGraph module graph + * @param {Module} module module + * @returns {Set} set of modules + */ +const getOutgoingAsyncModules = (moduleGraph, module) => { + /** @type {Set} */ + const set = new Set(); + /** @type {Set} */ + const seen = new Set(); + (function g(/** @type {Module} */ module) { + if (!moduleGraph.isAsync(module) || seen.has(module)) return; + seen.add(module); + if (module.buildMeta && module.buildMeta.async) { + set.add(module); + } else { + const outgoingConnectionMap = + moduleGraph.getOutgoingConnectionsByModule(module); + if (outgoingConnectionMap) { + for (const [module, connections] of outgoingConnectionMap) { + if ( + connections.some( + (c) => + c.dependency instanceof HarmonyImportDependency && + c.isTargetActive(undefined) + ) && + module + ) { + g(module); + } + } + } + } + })(module); + return set; +}; + +module.exports.getOutgoingAsyncModules = getOutgoingAsyncModules; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/async-modules/AwaitDependenciesInitFragment.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/async-modules/AwaitDependenciesInitFragment.js new file mode 100644 index 0000000000000000000000000000000000000000..a0a25a8e832c2bc1ac018235d6e3df4c75883a27 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/async-modules/AwaitDependenciesInitFragment.js @@ -0,0 +1,87 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const InitFragment = require("../InitFragment"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ + +/** + * @extends {InitFragment} + */ +class AwaitDependenciesInitFragment extends InitFragment { + /** + * @param {Map} dependencies maps an import var to an async module that needs to be awaited + */ + constructor(dependencies) { + super( + undefined, + InitFragment.STAGE_ASYNC_DEPENDENCIES, + 0, + "await-dependencies" + ); + this.dependencies = dependencies; + } + + /** + * @param {AwaitDependenciesInitFragment} other other AwaitDependenciesInitFragment + * @returns {AwaitDependenciesInitFragment} AwaitDependenciesInitFragment + */ + merge(other) { + const dependencies = new Map(other.dependencies); + for (const [key, value] of this.dependencies) { + dependencies.set(key, value); + } + return new AwaitDependenciesInitFragment(dependencies); + } + + /** + * @param {GenerateContext} context context + * @returns {string | Source | undefined} the source code that will be included as initialization code + */ + getContent({ runtimeRequirements, runtimeTemplate }) { + runtimeRequirements.add(RuntimeGlobals.module); + if (this.dependencies.size === 0) { + return ""; + } + + const importVars = [...this.dependencies.keys()]; + const asyncModuleValues = [...this.dependencies.values()].join(", "); + + const templateInput = [ + `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${asyncModuleValues}]);` + ]; + + if ( + this.dependencies.size === 1 || + !runtimeTemplate.supportsDestructuring() + ) { + templateInput.push( + "var __webpack_async_dependencies_result__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);" + ); + for (const [index, importVar] of importVars.entries()) { + templateInput.push( + `${importVar} = __webpack_async_dependencies_result__[${index}];` + ); + } + } else { + const importVarsStr = importVars.join(", "); + + templateInput.push( + `([${importVarsStr}] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);` + ); + } + + templateInput.push(""); + + return Template.asString(templateInput); + } +} + +module.exports = AwaitDependenciesInitFragment; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/async-modules/InferAsyncModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/async-modules/InferAsyncModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..3ced0bcc63d3df47f1a520028aabd9f678022914 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/async-modules/InferAsyncModulesPlugin.js @@ -0,0 +1,54 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +const PLUGIN_NAME = "InferAsyncModulesPlugin"; + +class InferAsyncModulesPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const { moduleGraph } = compilation; + compilation.hooks.finishModules.tap(PLUGIN_NAME, (modules) => { + /** @type {Set} */ + const queue = new Set(); + for (const module of modules) { + if (module.buildMeta && module.buildMeta.async) { + queue.add(module); + } + } + for (const module of queue) { + moduleGraph.setAsync(module); + for (const [ + originModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if ( + connections.some( + (c) => + c.dependency instanceof HarmonyImportDependency && + c.isTargetActive(undefined) + ) + ) { + queue.add(/** @type {Module} */ (originModule)); + } + } + } + }); + }); + } +} + +module.exports = InferAsyncModulesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/buildChunkGraph.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/buildChunkGraph.js new file mode 100644 index 0000000000000000000000000000000000000000..117e98ed39421951518785149576526254f830bd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/buildChunkGraph.js @@ -0,0 +1,1362 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const AsyncDependencyToInitialChunkError = require("./AsyncDependencyToInitialChunkError"); +const { connectChunkGroupParentAndChild } = require("./GraphHelpers"); +const ModuleGraphConnection = require("./ModuleGraphConnection"); +const { getEntryRuntime, mergeRuntime } = require("./util/runtime"); + +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Entrypoint")} Entrypoint */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @typedef {object} QueueItem + * @property {number} action + * @property {DependenciesBlock} block + * @property {Module} module + * @property {Chunk} chunk + * @property {ChunkGroup} chunkGroup + * @property {ChunkGroupInfo} chunkGroupInfo + */ + +/** + * @typedef {object} ChunkGroupInfo + * @property {ChunkGroup} chunkGroup the chunk group + * @property {RuntimeSpec} runtime the runtimes + * @property {boolean} initialized is this chunk group initialized + * @property {bigint | undefined} minAvailableModules current minimal set of modules available at this point + * @property {bigint[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules + * @property {Set=} skippedItems modules that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking) + * @property {Set<[Module, ModuleGraphConnection[]]>=} skippedModuleConnections referenced modules that where skipped because they were not active in this runtime + * @property {bigint | undefined} resultingAvailableModules set of modules available including modules from this chunk group + * @property {Set | undefined} children set of children chunk groups, that will be revisited when availableModules shrink + * @property {Set | undefined} availableSources set of chunk groups that are the source for minAvailableModules + * @property {Set | undefined} availableChildren set of chunk groups which depend on the this chunk group as availableSource + * @property {number} preOrderIndex next pre order index + * @property {number} postOrderIndex next post order index + * @property {boolean} chunkLoading has a chunk loading mechanism + * @property {boolean} asyncChunks create async chunks + */ + +/** + * @typedef {object} BlockChunkGroupConnection + * @property {ChunkGroupInfo} originChunkGroupInfo origin chunk group + * @property {ChunkGroup} chunkGroup referenced chunk group + */ + +/** @typedef {(Module | ConnectionState | ModuleGraphConnection)[]} BlockModulesInTuples */ +/** @typedef {(Module | ConnectionState | ModuleGraphConnection[])[]} BlockModulesInFlattenTuples */ +/** @typedef {Map} BlockModulesMap */ +/** @typedef {Map} MaskByChunk */ +/** @typedef {Set} BlocksWithNestedBlocks */ +/** @typedef {Map} BlockConnections */ +/** @typedef {Map} ChunkGroupInfoMap */ +/** @typedef {Set} AllCreatedChunkGroups */ +/** @typedef {Map} InputEntrypointsAndModules */ + +const ZERO_BIGINT = BigInt(0); +const ONE_BIGINT = BigInt(1); + +/** + * @param {bigint} mask The mask to test + * @param {number} ordinal The ordinal of the bit to test + * @returns {boolean} If the ordinal-th bit is set in the mask + */ +const isOrdinalSetInMask = (mask, ordinal) => + BigInt.asUintN(1, mask >> BigInt(ordinal)) !== ZERO_BIGINT; + +/** + * @param {ModuleGraphConnection[]} connections list of connections + * @param {RuntimeSpec} runtime for which runtime + * @returns {ConnectionState} connection state + */ +const getActiveStateOfConnections = (connections, runtime) => { + let merged = connections[0].getActiveState(runtime); + if (merged === true) return true; + for (let i = 1; i < connections.length; i++) { + const c = connections[i]; + merged = ModuleGraphConnection.addConnectionStates( + merged, + c.getActiveState(runtime) + ); + if (merged === true) return true; + } + return merged; +}; + +/** + * @param {Module} module module + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime runtime + * @param {BlockModulesMap} blockModulesMap block modules map + */ +const extractBlockModules = (module, moduleGraph, runtime, blockModulesMap) => { + /** @type {DependenciesBlock | undefined} */ + let blockCache; + /** @type {BlockModulesInTuples | undefined} */ + let modules; + + /** @type {BlockModulesInTuples[]} */ + const arrays = []; + + /** @type {DependenciesBlock[]} */ + const queue = [module]; + while (queue.length > 0) { + const block = /** @type {DependenciesBlock} */ (queue.pop()); + /** @type {Module[]} */ + const arr = []; + arrays.push(arr); + blockModulesMap.set(block, arr); + for (const b of block.blocks) { + queue.push(b); + } + } + + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const d = connection.dependency; + // We skip connections without dependency + if (!d) continue; + const m = connection.module; + // We skip connections without Module pointer + if (!m) continue; + // We skip weak connections + if (connection.weak) continue; + + const block = moduleGraph.getParentBlock(d); + let index = moduleGraph.getParentBlockIndex(d); + + // deprecated fallback + if (index < 0) { + index = /** @type {DependenciesBlock} */ (block).dependencies.indexOf(d); + } + + if (blockCache !== block) { + modules = + /** @type {BlockModulesInTuples} */ + ( + blockModulesMap.get( + (blockCache = /** @type {DependenciesBlock} */ (block)) + ) + ); + } + + const i = index * 3; + /** @type {BlockModulesInTuples} */ + (modules)[i] = m; + /** @type {BlockModulesInTuples} */ + (modules)[i + 1] = connection.getActiveState(runtime); + /** @type {BlockModulesInTuples} */ + (modules)[i + 2] = connection; + } + + for (const modules of arrays) { + if (modules.length === 0) continue; + let indexMap; + let length = 0; + outer: for (let j = 0; j < modules.length; j += 3) { + const m = modules[j]; + if (m === undefined) continue; + const state = /** @type {ConnectionState} */ (modules[j + 1]); + const connection = /** @type {ModuleGraphConnection} */ (modules[j + 2]); + if (indexMap === undefined) { + let i = 0; + for (; i < length; i += 3) { + if (modules[i] === m) { + const merged = /** @type {ConnectionState} */ (modules[i + 1]); + /** @type {ModuleGraphConnection[]} */ + (/** @type {unknown} */ (modules[i + 2])).push(connection); + if (merged === true) continue outer; + modules[i + 1] = ModuleGraphConnection.addConnectionStates( + merged, + state + ); + continue outer; + } + } + modules[length] = m; + length++; + modules[length] = state; + length++; + /** @type {ModuleGraphConnection[]} */ + (/** @type {unknown} */ (modules[length])) = [connection]; + length++; + if (length > 30) { + // To avoid worse case performance, we will use an index map for + // linear cost access, which allows to maintain O(n) complexity + // while keeping allocations down to a minimum + indexMap = new Map(); + for (let i = 0; i < length; i += 3) { + indexMap.set(modules[i], i + 1); + } + } + } else { + const idx = indexMap.get(m); + if (idx !== undefined) { + const merged = /** @type {ConnectionState} */ (modules[idx]); + /** @type {ModuleGraphConnection[]} */ + (/** @type {unknown} */ (modules[idx + 1])).push(connection); + if (merged === true) continue; + modules[idx] = ModuleGraphConnection.addConnectionStates( + merged, + state + ); + } else { + modules[length] = m; + length++; + modules[length] = state; + indexMap.set(m, length); + length++; + /** @type {ModuleGraphConnection[]} */ + ( + /** @type {unknown} */ + (modules[length]) + ) = [connection]; + length++; + } + } + } + modules.length = length; + } +}; + +/** + * @param {Logger} logger a logger + * @param {Compilation} compilation the compilation + * @param {InputEntrypointsAndModules} inputEntrypointsAndModules chunk groups which are processed with the modules + * @param {ChunkGroupInfoMap} chunkGroupInfoMap mapping from chunk group to available modules + * @param {BlockConnections} blockConnections connection for blocks + * @param {BlocksWithNestedBlocks} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {AllCreatedChunkGroups} allCreatedChunkGroups filled with all chunk groups that are created here + * @param {MaskByChunk} maskByChunk module content mask by chunk + */ +const visitModules = ( + logger, + compilation, + inputEntrypointsAndModules, + chunkGroupInfoMap, + blockConnections, + blocksWithNestedBlocks, + allCreatedChunkGroups, + maskByChunk +) => { + const { moduleGraph, chunkGraph, moduleMemCaches } = compilation; + + /** @type {Map} */ + const blockModulesRuntimeMap = new Map(); + + /** @type {BlockModulesMap | undefined} */ + let blockModulesMap; + + /** @type {Map} */ + const ordinalByModule = new Map(); + + /** + * @param {Module} module The module to look up + * @returns {number} The ordinal of the module in masks + */ + const getModuleOrdinal = (module) => { + let ordinal = ordinalByModule.get(module); + if (ordinal === undefined) { + ordinal = ordinalByModule.size; + ordinalByModule.set(module, ordinal); + } + return ordinal; + }; + + for (const chunk of compilation.chunks) { + let mask = ZERO_BIGINT; + for (const m of chunkGraph.getChunkModulesIterable(chunk)) { + mask |= ONE_BIGINT << BigInt(getModuleOrdinal(m)); + } + maskByChunk.set(chunk, mask); + } + + /** + * @param {DependenciesBlock} block block + * @param {RuntimeSpec} runtime runtime + * @returns {BlockModulesInFlattenTuples | undefined} block modules in flatten tuples + */ + const getBlockModules = (block, runtime) => { + blockModulesMap = blockModulesRuntimeMap.get(runtime); + if (blockModulesMap === undefined) { + /** @type {BlockModulesMap} */ + blockModulesMap = new Map(); + blockModulesRuntimeMap.set(runtime, blockModulesMap); + } + let blockModules = blockModulesMap.get(block); + if (blockModules !== undefined) return blockModules; + const module = /** @type {Module} */ (block.getRootBlock()); + const memCache = moduleMemCaches && moduleMemCaches.get(module); + if (memCache !== undefined) { + /** @type {BlockModulesMap} */ + const map = memCache.provide( + "bundleChunkGraph.blockModules", + runtime, + () => { + logger.time("visitModules: prepare"); + const map = new Map(); + extractBlockModules(module, moduleGraph, runtime, map); + logger.timeAggregate("visitModules: prepare"); + return map; + } + ); + for (const [block, blockModules] of map) { + blockModulesMap.set(block, blockModules); + } + return map.get(block); + } + logger.time("visitModules: prepare"); + extractBlockModules(module, moduleGraph, runtime, blockModulesMap); + blockModules = + /** @type {BlockModulesInFlattenTuples} */ + (blockModulesMap.get(block)); + logger.timeAggregate("visitModules: prepare"); + return blockModules; + }; + + let statProcessedQueueItems = 0; + let statProcessedBlocks = 0; + let statConnectedChunkGroups = 0; + let statProcessedChunkGroupsForMerging = 0; + let statMergedAvailableModuleSets = 0; + const statForkedAvailableModules = 0; + const statForkedAvailableModulesCount = 0; + const statForkedAvailableModulesCountPlus = 0; + const statForkedMergedModulesCount = 0; + const statForkedMergedModulesCountPlus = 0; + const statForkedResultModulesCount = 0; + let statChunkGroupInfoUpdated = 0; + let statChildChunkGroupsReconnected = 0; + + let nextChunkGroupIndex = 0; + let nextFreeModulePreOrderIndex = 0; + let nextFreeModulePostOrderIndex = 0; + + /** @type {Map} */ + const blockChunkGroups = new Map(); + + /** @type {Map>} */ + const blocksByChunkGroups = new Map(); + + /** @type {Map} */ + const namedChunkGroups = new Map(); + + /** @type {Map} */ + const namedAsyncEntrypoints = new Map(); + + /** @type {Set} */ + const outdatedOrderIndexChunkGroups = new Set(); + + const ADD_AND_ENTER_ENTRY_MODULE = 0; + const ADD_AND_ENTER_MODULE = 1; + const ENTER_MODULE = 2; + const PROCESS_BLOCK = 3; + const PROCESS_ENTRY_BLOCK = 4; + const LEAVE_MODULE = 5; + + /** @type {QueueItem[]} */ + let queue = []; + + /** @type {Map>} */ + const queueConnect = new Map(); + /** @type {Set} */ + const chunkGroupsForCombining = new Set(); + + // Fill queue with entrypoint modules + // Create ChunkGroupInfo for entrypoints + for (const [chunkGroup, modules] of inputEntrypointsAndModules) { + const runtime = getEntryRuntime( + compilation, + /** @type {string} */ (chunkGroup.name), + chunkGroup.options + ); + /** @type {ChunkGroupInfo} */ + const chunkGroupInfo = { + initialized: false, + chunkGroup, + runtime, + minAvailableModules: undefined, + availableModulesToBeMerged: [], + skippedItems: undefined, + resultingAvailableModules: undefined, + children: undefined, + availableSources: undefined, + availableChildren: undefined, + preOrderIndex: 0, + postOrderIndex: 0, + chunkLoading: + chunkGroup.options.chunkLoading !== undefined + ? chunkGroup.options.chunkLoading !== false + : compilation.outputOptions.chunkLoading !== false, + asyncChunks: + chunkGroup.options.asyncChunks !== undefined + ? chunkGroup.options.asyncChunks + : compilation.outputOptions.asyncChunks !== false + }; + chunkGroup.index = nextChunkGroupIndex++; + if (chunkGroup.getNumberOfParents() > 0) { + // minAvailableModules for child entrypoints are unknown yet, set to undefined. + // This means no module is added until other sets are merged into + // this minAvailableModules (by the parent entrypoints) + const skippedItems = new Set(modules); + chunkGroupInfo.skippedItems = skippedItems; + chunkGroupsForCombining.add(chunkGroupInfo); + } else { + // The application may start here: We start with an empty list of available modules + chunkGroupInfo.minAvailableModules = ZERO_BIGINT; + const chunk = chunkGroup.getEntrypointChunk(); + for (const module of modules) { + queue.push({ + action: ADD_AND_ENTER_MODULE, + block: module, + module, + chunk, + chunkGroup, + chunkGroupInfo + }); + } + } + chunkGroupInfoMap.set(chunkGroup, chunkGroupInfo); + if (chunkGroup.name) { + namedChunkGroups.set(chunkGroup.name, chunkGroupInfo); + } + } + // Fill availableSources with parent-child dependencies between entrypoints + for (const chunkGroupInfo of chunkGroupsForCombining) { + const { chunkGroup } = chunkGroupInfo; + chunkGroupInfo.availableSources = new Set(); + for (const parent of chunkGroup.parentsIterable) { + const parentChunkGroupInfo = + /** @type {ChunkGroupInfo} */ + (chunkGroupInfoMap.get(parent)); + chunkGroupInfo.availableSources.add(parentChunkGroupInfo); + if (parentChunkGroupInfo.availableChildren === undefined) { + parentChunkGroupInfo.availableChildren = new Set(); + } + parentChunkGroupInfo.availableChildren.add(chunkGroupInfo); + } + } + // pop() is used to read from the queue + // so it need to be reversed to be iterated in + // correct order + queue.reverse(); + + /** @type {Set} */ + const outdatedChunkGroupInfo = new Set(); + /** @type {Set<[ChunkGroupInfo, QueueItem | null]>} */ + const chunkGroupsForMerging = new Set(); + /** @type {QueueItem[]} */ + let queueDelayed = []; + + /** @type {[Module, ModuleGraphConnection[]][]} */ + const skipConnectionBuffer = []; + /** @type {Module[]} */ + const skipBuffer = []; + /** @type {QueueItem[]} */ + const queueBuffer = []; + + /** @type {Module} */ + let module; + /** @type {Chunk} */ + let chunk; + /** @type {ChunkGroup} */ + let chunkGroup; + /** @type {DependenciesBlock} */ + let block; + /** @type {ChunkGroupInfo} */ + let chunkGroupInfo; + + // For each async Block in graph + /** + * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock + * @returns {void} + */ + const iteratorBlock = (b) => { + // 1. We create a chunk group with single chunk in it for this Block + // but only once (blockChunkGroups map) + /** @type {ChunkGroupInfo | undefined} */ + let cgi = blockChunkGroups.get(b); + /** @type {ChunkGroup | undefined} */ + let c; + /** @type {Entrypoint | undefined} */ + let entrypoint; + const entryOptions = b.groupOptions && b.groupOptions.entryOptions; + if (cgi === undefined) { + const chunkName = (b.groupOptions && b.groupOptions.name) || b.chunkName; + if (entryOptions) { + cgi = namedAsyncEntrypoints.get(/** @type {string} */ (chunkName)); + if (!cgi) { + entrypoint = compilation.addAsyncEntrypoint( + entryOptions, + module, + /** @type {DependencyLocation} */ (b.loc), + /** @type {string} */ (b.request) + ); + maskByChunk.set(entrypoint.chunks[0], ZERO_BIGINT); + entrypoint.index = nextChunkGroupIndex++; + cgi = { + chunkGroup: entrypoint, + initialized: false, + runtime: + entrypoint.options.runtime || + /** @type {string | undefined} */ (entrypoint.name), + minAvailableModules: ZERO_BIGINT, + availableModulesToBeMerged: [], + skippedItems: undefined, + resultingAvailableModules: undefined, + children: undefined, + availableSources: undefined, + availableChildren: undefined, + preOrderIndex: 0, + postOrderIndex: 0, + chunkLoading: + entryOptions.chunkLoading !== undefined + ? entryOptions.chunkLoading !== false + : chunkGroupInfo.chunkLoading, + asyncChunks: + entryOptions.asyncChunks !== undefined + ? entryOptions.asyncChunks + : chunkGroupInfo.asyncChunks + }; + chunkGroupInfoMap.set( + entrypoint, + /** @type {ChunkGroupInfo} */ + (cgi) + ); + + chunkGraph.connectBlockAndChunkGroup(b, entrypoint); + if (chunkName) { + namedAsyncEntrypoints.set( + chunkName, + /** @type {ChunkGroupInfo} */ + (cgi) + ); + } + } else { + entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); + // TODO merge entryOptions + entrypoint.addOrigin( + module, + /** @type {DependencyLocation} */ (b.loc), + /** @type {string} */ (b.request) + ); + chunkGraph.connectBlockAndChunkGroup(b, entrypoint); + } + + // 2. We enqueue the DependenciesBlock for traversal + queueDelayed.push({ + action: PROCESS_ENTRY_BLOCK, + block: b, + module, + chunk: entrypoint.chunks[0], + chunkGroup: entrypoint, + chunkGroupInfo: /** @type {ChunkGroupInfo} */ (cgi) + }); + } else if (!chunkGroupInfo.asyncChunks || !chunkGroupInfo.chunkLoading) { + // Just queue the block into the current chunk group + queue.push({ + action: PROCESS_BLOCK, + block: b, + module, + chunk, + chunkGroup, + chunkGroupInfo + }); + } else { + cgi = chunkName ? namedChunkGroups.get(chunkName) : undefined; + if (!cgi) { + c = compilation.addChunkInGroup( + b.groupOptions || b.chunkName, + module, + /** @type {DependencyLocation} */ (b.loc), + /** @type {string} */ (b.request) + ); + maskByChunk.set(c.chunks[0], ZERO_BIGINT); + c.index = nextChunkGroupIndex++; + cgi = { + initialized: false, + chunkGroup: c, + runtime: chunkGroupInfo.runtime, + minAvailableModules: undefined, + availableModulesToBeMerged: [], + skippedItems: undefined, + resultingAvailableModules: undefined, + children: undefined, + availableSources: undefined, + availableChildren: undefined, + preOrderIndex: 0, + postOrderIndex: 0, + chunkLoading: chunkGroupInfo.chunkLoading, + asyncChunks: chunkGroupInfo.asyncChunks + }; + allCreatedChunkGroups.add(c); + chunkGroupInfoMap.set(c, cgi); + if (chunkName) { + namedChunkGroups.set(chunkName, cgi); + } + } else { + c = cgi.chunkGroup; + if (c.isInitial()) { + compilation.errors.push( + new AsyncDependencyToInitialChunkError( + /** @type {string} */ (chunkName), + module, + /** @type {DependencyLocation} */ (b.loc) + ) + ); + c = chunkGroup; + } else { + c.addOptions(b.groupOptions); + } + c.addOrigin( + module, + /** @type {DependencyLocation} */ (b.loc), + /** @type {string} */ (b.request) + ); + } + blockConnections.set(b, []); + } + blockChunkGroups.set(b, /** @type {ChunkGroupInfo} */ (cgi)); + } else if (entryOptions) { + entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); + } else { + c = cgi.chunkGroup; + } + + if (c !== undefined) { + // 2. We store the connection for the block + // to connect it later if needed + /** @type {BlockChunkGroupConnection[]} */ + (blockConnections.get(b)).push({ + originChunkGroupInfo: chunkGroupInfo, + chunkGroup: c + }); + + // 3. We enqueue the chunk group info creation/updating + let connectList = queueConnect.get(chunkGroupInfo); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(chunkGroupInfo, connectList); + } + connectList.add([ + /** @type {ChunkGroupInfo} */ (cgi), + { + action: PROCESS_BLOCK, + block: b, + module, + chunk: c.chunks[0], + chunkGroup: c, + chunkGroupInfo: /** @type {ChunkGroupInfo} */ (cgi) + } + ]); + } else if (entrypoint !== undefined) { + chunkGroupInfo.chunkGroup.addAsyncEntrypoint(entrypoint); + } + }; + + /** + * @param {DependenciesBlock} block the block + * @returns {void} + */ + const processBlock = (block) => { + statProcessedBlocks++; + // get prepared block info + const blockModules = getBlockModules(block, chunkGroupInfo.runtime); + + if (blockModules !== undefined) { + const minAvailableModules = + /** @type {bigint} */ + (chunkGroupInfo.minAvailableModules); + // Buffer items because order need to be reversed to get indices correct + // Traverse all referenced modules + for (let i = 0, len = blockModules.length; i < len; i += 3) { + const refModule = /** @type {Module} */ (blockModules[i]); + // For single comparisons this might be cheaper + const isModuleInChunk = chunkGraph.isModuleInChunk(refModule, chunk); + + if (isModuleInChunk) { + // skip early if already connected + continue; + } + + const refOrdinal = /** @type {number} */ getModuleOrdinal(refModule); + const activeState = /** @type {ConnectionState} */ ( + blockModules[i + 1] + ); + if (activeState !== true) { + const connections = /** @type {ModuleGraphConnection[]} */ ( + blockModules[i + 2] + ); + skipConnectionBuffer.push([refModule, connections]); + // We skip inactive connections + if (activeState === false) continue; + } else if (isOrdinalSetInMask(minAvailableModules, refOrdinal)) { + // already in parent chunks, skip it for now + skipBuffer.push(refModule); + continue; + } + // enqueue, then add and enter to be in the correct order + // this is relevant with circular dependencies + queueBuffer.push({ + action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, + block: refModule, + module: refModule, + chunk, + chunkGroup, + chunkGroupInfo + }); + } + // Add buffered items in reverse order + if (skipConnectionBuffer.length > 0) { + let { skippedModuleConnections } = chunkGroupInfo; + if (skippedModuleConnections === undefined) { + chunkGroupInfo.skippedModuleConnections = skippedModuleConnections = + new Set(); + } + for (let i = skipConnectionBuffer.length - 1; i >= 0; i--) { + skippedModuleConnections.add(skipConnectionBuffer[i]); + } + skipConnectionBuffer.length = 0; + } + if (skipBuffer.length > 0) { + let { skippedItems } = chunkGroupInfo; + if (skippedItems === undefined) { + chunkGroupInfo.skippedItems = skippedItems = new Set(); + } + for (let i = skipBuffer.length - 1; i >= 0; i--) { + skippedItems.add(skipBuffer[i]); + } + skipBuffer.length = 0; + } + if (queueBuffer.length > 0) { + for (let i = queueBuffer.length - 1; i >= 0; i--) { + queue.push(queueBuffer[i]); + } + queueBuffer.length = 0; + } + } + + // Traverse all Blocks + for (const b of block.blocks) { + iteratorBlock(b); + } + + if (block.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); + } + }; + + /** + * @param {DependenciesBlock} block the block + * @returns {void} + */ + const processEntryBlock = (block) => { + statProcessedBlocks++; + // get prepared block info + const blockModules = getBlockModules(block, chunkGroupInfo.runtime); + + if (blockModules !== undefined) { + // Traverse all referenced modules in reverse order + for (let i = blockModules.length - 3; i >= 0; i -= 3) { + const refModule = /** @type {Module} */ (blockModules[i]); + const activeState = /** @type {ConnectionState} */ ( + blockModules[i + 1] + ); + // enqueue, then add and enter to be in the correct order + // this is relevant with circular dependencies + queue.push({ + action: + activeState === true ? ADD_AND_ENTER_ENTRY_MODULE : PROCESS_BLOCK, + block: refModule, + module: refModule, + chunk, + chunkGroup, + chunkGroupInfo + }); + } + } + + // Traverse all Blocks + for (const b of block.blocks) { + iteratorBlock(b); + } + + if (block.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); + } + }; + + const processQueue = () => { + while (queue.length) { + statProcessedQueueItems++; + const queueItem = /** @type {QueueItem} */ (queue.pop()); + module = queueItem.module; + block = queueItem.block; + chunk = queueItem.chunk; + chunkGroup = queueItem.chunkGroup; + chunkGroupInfo = queueItem.chunkGroupInfo; + + switch (queueItem.action) { + case ADD_AND_ENTER_ENTRY_MODULE: + chunkGraph.connectChunkAndEntryModule( + chunk, + module, + /** @type {Entrypoint} */ (chunkGroup) + ); + // fallthrough + case ADD_AND_ENTER_MODULE: { + const isModuleInChunk = chunkGraph.isModuleInChunk(module, chunk); + + if (isModuleInChunk) { + // already connected, skip it + break; + } + // We connect Module and Chunk + chunkGraph.connectChunkAndModule(chunk, module); + const moduleOrdinal = getModuleOrdinal(module); + let chunkMask = /** @type {bigint} */ (maskByChunk.get(chunk)); + chunkMask |= ONE_BIGINT << BigInt(moduleOrdinal); + maskByChunk.set(chunk, chunkMask); + } + // fallthrough + case ENTER_MODULE: { + const index = chunkGroup.getModulePreOrderIndex(module); + if (index === undefined) { + chunkGroup.setModulePreOrderIndex( + module, + chunkGroupInfo.preOrderIndex++ + ); + } + + if ( + moduleGraph.setPreOrderIndexIfUnset( + module, + nextFreeModulePreOrderIndex + ) + ) { + nextFreeModulePreOrderIndex++; + } + + // reuse queueItem + queueItem.action = LEAVE_MODULE; + queue.push(queueItem); + } + // fallthrough + case PROCESS_BLOCK: { + processBlock(block); + break; + } + case PROCESS_ENTRY_BLOCK: { + processEntryBlock(block); + break; + } + case LEAVE_MODULE: { + const index = chunkGroup.getModulePostOrderIndex(module); + if (index === undefined) { + chunkGroup.setModulePostOrderIndex( + module, + chunkGroupInfo.postOrderIndex++ + ); + } + + if ( + moduleGraph.setPostOrderIndexIfUnset( + module, + nextFreeModulePostOrderIndex + ) + ) { + nextFreeModulePostOrderIndex++; + } + break; + } + } + } + }; + + /** + * @param {ChunkGroupInfo} chunkGroupInfo The info object for the chunk group + * @returns {bigint} The mask of available modules after the chunk group + */ + const calculateResultingAvailableModules = (chunkGroupInfo) => { + if (chunkGroupInfo.resultingAvailableModules !== undefined) { + return chunkGroupInfo.resultingAvailableModules; + } + + let resultingAvailableModules = /** @type {bigint} */ ( + chunkGroupInfo.minAvailableModules + ); + + // add the modules from the chunk group to the set + for (const chunk of chunkGroupInfo.chunkGroup.chunks) { + const mask = /** @type {bigint} */ (maskByChunk.get(chunk)); + resultingAvailableModules |= mask; + } + + return (chunkGroupInfo.resultingAvailableModules = + resultingAvailableModules); + }; + + const processConnectQueue = () => { + // Figure out new parents for chunk groups + // to get new available modules for these children + for (const [chunkGroupInfo, targets] of queueConnect) { + // 1. Add new targets to the list of children + if (chunkGroupInfo.children === undefined) { + chunkGroupInfo.children = new Set(); + } + for (const [target] of targets) { + chunkGroupInfo.children.add(target); + } + + // 2. Calculate resulting available modules + const resultingAvailableModules = + calculateResultingAvailableModules(chunkGroupInfo); + + const runtime = chunkGroupInfo.runtime; + + // 3. Update chunk group info + for (const [target, processBlock] of targets) { + target.availableModulesToBeMerged.push(resultingAvailableModules); + chunkGroupsForMerging.add([target, processBlock]); + const oldRuntime = target.runtime; + const newRuntime = mergeRuntime(oldRuntime, runtime); + if (oldRuntime !== newRuntime) { + target.runtime = newRuntime; + outdatedChunkGroupInfo.add(target); + } + } + + statConnectedChunkGroups += targets.size; + } + queueConnect.clear(); + }; + + const processChunkGroupsForMerging = () => { + statProcessedChunkGroupsForMerging += chunkGroupsForMerging.size; + + // Execute the merge + for (const [info, processBlock] of chunkGroupsForMerging) { + const availableModulesToBeMerged = info.availableModulesToBeMerged; + const cachedMinAvailableModules = info.minAvailableModules; + let minAvailableModules = cachedMinAvailableModules; + + statMergedAvailableModuleSets += availableModulesToBeMerged.length; + + for (const availableModules of availableModulesToBeMerged) { + if (minAvailableModules === undefined) { + minAvailableModules = availableModules; + } else { + minAvailableModules &= availableModules; + } + } + + const changed = minAvailableModules !== cachedMinAvailableModules; + + availableModulesToBeMerged.length = 0; + if (changed) { + info.minAvailableModules = minAvailableModules; + info.resultingAvailableModules = undefined; + outdatedChunkGroupInfo.add(info); + } + + if (processBlock) { + let blocks = blocksByChunkGroups.get(info); + if (!blocks) { + blocksByChunkGroups.set(info, (blocks = new Set())); + } + + // Whether to walk block depends on minAvailableModules and input block. + // We can treat creating chunk group as a function with 2 input, entry block and minAvailableModules + // If input is the same, we can skip re-walk + let needWalkBlock = !info.initialized || changed; + if (!blocks.has(processBlock.block)) { + needWalkBlock = true; + blocks.add(processBlock.block); + } + + if (needWalkBlock) { + info.initialized = true; + queueDelayed.push(processBlock); + } + } + } + chunkGroupsForMerging.clear(); + }; + + const processChunkGroupsForCombining = () => { + for (const info of chunkGroupsForCombining) { + for (const source of /** @type {Set} */ ( + info.availableSources + )) { + if (source.minAvailableModules === undefined) { + chunkGroupsForCombining.delete(info); + break; + } + } + } + + for (const info of chunkGroupsForCombining) { + let availableModules = ZERO_BIGINT; + // combine minAvailableModules from all resultingAvailableModules + for (const source of /** @type {Set} */ ( + info.availableSources + )) { + const resultingAvailableModules = + calculateResultingAvailableModules(source); + availableModules |= resultingAvailableModules; + } + info.minAvailableModules = availableModules; + info.resultingAvailableModules = undefined; + outdatedChunkGroupInfo.add(info); + } + chunkGroupsForCombining.clear(); + }; + + const processOutdatedChunkGroupInfo = () => { + statChunkGroupInfoUpdated += outdatedChunkGroupInfo.size; + // Revisit skipped elements + for (const info of outdatedChunkGroupInfo) { + // 1. Reconsider skipped items + if (info.skippedItems !== undefined) { + const minAvailableModules = + /** @type {bigint} */ + (info.minAvailableModules); + for (const module of info.skippedItems) { + const ordinal = getModuleOrdinal(module); + if (!isOrdinalSetInMask(minAvailableModules, ordinal)) { + queue.push({ + action: ADD_AND_ENTER_MODULE, + block: module, + module, + chunk: info.chunkGroup.chunks[0], + chunkGroup: info.chunkGroup, + chunkGroupInfo: info + }); + info.skippedItems.delete(module); + } + } + } + + // 2. Reconsider skipped connections + if (info.skippedModuleConnections !== undefined) { + const minAvailableModules = + /** @type {bigint} */ + (info.minAvailableModules); + for (const entry of info.skippedModuleConnections) { + const [module, connections] = entry; + const activeState = getActiveStateOfConnections( + connections, + info.runtime + ); + if (activeState === false) continue; + if (activeState === true) { + const ordinal = getModuleOrdinal(module); + info.skippedModuleConnections.delete(entry); + if (isOrdinalSetInMask(minAvailableModules, ordinal)) { + /** @type {NonNullable} */ + (info.skippedItems).add(module); + continue; + } + } + queue.push({ + action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, + block: module, + module, + chunk: info.chunkGroup.chunks[0], + chunkGroup: info.chunkGroup, + chunkGroupInfo: info + }); + } + } + + // 2. Reconsider children chunk groups + if (info.children !== undefined) { + statChildChunkGroupsReconnected += info.children.size; + for (const cgi of info.children) { + let connectList = queueConnect.get(info); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(info, connectList); + } + connectList.add([cgi, null]); + } + } + + // 3. Reconsider chunk groups for combining + if (info.availableChildren !== undefined) { + for (const cgi of info.availableChildren) { + chunkGroupsForCombining.add(cgi); + } + } + outdatedOrderIndexChunkGroups.add(info); + } + outdatedChunkGroupInfo.clear(); + }; + + // Iterative traversal of the Module graph + // Recursive would be simpler to write but could result in Stack Overflows + while (queue.length || queueConnect.size) { + logger.time("visitModules: visiting"); + processQueue(); + logger.timeAggregateEnd("visitModules: prepare"); + logger.timeEnd("visitModules: visiting"); + + if (chunkGroupsForCombining.size > 0) { + logger.time("visitModules: combine available modules"); + processChunkGroupsForCombining(); + logger.timeEnd("visitModules: combine available modules"); + } + + if (queueConnect.size > 0) { + logger.time("visitModules: calculating available modules"); + processConnectQueue(); + logger.timeEnd("visitModules: calculating available modules"); + + if (chunkGroupsForMerging.size > 0) { + logger.time("visitModules: merging available modules"); + processChunkGroupsForMerging(); + logger.timeEnd("visitModules: merging available modules"); + } + } + + if (outdatedChunkGroupInfo.size > 0) { + logger.time("visitModules: check modules for revisit"); + processOutdatedChunkGroupInfo(); + logger.timeEnd("visitModules: check modules for revisit"); + } + + // Run queueDelayed when all items of the queue are processed + // This is important to get the global indexing correct + // Async blocks should be processed after all sync blocks are processed + if (queue.length === 0) { + const tempQueue = queue; + queue = queueDelayed.reverse(); + queueDelayed = tempQueue; + } + } + + for (const info of outdatedOrderIndexChunkGroups) { + const { chunkGroup, runtime } = info; + + const blocks = blocksByChunkGroups.get(info); + + if (!blocks) { + continue; + } + + for (const block of blocks) { + let preOrderIndex = 0; + let postOrderIndex = 0; + /** + * @param {DependenciesBlock} current current + * @param {BlocksWithNestedBlocks} visited visited dependencies blocks + */ + const process = (current, visited) => { + const blockModules = + /** @type {BlockModulesInFlattenTuples} */ + (getBlockModules(current, runtime)); + for (let i = 0, len = blockModules.length; i < len; i += 3) { + const activeState = /** @type {ConnectionState} */ ( + blockModules[i + 1] + ); + if (activeState === false) { + continue; + } + const refModule = /** @type {Module} */ (blockModules[i]); + if (visited.has(refModule)) { + continue; + } + + visited.add(refModule); + + if (refModule) { + chunkGroup.setModulePreOrderIndex(refModule, preOrderIndex++); + process(refModule, visited); + chunkGroup.setModulePostOrderIndex(refModule, postOrderIndex++); + } + } + }; + process(block, new Set()); + } + } + outdatedOrderIndexChunkGroups.clear(); + ordinalByModule.clear(); + + logger.log( + `${statProcessedQueueItems} queue items processed (${statProcessedBlocks} blocks)` + ); + logger.log(`${statConnectedChunkGroups} chunk groups connected`); + logger.log( + `${statProcessedChunkGroupsForMerging} chunk groups processed for merging (${statMergedAvailableModuleSets} module sets, ${statForkedAvailableModules} forked, ${statForkedAvailableModulesCount} + ${statForkedAvailableModulesCountPlus} modules forked, ${statForkedMergedModulesCount} + ${statForkedMergedModulesCountPlus} modules merged into fork, ${statForkedResultModulesCount} resulting modules)` + ); + logger.log( + `${statChunkGroupInfoUpdated} chunk group info updated (${statChildChunkGroupsReconnected} already connected chunk groups reconnected)` + ); +}; + +/** + * @param {Compilation} compilation the compilation + * @param {BlocksWithNestedBlocks} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {BlockConnections} blockConnections connection for blocks + * @param {MaskByChunk} maskByChunk mapping from chunk to module mask + */ +const connectChunkGroups = ( + compilation, + blocksWithNestedBlocks, + blockConnections, + maskByChunk +) => { + const { chunkGraph } = compilation; + + /** + * Helper function to check if all modules of a chunk are available + * @param {ChunkGroup} chunkGroup the chunkGroup to scan + * @param {bigint} availableModules the comparator set + * @returns {boolean} return true if all modules of a chunk are available + */ + const areModulesAvailable = (chunkGroup, availableModules) => { + for (const chunk of chunkGroup.chunks) { + const chunkMask = /** @type {bigint} */ (maskByChunk.get(chunk)); + if ((chunkMask & availableModules) !== chunkMask) return false; + } + return true; + }; + + // For each edge in the basic chunk graph + for (const [block, connections] of blockConnections) { + // 1. Check if connection is needed + // When none of the dependencies need to be connected + // we can skip all of them + // It's not possible to filter each item so it doesn't create inconsistent + // connections and modules can only create one version + // TODO maybe decide this per runtime + if ( + // TODO is this needed? + !blocksWithNestedBlocks.has(block) && + connections.every(({ chunkGroup, originChunkGroupInfo }) => + areModulesAvailable( + chunkGroup, + /** @type {bigint} */ (originChunkGroupInfo.resultingAvailableModules) + ) + ) + ) { + continue; + } + + // 2. Foreach edge + for (let i = 0; i < connections.length; i++) { + const { chunkGroup, originChunkGroupInfo } = connections[i]; + + // 3. Connect block with chunk + chunkGraph.connectBlockAndChunkGroup(block, chunkGroup); + + // 4. Connect chunk with parent + connectChunkGroupParentAndChild( + originChunkGroupInfo.chunkGroup, + chunkGroup + ); + } + } +}; + +/** + * Remove all unconnected chunk groups + * @param {Compilation} compilation the compilation + * @param {Iterable} allCreatedChunkGroups all chunk groups that where created before + */ +const cleanupUnconnectedGroups = (compilation, allCreatedChunkGroups) => { + const { chunkGraph } = compilation; + + for (const chunkGroup of allCreatedChunkGroups) { + if (chunkGroup.getNumberOfParents() === 0) { + for (const chunk of chunkGroup.chunks) { + compilation.chunks.delete(chunk); + chunkGraph.disconnectChunk(chunk); + } + chunkGraph.disconnectChunkGroup(chunkGroup); + chunkGroup.remove(); + } + } +}; + +/** + * This method creates the Chunk graph from the Module graph + * @param {Compilation} compilation the compilation + * @param {InputEntrypointsAndModules} inputEntrypointsAndModules chunk groups which are processed with the modules + * @returns {void} + */ +const buildChunkGraph = (compilation, inputEntrypointsAndModules) => { + const logger = compilation.getLogger("webpack.buildChunkGraph"); + + // SHARED STATE + + /** @type {BlockConnections} */ + const blockConnections = new Map(); + + /** @type {AllCreatedChunkGroups} */ + const allCreatedChunkGroups = new Set(); + + /** @type {ChunkGroupInfoMap} */ + const chunkGroupInfoMap = new Map(); + + /** @type {BlocksWithNestedBlocks} */ + const blocksWithNestedBlocks = new Set(); + + /** @type {MaskByChunk} */ + const maskByChunk = new Map(); + + // PART ONE + + logger.time("visitModules"); + visitModules( + logger, + compilation, + inputEntrypointsAndModules, + chunkGroupInfoMap, + blockConnections, + blocksWithNestedBlocks, + allCreatedChunkGroups, + maskByChunk + ); + logger.timeEnd("visitModules"); + + // PART TWO + + logger.time("connectChunkGroups"); + connectChunkGroups( + compilation, + blocksWithNestedBlocks, + blockConnections, + maskByChunk + ); + logger.timeEnd("connectChunkGroups"); + + for (const [chunkGroup, chunkGroupInfo] of chunkGroupInfoMap) { + for (const chunk of chunkGroup.chunks) { + chunk.runtime = mergeRuntime(chunk.runtime, chunkGroupInfo.runtime); + } + } + + // Cleanup work + + logger.time("cleanup"); + cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); + logger.timeEnd("cleanup"); +}; + +module.exports = buildChunkGraph; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/AddBuildDependenciesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/AddBuildDependenciesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7d271e26a5d73d36fdc6cc7c094a8c475d474f6a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/AddBuildDependenciesPlugin.js @@ -0,0 +1,32 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "AddBuildDependenciesPlugin"; + +class AddBuildDependenciesPlugin { + /** + * @param {Iterable} buildDependencies list of build dependencies + */ + constructor(buildDependencies) { + this.buildDependencies = new Set(buildDependencies); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.buildDependencies.addAll(this.buildDependencies); + }); + } +} + +module.exports = AddBuildDependenciesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/AddManagedPathsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/AddManagedPathsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d8e860f5272f0af99e9c590f09f44ee8665d2fb0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/AddManagedPathsPlugin.js @@ -0,0 +1,40 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../Compiler")} Compiler */ + +class AddManagedPathsPlugin { + /** + * @param {Iterable} managedPaths list of managed paths + * @param {Iterable} immutablePaths list of immutable paths + * @param {Iterable} unmanagedPaths list of unmanaged paths + */ + constructor(managedPaths, immutablePaths, unmanagedPaths) { + this.managedPaths = new Set(managedPaths); + this.immutablePaths = new Set(immutablePaths); + this.unmanagedPaths = new Set(unmanagedPaths); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + for (const managedPath of this.managedPaths) { + compiler.managedPaths.add(managedPath); + } + for (const immutablePath of this.immutablePaths) { + compiler.immutablePaths.add(immutablePath); + } + for (const unmanagedPath of this.unmanagedPaths) { + compiler.unmanagedPaths.add(unmanagedPath); + } + } +} + +module.exports = AddManagedPathsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/IdleFileCachePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/IdleFileCachePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..78ef83b99649282c27c6e8e909084c467807f6eb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/IdleFileCachePlugin.js @@ -0,0 +1,242 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Cache = require("../Cache"); +const ProgressPlugin = require("../ProgressPlugin"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("./PackFileCacheStrategy")} PackFileCacheStrategy */ + +const BUILD_DEPENDENCIES_KEY = Symbol("build dependencies key"); +const PLUGIN_NAME = "IdleFileCachePlugin"; + +class IdleFileCachePlugin { + /** + * @param {PackFileCacheStrategy} strategy cache strategy + * @param {number} idleTimeout timeout + * @param {number} idleTimeoutForInitialStore initial timeout + * @param {number} idleTimeoutAfterLargeChanges timeout after changes + */ + constructor( + strategy, + idleTimeout, + idleTimeoutForInitialStore, + idleTimeoutAfterLargeChanges + ) { + this.strategy = strategy; + this.idleTimeout = idleTimeout; + this.idleTimeoutForInitialStore = idleTimeoutForInitialStore; + this.idleTimeoutAfterLargeChanges = idleTimeoutAfterLargeChanges; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const strategy = this.strategy; + const idleTimeout = this.idleTimeout; + const idleTimeoutForInitialStore = Math.min( + idleTimeout, + this.idleTimeoutForInitialStore + ); + const idleTimeoutAfterLargeChanges = this.idleTimeoutAfterLargeChanges; + const resolvedPromise = Promise.resolve(); + + let timeSpendInBuild = 0; + let timeSpendInStore = 0; + let avgTimeSpendInStore = 0; + + /** @type {Map Promise>} */ + const pendingIdleTasks = new Map(); + + compiler.cache.hooks.store.tap( + { name: PLUGIN_NAME, stage: Cache.STAGE_DISK }, + (identifier, etag, data) => { + pendingIdleTasks.set(identifier, () => + strategy.store(identifier, etag, data) + ); + } + ); + + compiler.cache.hooks.get.tapPromise( + { name: PLUGIN_NAME, stage: Cache.STAGE_DISK }, + (identifier, etag, gotHandlers) => { + const restore = () => + strategy.restore(identifier, etag).then((cacheEntry) => { + if (cacheEntry === undefined) { + gotHandlers.push((result, callback) => { + if (result !== undefined) { + pendingIdleTasks.set(identifier, () => + strategy.store(identifier, etag, result) + ); + } + callback(); + }); + } else { + return cacheEntry; + } + }); + const pendingTask = pendingIdleTasks.get(identifier); + if (pendingTask !== undefined) { + pendingIdleTasks.delete(identifier); + return pendingTask().then(restore); + } + return restore(); + } + ); + + compiler.cache.hooks.storeBuildDependencies.tap( + { name: PLUGIN_NAME, stage: Cache.STAGE_DISK }, + (dependencies) => { + pendingIdleTasks.set(BUILD_DEPENDENCIES_KEY, () => + Promise.resolve().then(() => + strategy.storeBuildDependencies(dependencies) + ) + ); + } + ); + + compiler.cache.hooks.shutdown.tapPromise( + { name: PLUGIN_NAME, stage: Cache.STAGE_DISK }, + () => { + if (idleTimer) { + clearTimeout(idleTimer); + idleTimer = undefined; + } + isIdle = false; + const reportProgress = ProgressPlugin.getReporter(compiler); + const jobs = [...pendingIdleTasks.values()]; + if (reportProgress) reportProgress(0, "process pending cache items"); + const promises = jobs.map((fn) => fn()); + pendingIdleTasks.clear(); + promises.push(currentIdlePromise); + const promise = Promise.all(promises); + currentIdlePromise = promise.then(() => strategy.afterAllStored()); + if (reportProgress) { + currentIdlePromise = currentIdlePromise.then(() => { + reportProgress(1, "stored"); + }); + } + return currentIdlePromise.then(() => { + // Reset strategy + if (strategy.clear) strategy.clear(); + }); + } + ); + + /** @type {Promise} */ + let currentIdlePromise = resolvedPromise; + let isIdle = false; + let isInitialStore = true; + const processIdleTasks = () => { + if (isIdle) { + const startTime = Date.now(); + if (pendingIdleTasks.size > 0) { + const promises = [currentIdlePromise]; + const maxTime = startTime + 100; + let maxCount = 100; + for (const [filename, factory] of pendingIdleTasks) { + pendingIdleTasks.delete(filename); + promises.push(factory()); + if (maxCount-- <= 0 || Date.now() > maxTime) break; + } + currentIdlePromise = Promise.all( + /** @type {Promise[]} */ + (promises) + ); + currentIdlePromise.then(() => { + timeSpendInStore += Date.now() - startTime; + // Allow to exit the process between + idleTimer = setTimeout(processIdleTasks, 0); + idleTimer.unref(); + }); + return; + } + currentIdlePromise = currentIdlePromise + .then(async () => { + await strategy.afterAllStored(); + timeSpendInStore += Date.now() - startTime; + avgTimeSpendInStore = + Math.max(avgTimeSpendInStore, timeSpendInStore) * 0.9 + + timeSpendInStore * 0.1; + timeSpendInStore = 0; + timeSpendInBuild = 0; + }) + .catch((err) => { + const logger = compiler.getInfrastructureLogger(PLUGIN_NAME); + logger.warn(`Background tasks during idle failed: ${err.message}`); + logger.debug(err.stack); + }); + isInitialStore = false; + } + }; + /** @type {ReturnType | undefined} */ + let idleTimer; + compiler.cache.hooks.beginIdle.tap( + { name: PLUGIN_NAME, stage: Cache.STAGE_DISK }, + () => { + const isLargeChange = timeSpendInBuild > avgTimeSpendInStore * 2; + if (isInitialStore && idleTimeoutForInitialStore < idleTimeout) { + compiler + .getInfrastructureLogger(PLUGIN_NAME) + .log( + `Initial cache was generated and cache will be persisted in ${ + idleTimeoutForInitialStore / 1000 + }s.` + ); + } else if ( + isLargeChange && + idleTimeoutAfterLargeChanges < idleTimeout + ) { + compiler + .getInfrastructureLogger(PLUGIN_NAME) + .log( + `Spend ${Math.round(timeSpendInBuild) / 1000}s in build and ${ + Math.round(avgTimeSpendInStore) / 1000 + }s in average in cache store. This is considered as large change and cache will be persisted in ${ + idleTimeoutAfterLargeChanges / 1000 + }s.` + ); + } + idleTimer = setTimeout( + () => { + idleTimer = undefined; + isIdle = true; + resolvedPromise.then(processIdleTasks); + }, + Math.min( + isInitialStore ? idleTimeoutForInitialStore : Infinity, + isLargeChange ? idleTimeoutAfterLargeChanges : Infinity, + idleTimeout + ) + ); + idleTimer.unref(); + } + ); + compiler.cache.hooks.endIdle.tap( + { name: PLUGIN_NAME, stage: Cache.STAGE_DISK }, + () => { + if (idleTimer) { + clearTimeout(idleTimer); + idleTimer = undefined; + } + isIdle = false; + } + ); + compiler.hooks.done.tap(PLUGIN_NAME, (stats) => { + // 10% build overhead is ignored, as it's not cacheable + timeSpendInBuild *= 0.9; + timeSpendInBuild += + /** @type {number} */ (stats.endTime) - + /** @type {number} */ (stats.startTime); + }); + } +} + +module.exports = IdleFileCachePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/MemoryCachePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/MemoryCachePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..88248ce2120d949e931de4795e844aaaab8299d5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/MemoryCachePlugin.js @@ -0,0 +1,59 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Cache = require("../Cache"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Cache").Data} Data */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +class MemoryCachePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + /** @type {Map} */ + const cache = new Map(); + compiler.cache.hooks.store.tap( + { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, data) => { + cache.set(identifier, { etag, data }); + } + ); + compiler.cache.hooks.get.tap( + { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, gotHandlers) => { + const cacheEntry = cache.get(identifier); + if (cacheEntry === null) { + return null; + } else if (cacheEntry !== undefined) { + return cacheEntry.etag === etag ? cacheEntry.data : null; + } + gotHandlers.push((result, callback) => { + if (result === undefined) { + cache.set(identifier, null); + } else { + cache.set(identifier, { etag, data: result }); + } + return callback(); + }); + } + ); + compiler.cache.hooks.shutdown.tap( + { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, + () => { + cache.clear(); + } + ); + } +} + +module.exports = MemoryCachePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/MemoryWithGcCachePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/MemoryWithGcCachePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..e42e49eed2f7e65bd222976fec500c98a08a281f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/MemoryWithGcCachePlugin.js @@ -0,0 +1,143 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Cache = require("../Cache"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Cache").Data} Data */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +/** + * @typedef {object} MemoryWithGcCachePluginOptions + * @property {number} maxGenerations max generations + */ + +const PLUGIN_NAME = "MemoryWithGcCachePlugin"; + +class MemoryWithGcCachePlugin { + /** + * @param {MemoryWithGcCachePluginOptions} options options + */ + constructor({ maxGenerations }) { + this._maxGenerations = maxGenerations; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const maxGenerations = this._maxGenerations; + /** @type {Map} */ + const cache = new Map(); + /** @type {Map} */ + const oldCache = new Map(); + let generation = 0; + let cachePosition = 0; + const logger = compiler.getInfrastructureLogger(PLUGIN_NAME); + compiler.hooks.afterDone.tap(PLUGIN_NAME, () => { + generation++; + let clearedEntries = 0; + let lastClearedIdentifier; + // Avoid coverage problems due indirect changes + /* istanbul ignore next */ + for (const [identifier, entry] of oldCache) { + if (entry.until > generation) break; + + oldCache.delete(identifier); + if (cache.get(identifier) === undefined) { + cache.delete(identifier); + clearedEntries++; + lastClearedIdentifier = identifier; + } + } + if (clearedEntries > 0 || oldCache.size > 0) { + logger.log( + `${cache.size - oldCache.size} active entries, ${ + oldCache.size + } recently unused cached entries${ + clearedEntries > 0 + ? `, ${clearedEntries} old unused cache entries removed e. g. ${lastClearedIdentifier}` + : "" + }` + ); + } + let i = (cache.size / maxGenerations) | 0; + let j = cachePosition >= cache.size ? 0 : cachePosition; + cachePosition = j + i; + for (const [identifier, entry] of cache) { + if (j !== 0) { + j--; + continue; + } + if (entry !== undefined) { + // We don't delete the cache entry, but set it to undefined instead + // This reserves the location in the data table and avoids rehashing + // when constantly adding and removing entries. + // It will be deleted when removed from oldCache. + cache.set(identifier, undefined); + oldCache.delete(identifier); + oldCache.set(identifier, { + entry, + until: generation + maxGenerations + }); + if (i-- === 0) break; + } + } + }); + compiler.cache.hooks.store.tap( + { name: PLUGIN_NAME, stage: Cache.STAGE_MEMORY }, + (identifier, etag, data) => { + cache.set(identifier, { etag, data }); + } + ); + compiler.cache.hooks.get.tap( + { name: PLUGIN_NAME, stage: Cache.STAGE_MEMORY }, + (identifier, etag, gotHandlers) => { + const cacheEntry = cache.get(identifier); + if (cacheEntry === null) { + return null; + } else if (cacheEntry !== undefined) { + return cacheEntry.etag === etag ? cacheEntry.data : null; + } + const oldCacheEntry = oldCache.get(identifier); + if (oldCacheEntry !== undefined) { + const cacheEntry = oldCacheEntry.entry; + if (cacheEntry === null) { + oldCache.delete(identifier); + cache.set(identifier, cacheEntry); + return null; + } + if (cacheEntry.etag !== etag) return null; + oldCache.delete(identifier); + cache.set(identifier, cacheEntry); + return cacheEntry.data; + } + gotHandlers.push((result, callback) => { + if (result === undefined) { + cache.set(identifier, null); + } else { + cache.set(identifier, { etag, data: result }); + } + return callback(); + }); + } + ); + compiler.cache.hooks.shutdown.tap( + { name: PLUGIN_NAME, stage: Cache.STAGE_MEMORY }, + () => { + cache.clear(); + oldCache.clear(); + } + ); + } +} + +module.exports = MemoryWithGcCachePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/PackFileCacheStrategy.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/PackFileCacheStrategy.js new file mode 100644 index 0000000000000000000000000000000000000000..0c8ab23e926146e0077058794113e42106dfbe75 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/PackFileCacheStrategy.js @@ -0,0 +1,1553 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const FileSystemInfo = require("../FileSystemInfo"); +const ProgressPlugin = require("../ProgressPlugin"); +const { formatSize } = require("../SizeFormatHelpers"); +const SerializerMiddleware = require("../serialization/SerializerMiddleware"); +const LazySet = require("../util/LazySet"); +const makeSerializable = require("../util/makeSerializable"); +const memoize = require("../util/memoize"); +const { + NOT_SERIALIZABLE, + createFileSerializer +} = require("../util/serialization"); + +/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ +/** @typedef {import("../Cache").Data} Data */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../FileSystemInfo").ResolveBuildDependenciesResult} ResolveBuildDependenciesResult */ +/** @typedef {import("../FileSystemInfo").ResolveResults} ResolveResults */ +/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ +/** @typedef {import("../logging/Logger").Logger} Logger */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ + +/** @typedef {Set} Items */ +/** @typedef {Set} BuildDependencies */ +/** @typedef {Map} ItemInfo */ + +class PackContainer { + /** + * @param {Pack} data stored data + * @param {string} version version identifier + * @param {Snapshot} buildSnapshot snapshot of all build dependencies + * @param {BuildDependencies} buildDependencies list of all unresolved build dependencies captured + * @param {ResolveResults} resolveResults result of the resolved build dependencies + * @param {Snapshot} resolveBuildDependenciesSnapshot snapshot of the dependencies of the build dependencies resolving + */ + constructor( + data, + version, + buildSnapshot, + buildDependencies, + resolveResults, + resolveBuildDependenciesSnapshot + ) { + this.data = data; + this.version = version; + this.buildSnapshot = buildSnapshot; + this.buildDependencies = buildDependencies; + this.resolveResults = resolveResults; + this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize({ write, writeLazy }) { + write(this.version); + write(this.buildSnapshot); + write(this.buildDependencies); + write(this.resolveResults); + write(this.resolveBuildDependenciesSnapshot); + /** @type {NonNullable} */ + (writeLazy)(this.data); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize({ read }) { + this.version = read(); + this.buildSnapshot = read(); + this.buildDependencies = read(); + this.resolveResults = read(); + this.resolveBuildDependenciesSnapshot = read(); + this.data = read(); + } +} + +makeSerializable( + PackContainer, + "webpack/lib/cache/PackFileCacheStrategy", + "PackContainer" +); + +const MIN_CONTENT_SIZE = 1024 * 1024; // 1 MB +const CONTENT_COUNT_TO_MERGE = 10; +const MIN_ITEMS_IN_FRESH_PACK = 100; +const MAX_ITEMS_IN_FRESH_PACK = 50000; +const MAX_TIME_IN_FRESH_PACK = 1 * 60 * 1000; // 1 min + +class PackItemInfo { + /** + * @param {string} identifier identifier of item + * @param {string | null | undefined} etag etag of item + * @param {Data} value fresh value of item + */ + constructor(identifier, etag, value) { + this.identifier = identifier; + this.etag = etag; + this.location = -1; + this.lastAccess = Date.now(); + this.freshValue = value; + } +} + +class Pack { + /** + * @param {Logger} logger a logger + * @param {number} maxAge max age of cache items + */ + constructor(logger, maxAge) { + /** @type {ItemInfo} */ + this.itemInfo = new Map(); + /** @type {(string | undefined)[]} */ + this.requests = []; + this.requestsTimeout = undefined; + /** @type {ItemInfo} */ + this.freshContent = new Map(); + /** @type {(undefined | PackContent)[]} */ + this.content = []; + this.invalid = false; + this.logger = logger; + this.maxAge = maxAge; + } + + /** + * @param {string} identifier identifier + */ + _addRequest(identifier) { + this.requests.push(identifier); + if (this.requestsTimeout === undefined) { + this.requestsTimeout = setTimeout(() => { + this.requests.push(undefined); + this.requestsTimeout = undefined; + }, MAX_TIME_IN_FRESH_PACK); + if (this.requestsTimeout.unref) this.requestsTimeout.unref(); + } + } + + stopCapturingRequests() { + if (this.requestsTimeout !== undefined) { + clearTimeout(this.requestsTimeout); + this.requestsTimeout = undefined; + } + } + + /** + * @param {string} identifier unique name for the resource + * @param {string | null} etag etag of the resource + * @returns {Data} cached content + */ + get(identifier, etag) { + const info = this.itemInfo.get(identifier); + this._addRequest(identifier); + if (info === undefined) { + return; + } + if (info.etag !== etag) return null; + info.lastAccess = Date.now(); + const loc = info.location; + if (loc === -1) { + return info.freshValue; + } + if (!this.content[loc]) { + return; + } + return /** @type {PackContent} */ (this.content[loc]).get(identifier); + } + + /** + * @param {string} identifier unique name for the resource + * @param {string | null} etag etag of the resource + * @param {Data} data cached content + * @returns {void} + */ + set(identifier, etag, data) { + if (!this.invalid) { + this.invalid = true; + this.logger.log(`Pack got invalid because of write to: ${identifier}`); + } + const info = this.itemInfo.get(identifier); + if (info === undefined) { + const newInfo = new PackItemInfo(identifier, etag, data); + this.itemInfo.set(identifier, newInfo); + this._addRequest(identifier); + this.freshContent.set(identifier, newInfo); + } else { + const loc = info.location; + if (loc >= 0) { + this._addRequest(identifier); + this.freshContent.set(identifier, info); + const content = /** @type {PackContent} */ (this.content[loc]); + content.delete(identifier); + if (content.items.size === 0) { + this.content[loc] = undefined; + this.logger.debug("Pack %d got empty and is removed", loc); + } + } + info.freshValue = data; + info.lastAccess = Date.now(); + info.etag = etag; + info.location = -1; + } + } + + getContentStats() { + let count = 0; + let size = 0; + for (const content of this.content) { + if (content !== undefined) { + count++; + const s = content.getSize(); + if (s > 0) { + size += s; + } + } + } + return { count, size }; + } + + /** + * @returns {number} new location of data entries + */ + _findLocation() { + let i; + for (i = 0; i < this.content.length && this.content[i] !== undefined; i++); + return i; + } + + /** + * @private + * @param {Items} items items + * @param {Items} usedItems used items + * @param {number} newLoc new location + */ + _gcAndUpdateLocation(items, usedItems, newLoc) { + let count = 0; + let lastGC; + const now = Date.now(); + for (const identifier of items) { + const info = /** @type {PackItemInfo} */ (this.itemInfo.get(identifier)); + if (now - info.lastAccess > this.maxAge) { + this.itemInfo.delete(identifier); + items.delete(identifier); + usedItems.delete(identifier); + count++; + lastGC = identifier; + } else { + info.location = newLoc; + } + } + if (count > 0) { + this.logger.log( + "Garbage Collected %d old items at pack %d (%d items remaining) e. g. %s", + count, + newLoc, + items.size, + lastGC + ); + } + } + + _persistFreshContent() { + /** @typedef {{ items: Items, map: Content, loc: number }} PackItem */ + const itemsCount = this.freshContent.size; + if (itemsCount > 0) { + const packCount = Math.ceil(itemsCount / MAX_ITEMS_IN_FRESH_PACK); + const itemsPerPack = Math.ceil(itemsCount / packCount); + /** @type {PackItem[]} */ + const packs = []; + let i = 0; + let ignoreNextTimeTick = false; + const createNextPack = () => { + const loc = this._findLocation(); + this.content[loc] = /** @type {EXPECTED_ANY} */ (null); // reserve + /** @type {PackItem} */ + const pack = { + items: new Set(), + map: new Map(), + loc + }; + packs.push(pack); + return pack; + }; + let pack = createNextPack(); + if (this.requestsTimeout !== undefined) { + clearTimeout(this.requestsTimeout); + } + for (const identifier of this.requests) { + if (identifier === undefined) { + if (ignoreNextTimeTick) { + ignoreNextTimeTick = false; + } else if (pack.items.size >= MIN_ITEMS_IN_FRESH_PACK) { + i = 0; + pack = createNextPack(); + } + continue; + } + const info = this.freshContent.get(identifier); + if (info === undefined) continue; + pack.items.add(identifier); + pack.map.set(identifier, info.freshValue); + info.location = pack.loc; + info.freshValue = undefined; + this.freshContent.delete(identifier); + if (++i > itemsPerPack) { + i = 0; + pack = createNextPack(); + ignoreNextTimeTick = true; + } + } + this.requests.length = 0; + for (const pack of packs) { + this.content[pack.loc] = new PackContent( + pack.items, + new Set(pack.items), + new PackContentItems(pack.map) + ); + } + this.logger.log( + `${itemsCount} fresh items in cache put into pack ${ + packs.length > 1 + ? packs + .map((pack) => `${pack.loc} (${pack.items.size} items)`) + .join(", ") + : packs[0].loc + }` + ); + } + } + + /** + * Merges small content files to a single content file + */ + _optimizeSmallContent() { + // 1. Find all small content files + // Treat unused content files separately to avoid + // a merge-split cycle + /** @type {number[]} */ + const smallUsedContents = []; + /** @type {number} */ + let smallUsedContentSize = 0; + /** @type {number[]} */ + const smallUnusedContents = []; + /** @type {number} */ + let smallUnusedContentSize = 0; + for (let i = 0; i < this.content.length; i++) { + const content = this.content[i]; + if (content === undefined) continue; + if (content.outdated) continue; + const size = content.getSize(); + if (size < 0 || size > MIN_CONTENT_SIZE) continue; + if (content.used.size > 0) { + smallUsedContents.push(i); + smallUsedContentSize += size; + } else { + smallUnusedContents.push(i); + smallUnusedContentSize += size; + } + } + + // 2. Check if minimum number is reached + let mergedIndices; + if ( + smallUsedContents.length >= CONTENT_COUNT_TO_MERGE || + smallUsedContentSize > MIN_CONTENT_SIZE + ) { + mergedIndices = smallUsedContents; + } else if ( + smallUnusedContents.length >= CONTENT_COUNT_TO_MERGE || + smallUnusedContentSize > MIN_CONTENT_SIZE + ) { + mergedIndices = smallUnusedContents; + } else { + return; + } + + /** @type {PackContent[] } */ + const mergedContent = []; + + // 3. Remove old content entries + for (const i of mergedIndices) { + mergedContent.push(/** @type {PackContent} */ (this.content[i])); + this.content[i] = undefined; + } + + // 4. Determine merged items + /** @type {Items} */ + const mergedItems = new Set(); + /** @type {Items} */ + const mergedUsedItems = new Set(); + /** @type {((map: Content) => Promise)[]} */ + const addToMergedMap = []; + for (const content of mergedContent) { + for (const identifier of content.items) { + mergedItems.add(identifier); + } + for (const identifier of content.used) { + mergedUsedItems.add(identifier); + } + addToMergedMap.push(async (map) => { + // unpack existing content + // after that values are accessible in .content + await content.unpack( + "it should be merged with other small pack contents" + ); + for (const [identifier, value] of /** @type {Content} */ ( + content.content + )) { + map.set(identifier, value); + } + }); + } + + // 5. GC and update location of merged items + const newLoc = this._findLocation(); + this._gcAndUpdateLocation(mergedItems, mergedUsedItems, newLoc); + + // 6. If not empty, store content somewhere + if (mergedItems.size > 0) { + this.content[newLoc] = new PackContent( + mergedItems, + mergedUsedItems, + memoize(async () => { + /** @type {Content} */ + const map = new Map(); + await Promise.all(addToMergedMap.map((fn) => fn(map))); + return new PackContentItems(map); + }) + ); + this.logger.log( + "Merged %d small files with %d cache items into pack %d", + mergedContent.length, + mergedItems.size, + newLoc + ); + } + } + + /** + * Split large content files with used and unused items + * into two parts to separate used from unused items + */ + _optimizeUnusedContent() { + // 1. Find a large content file with used and unused items + for (let i = 0; i < this.content.length; i++) { + const content = this.content[i]; + if (content === undefined) continue; + const size = content.getSize(); + if (size < MIN_CONTENT_SIZE) continue; + const used = content.used.size; + const total = content.items.size; + if (used > 0 && used < total) { + // 2. Remove this content + this.content[i] = undefined; + + // 3. Determine items for the used content file + const usedItems = new Set(content.used); + const newLoc = this._findLocation(); + this._gcAndUpdateLocation(usedItems, usedItems, newLoc); + + // 4. Create content file for used items + if (usedItems.size > 0) { + this.content[newLoc] = new PackContent( + usedItems, + new Set(usedItems), + async () => { + await content.unpack( + "it should be splitted into used and unused items" + ); + /** @type {Content} */ + const map = new Map(); + for (const identifier of usedItems) { + map.set( + identifier, + /** @type {Content} */ + (content.content).get(identifier) + ); + } + return new PackContentItems(map); + } + ); + } + + // 5. Determine items for the unused content file + const unusedItems = new Set(content.items); + const usedOfUnusedItems = new Set(); + for (const identifier of usedItems) { + unusedItems.delete(identifier); + } + const newUnusedLoc = this._findLocation(); + this._gcAndUpdateLocation(unusedItems, usedOfUnusedItems, newUnusedLoc); + + // 6. Create content file for unused items + if (unusedItems.size > 0) { + this.content[newUnusedLoc] = new PackContent( + unusedItems, + usedOfUnusedItems, + async () => { + await content.unpack( + "it should be splitted into used and unused items" + ); + const map = new Map(); + for (const identifier of unusedItems) { + map.set( + identifier, + /** @type {Content} */ + (content.content).get(identifier) + ); + } + return new PackContentItems(map); + } + ); + } + + this.logger.log( + "Split pack %d into pack %d with %d used items and pack %d with %d unused items", + i, + newLoc, + usedItems.size, + newUnusedLoc, + unusedItems.size + ); + + // optimizing only one of them is good enough and + // reduces the amount of serialization needed + return; + } + } + } + + /** + * Find the content with the oldest item and run GC on that. + * Only runs for one content to avoid large invalidation. + */ + _gcOldestContent() { + /** @type {PackItemInfo | undefined} */ + let oldest; + for (const info of this.itemInfo.values()) { + if (oldest === undefined || info.lastAccess < oldest.lastAccess) { + oldest = info; + } + } + if ( + Date.now() - /** @type {PackItemInfo} */ (oldest).lastAccess > + this.maxAge + ) { + const loc = /** @type {PackItemInfo} */ (oldest).location; + if (loc < 0) return; + const content = /** @type {PackContent} */ (this.content[loc]); + const items = new Set(content.items); + const usedItems = new Set(content.used); + this._gcAndUpdateLocation(items, usedItems, loc); + + this.content[loc] = + items.size > 0 + ? new PackContent(items, usedItems, async () => { + await content.unpack( + "it contains old items that should be garbage collected" + ); + const map = new Map(); + for (const identifier of items) { + map.set( + identifier, + /** @type {Content} */ + (content.content).get(identifier) + ); + } + return new PackContentItems(map); + }) + : undefined; + } + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize({ write, writeSeparate }) { + this._persistFreshContent(); + this._optimizeSmallContent(); + this._optimizeUnusedContent(); + this._gcOldestContent(); + for (const identifier of this.itemInfo.keys()) { + write(identifier); + } + write(null); // null as marker of the end of keys + for (const info of this.itemInfo.values()) { + write(info.etag); + } + for (const info of this.itemInfo.values()) { + write(info.lastAccess); + } + for (let i = 0; i < this.content.length; i++) { + const content = this.content[i]; + if (content !== undefined) { + write(content.items); + content.writeLazy((lazy) => + /** @type {NonNullable} */ + (writeSeparate)(lazy, { name: `${i}` }) + ); + } else { + write(undefined); // undefined marks an empty content slot + } + } + write(null); // null as marker of the end of items + } + + /** + * @param {ObjectDeserializerContext & { logger: Logger }} context context + */ + deserialize({ read, logger }) { + this.logger = logger; + { + const items = []; + let item = read(); + while (item !== null) { + items.push(item); + item = read(); + } + this.itemInfo.clear(); + const infoItems = items.map((identifier) => { + const info = new PackItemInfo(identifier, undefined, undefined); + this.itemInfo.set(identifier, info); + return info; + }); + for (const info of infoItems) { + info.etag = read(); + } + for (const info of infoItems) { + info.lastAccess = read(); + } + } + this.content.length = 0; + let items = read(); + while (items !== null) { + if (items === undefined) { + this.content.push(items); + } else { + const idx = this.content.length; + const lazy = read(); + this.content.push( + new PackContent( + items, + new Set(), + lazy, + logger, + `${this.content.length}` + ) + ); + for (const identifier of items) { + /** @type {PackItemInfo} */ + (this.itemInfo.get(identifier)).location = idx; + } + } + items = read(); + } + } +} + +makeSerializable(Pack, "webpack/lib/cache/PackFileCacheStrategy", "Pack"); + +/** @typedef {Map} Content */ + +class PackContentItems { + /** + * @param {Content} map items + */ + constructor(map) { + this.map = map; + } + + /** + * @param {ObjectSerializerContext & { logger: Logger, profile: boolean | undefined }} context context + */ + serialize({ write, snapshot, rollback, logger, profile }) { + if (profile) { + write(false); + for (const [key, value] of this.map) { + const s = snapshot(); + try { + write(key); + const start = process.hrtime(); + write(value); + const durationHr = process.hrtime(start); + const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; + if (duration > 1) { + if (duration > 500) { + logger.error(`Serialization of '${key}': ${duration} ms`); + } else if (duration > 50) { + logger.warn(`Serialization of '${key}': ${duration} ms`); + } else if (duration > 10) { + logger.info(`Serialization of '${key}': ${duration} ms`); + } else if (duration > 5) { + logger.log(`Serialization of '${key}': ${duration} ms`); + } else { + logger.debug(`Serialization of '${key}': ${duration} ms`); + } + } + } catch (err) { + rollback(s); + if (err === NOT_SERIALIZABLE) continue; + const msg = "Skipped not serializable cache item"; + const notSerializableErr = /** @type {Error} */ (err); + if (notSerializableErr.message.includes("ModuleBuildError")) { + logger.log( + `${msg} (in build error): ${notSerializableErr.message}` + ); + logger.debug( + `${msg} '${key}' (in build error): ${notSerializableErr.stack}` + ); + } else { + logger.warn(`${msg}: ${notSerializableErr.message}`); + logger.debug(`${msg} '${key}': ${notSerializableErr.stack}`); + } + } + } + write(null); + return; + } + // Try to serialize all at once + const s = snapshot(); + try { + write(true); + write(this.map); + } catch (_err) { + rollback(s); + + // Try to serialize each item on it's own + write(false); + for (const [key, value] of this.map) { + const s = snapshot(); + try { + write(key); + write(value); + } catch (err) { + rollback(s); + if (err === NOT_SERIALIZABLE) continue; + const notSerializableErr = /** @type {Error} */ (err); + logger.warn( + `Skipped not serializable cache item '${key}': ${notSerializableErr.message}` + ); + logger.debug(notSerializableErr.stack); + } + } + write(null); + } + } + + /** + * @param {ObjectDeserializerContext & { logger: Logger, profile: boolean | undefined }} context context + */ + deserialize({ read, logger, profile }) { + if (read()) { + this.map = read(); + } else if (profile) { + const map = new Map(); + let key = read(); + while (key !== null) { + const start = process.hrtime(); + const value = read(); + const durationHr = process.hrtime(start); + const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; + if (duration > 1) { + if (duration > 100) { + logger.error(`Deserialization of '${key}': ${duration} ms`); + } else if (duration > 20) { + logger.warn(`Deserialization of '${key}': ${duration} ms`); + } else if (duration > 5) { + logger.info(`Deserialization of '${key}': ${duration} ms`); + } else if (duration > 2) { + logger.log(`Deserialization of '${key}': ${duration} ms`); + } else { + logger.debug(`Deserialization of '${key}': ${duration} ms`); + } + } + map.set(key, value); + key = read(); + } + this.map = map; + } else { + const map = new Map(); + let key = read(); + while (key !== null) { + map.set(key, read()); + key = read(); + } + this.map = map; + } + } +} + +makeSerializable( + PackContentItems, + "webpack/lib/cache/PackFileCacheStrategy", + "PackContentItems" +); + +/** @typedef {(() => Promise | PackContentItems) & Partial<{ options: { size?: number }}>} LazyFunction */ + +class PackContent { + /* + This class can be in these states: + | this.lazy | this.content | this.outdated | state + A1 | undefined | Map | false | fresh content + A2 | undefined | Map | true | (will not happen) + B1 | lazy () => {} | undefined | false | not deserialized + B2 | lazy () => {} | undefined | true | not deserialized, but some items has been removed + C1 | lazy* () => {} | Map | false | deserialized + C2 | lazy* () => {} | Map | true | deserialized, and some items has been removed + + this.used is a subset of this.items. + this.items is a subset of this.content.keys() resp. this.lazy().map.keys() + When this.outdated === false, this.items === this.content.keys() resp. this.lazy().map.keys() + When this.outdated === true, this.items should be used to recreated this.lazy/this.content. + When this.lazy and this.content is set, they contain the same data. + this.get must only be called with a valid item from this.items. + In state C this.lazy is unMemoized + */ + + /** + * @param {Items} items keys + * @param {Items} usedItems used keys + * @param {PackContentItems | (() => Promise)} dataOrFn sync or async content + * @param {Logger=} logger logger for logging + * @param {string=} lazyName name of dataOrFn for logging + */ + constructor(items, usedItems, dataOrFn, logger, lazyName) { + this.items = items; + /** @type {LazyFunction | undefined} */ + this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined; + /** @type {Content | undefined} */ + this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map; + this.outdated = false; + this.used = usedItems; + this.logger = logger; + this.lazyName = lazyName; + } + + /** + * @param {string} identifier identifier + * @returns {string | Promise} result + */ + get(identifier) { + this.used.add(identifier); + if (this.content) { + return this.content.get(identifier); + } + + const logger = /** @type {Logger} */ (this.logger); + // We are in state B + const { lazyName } = this; + /** @type {string | undefined} */ + let timeMessage; + if (lazyName) { + // only log once + this.lazyName = undefined; + timeMessage = `restore cache content ${lazyName} (${formatSize( + this.getSize() + )})`; + logger.log( + `starting to restore cache content ${lazyName} (${formatSize( + this.getSize() + )}) because of request to: ${identifier}` + ); + logger.time(timeMessage); + } + const value = /** @type {LazyFunction} */ (this.lazy)(); + if ("then" in value) { + return value.then((data) => { + const map = data.map; + if (timeMessage) { + logger.timeEnd(timeMessage); + } + // Move to state C + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + return map.get(identifier); + }); + } + + const map = value.map; + if (timeMessage) { + logger.timeEnd(timeMessage); + } + // Move to state C + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + return map.get(identifier); + } + + /** + * @param {string} reason explanation why unpack is necessary + * @returns {void | Promise} maybe a promise if lazy + */ + unpack(reason) { + if (this.content) return; + + const logger = /** @type {Logger} */ (this.logger); + // Move from state B to C + if (this.lazy) { + const { lazyName } = this; + /** @type {string | undefined} */ + let timeMessage; + if (lazyName) { + // only log once + this.lazyName = undefined; + timeMessage = `unpack cache content ${lazyName} (${formatSize( + this.getSize() + )})`; + logger.log( + `starting to unpack cache content ${lazyName} (${formatSize( + this.getSize() + )}) because ${reason}` + ); + logger.time(timeMessage); + } + const value = + /** @type {PackContentItems | Promise} */ + (this.lazy()); + if ("then" in value) { + return value.then((data) => { + if (timeMessage) { + logger.timeEnd(timeMessage); + } + this.content = data.map; + }); + } + if (timeMessage) { + logger.timeEnd(timeMessage); + } + this.content = value.map; + } + } + + /** + * @returns {number} size of the content or -1 if not known + */ + getSize() { + if (!this.lazy) return -1; + const options = + /** @type {{ options: { size?: number } }} */ + (this.lazy).options; + if (!options) return -1; + const size = options.size; + if (typeof size !== "number") return -1; + return size; + } + + /** + * @param {string} identifier identifier + */ + delete(identifier) { + this.items.delete(identifier); + this.used.delete(identifier); + this.outdated = true; + } + + /** + * @param {(lazy: LazyFunction) => (() => PackContentItems | Promise)} write write function + * @returns {void} + */ + writeLazy(write) { + if (!this.outdated && this.lazy) { + // State B1 or C1 + // this.lazy is still the valid deserialized version + write(this.lazy); + return; + } + if (!this.outdated && this.content) { + // State A1 + const map = new Map(this.content); + // Move to state C1 + this.lazy = SerializerMiddleware.unMemoizeLazy( + write(() => new PackContentItems(map)) + ); + return; + } + if (this.content) { + // State A2 or C2 + /** @type {Content} */ + const map = new Map(); + for (const item of this.items) { + map.set(item, this.content.get(item)); + } + // Move to state C1 + this.outdated = false; + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy( + write(() => new PackContentItems(map)) + ); + return; + } + const logger = /** @type {Logger} */ (this.logger); + // State B2 + const { lazyName } = this; + /** @type {string | undefined} */ + let timeMessage; + if (lazyName) { + // only log once + this.lazyName = undefined; + timeMessage = `unpack cache content ${lazyName} (${formatSize( + this.getSize() + )})`; + logger.log( + `starting to unpack cache content ${lazyName} (${formatSize( + this.getSize() + )}) because it's outdated and need to be serialized` + ); + logger.time(timeMessage); + } + const value = /** @type {LazyFunction} */ (this.lazy)(); + this.outdated = false; + if ("then" in value) { + // Move to state B1 + this.lazy = write(() => + value.then((data) => { + if (timeMessage) { + logger.timeEnd(timeMessage); + } + const oldMap = data.map; + /** @type {Content} */ + const map = new Map(); + for (const item of this.items) { + map.set(item, oldMap.get(item)); + } + // Move to state C1 (or maybe C2) + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + + return new PackContentItems(map); + }) + ); + } else { + // Move to state C1 + if (timeMessage) { + logger.timeEnd(timeMessage); + } + const oldMap = value.map; + /** @type {Content} */ + const map = new Map(); + for (const item of this.items) { + map.set(item, oldMap.get(item)); + } + this.content = map; + this.lazy = write(() => new PackContentItems(map)); + } + } +} + +/** + * @param {Buffer} buf buffer + * @returns {Buffer} buffer that can be collected + */ +const allowCollectingMemory = (buf) => { + const wasted = buf.buffer.byteLength - buf.byteLength; + if (wasted > 8192 && (wasted > 1048576 || wasted > buf.byteLength)) { + return Buffer.from(buf); + } + return buf; +}; + +class PackFileCacheStrategy { + /** + * @param {object} options options + * @param {Compiler} options.compiler the compiler + * @param {IntermediateFileSystem} options.fs the filesystem + * @param {string} options.context the context directory + * @param {string} options.cacheLocation the location of the cache data + * @param {string} options.version version identifier + * @param {Logger} options.logger a logger + * @param {SnapshotOptions} options.snapshot options regarding snapshotting + * @param {number} options.maxAge max age of cache items + * @param {boolean | undefined} options.profile track and log detailed timing information for individual cache items + * @param {boolean | undefined} options.allowCollectingMemory allow to collect unused memory created during deserialization + * @param {false | "gzip" | "brotli" | undefined} options.compression compression used + * @param {boolean | undefined} options.readonly disable storing cache into filesystem + */ + constructor({ + compiler, + fs, + context, + cacheLocation, + version, + logger, + snapshot, + maxAge, + profile, + allowCollectingMemory, + compression, + readonly + }) { + /** @type {import("../serialization/Serializer")} */ + this.fileSerializer = createFileSerializer( + fs, + /** @type {string | Hash} */ + (compiler.options.output.hashFunction) + ); + this.fileSystemInfo = new FileSystemInfo(fs, { + managedPaths: snapshot.managedPaths, + immutablePaths: snapshot.immutablePaths, + logger: logger.getChildLogger("webpack.FileSystemInfo"), + hashFunction: compiler.options.output.hashFunction + }); + this.compiler = compiler; + this.context = context; + this.cacheLocation = cacheLocation; + this.version = version; + this.logger = logger; + this.maxAge = maxAge; + this.profile = profile; + this.readonly = readonly; + this.allowCollectingMemory = allowCollectingMemory; + this.compression = compression; + this._extension = + compression === "brotli" + ? ".pack.br" + : compression === "gzip" + ? ".pack.gz" + : ".pack"; + this.snapshot = snapshot; + /** @type {BuildDependencies} */ + this.buildDependencies = new Set(); + /** @type {LazySet} */ + this.newBuildDependencies = new LazySet(); + /** @type {Snapshot | undefined} */ + this.resolveBuildDependenciesSnapshot = undefined; + /** @type {ResolveResults | undefined} */ + this.resolveResults = undefined; + /** @type {Snapshot | undefined} */ + this.buildSnapshot = undefined; + /** @type {Promise | undefined} */ + this.packPromise = this._openPack(); + this.storePromise = Promise.resolve(); + } + + /** + * @returns {Promise} pack + */ + _getPack() { + if (this.packPromise === undefined) { + this.packPromise = this.storePromise.then(() => this._openPack()); + } + return this.packPromise; + } + + /** + * @returns {Promise} the pack + */ + _openPack() { + const { logger, profile, cacheLocation, version } = this; + /** @type {Snapshot} */ + let buildSnapshot; + /** @type {BuildDependencies} */ + let buildDependencies; + /** @type {BuildDependencies} */ + let newBuildDependencies; + /** @type {Snapshot} */ + let resolveBuildDependenciesSnapshot; + /** @type {ResolveResults | undefined} */ + let resolveResults; + logger.time("restore cache container"); + return this.fileSerializer + .deserialize(null, { + filename: `${cacheLocation}/index${this._extension}`, + extension: `${this._extension}`, + logger, + profile, + retainedBuffer: this.allowCollectingMemory + ? allowCollectingMemory + : undefined + }) + .catch((err) => { + if (err.code !== "ENOENT") { + logger.warn( + `Restoring pack failed from ${cacheLocation}${this._extension}: ${err}` + ); + logger.debug(err.stack); + } else { + logger.debug( + `No pack exists at ${cacheLocation}${this._extension}: ${err}` + ); + } + return undefined; + }) + .then((packContainer) => { + logger.timeEnd("restore cache container"); + if (!packContainer) return; + if (!(packContainer instanceof PackContainer)) { + logger.warn( + `Restored pack from ${cacheLocation}${this._extension}, but contained content is unexpected.`, + packContainer + ); + return; + } + if (packContainer.version !== version) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but version doesn't match.` + ); + return; + } + logger.time("check build dependencies"); + return Promise.all([ + new Promise((resolve, _reject) => { + this.fileSystemInfo.checkSnapshotValid( + packContainer.buildSnapshot, + (err, valid) => { + if (err) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of build dependencies errored: ${err}.` + ); + logger.debug(err.stack); + return resolve(false); + } + if (!valid) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but build dependencies have changed.` + ); + return resolve(false); + } + buildSnapshot = packContainer.buildSnapshot; + return resolve(true); + } + ); + }), + new Promise((resolve, _reject) => { + this.fileSystemInfo.checkSnapshotValid( + packContainer.resolveBuildDependenciesSnapshot, + (err, valid) => { + if (err) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of resolving of build dependencies errored: ${err}.` + ); + logger.debug(err.stack); + return resolve(false); + } + if (valid) { + resolveBuildDependenciesSnapshot = + packContainer.resolveBuildDependenciesSnapshot; + buildDependencies = packContainer.buildDependencies; + resolveResults = packContainer.resolveResults; + return resolve(true); + } + logger.log( + "resolving of build dependencies is invalid, will re-resolve build dependencies" + ); + this.fileSystemInfo.checkResolveResultsValid( + packContainer.resolveResults, + (err, valid) => { + if (err) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but resolving of build dependencies errored: ${err}.` + ); + logger.debug(err.stack); + return resolve(false); + } + if (valid) { + newBuildDependencies = packContainer.buildDependencies; + resolveResults = packContainer.resolveResults; + return resolve(true); + } + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but build dependencies resolve to different locations.` + ); + return resolve(false); + } + ); + } + ); + }) + ]) + .catch((err) => { + logger.timeEnd("check build dependencies"); + throw err; + }) + .then(([buildSnapshotValid, resolveValid]) => { + logger.timeEnd("check build dependencies"); + if (buildSnapshotValid && resolveValid) { + logger.time("restore cache content metadata"); + const d = /** @type {TODO} */ (packContainer).data(); + logger.timeEnd("restore cache content metadata"); + return d; + } + return undefined; + }); + }) + .then((pack) => { + if (pack) { + pack.maxAge = this.maxAge; + this.buildSnapshot = buildSnapshot; + if (buildDependencies) this.buildDependencies = buildDependencies; + if (newBuildDependencies) { + this.newBuildDependencies.addAll(newBuildDependencies); + } + this.resolveResults = resolveResults; + this.resolveBuildDependenciesSnapshot = + resolveBuildDependenciesSnapshot; + return pack; + } + return new Pack(logger, this.maxAge); + }) + .catch((err) => { + this.logger.warn( + `Restoring pack from ${cacheLocation}${this._extension} failed: ${err}` + ); + this.logger.debug(err.stack); + return new Pack(logger, this.maxAge); + }); + } + + /** + * @param {string} identifier unique name for the resource + * @param {Etag | null} etag etag of the resource + * @param {Data} data cached content + * @returns {Promise} promise + */ + store(identifier, etag, data) { + if (this.readonly) return Promise.resolve(); + + return this._getPack().then((pack) => { + pack.set(identifier, etag === null ? null : etag.toString(), data); + }); + } + + /** + * @param {string} identifier unique name for the resource + * @param {Etag | null} etag etag of the resource + * @returns {Promise} promise to the cached content + */ + restore(identifier, etag) { + return this._getPack() + .then((pack) => + pack.get(identifier, etag === null ? null : etag.toString()) + ) + .catch((err) => { + if (err && err.code !== "ENOENT") { + this.logger.warn( + `Restoring failed for ${identifier} from pack: ${err}` + ); + this.logger.debug(err.stack); + } + }); + } + + /** + * @param {LazySet | Iterable} dependencies dependencies to store + */ + storeBuildDependencies(dependencies) { + if (this.readonly) return; + this.newBuildDependencies.addAll(dependencies); + } + + afterAllStored() { + const packPromise = this.packPromise; + if (packPromise === undefined) return Promise.resolve(); + const reportProgress = ProgressPlugin.getReporter(this.compiler); + return (this.storePromise = packPromise + .then((pack) => { + pack.stopCapturingRequests(); + if (!pack.invalid) return; + this.packPromise = undefined; + this.logger.log("Storing pack..."); + let promise; + const newBuildDependencies = new Set(); + for (const dep of this.newBuildDependencies) { + if (!this.buildDependencies.has(dep)) { + newBuildDependencies.add(dep); + } + } + if (newBuildDependencies.size > 0 || !this.buildSnapshot) { + if (reportProgress) reportProgress(0.5, "resolve build dependencies"); + this.logger.debug( + `Capturing build dependencies... (${[...newBuildDependencies].join(", ")})` + ); + promise = new Promise( + /** + * @param {(value?: undefined) => void} resolve resolve + * @param {(reason?: Error) => void} reject reject + */ + (resolve, reject) => { + this.logger.time("resolve build dependencies"); + this.fileSystemInfo.resolveBuildDependencies( + this.context, + newBuildDependencies, + (err, result) => { + this.logger.timeEnd("resolve build dependencies"); + if (err) return reject(err); + + this.logger.time("snapshot build dependencies"); + const { + files, + directories, + missing, + resolveResults, + resolveDependencies + } = /** @type {ResolveBuildDependenciesResult} */ (result); + if (this.resolveResults) { + for (const [key, value] of resolveResults) { + this.resolveResults.set(key, value); + } + } else { + this.resolveResults = resolveResults; + } + if (reportProgress) { + reportProgress( + 0.6, + "snapshot build dependencies", + "resolving" + ); + } + this.fileSystemInfo.createSnapshot( + undefined, + resolveDependencies.files, + resolveDependencies.directories, + resolveDependencies.missing, + this.snapshot.resolveBuildDependencies, + (err, snapshot) => { + if (err) { + this.logger.timeEnd("snapshot build dependencies"); + return reject(err); + } + if (!snapshot) { + this.logger.timeEnd("snapshot build dependencies"); + return reject( + new Error("Unable to snapshot resolve dependencies") + ); + } + if (this.resolveBuildDependenciesSnapshot) { + this.resolveBuildDependenciesSnapshot = + this.fileSystemInfo.mergeSnapshots( + this.resolveBuildDependenciesSnapshot, + snapshot + ); + } else { + this.resolveBuildDependenciesSnapshot = snapshot; + } + if (reportProgress) { + reportProgress( + 0.7, + "snapshot build dependencies", + "modules" + ); + } + this.fileSystemInfo.createSnapshot( + undefined, + files, + directories, + missing, + this.snapshot.buildDependencies, + (err, snapshot) => { + this.logger.timeEnd("snapshot build dependencies"); + if (err) return reject(err); + if (!snapshot) { + return reject( + new Error("Unable to snapshot build dependencies") + ); + } + this.logger.debug("Captured build dependencies"); + + if (this.buildSnapshot) { + this.buildSnapshot = + this.fileSystemInfo.mergeSnapshots( + this.buildSnapshot, + snapshot + ); + } else { + this.buildSnapshot = snapshot; + } + + resolve(); + } + ); + } + ); + } + ); + } + ); + } else { + promise = Promise.resolve(); + } + return promise.then(() => { + if (reportProgress) reportProgress(0.8, "serialize pack"); + this.logger.time("store pack"); + const updatedBuildDependencies = new Set(this.buildDependencies); + for (const dep of newBuildDependencies) { + updatedBuildDependencies.add(dep); + } + const content = new PackContainer( + pack, + this.version, + /** @type {Snapshot} */ + (this.buildSnapshot), + updatedBuildDependencies, + /** @type {ResolveResults} */ + (this.resolveResults), + /** @type {Snapshot} */ + (this.resolveBuildDependenciesSnapshot) + ); + return this.fileSerializer + .serialize(content, { + filename: `${this.cacheLocation}/index${this._extension}`, + extension: `${this._extension}`, + logger: this.logger, + profile: this.profile + }) + .then(() => { + for (const dep of newBuildDependencies) { + this.buildDependencies.add(dep); + } + this.newBuildDependencies.clear(); + this.logger.timeEnd("store pack"); + const stats = pack.getContentStats(); + this.logger.log( + "Stored pack (%d items, %d files, %d MiB)", + pack.itemInfo.size, + stats.count, + Math.round(stats.size / 1024 / 1024) + ); + }) + .catch((err) => { + this.logger.timeEnd("store pack"); + this.logger.warn(`Caching failed for pack: ${err}`); + this.logger.debug(err.stack); + }); + }); + }) + .catch((err) => { + this.logger.warn(`Caching failed for pack: ${err}`); + this.logger.debug(err.stack); + })); + } + + clear() { + this.fileSystemInfo.clear(); + this.buildDependencies.clear(); + this.newBuildDependencies.clear(); + this.resolveBuildDependenciesSnapshot = undefined; + this.resolveResults = undefined; + this.buildSnapshot = undefined; + this.packPromise = undefined; + } +} + +module.exports = PackFileCacheStrategy; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/ResolverCachePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/ResolverCachePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..e28a8896c4a70e07b6544db3632eb7852b449ad7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/ResolverCachePlugin.js @@ -0,0 +1,456 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const LazySet = require("../util/LazySet"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */ +/** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */ +/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */ +/** @typedef {import("enhanced-resolve").Resolver} Resolver */ +/** @typedef {import("../CacheFacade").ItemCacheFacade} ItemCacheFacade */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../FileSystemInfo")} FileSystemInfo */ +/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ +/** @typedef {import("../FileSystemInfo").SnapshotOptions} SnapshotOptions */ +/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** + * @template T + * @typedef {import("tapable").SyncHook} SyncHook + */ + +/** + * @template H + * @typedef {import("tapable").HookMapInterceptor} HookMapInterceptor + */ + +class CacheEntry { + /** + * @param {ResolveRequest} result result + * @param {Snapshot} snapshot snapshot + */ + constructor(result, snapshot) { + this.result = result; + this.snapshot = snapshot; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize({ write }) { + write(this.result); + write(this.snapshot); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize({ read }) { + this.result = read(); + this.snapshot = read(); + } +} + +makeSerializable(CacheEntry, "webpack/lib/cache/ResolverCachePlugin"); + +/** + * @template T + * @param {Set | LazySet} set set to add items to + * @param {Set | LazySet | Iterable} otherSet set to add items from + * @returns {void} + */ +const addAllToSet = (set, otherSet) => { + if (set instanceof LazySet) { + set.addAll(otherSet); + } else { + for (const item of otherSet) { + set.add(item); + } + } +}; + +/** + * @template {object} T + * @param {T} object an object + * @param {boolean} excludeContext if true, context is not included in string + * @returns {string} stringified version + */ +const objectToString = (object, excludeContext) => { + let str = ""; + for (const key in object) { + if (excludeContext && key === "context") continue; + const value = object[key]; + str += + typeof value === "object" && value !== null + ? `|${key}=[${objectToString(value, false)}|]` + : `|${key}=|${value}`; + } + return str; +}; + +/** @typedef {NonNullable} Yield */ + +const PLUGIN_NAME = "ResolverCachePlugin"; + +class ResolverCachePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const cache = compiler.getCache(PLUGIN_NAME); + /** @type {FileSystemInfo} */ + let fileSystemInfo; + /** @type {SnapshotOptions | undefined} */ + let snapshotOptions; + let realResolves = 0; + let cachedResolves = 0; + let cacheInvalidResolves = 0; + let concurrentResolves = 0; + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + snapshotOptions = compilation.options.snapshot.resolve; + fileSystemInfo = compilation.fileSystemInfo; + compilation.hooks.finishModules.tap(PLUGIN_NAME, () => { + if (realResolves + cachedResolves > 0) { + const logger = compilation.getLogger(`webpack.${PLUGIN_NAME}`); + logger.log( + `${Math.round( + (100 * realResolves) / (realResolves + cachedResolves) + )}% really resolved (${realResolves} real resolves with ${cacheInvalidResolves} cached but invalid, ${cachedResolves} cached valid, ${concurrentResolves} concurrent)` + ); + realResolves = 0; + cachedResolves = 0; + cacheInvalidResolves = 0; + concurrentResolves = 0; + } + }); + }); + + /** @typedef {(err?: Error | null, resolveRequest?: ResolveRequest | null) => void} Callback */ + /** @typedef {ResolveRequest & { _ResolverCachePluginCacheMiss: true }} ResolveRequestWithCacheMiss */ + + /** + * @param {ItemCacheFacade} itemCache cache + * @param {Resolver} resolver the resolver + * @param {ResolveContext} resolveContext context for resolving meta info + * @param {ResolveRequest} request the request info object + * @param {Callback} callback callback function + * @returns {void} + */ + const doRealResolve = ( + itemCache, + resolver, + resolveContext, + request, + callback + ) => { + realResolves++; + const newRequest = + /** @type {ResolveRequestWithCacheMiss} */ + ({ + _ResolverCachePluginCacheMiss: true, + ...request + }); + /** @type {ResolveContext} */ + const newResolveContext = { + ...resolveContext, + stack: new Set(), + /** @type {LazySet} */ + missingDependencies: new LazySet(), + /** @type {LazySet} */ + fileDependencies: new LazySet(), + /** @type {LazySet} */ + contextDependencies: new LazySet() + }; + /** @type {ResolveRequest[] | undefined} */ + let yieldResult; + let withYield = false; + if (typeof newResolveContext.yield === "function") { + yieldResult = []; + withYield = true; + newResolveContext.yield = (obj) => + /** @type {ResolveRequest[]} */ + (yieldResult).push(obj); + } + /** + * @param {"fileDependencies" | "contextDependencies" | "missingDependencies"} key key + */ + const propagate = (key) => { + if (resolveContext[key]) { + addAllToSet( + /** @type {Set} */ (resolveContext[key]), + /** @type {Set} */ (newResolveContext[key]) + ); + } + }; + const resolveTime = Date.now(); + resolver.doResolve( + resolver.hooks.resolve, + newRequest, + "Cache miss", + newResolveContext, + (err, result) => { + propagate("fileDependencies"); + propagate("contextDependencies"); + propagate("missingDependencies"); + if (err) return callback(err); + const fileDependencies = newResolveContext.fileDependencies; + const contextDependencies = newResolveContext.contextDependencies; + const missingDependencies = newResolveContext.missingDependencies; + fileSystemInfo.createSnapshot( + resolveTime, + /** @type {Set} */ + (fileDependencies), + /** @type {Set} */ + (contextDependencies), + /** @type {Set} */ + (missingDependencies), + snapshotOptions, + (err, snapshot) => { + if (err) return callback(err); + const resolveResult = withYield ? yieldResult : result; + // since we intercept resolve hook + // we still can get result in callback + if (withYield && result) { + /** @type {ResolveRequest[]} */ + (yieldResult).push(result); + } + if (!snapshot) { + if (resolveResult) { + return callback( + null, + /** @type {ResolveRequest} */ + (resolveResult) + ); + } + return callback(); + } + itemCache.store( + new CacheEntry( + /** @type {ResolveRequest} */ + (resolveResult), + snapshot + ), + (storeErr) => { + if (storeErr) return callback(storeErr); + if (resolveResult) { + return callback( + null, + /** @type {ResolveRequest} */ + (resolveResult) + ); + } + callback(); + } + ); + } + ); + } + ); + }; + compiler.resolverFactory.hooks.resolver.intercept({ + factory(type, _hook) { + /** @typedef {(err?: Error, resolveRequest?: ResolveRequest) => void} ActiveRequest */ + /** @type {Map} */ + const activeRequests = new Map(); + /** @type {Map} */ + const activeRequestsWithYield = new Map(); + const hook = + /** @type {SyncHook<[Resolver, ResolveOptions, ResolveOptionsWithDependencyType]>} */ + (_hook); + hook.tap(PLUGIN_NAME, (resolver, options, userOptions) => { + if ( + /** @type {ResolveOptions & { cache: boolean }} */ + (options).cache !== true + ) { + return; + } + const optionsIdent = objectToString(userOptions, false); + const cacheWithContext = + options.cacheWithContext !== undefined + ? options.cacheWithContext + : false; + resolver.hooks.resolve.tapAsync( + { + name: PLUGIN_NAME, + stage: -100 + }, + (request, resolveContext, callback) => { + if ( + /** @type {ResolveRequestWithCacheMiss} */ + (request)._ResolverCachePluginCacheMiss || + !fileSystemInfo + ) { + return callback(); + } + const withYield = typeof resolveContext.yield === "function"; + const identifier = `${type}${ + withYield ? "|yield" : "|default" + }${optionsIdent}${objectToString(request, !cacheWithContext)}`; + + if (withYield) { + const activeRequest = activeRequestsWithYield.get(identifier); + if (activeRequest) { + activeRequest[0].push(callback); + activeRequest[1].push( + /** @type {Yield} */ + (resolveContext.yield) + ); + return; + } + } else { + const activeRequest = activeRequests.get(identifier); + if (activeRequest) { + activeRequest.push(callback); + return; + } + } + const itemCache = cache.getItemCache(identifier, null); + /** @type {Callback[] | false | undefined} */ + let callbacks; + /** @type {Yield[] | undefined} */ + let yields; + + /** + * @type {(err?: Error | null, result?: ResolveRequest | ResolveRequest[] | null) => void} + */ + const done = withYield + ? (err, result) => { + if (callbacks === undefined) { + if (err) { + callback(err); + } else { + if (result) { + for (const r of /** @type {ResolveRequest[]} */ ( + result + )) { + /** @type {Yield} */ + (resolveContext.yield)(r); + } + } + callback(null, null); + } + yields = undefined; + callbacks = false; + } else { + const definedCallbacks = + /** @type {Callback[]} */ + (callbacks); + + if (err) { + for (const cb of definedCallbacks) cb(err); + } else { + for (let i = 0; i < definedCallbacks.length; i++) { + const cb = definedCallbacks[i]; + const yield_ = /** @type {Yield[]} */ (yields)[i]; + if (result) { + for (const r of /** @type {ResolveRequest[]} */ ( + result + )) { + yield_(r); + } + } + cb(null, null); + } + } + activeRequestsWithYield.delete(identifier); + yields = undefined; + callbacks = false; + } + } + : (err, result) => { + if (callbacks === undefined) { + callback(err, /** @type {ResolveRequest} */ (result)); + callbacks = false; + } else { + for (const callback of /** @type {Callback[]} */ ( + callbacks + )) { + callback(err, /** @type {ResolveRequest} */ (result)); + } + activeRequests.delete(identifier); + callbacks = false; + } + }; + /** + * @param {(Error | null)=} err error if any + * @param {(CacheEntry | null)=} cacheEntry cache entry + * @returns {void} + */ + const processCacheResult = (err, cacheEntry) => { + if (err) return done(err); + + if (cacheEntry) { + const { snapshot, result } = cacheEntry; + fileSystemInfo.checkSnapshotValid(snapshot, (err, valid) => { + if (err || !valid) { + cacheInvalidResolves++; + return doRealResolve( + itemCache, + resolver, + resolveContext, + request, + done + ); + } + cachedResolves++; + if (resolveContext.missingDependencies) { + addAllToSet( + /** @type {Set} */ + (resolveContext.missingDependencies), + snapshot.getMissingIterable() + ); + } + if (resolveContext.fileDependencies) { + addAllToSet( + /** @type {Set} */ + (resolveContext.fileDependencies), + snapshot.getFileIterable() + ); + } + if (resolveContext.contextDependencies) { + addAllToSet( + /** @type {Set} */ + (resolveContext.contextDependencies), + snapshot.getContextIterable() + ); + } + done(null, result); + }); + } else { + doRealResolve( + itemCache, + resolver, + resolveContext, + request, + done + ); + } + }; + itemCache.get(processCacheResult); + if (withYield && callbacks === undefined) { + callbacks = [callback]; + yields = [/** @type {Yield} */ (resolveContext.yield)]; + activeRequestsWithYield.set(identifier, [callbacks, yields]); + } else if (callbacks === undefined) { + callbacks = [callback]; + activeRequests.set(identifier, callbacks); + } + } + ); + }); + return hook; + } + }); + } +} + +module.exports = ResolverCachePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/getLazyHashedEtag.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/getLazyHashedEtag.js new file mode 100644 index 0000000000000000000000000000000000000000..3007754db7403c5a1c2d717cd8be90114e701dbc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/getLazyHashedEtag.js @@ -0,0 +1,82 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { DEFAULTS } = require("../config/defaults"); +const createHash = require("../util/createHash"); + +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {typeof import("../util/Hash")} HashConstructor */ + +/** + * @typedef {object} HashableObject + * @property {(hash: Hash) => void} updateHash + */ + +class LazyHashedEtag { + /** + * @param {HashableObject} obj object with updateHash method + * @param {string | HashConstructor} hashFunction the hash function to use + */ + constructor(obj, hashFunction = DEFAULTS.HASH_FUNCTION) { + this._obj = obj; + this._hash = undefined; + this._hashFunction = hashFunction; + } + + /** + * @returns {string} hash of object + */ + toString() { + if (this._hash === undefined) { + const hash = createHash(this._hashFunction); + this._obj.updateHash(hash); + this._hash = /** @type {string} */ (hash.digest("base64")); + } + return this._hash; + } +} + +/** @type {Map>} */ +const mapStrings = new Map(); + +/** @type {WeakMap>} */ +const mapObjects = new WeakMap(); + +/** + * @param {HashableObject} obj object with updateHash method + * @param {(string | HashConstructor)=} hashFunction the hash function to use + * @returns {LazyHashedEtag} etag + */ +const getter = (obj, hashFunction = DEFAULTS.HASH_FUNCTION) => { + let innerMap; + if (typeof hashFunction === "string") { + innerMap = mapStrings.get(hashFunction); + if (innerMap === undefined) { + const newHash = new LazyHashedEtag(obj, hashFunction); + innerMap = new WeakMap(); + innerMap.set(obj, newHash); + mapStrings.set(hashFunction, innerMap); + return newHash; + } + } else { + innerMap = mapObjects.get(hashFunction); + if (innerMap === undefined) { + const newHash = new LazyHashedEtag(obj, hashFunction); + innerMap = new WeakMap(); + innerMap.set(obj, newHash); + mapObjects.set(hashFunction, innerMap); + return newHash; + } + } + const hash = innerMap.get(obj); + if (hash !== undefined) return hash; + const newHash = new LazyHashedEtag(obj, hashFunction); + innerMap.set(obj, newHash); + return newHash; +}; + +module.exports = getter; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/mergeEtags.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/mergeEtags.js new file mode 100644 index 0000000000000000000000000000000000000000..9a212f218a4e75a65dc33decb9ffb334976e5a95 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cache/mergeEtags.js @@ -0,0 +1,69 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../Cache").Etag} Etag */ + +class MergedEtag { + /** + * @param {Etag} a first + * @param {Etag} b second + */ + constructor(a, b) { + this.a = a; + this.b = b; + } + + toString() { + return `${this.a.toString()}|${this.b.toString()}`; + } +} + +const dualObjectMap = new WeakMap(); +const objectStringMap = new WeakMap(); + +/** + * @param {Etag} a first + * @param {Etag} b second + * @returns {Etag} result + */ +const mergeEtags = (a, b) => { + if (typeof a === "string") { + if (typeof b === "string") { + return `${a}|${b}`; + } + const temp = b; + b = a; + a = temp; + } else if (typeof b !== "string") { + // both a and b are objects + let map = dualObjectMap.get(a); + if (map === undefined) { + dualObjectMap.set(a, (map = new WeakMap())); + } + const mergedEtag = map.get(b); + if (mergedEtag === undefined) { + const newMergedEtag = new MergedEtag(a, b); + map.set(b, newMergedEtag); + return newMergedEtag; + } + return mergedEtag; + } + // a is object, b is string + let map = objectStringMap.get(a); + if (map === undefined) { + objectStringMap.set(a, (map = new Map())); + } + const mergedEtag = map.get(b); + if (mergedEtag === undefined) { + const newMergedEtag = new MergedEtag(a, b); + map.set(b, newMergedEtag); + return newMergedEtag; + } + return mergedEtag; +}; + +module.exports = mergeEtags; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cli.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..1d38af32bc8e9f6ec4e28f67def49b666819c760 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/cli.js @@ -0,0 +1,898 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const path = require("path"); +const tty = require("tty"); +const webpackSchema = require("../schemas/WebpackOptions.json"); + +/** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */ +/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ +/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ +/** @typedef {JSONSchema4 | JSONSchema6 | JSONSchema7} JSONSchema */ +/** @typedef {JSONSchema & { absolutePath: boolean, instanceof: string, cli: { helper?: boolean, exclude?: boolean, description?: string, negatedDescription?: string, resetDescription?: string } }} Schema */ + +// TODO add originPath to PathItem for better errors +/** + * @typedef {object} PathItem + * @property {Schema} schema the part of the schema + * @property {string} path the path in the config + */ + +/** @typedef {"unknown-argument" | "unexpected-non-array-in-path" | "unexpected-non-object-in-path" | "multiple-values-unexpected" | "invalid-value"} ProblemType */ + +/** @typedef {string | number | boolean | RegExp} Value */ + +/** + * @typedef {object} Problem + * @property {ProblemType} type + * @property {string} path + * @property {string} argument + * @property {Value=} value + * @property {number=} index + * @property {string=} expected + */ + +/** + * @typedef {object} LocalProblem + * @property {ProblemType} type + * @property {string} path + * @property {string=} expected + */ + +/** @typedef {{ [key: string]: EnumValue }} EnumValueObject */ +/** @typedef {EnumValue[]} EnumValueArray */ +/** @typedef {string | number | boolean | EnumValueObject | EnumValueArray | null} EnumValue */ + +/** + * @typedef {object} ArgumentConfig + * @property {string=} description + * @property {string=} negatedDescription + * @property {string} path + * @property {boolean} multiple + * @property {"enum" | "string" | "path" | "number" | "boolean" | "RegExp" | "reset"} type + * @property {EnumValue[]=} values + */ + +/** @typedef {"string" | "number" | "boolean"} SimpleType */ + +/** + * @typedef {object} Argument + * @property {string | undefined} description + * @property {SimpleType} simpleType + * @property {boolean} multiple + * @property {ArgumentConfig[]} configs + */ + +/** @typedef {Record} Flags */ + +/** @typedef {Record} ObjectConfiguration */ + +/** + * @param {Schema=} schema a json schema to create arguments for (by default webpack schema is used) + * @returns {Flags} object of arguments + */ +const getArguments = (schema = webpackSchema) => { + /** @type {Flags} */ + const flags = {}; + + /** + * @param {string} input input + * @returns {string} result + */ + const pathToArgumentName = (input) => + input + .replace(/\./g, "-") + .replace(/\[\]/g, "") + .replace( + /(\p{Uppercase_Letter}+|\p{Lowercase_Letter}|\d)(\p{Uppercase_Letter}+)/gu, + "$1-$2" + ) + .replace(/-?[^\p{Uppercase_Letter}\p{Lowercase_Letter}\d]+/gu, "-") + .toLowerCase(); + + /** + * @param {string} path path + * @returns {Schema} schema part + */ + const getSchemaPart = (path) => { + const newPath = path.split("/"); + + let schemaPart = schema; + + for (let i = 1; i < newPath.length; i++) { + const inner = schemaPart[/** @type {keyof Schema} */ (newPath[i])]; + + if (!inner) { + break; + } + + schemaPart = inner; + } + + return schemaPart; + }; + + /** + * @param {PathItem[]} path path in the schema + * @returns {string | undefined} description + */ + const getDescription = (path) => { + for (const { schema } of path) { + if (schema.cli) { + if (schema.cli.helper) continue; + if (schema.cli.description) return schema.cli.description; + } + if (schema.description) return schema.description; + } + }; + + /** + * @param {PathItem[]} path path in the schema + * @returns {string | undefined} negative description + */ + const getNegatedDescription = (path) => { + for (const { schema } of path) { + if (schema.cli) { + if (schema.cli.helper) continue; + if (schema.cli.negatedDescription) return schema.cli.negatedDescription; + } + } + }; + + /** + * @param {PathItem[]} path path in the schema + * @returns {string | undefined} reset description + */ + const getResetDescription = (path) => { + for (const { schema } of path) { + if (schema.cli) { + if (schema.cli.helper) continue; + if (schema.cli.resetDescription) return schema.cli.resetDescription; + } + } + }; + + /** + * @param {Schema} schemaPart schema + * @returns {Pick | undefined} partial argument config + */ + const schemaToArgumentConfig = (schemaPart) => { + if (schemaPart.enum) { + return { + type: "enum", + values: schemaPart.enum + }; + } + switch (schemaPart.type) { + case "number": + return { + type: "number" + }; + case "string": + return { + type: schemaPart.absolutePath ? "path" : "string" + }; + case "boolean": + return { + type: "boolean" + }; + } + if (schemaPart.instanceof === "RegExp") { + return { + type: "RegExp" + }; + } + return undefined; + }; + + /** + * @param {PathItem[]} path path in the schema + * @returns {void} + */ + const addResetFlag = (path) => { + const schemaPath = path[0].path; + const name = pathToArgumentName(`${schemaPath}.reset`); + const description = + getResetDescription(path) || + `Clear all items provided in '${schemaPath}' configuration. ${getDescription( + path + )}`; + flags[name] = { + configs: [ + { + type: "reset", + multiple: false, + description, + path: schemaPath + } + ], + description: undefined, + simpleType: + /** @type {SimpleType} */ + (/** @type {unknown} */ (undefined)), + multiple: /** @type {boolean} */ (/** @type {unknown} */ (undefined)) + }; + }; + + /** + * @param {PathItem[]} path full path in schema + * @param {boolean} multiple inside of an array + * @returns {number} number of arguments added + */ + const addFlag = (path, multiple) => { + const argConfigBase = schemaToArgumentConfig(path[0].schema); + if (!argConfigBase) return 0; + + const negatedDescription = getNegatedDescription(path); + const name = pathToArgumentName(path[0].path); + /** @type {ArgumentConfig} */ + const argConfig = { + ...argConfigBase, + multiple, + description: getDescription(path), + path: path[0].path + }; + + if (negatedDescription) { + argConfig.negatedDescription = negatedDescription; + } + + if (!flags[name]) { + flags[name] = { + configs: [], + description: undefined, + simpleType: + /** @type {SimpleType} */ + (/** @type {unknown} */ (undefined)), + multiple: /** @type {boolean} */ (/** @type {unknown} */ (undefined)) + }; + } + + if ( + flags[name].configs.some( + (item) => JSON.stringify(item) === JSON.stringify(argConfig) + ) + ) { + return 0; + } + + if ( + flags[name].configs.some( + (item) => item.type === argConfig.type && item.multiple !== multiple + ) + ) { + if (multiple) { + throw new Error( + `Conflicting schema for ${path[0].path} with ${argConfig.type} type (array type must be before single item type)` + ); + } + return 0; + } + + flags[name].configs.push(argConfig); + + return 1; + }; + + // TODO support `not` and `if/then/else` + // TODO support `const`, but we don't use it on our schema + /** + * @param {Schema} schemaPart the current schema + * @param {string} schemaPath the current path in the schema + * @param {PathItem[]} path all previous visited schemaParts + * @param {string | null} inArray if inside of an array, the path to the array + * @returns {number} added arguments + */ + const traverse = (schemaPart, schemaPath = "", path = [], inArray = null) => { + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } + + const repetitions = path.filter(({ schema }) => schema === schemaPart); + if ( + repetitions.length >= 2 || + repetitions.some(({ path }) => path === schemaPath) + ) { + return 0; + } + + if (schemaPart.cli && schemaPart.cli.exclude) return 0; + + /** @type {PathItem[]} */ + const fullPath = [{ schema: schemaPart, path: schemaPath }, ...path]; + + let addedArguments = 0; + + addedArguments += addFlag(fullPath, Boolean(inArray)); + + if (schemaPart.type === "object") { + if (schemaPart.properties) { + for (const property of Object.keys(schemaPart.properties)) { + addedArguments += traverse( + /** @type {Schema} */ + (schemaPart.properties[property]), + schemaPath ? `${schemaPath}.${property}` : property, + fullPath, + inArray + ); + } + } + + return addedArguments; + } + + if (schemaPart.type === "array") { + if (inArray) { + return 0; + } + if (Array.isArray(schemaPart.items)) { + const i = 0; + for (const item of schemaPart.items) { + addedArguments += traverse( + /** @type {Schema} */ + (item), + `${schemaPath}.${i}`, + fullPath, + schemaPath + ); + } + + return addedArguments; + } + + addedArguments += traverse( + /** @type {Schema} */ + (schemaPart.items), + `${schemaPath}[]`, + fullPath, + schemaPath + ); + + if (addedArguments > 0) { + addResetFlag(fullPath); + addedArguments++; + } + + return addedArguments; + } + + const maybeOf = schemaPart.oneOf || schemaPart.anyOf || schemaPart.allOf; + + if (maybeOf) { + const items = maybeOf; + + for (let i = 0; i < items.length; i++) { + addedArguments += traverse( + /** @type {Schema} */ + (items[i]), + schemaPath, + fullPath, + inArray + ); + } + + return addedArguments; + } + + return addedArguments; + }; + + traverse(schema); + + // Summarize flags + for (const name of Object.keys(flags)) { + /** @type {Argument} */ + const argument = flags[name]; + argument.description = argument.configs.reduce((desc, { description }) => { + if (!desc) return description; + if (!description) return desc; + if (desc.includes(description)) return desc; + return `${desc} ${description}`; + }, /** @type {string | undefined} */ (undefined)); + argument.simpleType = + /** @type {SimpleType} */ + ( + argument.configs.reduce((t, argConfig) => { + /** @type {SimpleType} */ + let type = "string"; + switch (argConfig.type) { + case "number": + type = "number"; + break; + case "reset": + case "boolean": + type = "boolean"; + break; + case "enum": { + const values = + /** @type {NonNullable} */ + (argConfig.values); + + if (values.every((v) => typeof v === "boolean")) type = "boolean"; + if (values.every((v) => typeof v === "number")) type = "number"; + break; + } + } + if (t === undefined) return type; + return t === type ? t : "string"; + }, /** @type {SimpleType | undefined} */ (undefined)) + ); + argument.multiple = argument.configs.some((c) => c.multiple); + } + + return flags; +}; + +const cliAddedItems = new WeakMap(); + +/** @typedef {string | number} Property */ + +/** + * @param {ObjectConfiguration} config configuration + * @param {string} schemaPath path in the config + * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined + * @returns {{ problem?: LocalProblem, object?: ObjectConfiguration, property?: Property, value?: EXPECTED_OBJECT | EXPECTED_ANY[] }} problem or object with property and value + */ +const getObjectAndProperty = (config, schemaPath, index = 0) => { + if (!schemaPath) return { value: config }; + const parts = schemaPath.split("."); + const property = /** @type {string} */ (parts.pop()); + let current = config; + let i = 0; + for (const part of parts) { + const isArray = part.endsWith("[]"); + const name = isArray ? part.slice(0, -2) : part; + let value = current[name]; + if (isArray) { + if (value === undefined) { + value = {}; + current[name] = [...Array.from({ length: index }), value]; + cliAddedItems.set(current[name], index + 1); + } else if (!Array.isArray(value)) { + return { + problem: { + type: "unexpected-non-array-in-path", + path: parts.slice(0, i).join(".") + } + }; + } else { + let addedItems = cliAddedItems.get(value) || 0; + while (addedItems <= index) { + value.push(undefined); + addedItems++; + } + cliAddedItems.set(value, addedItems); + const x = value.length - addedItems + index; + if (value[x] === undefined) { + value[x] = {}; + } else if (value[x] === null || typeof value[x] !== "object") { + return { + problem: { + type: "unexpected-non-object-in-path", + path: parts.slice(0, i).join(".") + } + }; + } + value = value[x]; + } + } else if (value === undefined) { + value = current[name] = {}; + } else if (value === null || typeof value !== "object") { + return { + problem: { + type: "unexpected-non-object-in-path", + path: parts.slice(0, i).join(".") + } + }; + } + current = value; + i++; + } + const value = current[property]; + if (property.endsWith("[]")) { + const name = property.slice(0, -2); + const value = current[name]; + if (value === undefined) { + current[name] = [...Array.from({ length: index }), undefined]; + cliAddedItems.set(current[name], index + 1); + return { object: current[name], property: index, value: undefined }; + } else if (!Array.isArray(value)) { + current[name] = [value, ...Array.from({ length: index }), undefined]; + cliAddedItems.set(current[name], index + 1); + return { object: current[name], property: index + 1, value: undefined }; + } + let addedItems = cliAddedItems.get(value) || 0; + while (addedItems <= index) { + value.push(undefined); + addedItems++; + } + cliAddedItems.set(value, addedItems); + const x = value.length - addedItems + index; + if (value[x] === undefined) { + value[x] = {}; + } else if (value[x] === null || typeof value[x] !== "object") { + return { + problem: { + type: "unexpected-non-object-in-path", + path: schemaPath + } + }; + } + return { + object: value, + property: x, + value: value[x] + }; + } + return { object: current, property, value }; +}; + +/** + * @param {ObjectConfiguration} config configuration + * @param {string} schemaPath path in the config + * @param {ParsedValue} value parsed value + * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined + * @returns {LocalProblem | null} problem or null for success + */ +const setValue = (config, schemaPath, value, index) => { + const { problem, object, property } = getObjectAndProperty( + config, + schemaPath, + index + ); + if (problem) return problem; + /** @type {ObjectConfiguration} */ + (object)[/** @type {Property} */ (property)] = value; + return null; +}; + +/** + * @param {ArgumentConfig} argConfig processing instructions + * @param {ObjectConfiguration} config configuration + * @param {Value} value the value + * @param {number | undefined} index the index if multiple values provided + * @returns {LocalProblem | null} a problem if any + */ +const processArgumentConfig = (argConfig, config, value, index) => { + if (index !== undefined && !argConfig.multiple) { + return { + type: "multiple-values-unexpected", + path: argConfig.path + }; + } + const parsed = parseValueForArgumentConfig(argConfig, value); + if (parsed === undefined) { + return { + type: "invalid-value", + path: argConfig.path, + expected: getExpectedValue(argConfig) + }; + } + const problem = setValue(config, argConfig.path, parsed, index); + if (problem) return problem; + return null; +}; + +/** + * @param {ArgumentConfig} argConfig processing instructions + * @returns {string | undefined} expected message + */ +const getExpectedValue = (argConfig) => { + switch (argConfig.type) { + case "boolean": + return "true | false"; + case "RegExp": + return "regular expression (example: /ab?c*/)"; + case "enum": + return /** @type {NonNullable} */ ( + argConfig.values + ) + .map((v) => `${v}`) + .join(" | "); + case "reset": + return "true (will reset the previous value to an empty array)"; + default: + return argConfig.type; + } +}; + +/** @typedef {null | string | number | boolean | RegExp | EnumValue | []} ParsedValue */ + +/** + * @param {ArgumentConfig} argConfig processing instructions + * @param {Value} value the value + * @returns {ParsedValue | undefined} parsed value + */ +const parseValueForArgumentConfig = (argConfig, value) => { + switch (argConfig.type) { + case "string": + if (typeof value === "string") { + return value; + } + break; + case "path": + if (typeof value === "string") { + return path.resolve(value); + } + break; + case "number": + if (typeof value === "number") return value; + if (typeof value === "string" && /^[+-]?\d*(\.\d*)[eE]\d+$/) { + const n = Number(value); + if (!Number.isNaN(n)) return n; + } + break; + case "boolean": + if (typeof value === "boolean") return value; + if (value === "true") return true; + if (value === "false") return false; + break; + case "RegExp": + if (value instanceof RegExp) return value; + if (typeof value === "string") { + // cspell:word yugi + const match = /^\/(.*)\/([yugi]*)$/.exec(value); + if (match && !/[^\\]\//.test(match[1])) { + return new RegExp(match[1], match[2]); + } + } + break; + case "enum": { + const values = + /** @type {EnumValue[]} */ + (argConfig.values); + if (values.includes(/** @type {Exclude} */ (value))) { + return value; + } + for (const item of values) { + if (`${item}` === value) return item; + } + break; + } + case "reset": + if (value === true) return []; + break; + } +}; + +/** @typedef {Record} Values */ + +/** + * @param {Flags} args object of arguments + * @param {ObjectConfiguration} config configuration + * @param {Values} values object with values + * @returns {Problem[] | null} problems or null for success + */ +const processArguments = (args, config, values) => { + /** @type {Problem[]} */ + const problems = []; + for (const key of Object.keys(values)) { + const arg = args[key]; + if (!arg) { + problems.push({ + type: "unknown-argument", + path: "", + argument: key + }); + continue; + } + /** + * @param {Value} value value + * @param {number | undefined} i index + */ + const processValue = (value, i) => { + const currentProblems = []; + for (const argConfig of arg.configs) { + const problem = processArgumentConfig(argConfig, config, value, i); + if (!problem) { + return; + } + currentProblems.push({ + ...problem, + argument: key, + value, + index: i + }); + } + problems.push(...currentProblems); + }; + const value = values[key]; + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + processValue(value[i], i); + } + } else { + processValue(value, undefined); + } + } + if (problems.length === 0) return null; + return problems; +}; + +/** + * @returns {boolean} true when colors supported, otherwise false + */ +const isColorSupported = () => { + const { env = {}, argv = [], platform = "" } = process; + + const isDisabled = "NO_COLOR" in env || argv.includes("--no-color"); + const isForced = "FORCE_COLOR" in env || argv.includes("--color"); + const isWindows = platform === "win32"; + const isDumbTerminal = env.TERM === "dumb"; + + const isCompatibleTerminal = tty.isatty(1) && env.TERM && !isDumbTerminal; + + const isCI = + "CI" in env && + ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env); + + return ( + !isDisabled && + (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI) + ); +}; + +/** + * @param {number} index index + * @param {string} string string + * @param {string} close close + * @param {string=} replace replace + * @param {string=} head head + * @param {string=} tail tail + * @param {number=} next next + * @returns {string} result + */ +const replaceClose = ( + index, + string, + close, + replace, + head = string.slice(0, Math.max(0, index)) + replace, + tail = string.slice(Math.max(0, index + close.length)), + next = tail.indexOf(close) +) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace)); + +/** + * @param {number} index index to replace + * @param {string} string string + * @param {string} open open string + * @param {string} close close string + * @param {string=} replace extra replace + * @returns {string} result + */ +const clearBleed = (index, string, open, close, replace) => + index < 0 + ? open + string + close + : open + replaceClose(index, string, close, replace) + close; + +/** @typedef {(value: EXPECTED_ANY) => string} PrintFunction */ + +/** + * @param {string} open open string + * @param {string} close close string + * @param {string=} replace extra replace + * @param {number=} at at + * @returns {PrintFunction} function to create color + */ +const filterEmpty = + (open, close, replace = open, at = open.length + 1) => + (string) => + string || !(string === "" || string === undefined) + ? clearBleed(`${string}`.indexOf(close, at), string, open, close, replace) + : ""; + +/** + * @param {number} open open code + * @param {number} close close code + * @param {string=} replace extra replace + * @returns {PrintFunction} result + */ +const init = (open, close, replace) => + filterEmpty(`\u001B[${open}m`, `\u001B[${close}m`, replace); + +/** + * @typedef {{ + * reset: PrintFunction + * bold: PrintFunction + * dim: PrintFunction + * italic: PrintFunction + * underline: PrintFunction + * inverse: PrintFunction + * hidden: PrintFunction + * strikethrough: PrintFunction + * black: PrintFunction + * red: PrintFunction + * green: PrintFunction + * yellow: PrintFunction + * blue: PrintFunction + * magenta: PrintFunction + * cyan: PrintFunction + * white: PrintFunction + * gray: PrintFunction + * bgBlack: PrintFunction + * bgRed: PrintFunction + * bgGreen: PrintFunction + * bgYellow: PrintFunction + * bgBlue: PrintFunction + * bgMagenta: PrintFunction + * bgCyan: PrintFunction + * bgWhite: PrintFunction + * blackBright: PrintFunction + * redBright: PrintFunction + * greenBright: PrintFunction + * yellowBright: PrintFunction + * blueBright: PrintFunction + * magentaBright: PrintFunction + * cyanBright: PrintFunction + * whiteBright: PrintFunction + * bgBlackBright: PrintFunction + * bgRedBright: PrintFunction + * bgGreenBright: PrintFunction + * bgYellowBright: PrintFunction + * bgBlueBright: PrintFunction + * bgMagentaBright: PrintFunction + * bgCyanBright: PrintFunction + * bgWhiteBright: PrintFunction + }} Colors */ + +/** + * @typedef {object} ColorsOptions + * @property {boolean=} useColor force use colors + */ + +/** + * @param {ColorsOptions=} options options + * @returns {Colors} colors + */ +const createColors = ({ useColor = isColorSupported() } = {}) => ({ + reset: useColor ? init(0, 0) : String, + bold: useColor ? init(1, 22, "\u001B[22m\u001B[1m") : String, + dim: useColor ? init(2, 22, "\u001B[22m\u001B[2m") : String, + italic: useColor ? init(3, 23) : String, + underline: useColor ? init(4, 24) : String, + inverse: useColor ? init(7, 27) : String, + hidden: useColor ? init(8, 28) : String, + strikethrough: useColor ? init(9, 29) : String, + black: useColor ? init(30, 39) : String, + red: useColor ? init(31, 39) : String, + green: useColor ? init(32, 39) : String, + yellow: useColor ? init(33, 39) : String, + blue: useColor ? init(34, 39) : String, + magenta: useColor ? init(35, 39) : String, + cyan: useColor ? init(36, 39) : String, + white: useColor ? init(37, 39) : String, + gray: useColor ? init(90, 39) : String, + bgBlack: useColor ? init(40, 49) : String, + bgRed: useColor ? init(41, 49) : String, + bgGreen: useColor ? init(42, 49) : String, + bgYellow: useColor ? init(43, 49) : String, + bgBlue: useColor ? init(44, 49) : String, + bgMagenta: useColor ? init(45, 49) : String, + bgCyan: useColor ? init(46, 49) : String, + bgWhite: useColor ? init(47, 49) : String, + blackBright: useColor ? init(90, 39) : String, + redBright: useColor ? init(91, 39) : String, + greenBright: useColor ? init(92, 39) : String, + yellowBright: useColor ? init(93, 39) : String, + blueBright: useColor ? init(94, 39) : String, + magentaBright: useColor ? init(95, 39) : String, + cyanBright: useColor ? init(96, 39) : String, + whiteBright: useColor ? init(97, 39) : String, + bgBlackBright: useColor ? init(100, 49) : String, + bgRedBright: useColor ? init(101, 49) : String, + bgGreenBright: useColor ? init(102, 49) : String, + bgYellowBright: useColor ? init(103, 49) : String, + bgBlueBright: useColor ? init(104, 49) : String, + bgMagentaBright: useColor ? init(105, 49) : String, + bgCyanBright: useColor ? init(106, 49) : String, + bgWhiteBright: useColor ? init(107, 49) : String +}); + +module.exports.createColors = createColors; +module.exports.getArguments = getArguments; +module.exports.isColorSupported = isColorSupported; +module.exports.processArguments = processArguments; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/browserslistTargetHandler.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/browserslistTargetHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..196cfa143fe7a70659cf7bc5f78295728784df15 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/browserslistTargetHandler.js @@ -0,0 +1,363 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + +"use strict"; + +const path = require("path"); +const browserslist = require("browserslist"); + +/** @typedef {import("./target").ApiTargetProperties} ApiTargetProperties */ +/** @typedef {import("./target").EcmaTargetProperties} EcmaTargetProperties */ +/** @typedef {import("./target").PlatformTargetProperties} PlatformTargetProperties */ + +// [[C:]/path/to/config][:env] +const inputRx = /^(?:((?:[A-Z]:)?[/\\].*?))?(?::(.+?))?$/i; + +/** + * @typedef {object} BrowserslistHandlerConfig + * @property {string=} configPath + * @property {string=} env + * @property {string=} query + */ + +/** + * @param {string | null | undefined} input input string + * @param {string} context the context directory + * @returns {BrowserslistHandlerConfig} config + */ +const parse = (input, context) => { + if (!input) { + return {}; + } + + if (path.isAbsolute(input)) { + const [, configPath, env] = inputRx.exec(input) || []; + return { configPath, env }; + } + + const config = browserslist.findConfig(context); + + if (config && Object.keys(config).includes(input)) { + return { env: input }; + } + + return { query: input }; +}; + +/** + * @param {string | null | undefined} input input string + * @param {string} context the context directory + * @returns {string[] | undefined} selected browsers + */ +const load = (input, context) => { + const { configPath, env, query } = parse(input, context); + + // if a query is specified, then use it, else + // if a path to a config is specified then load it, else + // find a nearest config + const config = + query || + (configPath + ? browserslist.loadConfig({ + config: configPath, + env + }) + : browserslist.loadConfig({ path: context, env })); + + if (!config) return; + return browserslist(config); +}; + +/** + * @param {string[]} browsers supported browsers list + * @returns {EcmaTargetProperties & PlatformTargetProperties & ApiTargetProperties} target properties + */ +const resolve = (browsers) => { + /** + * Checks all against a version number + * @param {Record} versions first supported version + * @returns {boolean} true if supports + */ + const rawChecker = (versions) => + browsers.every((v) => { + const [name, parsedVersion] = v.split(" "); + if (!name) return false; + const requiredVersion = versions[name]; + if (!requiredVersion) return false; + const [parsedMajor, parserMinor] = + // safari TP supports all features for normal safari + parsedVersion === "TP" + ? [Infinity, Infinity] + : parsedVersion.includes("-") + ? parsedVersion.split("-")[0].split(".") + : parsedVersion.split("."); + if (typeof requiredVersion === "number") { + return Number(parsedMajor) >= requiredVersion; + } + return requiredVersion[0] === Number(parsedMajor) + ? Number(parserMinor) >= requiredVersion[1] + : Number(parsedMajor) > requiredVersion[0]; + }); + const anyNode = browsers.some((b) => b.startsWith("node ")); + const anyBrowser = browsers.some((b) => /^(?!node)/.test(b)); + const browserProperty = !anyBrowser ? false : anyNode ? null : true; + const nodeProperty = !anyNode ? false : anyBrowser ? null : true; + // Internet Explorer Mobile, Blackberry browser and Opera Mini are very old browsers, they do not support new features + const es6DynamicImport = rawChecker({ + /* eslint-disable camelcase */ + chrome: 63, + and_chr: 63, + edge: 79, + firefox: 67, + and_ff: 67, + // ie: Not supported + opera: 50, + op_mob: 46, + safari: [11, 1], + ios_saf: [11, 3], + samsung: [8, 2], + android: 63, + and_qq: [10, 4], + baidu: [13, 18], + and_uc: [15, 5], + kaios: [3, 0], + node: [12, 17] + /* eslint-enable camelcase */ + }); + + return { + /* eslint-disable camelcase */ + const: rawChecker({ + chrome: 49, + and_chr: 49, + edge: 12, + // Prior to Firefox 13, const is implemented, but re-assignment is not failing. + // Prior to Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError. + firefox: 36, + and_ff: 36, + // Not supported in for-in and for-of loops + // ie: Not supported + opera: 36, + op_mob: 36, + safari: [10, 0], + ios_saf: [10, 0], + // Before 5.0 supported correctly in strict mode, otherwise supported without block scope + samsung: [5, 0], + android: 37, + and_qq: [10, 4], + // Supported correctly in strict mode, otherwise supported without block scope + baidu: [13, 18], + and_uc: [12, 12], + kaios: [2, 5], + node: [6, 0] + }), + arrowFunction: rawChecker({ + chrome: 45, + and_chr: 45, + edge: 12, + // The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required. + // Prior to Firefox 39, a line terminator (\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\n => {} will now throw a SyntaxError in this and later versions. + firefox: 39, + and_ff: 39, + // ie: Not supported, + opera: 32, + op_mob: 32, + safari: 10, + ios_saf: 10, + samsung: [5, 0], + android: 45, + and_qq: [10, 4], + baidu: [7, 12], + and_uc: [12, 12], + kaios: [2, 5], + node: [6, 0] + }), + forOf: rawChecker({ + chrome: 38, + and_chr: 38, + edge: 12, + // Prior to Firefox 51, using the for...of loop construct with the const keyword threw a SyntaxError ("missing = in const declaration"). + firefox: 51, + and_ff: 51, + // ie: Not supported, + opera: 25, + op_mob: 25, + safari: 7, + ios_saf: 7, + samsung: [3, 0], + android: 38, + // and_qq: Unknown support + // baidu: Unknown support + // and_uc: Unknown support + kaios: [3, 0], + node: [0, 12] + }), + destructuring: rawChecker({ + chrome: 49, + and_chr: 49, + edge: 14, + firefox: 41, + and_ff: 41, + // ie: Not supported, + opera: 36, + op_mob: 36, + safari: 8, + ios_saf: 8, + samsung: [5, 0], + android: 49, + // and_qq: Unknown support + // baidu: Unknown support + // and_uc: Unknown support + kaios: [2, 5], + node: [6, 0] + }), + bigIntLiteral: rawChecker({ + chrome: 67, + and_chr: 67, + edge: 79, + firefox: 68, + and_ff: 68, + // ie: Not supported, + opera: 54, + op_mob: 48, + safari: 14, + ios_saf: 14, + samsung: [9, 2], + android: 67, + and_qq: [13, 1], + baidu: [13, 18], + and_uc: [15, 5], + kaios: [3, 0], + node: [10, 4] + }), + // Support syntax `import` and `export` and no limitations and bugs on Node.js + // Not include `export * as namespace` + module: rawChecker({ + chrome: 61, + and_chr: 61, + edge: 16, + firefox: 60, + and_ff: 60, + // ie: Not supported, + opera: 48, + op_mob: 45, + safari: [10, 1], + ios_saf: [10, 3], + samsung: [8, 0], + android: 61, + and_qq: [10, 4], + baidu: [13, 18], + and_uc: [15, 5], + kaios: [3, 0], + node: [12, 17] + }), + dynamicImport: es6DynamicImport, + dynamicImportInWorker: es6DynamicImport && !anyNode, + // browserslist does not have info about globalThis + // so this is based on mdn-browser-compat-data + globalThis: rawChecker({ + chrome: 71, + and_chr: 71, + edge: 79, + firefox: 65, + and_ff: 65, + // ie: Not supported, + opera: 58, + op_mob: 50, + safari: [12, 1], + ios_saf: [12, 2], + samsung: [10, 1], + android: 71, + // and_qq: Unknown support + // baidu: Unknown support + // and_uc: Unknown support + kaios: [3, 0], + node: 12 + }), + optionalChaining: rawChecker({ + chrome: 80, + and_chr: 80, + edge: 80, + firefox: 74, + and_ff: 79, + // ie: Not supported, + opera: 67, + op_mob: 64, + safari: [13, 1], + ios_saf: [13, 4], + samsung: 13, + android: 80, + // and_qq: Not supported + // baidu: Not supported + // and_uc: Not supported + kaios: [3, 0], + node: 14 + }), + templateLiteral: rawChecker({ + chrome: 41, + and_chr: 41, + edge: 13, + firefox: 34, + and_ff: 34, + // ie: Not supported, + opera: 29, + op_mob: 64, + safari: [9, 1], + ios_saf: 9, + samsung: 4, + android: 41, + and_qq: [10, 4], + baidu: [7, 12], + and_uc: [12, 12], + kaios: [2, 5], + node: 4 + }), + asyncFunction: rawChecker({ + chrome: 55, + and_chr: 55, + edge: 15, + firefox: 52, + and_ff: 52, + // ie: Not supported, + opera: 42, + op_mob: 42, + safari: 11, + ios_saf: 11, + samsung: [6, 2], + android: 55, + and_qq: [13, 1], + baidu: [13, 18], + and_uc: [15, 5], + kaios: 3, + node: [7, 6] + }), + /* eslint-enable camelcase */ + browser: browserProperty, + electron: false, + node: nodeProperty, + nwjs: false, + web: browserProperty, + webworker: false, + + document: browserProperty, + fetchWasm: browserProperty, + global: nodeProperty, + importScripts: false, + importScriptsInWorker: true, + nodeBuiltins: nodeProperty, + nodePrefixForCoreModules: + nodeProperty && + !browsers.some((b) => b.startsWith("node 15")) && + rawChecker({ + node: [14, 18] + }), + require: nodeProperty + }; +}; + +module.exports = { + load, + resolve +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/defaults.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/defaults.js new file mode 100644 index 0000000000000000000000000000000000000000..613968ab84fe68f284138fe0ad6b60c39c577074 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/defaults.js @@ -0,0 +1,1761 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const { + ASSET_MODULE_TYPE, + ASSET_MODULE_TYPE_INLINE, + ASSET_MODULE_TYPE_RESOURCE, + CSS_MODULE_TYPE, + CSS_MODULE_TYPE_AUTO, + CSS_MODULE_TYPE_GLOBAL, + CSS_MODULE_TYPE_MODULE, + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM, + JSON_MODULE_TYPE, + WEBASSEMBLY_MODULE_TYPE_ASYNC, + WEBASSEMBLY_MODULE_TYPE_SYNC +} = require("../ModuleTypeConstants"); +const Template = require("../Template"); +const { cleverMerge } = require("../util/cleverMerge"); +const { + getDefaultTarget, + getTargetProperties, + getTargetsProperties +} = require("./target"); + +/** @typedef {import("../../declarations/WebpackOptions").CacheOptions} CacheOptions */ +/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptionsNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").Context} Context */ +/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorOptions} CssGeneratorOptions */ +/** @typedef {import("../../declarations/WebpackOptions").CssParserOptions} CssParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */ +/** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */ +/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").Environment} Environment */ +/** @typedef {import("../../declarations/WebpackOptions").Experiments} Experiments */ +/** @typedef {import("../../declarations/WebpackOptions").ExperimentsNormalized} ExperimentsNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */ +/** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */ +/** @typedef {import("../../declarations/WebpackOptions").FileCacheOptions} FileCacheOptions */ +/** @typedef {import("../../declarations/WebpackOptions").GeneratorOptionsByModuleTypeKnown} GeneratorOptionsByModuleTypeKnown */ +/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").JsonGeneratorOptions} JsonGeneratorOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Library} Library */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */ +/** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */ +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */ +/** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */ +/** @typedef {import("../../declarations/WebpackOptions").ParserOptionsByModuleTypeKnown} ParserOptionsByModuleTypeKnown */ +/** @typedef {import("../../declarations/WebpackOptions").Performance} Performance */ +/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */ +/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Target} Target */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("./target").PlatformTargetProperties} PlatformTargetProperties */ +/** @typedef {import("./target").TargetProperties} TargetProperties */ + +/** + * @typedef {object} ResolvedOptions + * @property {PlatformTargetProperties | false} platform - platform target properties + */ + +const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i; +const DEFAULT_CACHE_NAME = "default"; +const DEFAULTS = { + // TODO webpack 6 - use xxhash64 + HASH_FUNCTION: "md4" +}; + +/** + * Sets a constant default value when undefined + * @template T + * @template {keyof T} P + * @param {T} obj an object + * @param {P} prop a property of this object + * @param {T[P]} value a default value of the property + * @returns {void} + */ +const D = (obj, prop, value) => { + if (obj[prop] === undefined) { + obj[prop] = value; + } +}; + +/** + * Sets a dynamic default value when undefined, by calling the factory function + * @template T + * @template {keyof T} P + * @param {T} obj an object + * @param {P} prop a property of this object + * @param {() => T[P]} factory a default value factory for the property + * @returns {void} + */ +const F = (obj, prop, factory) => { + if (obj[prop] === undefined) { + obj[prop] = factory(); + } +}; + +/** + * Sets a dynamic default value when undefined, by calling the factory function. + * factory must return an array or undefined + * When the current value is already an array an contains "..." it's replaced with + * the result of the factory function + * @template T + * @template {keyof T} P + * @param {T} obj an object + * @param {P} prop a property of this object + * @param {() => T[P]} factory a default value factory for the property + * @returns {void} + */ +const A = (obj, prop, factory) => { + const value = obj[prop]; + if (value === undefined) { + obj[prop] = factory(); + } else if (Array.isArray(value)) { + /** @type {EXPECTED_ANY[] | undefined} */ + let newArray; + for (let i = 0; i < value.length; i++) { + const item = value[i]; + if (item === "...") { + if (newArray === undefined) { + newArray = value.slice(0, i); + obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray)); + } + const items = /** @type {EXPECTED_ANY[]} */ ( + /** @type {unknown} */ (factory()) + ); + if (items !== undefined) { + for (const item of items) { + newArray.push(item); + } + } + } else if (newArray !== undefined) { + newArray.push(item); + } + } + } +}; + +/** + * @param {WebpackOptionsNormalized} options options to be modified + * @returns {void} + */ +const applyWebpackOptionsBaseDefaults = (options) => { + F(options, "context", () => process.cwd()); + applyInfrastructureLoggingDefaults(options.infrastructureLogging); +}; + +/** + * @param {WebpackOptionsNormalized} options options to be modified + * @param {number=} compilerIndex index of compiler + * @returns {ResolvedOptions} Resolved options after apply defaults + */ +const applyWebpackOptionsDefaults = (options, compilerIndex) => { + F(options, "context", () => process.cwd()); + F(options, "target", () => + getDefaultTarget(/** @type {string} */ (options.context)) + ); + + const { mode, name, target } = options; + + const targetProperties = + target === false + ? /** @type {false} */ (false) + : typeof target === "string" + ? getTargetProperties(target, /** @type {Context} */ (options.context)) + : getTargetsProperties( + /** @type {string[]} */ (target), + /** @type {Context} */ (options.context) + ); + + const development = mode === "development"; + const production = mode === "production" || !mode; + + if (typeof options.entry !== "function") { + for (const key of Object.keys(options.entry)) { + F( + options.entry[key], + "import", + () => /** @type {[string]} */ (["./src"]) + ); + } + } + + F(options, "devtool", () => (development ? "eval" : false)); + D(options, "watch", false); + D(options, "profile", false); + D(options, "parallelism", 100); + D(options, "recordsInputPath", false); + D(options, "recordsOutputPath", false); + + applyExperimentsDefaults(options.experiments, { + production, + development, + targetProperties + }); + + const futureDefaults = + /** @type {NonNullable} */ + (options.experiments.futureDefaults); + + F(options, "cache", () => + development ? { type: /** @type {"memory"} */ ("memory") } : false + ); + applyCacheDefaults(options.cache, { + name: name || DEFAULT_CACHE_NAME, + mode: mode || "production", + development, + cacheUnaffected: options.experiments.cacheUnaffected, + futureDefaults, + compilerIndex + }); + const cache = Boolean(options.cache); + + applySnapshotDefaults(options.snapshot, { + production, + futureDefaults + }); + + applyOutputDefaults(options.output, { + context: /** @type {Context} */ (options.context), + targetProperties, + isAffectedByBrowserslist: + target === undefined || + (typeof target === "string" && target.startsWith("browserslist")) || + (Array.isArray(target) && + target.some((target) => target.startsWith("browserslist"))), + outputModule: + /** @type {NonNullable} */ + (options.experiments.outputModule), + development, + entry: options.entry, + futureDefaults, + asyncWebAssembly: + /** @type {NonNullable} */ + (options.experiments.asyncWebAssembly) + }); + + applyModuleDefaults(options.module, { + cache, + syncWebAssembly: + /** @type {NonNullable} */ + (options.experiments.syncWebAssembly), + asyncWebAssembly: + /** @type {NonNullable} */ + (options.experiments.asyncWebAssembly), + css: + /** @type {NonNullable} */ + (options.experiments.css), + deferImport: + /** @type {NonNullable} */ + (options.experiments.deferImport), + futureDefaults, + isNode: targetProperties && targetProperties.node === true, + uniqueName: /** @type {string} */ (options.output.uniqueName), + targetProperties, + mode: options.mode + }); + + applyExternalsPresetsDefaults(options.externalsPresets, { + targetProperties, + buildHttp: Boolean(options.experiments.buildHttp) + }); + + applyLoaderDefaults( + /** @type {NonNullable} */ ( + options.loader + ), + { targetProperties, environment: options.output.environment } + ); + + F(options, "externalsType", () => { + const validExternalTypes = require("../../schemas/WebpackOptions.json") + .definitions.ExternalsType.enum; + + return options.output.library && + validExternalTypes.includes(options.output.library.type) + ? /** @type {ExternalsType} */ (options.output.library.type) + : options.output.module + ? "module-import" + : "var"; + }); + + applyNodeDefaults(options.node, { + futureDefaults: + /** @type {NonNullable} */ + (options.experiments.futureDefaults), + outputModule: + /** @type {NonNullable} */ + (options.output.module), + targetProperties + }); + + F(options, "performance", () => + production && + targetProperties && + (targetProperties.browser || targetProperties.browser === null) + ? {} + : false + ); + applyPerformanceDefaults( + /** @type {NonNullable} */ + (options.performance), + { + production + } + ); + + applyOptimizationDefaults(options.optimization, { + development, + production, + css: + /** @type {NonNullable} */ + (options.experiments.css), + records: Boolean(options.recordsInputPath || options.recordsOutputPath) + }); + + options.resolve = cleverMerge( + getResolveDefaults({ + cache, + context: /** @type {Context} */ (options.context), + targetProperties, + mode: /** @type {Mode} */ (options.mode), + css: + /** @type {NonNullable} */ + (options.experiments.css) + }), + options.resolve + ); + + options.resolveLoader = cleverMerge( + getResolveLoaderDefaults({ cache }), + options.resolveLoader + ); + + return { + platform: + targetProperties === false + ? targetProperties + : { + web: targetProperties.web, + browser: targetProperties.browser, + webworker: targetProperties.webworker, + node: targetProperties.node, + nwjs: targetProperties.nwjs, + electron: targetProperties.electron + } + }; +}; + +/** + * @param {ExperimentsNormalized} experiments options + * @param {object} options options + * @param {boolean} options.production is production + * @param {boolean} options.development is development mode + * @param {TargetProperties | false} options.targetProperties target properties + * @returns {void} + */ +const applyExperimentsDefaults = ( + experiments, + { production, development, targetProperties } +) => { + D(experiments, "futureDefaults", false); + D(experiments, "backCompat", !experiments.futureDefaults); + D(experiments, "syncWebAssembly", false); + D(experiments, "asyncWebAssembly", experiments.futureDefaults); + D(experiments, "outputModule", false); + D(experiments, "layers", false); + D(experiments, "lazyCompilation", undefined); + D(experiments, "buildHttp", undefined); + D(experiments, "cacheUnaffected", experiments.futureDefaults); + D(experiments, "deferImport", false); + F(experiments, "css", () => (experiments.futureDefaults ? true : undefined)); + + // TODO webpack 6: remove this. topLevelAwait should be enabled by default + let shouldEnableTopLevelAwait = true; + if (typeof experiments.topLevelAwait === "boolean") { + shouldEnableTopLevelAwait = experiments.topLevelAwait; + } + D(experiments, "topLevelAwait", shouldEnableTopLevelAwait); + + if (typeof experiments.buildHttp === "object") { + D(experiments.buildHttp, "frozen", production); + D(experiments.buildHttp, "upgrade", false); + } +}; + +/** + * @param {CacheOptionsNormalized} cache options + * @param {object} options options + * @param {string} options.name name + * @param {Mode} options.mode mode + * @param {boolean} options.futureDefaults is future defaults enabled + * @param {boolean} options.development is development mode + * @param {number=} options.compilerIndex index of compiler + * @param {Experiments["cacheUnaffected"]} options.cacheUnaffected the cacheUnaffected experiment is enabled + * @returns {void} + */ +const applyCacheDefaults = ( + cache, + { name, mode, development, cacheUnaffected, compilerIndex, futureDefaults } +) => { + if (cache === false) return; + switch (cache.type) { + case "filesystem": + F(cache, "name", () => + compilerIndex !== undefined + ? `${`${name}-${mode}`}__compiler${compilerIndex + 1}__` + : `${name}-${mode}` + ); + D(cache, "version", ""); + F(cache, "cacheDirectory", () => { + const cwd = process.cwd(); + /** @type {string | undefined} */ + let dir = cwd; + for (;;) { + try { + if (fs.statSync(path.join(dir, "package.json")).isFile()) break; + // eslint-disable-next-line no-empty + } catch (_err) {} + const parent = path.dirname(dir); + if (dir === parent) { + dir = undefined; + break; + } + dir = parent; + } + if (!dir) { + return path.resolve(cwd, ".cache/webpack"); + } else if (process.versions.pnp === "1") { + return path.resolve(dir, ".pnp/.cache/webpack"); + } else if (process.versions.pnp === "3") { + return path.resolve(dir, ".yarn/.cache/webpack"); + } + return path.resolve(dir, "node_modules/.cache/webpack"); + }); + F(cache, "cacheLocation", () => + path.resolve( + /** @type {NonNullable} */ + (cache.cacheDirectory), + /** @type {NonNullable} */ (cache.name) + ) + ); + D(cache, "hashAlgorithm", futureDefaults ? "xxhash64" : "md4"); + D(cache, "store", "pack"); + D(cache, "compression", false); + D(cache, "profile", false); + D(cache, "idleTimeout", 60000); + D(cache, "idleTimeoutForInitialStore", 5000); + D(cache, "idleTimeoutAfterLargeChanges", 1000); + D(cache, "maxMemoryGenerations", development ? 5 : Infinity); + D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month + D(cache, "allowCollectingMemory", development); + D(cache, "memoryCacheUnaffected", development && cacheUnaffected); + D(cache, "readonly", false); + D( + /** @type {NonNullable} */ + (cache.buildDependencies), + "defaultWebpack", + [path.resolve(__dirname, "..") + path.sep] + ); + break; + case "memory": + D(cache, "maxGenerations", Infinity); + D(cache, "cacheUnaffected", development && cacheUnaffected); + break; + } +}; + +/** + * @param {SnapshotOptions} snapshot options + * @param {object} options options + * @param {boolean} options.production is production + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => { + if (futureDefaults) { + F(snapshot, "managedPaths", () => + process.versions.pnp === "3" + ? [ + /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/ + ] + : [/^(.+?[\\/]node_modules[\\/])/] + ); + F(snapshot, "immutablePaths", () => + process.versions.pnp === "3" + ? [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/] + : [] + ); + } else { + A(snapshot, "managedPaths", () => { + if (process.versions.pnp === "3") { + const match = + /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( + require.resolve("watchpack") + ); + if (match) { + return [path.resolve(match[1], "unplugged")]; + } + } else { + const match = /^(.+?[\\/]node_modules[\\/])/.exec( + require.resolve("watchpack") + ); + if (match) { + return [match[1]]; + } + } + return []; + }); + A(snapshot, "immutablePaths", () => { + if (process.versions.pnp === "1") { + const match = + /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec( + require.resolve("watchpack") + ); + if (match) { + return [match[1]]; + } + } else if (process.versions.pnp === "3") { + const match = + /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( + require.resolve("watchpack") + ); + if (match) { + return [match[1]]; + } + } + return []; + }); + } + F(snapshot, "unmanagedPaths", () => []); + F(snapshot, "resolveBuildDependencies", () => ({ + timestamp: true, + hash: true + })); + F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true })); + F(snapshot, "module", () => + production ? { timestamp: true, hash: true } : { timestamp: true } + ); + F(snapshot, "resolve", () => + production ? { timestamp: true, hash: true } : { timestamp: true } + ); +}; + +/** + * @param {JavascriptParserOptions} parserOptions parser options + * @param {object} options options + * @param {boolean} options.futureDefaults is future defaults enabled + * @param {boolean} options.deferImport is defer import enabled + * @param {boolean} options.isNode is node target platform + * @returns {void} + */ +const applyJavascriptParserOptionsDefaults = ( + parserOptions, + { futureDefaults, deferImport, isNode } +) => { + D(parserOptions, "unknownContextRequest", "."); + D(parserOptions, "unknownContextRegExp", false); + D(parserOptions, "unknownContextRecursive", true); + D(parserOptions, "unknownContextCritical", true); + D(parserOptions, "exprContextRequest", "."); + D(parserOptions, "exprContextRegExp", false); + D(parserOptions, "exprContextRecursive", true); + D(parserOptions, "exprContextCritical", true); + D(parserOptions, "wrappedContextRegExp", /.*/); + D(parserOptions, "wrappedContextRecursive", true); + D(parserOptions, "wrappedContextCritical", false); + D(parserOptions, "strictThisContextOnImports", false); + D(parserOptions, "importMeta", true); + D(parserOptions, "dynamicImportMode", "lazy"); + D(parserOptions, "dynamicImportPrefetch", false); + D(parserOptions, "dynamicImportPreload", false); + D(parserOptions, "dynamicImportFetchPriority", false); + D(parserOptions, "createRequire", isNode); + D(parserOptions, "dynamicUrl", true); + D(parserOptions, "deferImport", deferImport); + if (futureDefaults) D(parserOptions, "exportsPresence", "error"); +}; + +/** + * @param {JsonGeneratorOptions} generatorOptions generator options + * @returns {void} + */ +const applyJsonGeneratorOptionsDefaults = (generatorOptions) => { + D(generatorOptions, "JSONParse", true); +}; + +/** + * @param {CssGeneratorOptions} generatorOptions generator options + * @param {object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @returns {void} + */ +const applyCssGeneratorOptionsDefaults = ( + generatorOptions, + { targetProperties } +) => { + D( + generatorOptions, + "exportsOnly", + !targetProperties || targetProperties.document === false + ); + D(generatorOptions, "esModule", true); +}; + +/** + * @param {ModuleOptions} module options + * @param {object} options options + * @param {boolean} options.cache is caching enabled + * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled + * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled + * @param {boolean} options.css is css enabled + * @param {boolean} options.futureDefaults is future defaults enabled + * @param {string} options.uniqueName the unique name + * @param {boolean} options.isNode is node target platform + * @param {boolean} options.deferImport is defer import enabled + * @param {TargetProperties | false} options.targetProperties target properties + * @param {Mode | undefined} options.mode mode + * @returns {void} + */ +const applyModuleDefaults = ( + module, + { + cache, + syncWebAssembly, + asyncWebAssembly, + css, + futureDefaults, + isNode, + uniqueName, + targetProperties, + mode, + deferImport + } +) => { + if (cache) { + D( + module, + "unsafeCache", + /** + * @param {Module} module module + * @returns {boolean} true, if we want to cache the module + */ + (module) => { + const name = module.nameForCondition(); + if (!name) { + return false; + } + return NODE_MODULES_REGEXP.test(name); + } + ); + } else { + D(module, "unsafeCache", false); + } + + F(module.parser, ASSET_MODULE_TYPE, () => ({})); + F( + /** @type {NonNullable} */ + (module.parser[ASSET_MODULE_TYPE]), + "dataUrlCondition", + () => ({}) + ); + if ( + typeof ( + /** @type {NonNullable} */ + (module.parser[ASSET_MODULE_TYPE]).dataUrlCondition + ) === "object" + ) { + D( + /** @type {NonNullable} */ + (module.parser[ASSET_MODULE_TYPE]).dataUrlCondition, + "maxSize", + 8096 + ); + } + + F(module.parser, "javascript", () => ({})); + F(module.parser, JSON_MODULE_TYPE, () => ({})); + D( + /** @type {NonNullable} */ + (module.parser[JSON_MODULE_TYPE]), + "exportsDepth", + mode === "development" ? 1 : Infinity + ); + + applyJavascriptParserOptionsDefaults( + /** @type {NonNullable} */ + (module.parser.javascript), + { + futureDefaults, + deferImport, + isNode + } + ); + + F(module.generator, "json", () => ({})); + applyJsonGeneratorOptionsDefaults( + /** @type {NonNullable} */ + (module.generator.json) + ); + + if (css) { + F(module.parser, CSS_MODULE_TYPE, () => ({})); + + D( + /** @type {NonNullable} */ + (module.parser[CSS_MODULE_TYPE]), + "import", + true + ); + D( + /** @type {NonNullable} */ + (module.parser[CSS_MODULE_TYPE]), + "url", + true + ); + D( + /** @type {NonNullable} */ + (module.parser[CSS_MODULE_TYPE]), + "namedExports", + true + ); + + F(module.generator, CSS_MODULE_TYPE, () => ({})); + + applyCssGeneratorOptionsDefaults( + /** @type {NonNullable} */ + (module.generator[CSS_MODULE_TYPE]), + { targetProperties } + ); + + const localIdentName = + uniqueName.length > 0 ? "[uniqueName]-[id]-[local]" : "[id]-[local]"; + + F(module.generator, CSS_MODULE_TYPE_AUTO, () => ({})); + D( + /** @type {NonNullable} */ + (module.generator[CSS_MODULE_TYPE_AUTO]), + "localIdentName", + localIdentName + ); + D( + /** @type {NonNullable} */ + (module.generator[CSS_MODULE_TYPE_AUTO]), + "exportsConvention", + "as-is" + ); + + F(module.generator, CSS_MODULE_TYPE_MODULE, () => ({})); + D( + /** @type {NonNullable} */ + (module.generator[CSS_MODULE_TYPE_MODULE]), + "localIdentName", + localIdentName + ); + D( + /** @type {NonNullable} */ + (module.generator[CSS_MODULE_TYPE_MODULE]), + "exportsConvention", + "as-is" + ); + + F(module.generator, CSS_MODULE_TYPE_GLOBAL, () => ({})); + D( + /** @type {NonNullable} */ + (module.generator[CSS_MODULE_TYPE_GLOBAL]), + "localIdentName", + localIdentName + ); + D( + /** @type {NonNullable} */ + (module.generator[CSS_MODULE_TYPE_GLOBAL]), + "exportsConvention", + "as-is" + ); + } + + A(module, "defaultRules", () => { + const esm = { + type: JAVASCRIPT_MODULE_TYPE_ESM, + resolve: { + byDependency: { + esm: { + fullySpecified: true + } + } + } + }; + const commonjs = { + type: JAVASCRIPT_MODULE_TYPE_DYNAMIC + }; + /** @type {RuleSetRules} */ + const rules = [ + { + mimetype: "application/node", + type: JAVASCRIPT_MODULE_TYPE_AUTO + }, + { + test: /\.json$/i, + type: JSON_MODULE_TYPE + }, + { + mimetype: "application/json", + type: JSON_MODULE_TYPE + }, + { + test: /\.mjs$/i, + ...esm + }, + { + test: /\.js$/i, + descriptionData: { + type: "module" + }, + ...esm + }, + { + test: /\.cjs$/i, + ...commonjs + }, + { + test: /\.js$/i, + descriptionData: { + type: "commonjs" + }, + ...commonjs + }, + { + mimetype: { + or: ["text/javascript", "application/javascript"] + }, + ...esm + } + ]; + if (asyncWebAssembly) { + const wasm = { + type: WEBASSEMBLY_MODULE_TYPE_ASYNC, + rules: [ + { + descriptionData: { + type: "module" + }, + resolve: { + fullySpecified: true + } + } + ] + }; + rules.push({ + test: /\.wasm$/i, + ...wasm + }); + rules.push({ + mimetype: "application/wasm", + ...wasm + }); + } else if (syncWebAssembly) { + const wasm = { + type: WEBASSEMBLY_MODULE_TYPE_SYNC, + rules: [ + { + descriptionData: { + type: "module" + }, + resolve: { + fullySpecified: true + } + } + ] + }; + rules.push({ + test: /\.wasm$/i, + ...wasm + }); + rules.push({ + mimetype: "application/wasm", + ...wasm + }); + } + if (css) { + const resolve = { + fullySpecified: true, + preferRelative: true + }; + rules.push({ + test: /\.css$/i, + type: CSS_MODULE_TYPE_AUTO, + resolve + }); + rules.push({ + mimetype: "text/css+module", + type: CSS_MODULE_TYPE_MODULE, + resolve + }); + rules.push({ + mimetype: "text/css", + type: CSS_MODULE_TYPE, + resolve + }); + } + rules.push( + { + dependency: "url", + oneOf: [ + { + scheme: /^data$/, + type: ASSET_MODULE_TYPE_INLINE + }, + { + type: ASSET_MODULE_TYPE_RESOURCE + } + ] + }, + { + assert: { type: JSON_MODULE_TYPE }, + type: JSON_MODULE_TYPE + }, + { + with: { type: JSON_MODULE_TYPE }, + type: JSON_MODULE_TYPE + } + ); + return rules; + }); +}; + +/** + * @param {Output} output options + * @param {object} options options + * @param {string} options.context context + * @param {TargetProperties | false} options.targetProperties target properties + * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist + * @param {boolean} options.outputModule is outputModule experiment enabled + * @param {boolean} options.development is development mode + * @param {Entry} options.entry entry option + * @param {boolean} options.futureDefaults is future defaults enabled + * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled + * @returns {void} + */ +const applyOutputDefaults = ( + output, + { + context, + targetProperties: tp, + isAffectedByBrowserslist, + outputModule, + development, + entry, + futureDefaults, + asyncWebAssembly + } +) => { + /** + * @param {Library=} library the library option + * @returns {string} a readable library name + */ + const getLibraryName = (library) => { + const libraryName = + typeof library === "object" && + library && + !Array.isArray(library) && + "type" in library + ? library.name + : /** @type {LibraryName} */ (library); + if (Array.isArray(libraryName)) { + return libraryName.join("."); + } else if (typeof libraryName === "object") { + return getLibraryName(libraryName.root); + } else if (typeof libraryName === "string") { + return libraryName; + } + return ""; + }; + + F(output, "uniqueName", () => { + const libraryName = getLibraryName(output.library).replace( + /^\[(\\*[\w:]+\\*)\](\.)|(\.)\[(\\*[\w:]+\\*)\](?=\.|$)|\[(\\*[\w:]+\\*)\]/g, + (m, a, d1, d2, b, c) => { + const content = a || b || c; + return content.startsWith("\\") && content.endsWith("\\") + ? `${d2 || ""}[${content.slice(1, -1)}]${d1 || ""}` + : ""; + } + ); + if (libraryName) return libraryName; + const pkgPath = path.resolve(context, "package.json"); + try { + const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf8")); + return packageInfo.name || ""; + } catch (err) { + if (/** @type {Error & { code: string }} */ (err).code !== "ENOENT") { + /** @type {Error & { code: string }} */ + (err).message += + `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`; + throw err; + } + return ""; + } + }); + + F(output, "module", () => Boolean(outputModule)); + + const environment = /** @type {Environment} */ (output.environment); + /** + * @param {boolean | undefined} v value + * @returns {boolean} true, when v is truthy or undefined + */ + const optimistic = (v) => v || v === undefined; + /** + * @param {boolean | undefined} v value + * @param {boolean | undefined} c condition + * @returns {boolean | undefined} true, when v is truthy or undefined, or c is truthy + */ + const conditionallyOptimistic = (v, c) => (v === undefined && c) || v; + + F( + environment, + "globalThis", + () => /** @type {boolean | undefined} */ (tp && tp.globalThis) + ); + F( + environment, + "bigIntLiteral", + () => + tp && optimistic(/** @type {boolean | undefined} */ (tp.bigIntLiteral)) + ); + F( + environment, + "const", + () => tp && optimistic(/** @type {boolean | undefined} */ (tp.const)) + ); + F( + environment, + "arrowFunction", + () => + tp && optimistic(/** @type {boolean | undefined} */ (tp.arrowFunction)) + ); + F( + environment, + "asyncFunction", + () => + tp && optimistic(/** @type {boolean | undefined} */ (tp.asyncFunction)) + ); + F( + environment, + "forOf", + () => tp && optimistic(/** @type {boolean | undefined} */ (tp.forOf)) + ); + F( + environment, + "destructuring", + () => + tp && optimistic(/** @type {boolean | undefined} */ (tp.destructuring)) + ); + F( + environment, + "optionalChaining", + () => + tp && optimistic(/** @type {boolean | undefined} */ (tp.optionalChaining)) + ); + F( + environment, + "nodePrefixForCoreModules", + () => + tp && + optimistic( + /** @type {boolean | undefined} */ (tp.nodePrefixForCoreModules) + ) + ); + F( + environment, + "templateLiteral", + () => + tp && optimistic(/** @type {boolean | undefined} */ (tp.templateLiteral)) + ); + F(environment, "dynamicImport", () => + conditionallyOptimistic( + /** @type {boolean | undefined} */ (tp && tp.dynamicImport), + output.module + ) + ); + F(environment, "dynamicImportInWorker", () => + conditionallyOptimistic( + /** @type {boolean | undefined} */ (tp && tp.dynamicImportInWorker), + output.module + ) + ); + F(environment, "module", () => + conditionallyOptimistic( + /** @type {boolean | undefined} */ (tp && tp.module), + output.module + ) + ); + F( + environment, + "document", + () => tp && optimistic(/** @type {boolean | undefined} */ (tp.document)) + ); + + D(output, "filename", output.module ? "[name].mjs" : "[name].js"); + F(output, "iife", () => !output.module); + D(output, "importFunctionName", "import"); + D(output, "importMetaName", "import.meta"); + F(output, "chunkFilename", () => { + const filename = + /** @type {NonNullable} */ + (output.filename); + if (typeof filename !== "function") { + const hasName = filename.includes("[name]"); + const hasId = filename.includes("[id]"); + const hasChunkHash = filename.includes("[chunkhash]"); + const hasContentHash = filename.includes("[contenthash]"); + // Anything changing depending on chunk is fine + if (hasChunkHash || hasContentHash || hasName || hasId) return filename; + // Otherwise prefix "[id]." in front of the basename to make it changing + return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); + } + return output.module ? "[id].mjs" : "[id].js"; + }); + F(output, "cssFilename", () => { + const filename = + /** @type {NonNullable} */ + (output.filename); + if (typeof filename !== "function") { + return filename.replace(/\.[mc]?js(\?|$)/, ".css$1"); + } + return "[id].css"; + }); + F(output, "cssChunkFilename", () => { + const chunkFilename = + /** @type {NonNullable} */ + (output.chunkFilename); + if (typeof chunkFilename !== "function") { + return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1"); + } + return "[id].css"; + }); + D(output, "assetModuleFilename", "[hash][ext][query]"); + D(output, "webassemblyModuleFilename", "[hash].module.wasm"); + D(output, "compareBeforeEmit", true); + D(output, "charset", !futureDefaults); + const uniqueNameId = Template.toIdentifier( + /** @type {NonNullable} */ (output.uniqueName) + ); + F(output, "hotUpdateGlobal", () => `webpackHotUpdate${uniqueNameId}`); + F(output, "chunkLoadingGlobal", () => `webpackChunk${uniqueNameId}`); + F(output, "globalObject", () => { + if (tp) { + if (tp.global) return "global"; + if (tp.globalThis) return "globalThis"; + } + return "self"; + }); + F(output, "chunkFormat", () => { + if (tp) { + const helpMessage = isAffectedByBrowserslist + ? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly." + : "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly."; + if (output.module) { + if (environment.dynamicImport) return "module"; + if (tp.document) return "array-push"; + throw new Error( + "For the selected environment is no default ESM chunk format available:\n" + + "ESM exports can be chosen when 'import()' is available.\n" + + `JSONP Array push can be chosen when 'document' is available.\n${ + helpMessage + }` + ); + } else { + if (tp.document) return "array-push"; + if (tp.require) return "commonjs"; + if (tp.nodeBuiltins) return "commonjs"; + if (tp.importScripts) return "array-push"; + throw new Error( + "For the selected environment is no default script chunk format available:\n" + + "JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" + + `CommonJs exports can be chosen when 'require' or node builtins are available.\n${ + helpMessage + }` + ); + } + } + throw new Error( + "Chunk format can't be selected by default when no target is specified" + ); + }); + D(output, "asyncChunks", true); + F(output, "chunkLoading", () => { + if (tp) { + switch (output.chunkFormat) { + case "array-push": + if (tp.document) return "jsonp"; + if (tp.importScripts) return "import-scripts"; + break; + case "commonjs": + if (tp.require) return "require"; + if (tp.nodeBuiltins) return "async-node"; + break; + case "module": + if (environment.dynamicImport) return "import"; + break; + } + if ( + (tp.require === null || + tp.nodeBuiltins === null || + tp.document === null || + tp.importScripts === null) && + output.module && + environment.dynamicImport + ) { + return "universal"; + } + } + return false; + }); + F(output, "workerChunkLoading", () => { + if (tp) { + switch (output.chunkFormat) { + case "array-push": + if (tp.importScriptsInWorker) return "import-scripts"; + break; + case "commonjs": + if (tp.require) return "require"; + if (tp.nodeBuiltins) return "async-node"; + break; + case "module": + if (environment.dynamicImportInWorker) return "import"; + break; + } + if ( + (tp.require === null || + tp.nodeBuiltins === null || + tp.importScriptsInWorker === null) && + output.module && + environment.dynamicImportInWorker + ) { + return "universal"; + } + } + return false; + }); + F(output, "wasmLoading", () => { + if (tp) { + if (tp.fetchWasm) return "fetch"; + if (tp.nodeBuiltins) return "async-node"; + if ( + (tp.nodeBuiltins === null || tp.fetchWasm === null) && + asyncWebAssembly && + output.module && + environment.dynamicImport + ) { + return "universal"; + } + } + return false; + }); + F(output, "workerWasmLoading", () => output.wasmLoading); + F(output, "devtoolNamespace", () => output.uniqueName); + if (output.library) { + F(output.library, "type", () => (output.module ? "module" : "var")); + } + F(output, "path", () => path.join(process.cwd(), "dist")); + F(output, "pathinfo", () => development); + D(output, "sourceMapFilename", "[file].map[query]"); + D( + output, + "hotUpdateChunkFilename", + `[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}` + ); + D( + output, + "hotUpdateMainFilename", + `[runtime].[fullhash].hot-update.${output.module ? "json.mjs" : "json"}` + ); + D(output, "crossOriginLoading", false); + F(output, "scriptType", () => (output.module ? "module" : false)); + D( + output, + "publicPath", + (tp && (tp.document || tp.importScripts)) || output.scriptType === "module" + ? "auto" + : "" + ); + D(output, "workerPublicPath", ""); + D(output, "chunkLoadTimeout", 120000); + F(output, "hashFunction", () => { + if (futureDefaults) { + DEFAULTS.HASH_FUNCTION = "xxhash64"; + return "xxhash64"; + } + + return "md4"; + }); + D(output, "hashDigest", "hex"); + D(output, "hashDigestLength", futureDefaults ? 16 : 20); + D(output, "strictModuleErrorHandling", false); + D(output, "strictModuleExceptionHandling", false); + + const { trustedTypes } = output; + if (trustedTypes) { + F( + trustedTypes, + "policyName", + () => + /** @type {NonNullable} */ + (output.uniqueName).replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack" + ); + D(trustedTypes, "onPolicyCreationFailure", "stop"); + } + + /** + * @param {(entryDescription: EntryDescription) => void} fn iterator + * @returns {void} + */ + const forEachEntry = (fn) => { + for (const name of Object.keys(entry)) { + fn(/** @type {{[k: string] : EntryDescription}} */ (entry)[name]); + } + }; + A(output, "enabledLibraryTypes", () => { + /** @type {LibraryType[]} */ + const enabledLibraryTypes = []; + if (output.library) { + enabledLibraryTypes.push(output.library.type); + } + forEachEntry((desc) => { + if (desc.library) { + enabledLibraryTypes.push(desc.library.type); + } + }); + return enabledLibraryTypes; + }); + + A(output, "enabledChunkLoadingTypes", () => { + const enabledChunkLoadingTypes = new Set(); + if (output.chunkLoading) { + enabledChunkLoadingTypes.add(output.chunkLoading); + } + if (output.workerChunkLoading) { + enabledChunkLoadingTypes.add(output.workerChunkLoading); + } + forEachEntry((desc) => { + if (desc.chunkLoading) { + enabledChunkLoadingTypes.add(desc.chunkLoading); + } + }); + return [...enabledChunkLoadingTypes]; + }); + + A(output, "enabledWasmLoadingTypes", () => { + const enabledWasmLoadingTypes = new Set(); + if (output.wasmLoading) { + enabledWasmLoadingTypes.add(output.wasmLoading); + } + if (output.workerWasmLoading) { + enabledWasmLoadingTypes.add(output.workerWasmLoading); + } + forEachEntry((desc) => { + if (desc.wasmLoading) { + enabledWasmLoadingTypes.add(desc.wasmLoading); + } + }); + return [...enabledWasmLoadingTypes]; + }); +}; + +/** + * @param {ExternalsPresets} externalsPresets options + * @param {object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @param {boolean} options.buildHttp buildHttp experiment enabled + * @returns {void} + */ +const applyExternalsPresetsDefaults = ( + externalsPresets, + { targetProperties, buildHttp } +) => { + D( + externalsPresets, + "web", + /** @type {boolean | undefined} */ + (!buildHttp && targetProperties && targetProperties.web) + ); + D( + externalsPresets, + "node", + /** @type {boolean | undefined} */ + (targetProperties && targetProperties.node) + ); + D( + externalsPresets, + "nwjs", + /** @type {boolean | undefined} */ + (targetProperties && targetProperties.nwjs) + ); + D( + externalsPresets, + "electron", + /** @type {boolean | undefined} */ + (targetProperties && targetProperties.electron) + ); + D( + externalsPresets, + "electronMain", + /** @type {boolean | undefined} */ + ( + targetProperties && + targetProperties.electron && + targetProperties.electronMain + ) + ); + D( + externalsPresets, + "electronPreload", + /** @type {boolean | undefined} */ + ( + targetProperties && + targetProperties.electron && + targetProperties.electronPreload + ) + ); + D( + externalsPresets, + "electronRenderer", + /** @type {boolean | undefined} */ + ( + targetProperties && + targetProperties.electron && + targetProperties.electronRenderer + ) + ); +}; + +/** + * @param {Loader} loader options + * @param {object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @param {Environment} options.environment environment + * @returns {void} + */ +const applyLoaderDefaults = (loader, { targetProperties, environment }) => { + F(loader, "target", () => { + if (targetProperties) { + if (targetProperties.electron) { + if (targetProperties.electronMain) return "electron-main"; + if (targetProperties.electronPreload) return "electron-preload"; + if (targetProperties.electronRenderer) return "electron-renderer"; + return "electron"; + } + if (targetProperties.nwjs) return "nwjs"; + if (targetProperties.node) return "node"; + if (targetProperties.web) return "web"; + } + }); + D(loader, "environment", environment); +}; + +/** + * @param {WebpackNode} node options + * @param {object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @param {boolean} options.futureDefaults is future defaults enabled + * @param {boolean} options.outputModule is output type is module + * @returns {void} + */ +const applyNodeDefaults = ( + node, + { futureDefaults, outputModule, targetProperties } +) => { + if (node === false) return; + + F(node, "global", () => { + if (targetProperties && targetProperties.global) return false; + // TODO webpack 6 should always default to false + return futureDefaults ? "warn" : true; + }); + + const handlerForNames = () => { + if (targetProperties && targetProperties.node) { + return outputModule ? "node-module" : "eval-only"; + } + // TODO webpack 6 should always default to false + return futureDefaults ? "warn-mock" : "mock"; + }; + + F(node, "__filename", handlerForNames); + F(node, "__dirname", handlerForNames); +}; + +/** + * @param {Performance} performance options + * @param {object} options options + * @param {boolean} options.production is production + * @returns {void} + */ +const applyPerformanceDefaults = (performance, { production }) => { + if (performance === false) return; + D(performance, "maxAssetSize", 250000); + D(performance, "maxEntrypointSize", 250000); + F(performance, "hints", () => (production ? "warning" : false)); +}; + +/** + * @param {Optimization} optimization options + * @param {object} options options + * @param {boolean} options.production is production + * @param {boolean} options.development is development + * @param {boolean} options.css is css enabled + * @param {boolean} options.records using records + * @returns {void} + */ +const applyOptimizationDefaults = ( + optimization, + { production, development, css, records } +) => { + D(optimization, "removeAvailableModules", false); + D(optimization, "removeEmptyChunks", true); + D(optimization, "mergeDuplicateChunks", true); + D(optimization, "flagIncludedChunks", production); + F(optimization, "moduleIds", () => { + if (production) return "deterministic"; + if (development) return "named"; + return "natural"; + }); + F(optimization, "chunkIds", () => { + if (production) return "deterministic"; + if (development) return "named"; + return "natural"; + }); + F(optimization, "sideEffects", () => (production ? true : "flag")); + D(optimization, "providedExports", true); + D(optimization, "usedExports", production); + D(optimization, "innerGraph", production); + D(optimization, "mangleExports", production); + D(optimization, "concatenateModules", production); + D(optimization, "avoidEntryIife", production); + D(optimization, "runtimeChunk", false); + D(optimization, "emitOnErrors", !production); + D(optimization, "checkWasmTypes", production); + D(optimization, "mangleWasmImports", false); + D(optimization, "portableRecords", records); + D(optimization, "realContentHash", production); + D(optimization, "minimize", production); + A(optimization, "minimizer", () => [ + { + apply: (compiler) => { + // Lazy load the Terser plugin + const TerserPlugin = require("terser-webpack-plugin"); + + new TerserPlugin({ + terserOptions: { + compress: { + passes: 2 + } + } + }).apply(/** @type {EXPECTED_ANY} */ (compiler)); + } + } + ]); + F(optimization, "nodeEnv", () => { + if (production) return "production"; + if (development) return "development"; + return false; + }); + const { splitChunks } = optimization; + if (splitChunks) { + A(splitChunks, "defaultSizeTypes", () => + css ? ["javascript", "css", "unknown"] : ["javascript", "unknown"] + ); + D(splitChunks, "hidePathInfo", production); + D(splitChunks, "chunks", "async"); + D(splitChunks, "usedExports", optimization.usedExports === true); + D(splitChunks, "minChunks", 1); + F(splitChunks, "minSize", () => (production ? 20000 : 10000)); + F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined)); + F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000)); + F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity)); + F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity)); + D(splitChunks, "automaticNameDelimiter", "-"); + const cacheGroups = + /** @type {NonNullable} */ + (splitChunks.cacheGroups); + F(cacheGroups, "default", () => ({ + idHint: "", + reuseExistingChunk: true, + minChunks: 2, + priority: -20 + })); + F(cacheGroups, "defaultVendors", () => ({ + idHint: "vendors", + reuseExistingChunk: true, + test: NODE_MODULES_REGEXP, + priority: -10 + })); + } +}; + +/** + * @param {object} options options + * @param {boolean} options.cache is cache enable + * @param {string} options.context build context + * @param {TargetProperties | false} options.targetProperties target properties + * @param {Mode} options.mode mode + * @param {boolean} options.css is css enabled + * @returns {ResolveOptions} resolve options + */ +const getResolveDefaults = ({ + cache, + context, + targetProperties, + mode, + css +}) => { + /** @type {string[]} */ + const conditions = ["webpack"]; + + conditions.push(mode === "development" ? "development" : "production"); + + if (targetProperties) { + if (targetProperties.webworker) conditions.push("worker"); + if (targetProperties.node) conditions.push("node"); + if (targetProperties.web) conditions.push("browser"); + if (targetProperties.electron) conditions.push("electron"); + if (targetProperties.nwjs) conditions.push("nwjs"); + } + + const jsExtensions = [".js", ".json", ".wasm"]; + + const tp = targetProperties; + const browserField = + tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer)); + + /** @type {() => ResolveOptions} */ + const cjsDeps = () => ({ + aliasFields: browserField ? ["browser"] : [], + mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], + conditionNames: ["require", "module", "..."], + extensions: [...jsExtensions] + }); + /** @type {() => ResolveOptions} */ + const esmDeps = () => ({ + aliasFields: browserField ? ["browser"] : [], + mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], + conditionNames: ["import", "module", "..."], + extensions: [...jsExtensions] + }); + + /** @type {ResolveOptions} */ + const resolveOptions = { + cache, + modules: ["node_modules"], + conditionNames: conditions, + mainFiles: ["index"], + extensions: [], + aliasFields: [], + exportsFields: ["exports"], + roots: [context], + mainFields: ["main"], + importsFields: ["imports"], + byDependency: { + wasm: esmDeps(), + esm: esmDeps(), + loaderImport: esmDeps(), + url: { + preferRelative: true + }, + worker: { + ...esmDeps(), + preferRelative: true + }, + commonjs: cjsDeps(), + amd: cjsDeps(), + // for backward-compat: loadModule + loader: cjsDeps(), + // for backward-compat: Custom Dependency + unknown: cjsDeps(), + // for backward-compat: getResolve without dependencyType + undefined: cjsDeps() + } + }; + + if (css) { + const styleConditions = []; + + styleConditions.push("webpack"); + styleConditions.push(mode === "development" ? "development" : "production"); + styleConditions.push("style"); + + /** @type {NonNullable} */ + (resolveOptions.byDependency)["css-import"] = { + // We avoid using any main files because we have to be consistent with CSS `@import` + // and CSS `@import` does not handle `main` files in directories, + // you should always specify the full URL for styles + mainFiles: [], + mainFields: ["style", "..."], + conditionNames: styleConditions, + extensions: [".css"], + preferRelative: true + }; + } + + return resolveOptions; +}; + +/** + * @param {object} options options + * @param {boolean} options.cache is cache enable + * @returns {ResolveOptions} resolve options + */ +const getResolveLoaderDefaults = ({ cache }) => { + /** @type {ResolveOptions} */ + const resolveOptions = { + cache, + conditionNames: ["loader", "require", "node"], + exportsFields: ["exports"], + mainFields: ["loader", "main"], + extensions: [".js"], + mainFiles: ["index"] + }; + + return resolveOptions; +}; + +/** + * @param {InfrastructureLogging} infrastructureLogging options + * @returns {void} + */ +const applyInfrastructureLoggingDefaults = (infrastructureLogging) => { + F(infrastructureLogging, "stream", () => process.stderr); + const tty = + /** @type {NonNullable} */ + (infrastructureLogging.stream).isTTY && process.env.TERM !== "dumb"; + D(infrastructureLogging, "level", "info"); + D(infrastructureLogging, "debug", false); + D(infrastructureLogging, "colors", tty); + D(infrastructureLogging, "appendOnly", !tty); +}; + +module.exports.DEFAULTS = DEFAULTS; +module.exports.applyWebpackOptionsBaseDefaults = + applyWebpackOptionsBaseDefaults; +module.exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/normalization.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/normalization.js new file mode 100644 index 0000000000000000000000000000000000000000..fbd001c349b10290ac7d91900ab81a2670630ea4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/normalization.js @@ -0,0 +1,569 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); + +/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptions */ +/** @typedef {import("../../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescriptionNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").EntryStatic} EntryStatic */ +/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").Externals} Externals */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptionsNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").Plugins} Plugins */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../WebpackError")} WebpackError */ + +const handledDeprecatedNoEmitOnErrors = util.deprecate( + /** + * @param {boolean} noEmitOnErrors no emit on errors + * @param {boolean | undefined} emitOnErrors emit on errors + * @returns {boolean} emit on errors + */ + (noEmitOnErrors, emitOnErrors) => { + if (emitOnErrors !== undefined && !noEmitOnErrors === !emitOnErrors) { + throw new Error( + "Conflicting use of 'optimization.noEmitOnErrors' and 'optimization.emitOnErrors'. Remove deprecated 'optimization.noEmitOnErrors' from config." + ); + } + return !noEmitOnErrors; + }, + "optimization.noEmitOnErrors is deprecated in favor of optimization.emitOnErrors", + "DEP_WEBPACK_CONFIGURATION_OPTIMIZATION_NO_EMIT_ON_ERRORS" +); + +/** + * @template T + * @template R + * @param {T | undefined} value value or not + * @param {(value: T) => R} fn nested handler + * @returns {R} result value + */ +const nestedConfig = (value, fn) => + value === undefined ? fn(/** @type {T} */ ({})) : fn(value); + +/** + * @template T + * @param {T|undefined} value value or not + * @returns {T} result value + */ +const cloneObject = (value) => /** @type {T} */ ({ ...value }); +/** + * @template T + * @template R + * @param {T | undefined} value value or not + * @param {(value: T) => R} fn nested handler + * @returns {R | undefined} result value + */ +const optionalNestedConfig = (value, fn) => + value === undefined ? undefined : fn(value); + +/** + * @template T + * @template R + * @param {T[] | undefined} value array or not + * @param {(value: T[]) => R[]} fn nested handler + * @returns {R[] | undefined} cloned value + */ +const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([])); + +/** + * @template T + * @template R + * @param {T[] | undefined} value array or not + * @param {(value: T[]) => R[]} fn nested handler + * @returns {R[] | undefined} cloned value + */ +const optionalNestedArray = (value, fn) => + Array.isArray(value) ? fn(value) : undefined; + +/** + * @template T + * @template R + * @param {Record|undefined} value value or not + * @param {(value: T) => R} fn nested handler + * @param {Record R>=} customKeys custom nested handler for some keys + * @returns {Record} result value + */ +const keyedNestedConfig = (value, fn, customKeys) => { + /* eslint-disable no-sequences */ + const result = + value === undefined + ? {} + : Object.keys(value).reduce( + (obj, key) => ( + (obj[key] = ( + customKeys && key in customKeys ? customKeys[key] : fn + )(value[key])), + obj + ), + /** @type {Record} */ ({}) + ); + /* eslint-enable no-sequences */ + if (customKeys) { + for (const key of Object.keys(customKeys)) { + if (!(key in result)) { + result[key] = customKeys[key](/** @type {T} */ ({})); + } + } + } + return result; +}; + +/** + * @param {WebpackOptions} config input config + * @returns {WebpackOptionsNormalized} normalized options + */ +const getNormalizedWebpackOptions = (config) => ({ + amd: config.amd, + bail: config.bail, + cache: + /** @type {NonNullable} */ + ( + optionalNestedConfig(config.cache, (cache) => { + if (cache === false) return false; + if (cache === true) { + return { + type: "memory", + maxGenerations: undefined + }; + } + switch (cache.type) { + case "filesystem": + return { + type: "filesystem", + allowCollectingMemory: cache.allowCollectingMemory, + maxMemoryGenerations: cache.maxMemoryGenerations, + maxAge: cache.maxAge, + profile: cache.profile, + buildDependencies: cloneObject(cache.buildDependencies), + cacheDirectory: cache.cacheDirectory, + cacheLocation: cache.cacheLocation, + hashAlgorithm: cache.hashAlgorithm, + compression: cache.compression, + idleTimeout: cache.idleTimeout, + idleTimeoutForInitialStore: cache.idleTimeoutForInitialStore, + idleTimeoutAfterLargeChanges: cache.idleTimeoutAfterLargeChanges, + name: cache.name, + store: cache.store, + version: cache.version, + readonly: cache.readonly + }; + case undefined: + case "memory": + return { + type: "memory", + maxGenerations: cache.maxGenerations + }; + default: + // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) + throw new Error(`Not implemented cache.type ${cache.type}`); + } + }) + ), + context: config.context, + dependencies: config.dependencies, + devServer: optionalNestedConfig(config.devServer, (devServer) => { + if (devServer === false) return false; + return { ...devServer }; + }), + devtool: config.devtool, + entry: + config.entry === undefined + ? { main: {} } + : typeof config.entry === "function" + ? ( + (fn) => () => + Promise.resolve().then(fn).then(getNormalizedEntryStatic) + )(config.entry) + : getNormalizedEntryStatic(config.entry), + experiments: nestedConfig(config.experiments, (experiments) => ({ + ...experiments, + buildHttp: optionalNestedConfig(experiments.buildHttp, (options) => + Array.isArray(options) ? { allowedUris: options } : options + ), + lazyCompilation: optionalNestedConfig( + experiments.lazyCompilation, + (options) => (options === true ? {} : options) + ) + })), + externals: /** @type {NonNullable} */ (config.externals), + externalsPresets: cloneObject(config.externalsPresets), + externalsType: config.externalsType, + ignoreWarnings: config.ignoreWarnings + ? config.ignoreWarnings.map((ignore) => { + if (typeof ignore === "function") return ignore; + const i = ignore instanceof RegExp ? { message: ignore } : ignore; + return (warning, { requestShortener }) => { + if (!i.message && !i.module && !i.file) return false; + if (i.message && !i.message.test(warning.message)) { + return false; + } + if ( + i.module && + (!(/** @type {WebpackError} */ (warning).module) || + !i.module.test( + /** @type {WebpackError} */ + (warning).module.readableIdentifier(requestShortener) + )) + ) { + return false; + } + if ( + i.file && + (!(/** @type {WebpackError} */ (warning).file) || + !i.file.test(/** @type {WebpackError} */ (warning).file)) + ) { + return false; + } + return true; + }; + }) + : undefined, + infrastructureLogging: cloneObject(config.infrastructureLogging), + loader: cloneObject(config.loader), + mode: config.mode, + module: + /** @type {ModuleOptionsNormalized} */ + ( + nestedConfig(config.module, (module) => ({ + noParse: module.noParse, + unsafeCache: module.unsafeCache, + parser: keyedNestedConfig(module.parser, cloneObject, { + javascript: (parserOptions) => ({ + unknownContextRequest: module.unknownContextRequest, + unknownContextRegExp: module.unknownContextRegExp, + unknownContextRecursive: module.unknownContextRecursive, + unknownContextCritical: module.unknownContextCritical, + exprContextRequest: module.exprContextRequest, + exprContextRegExp: module.exprContextRegExp, + exprContextRecursive: module.exprContextRecursive, + exprContextCritical: module.exprContextCritical, + wrappedContextRegExp: module.wrappedContextRegExp, + wrappedContextRecursive: module.wrappedContextRecursive, + wrappedContextCritical: module.wrappedContextCritical, + // TODO webpack 6 remove + strictExportPresence: module.strictExportPresence, + strictThisContextOnImports: module.strictThisContextOnImports, + ...parserOptions + }) + }), + generator: cloneObject(module.generator), + defaultRules: optionalNestedArray(module.defaultRules, (r) => [...r]), + rules: nestedArray(module.rules, (r) => [...r]) + })) + ), + name: config.name, + node: nestedConfig( + config.node, + (node) => + node && { + ...node + } + ), + optimization: nestedConfig(config.optimization, (optimization) => ({ + ...optimization, + runtimeChunk: getNormalizedOptimizationRuntimeChunk( + optimization.runtimeChunk + ), + splitChunks: nestedConfig( + optimization.splitChunks, + (splitChunks) => + splitChunks && { + ...splitChunks, + defaultSizeTypes: splitChunks.defaultSizeTypes + ? [...splitChunks.defaultSizeTypes] + : ["..."], + cacheGroups: cloneObject(splitChunks.cacheGroups) + } + ), + emitOnErrors: + optimization.noEmitOnErrors !== undefined + ? handledDeprecatedNoEmitOnErrors( + optimization.noEmitOnErrors, + optimization.emitOnErrors + ) + : optimization.emitOnErrors + })), + output: nestedConfig(config.output, (output) => { + const { library } = output; + const libraryAsName = /** @type {LibraryName} */ (library); + const libraryBase = + typeof library === "object" && + library && + !Array.isArray(library) && + "type" in library + ? library + : libraryAsName || output.libraryTarget + ? /** @type {LibraryOptions} */ ({ + name: libraryAsName + }) + : undefined; + /** @type {OutputNormalized} */ + const result = { + assetModuleFilename: output.assetModuleFilename, + asyncChunks: output.asyncChunks, + charset: output.charset, + chunkFilename: output.chunkFilename, + chunkFormat: output.chunkFormat, + chunkLoading: output.chunkLoading, + chunkLoadingGlobal: output.chunkLoadingGlobal, + chunkLoadTimeout: output.chunkLoadTimeout, + cssFilename: output.cssFilename, + cssChunkFilename: output.cssChunkFilename, + clean: output.clean, + compareBeforeEmit: output.compareBeforeEmit, + crossOriginLoading: output.crossOriginLoading, + devtoolFallbackModuleFilenameTemplate: + output.devtoolFallbackModuleFilenameTemplate, + devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate, + devtoolNamespace: output.devtoolNamespace, + environment: cloneObject(output.environment), + enabledChunkLoadingTypes: output.enabledChunkLoadingTypes + ? [...output.enabledChunkLoadingTypes] + : ["..."], + enabledLibraryTypes: output.enabledLibraryTypes + ? [...output.enabledLibraryTypes] + : ["..."], + enabledWasmLoadingTypes: output.enabledWasmLoadingTypes + ? [...output.enabledWasmLoadingTypes] + : ["..."], + filename: output.filename, + globalObject: output.globalObject, + hashDigest: output.hashDigest, + hashDigestLength: output.hashDigestLength, + hashFunction: output.hashFunction, + hashSalt: output.hashSalt, + hotUpdateChunkFilename: output.hotUpdateChunkFilename, + hotUpdateGlobal: output.hotUpdateGlobal, + hotUpdateMainFilename: output.hotUpdateMainFilename, + ignoreBrowserWarnings: output.ignoreBrowserWarnings, + iife: output.iife, + importFunctionName: output.importFunctionName, + importMetaName: output.importMetaName, + scriptType: output.scriptType, + // TODO webpack6 remove `libraryTarget`/`auxiliaryComment`/`amdContainer`/etc in favor of the `library` option + library: libraryBase && { + type: + output.libraryTarget !== undefined + ? output.libraryTarget + : libraryBase.type, + auxiliaryComment: + output.auxiliaryComment !== undefined + ? output.auxiliaryComment + : libraryBase.auxiliaryComment, + amdContainer: + output.amdContainer !== undefined + ? output.amdContainer + : libraryBase.amdContainer, + export: + output.libraryExport !== undefined + ? output.libraryExport + : libraryBase.export, + name: libraryBase.name, + umdNamedDefine: + output.umdNamedDefine !== undefined + ? output.umdNamedDefine + : libraryBase.umdNamedDefine + }, + module: output.module, + path: output.path, + pathinfo: output.pathinfo, + publicPath: output.publicPath, + sourceMapFilename: output.sourceMapFilename, + sourcePrefix: output.sourcePrefix, + strictModuleErrorHandling: output.strictModuleErrorHandling, + strictModuleExceptionHandling: output.strictModuleExceptionHandling, + trustedTypes: optionalNestedConfig( + output.trustedTypes, + (trustedTypes) => { + if (trustedTypes === true) return {}; + if (typeof trustedTypes === "string") { + return { policyName: trustedTypes }; + } + return { ...trustedTypes }; + } + ), + uniqueName: output.uniqueName, + wasmLoading: output.wasmLoading, + webassemblyModuleFilename: output.webassemblyModuleFilename, + workerPublicPath: output.workerPublicPath, + workerChunkLoading: output.workerChunkLoading, + workerWasmLoading: output.workerWasmLoading + }; + return result; + }), + parallelism: config.parallelism, + performance: optionalNestedConfig(config.performance, (performance) => { + if (performance === false) return false; + return { + ...performance + }; + }), + plugins: /** @type {Plugins} */ (nestedArray(config.plugins, (p) => [...p])), + profile: config.profile, + recordsInputPath: + config.recordsInputPath !== undefined + ? config.recordsInputPath + : config.recordsPath, + recordsOutputPath: + config.recordsOutputPath !== undefined + ? config.recordsOutputPath + : config.recordsPath, + resolve: nestedConfig(config.resolve, (resolve) => ({ + ...resolve, + byDependency: keyedNestedConfig(resolve.byDependency, cloneObject) + })), + resolveLoader: cloneObject(config.resolveLoader), + snapshot: nestedConfig(config.snapshot, (snapshot) => ({ + resolveBuildDependencies: optionalNestedConfig( + snapshot.resolveBuildDependencies, + (resolveBuildDependencies) => ({ + timestamp: resolveBuildDependencies.timestamp, + hash: resolveBuildDependencies.hash + }) + ), + buildDependencies: optionalNestedConfig( + snapshot.buildDependencies, + (buildDependencies) => ({ + timestamp: buildDependencies.timestamp, + hash: buildDependencies.hash + }) + ), + resolve: optionalNestedConfig(snapshot.resolve, (resolve) => ({ + timestamp: resolve.timestamp, + hash: resolve.hash + })), + module: optionalNestedConfig(snapshot.module, (module) => ({ + timestamp: module.timestamp, + hash: module.hash + })), + immutablePaths: optionalNestedArray(snapshot.immutablePaths, (p) => [...p]), + managedPaths: optionalNestedArray(snapshot.managedPaths, (p) => [...p]), + unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, (p) => [...p]) + })), + stats: nestedConfig(config.stats, (stats) => { + if (stats === false) { + return { + preset: "none" + }; + } + if (stats === true) { + return { + preset: "normal" + }; + } + if (typeof stats === "string") { + return { + preset: stats + }; + } + return { + ...stats + }; + }), + target: config.target, + watch: config.watch, + watchOptions: cloneObject(config.watchOptions) +}); + +/** + * @param {EntryStatic} entry static entry options + * @returns {EntryStaticNormalized} normalized static entry options + */ +const getNormalizedEntryStatic = (entry) => { + if (typeof entry === "string") { + return { + main: { + import: [entry] + } + }; + } + if (Array.isArray(entry)) { + return { + main: { + import: entry + } + }; + } + /** @type {EntryStaticNormalized} */ + const result = {}; + for (const key of Object.keys(entry)) { + const value = entry[key]; + if (typeof value === "string") { + result[key] = { + import: [value] + }; + } else if (Array.isArray(value)) { + result[key] = { + import: value + }; + } else { + result[key] = { + import: + /** @type {EntryDescriptionNormalized["import"]} */ + ( + value.import && + (Array.isArray(value.import) ? value.import : [value.import]) + ), + filename: value.filename, + layer: value.layer, + runtime: value.runtime, + baseUri: value.baseUri, + publicPath: value.publicPath, + chunkLoading: value.chunkLoading, + asyncChunks: value.asyncChunks, + wasmLoading: value.wasmLoading, + dependOn: + /** @type {EntryDescriptionNormalized["dependOn"]} */ + ( + value.dependOn && + (Array.isArray(value.dependOn) + ? value.dependOn + : [value.dependOn]) + ), + library: value.library + }; + } + } + return result; +}; + +/** + * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option + * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option + */ +const getNormalizedOptimizationRuntimeChunk = (runtimeChunk) => { + if (runtimeChunk === undefined) return; + if (runtimeChunk === false) return false; + if (runtimeChunk === "single") { + return { + name: () => "runtime" + }; + } + if (runtimeChunk === true || runtimeChunk === "multiple") { + return { + name: (entrypoint) => `runtime~${entrypoint.name}` + }; + } + const { name } = runtimeChunk; + return { + name: + typeof name === "function" + ? /** @type {Exclude["name"]} */ + (name) + : () => /** @type {string} */ (name) + }; +}; + +module.exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/target.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/target.js new file mode 100644 index 0000000000000000000000000000000000000000..e8bb48d00696c3103a676ed1f3a5042a42862719 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/config/target.js @@ -0,0 +1,378 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const memoize = require("../util/memoize"); + +const getBrowserslistTargetHandler = memoize(() => + require("./browserslistTargetHandler") +); + +/** + * @param {string} context the context directory + * @returns {string} default target + */ +const getDefaultTarget = (context) => { + const browsers = getBrowserslistTargetHandler().load(null, context); + return browsers ? "browserslist" : "web"; +}; + +/** + * @typedef {object} PlatformTargetProperties + * @property {boolean | null=} web web platform, importing of http(s) and std: is available + * @property {boolean | null=} browser browser platform, running in a normal web browser + * @property {boolean | null=} webworker (Web)Worker platform, running in a web/shared/service worker + * @property {boolean | null=} node node platform, require of node built-in modules is available + * @property {boolean | null=} nwjs nwjs platform, require of legacy nw.gui is available + * @property {boolean | null=} electron electron platform, require of some electron built-in modules is available + */ + +/** + * @typedef {object} ElectronContextTargetProperties + * @property {boolean | null} electronMain in main context + * @property {boolean | null} electronPreload in preload context + * @property {boolean | null} electronRenderer in renderer context with node integration + */ + +/** + * @typedef {object} ApiTargetProperties + * @property {boolean | null} require has require function available + * @property {boolean | null} nodeBuiltins has node.js built-in modules available + * @property {boolean | null} nodePrefixForCoreModules node.js allows to use `node:` prefix for core modules + * @property {boolean | null} document has document available (allows script tags) + * @property {boolean | null} importScripts has importScripts available + * @property {boolean | null} importScriptsInWorker has importScripts available when creating a worker + * @property {boolean | null} fetchWasm has fetch function available for WebAssembly + * @property {boolean | null} global has global variable available + */ + +/** + * @typedef {object} EcmaTargetProperties + * @property {boolean | null} globalThis has globalThis variable available + * @property {boolean | null} bigIntLiteral big int literal syntax is available + * @property {boolean | null} const const and let variable declarations are available + * @property {boolean | null} arrowFunction arrow functions are available + * @property {boolean | null} forOf for of iteration is available + * @property {boolean | null} destructuring destructuring is available + * @property {boolean | null} dynamicImport async import() is available + * @property {boolean | null} dynamicImportInWorker async import() is available when creating a worker + * @property {boolean | null} module ESM syntax is available (when in module) + * @property {boolean | null} optionalChaining optional chaining is available + * @property {boolean | null} templateLiteral template literal is available + * @property {boolean | null} asyncFunction async functions and await are available + */ + +/** + * @template T + * @typedef {{ [P in keyof T]?: never }} Never + */ + +/** + * @template A + * @template B + * @typedef {(A & Never) | (Never & B) | (A & B)} Mix + */ + +/** @typedef {Mix, Mix>} TargetProperties */ + +/** + * @param {string} major major version + * @param {string | undefined} minor minor version + * @returns {(vMajor: number, vMinor?: number) => boolean | undefined} check if version is greater or equal + */ +const versionDependent = (major, minor) => { + if (!major) { + return () => /** @type {undefined} */ (undefined); + } + /** @type {number} */ + const nMajor = Number(major); + /** @type {number} */ + const nMinor = minor ? Number(minor) : 0; + return (vMajor, vMinor = 0) => + nMajor > vMajor || (nMajor === vMajor && nMinor >= vMinor); +}; + +/** @type {[string, string, RegExp, (...args: string[]) => Partial][]} */ +const TARGETS = [ + [ + "browserslist / browserslist:env / browserslist:query / browserslist:path-to-config / browserslist:path-to-config:env", + "Resolve features from browserslist. Will resolve browserslist config automatically. Only browser or node queries are supported (electron is not supported). Examples: 'browserslist:modern' to use 'modern' environment from browserslist config", + /^browserslist(?::(.+))?$/, + (rest, context) => { + const browserslistTargetHandler = getBrowserslistTargetHandler(); + const browsers = browserslistTargetHandler.load( + rest ? rest.trim() : null, + context + ); + if (!browsers) { + throw new Error(`No browserslist config found to handle the 'browserslist' target. +See https://github.com/browserslist/browserslist#queries for possible ways to provide a config. +The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions). +You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'`); + } + + return browserslistTargetHandler.resolve(browsers); + } + ], + [ + "web", + "Web browser.", + /^web$/, + () => ({ + node: false, + web: true, + webworker: null, + browser: true, + electron: false, + nwjs: false, + + document: true, + importScriptsInWorker: true, + fetchWasm: true, + nodeBuiltins: false, + importScripts: false, + require: false, + global: false + }) + ], + [ + "webworker", + "Web Worker, SharedWorker or Service Worker.", + /^webworker$/, + () => ({ + node: false, + web: true, + webworker: true, + browser: true, + electron: false, + nwjs: false, + + importScripts: true, + importScriptsInWorker: true, + fetchWasm: true, + nodeBuiltins: false, + require: false, + document: false, + global: false + }) + ], + [ + "[async-]node[X[.Y]]", + "Node.js in version X.Y. The 'async-' prefix will load chunks asynchronously via 'fs' and 'vm' instead of 'require()'. Examples: node14.5, async-node10.", + /^(async-)?node((\d+)(?:\.(\d+))?)?$/, + (asyncFlag, _, major, minor) => { + const v = versionDependent(major, minor); + // see https://node.green/ + return { + node: true, + web: false, + webworker: false, + browser: false, + electron: false, + nwjs: false, + + require: !asyncFlag, + nodeBuiltins: true, + // v16.0.0, v14.18.0 + nodePrefixForCoreModules: Number(major) < 15 ? v(14, 18) : v(16), + global: true, + document: false, + fetchWasm: false, + importScripts: false, + importScriptsInWorker: false, + + globalThis: v(12), + const: v(6), + templateLiteral: v(4), + optionalChaining: v(14), + arrowFunction: v(6), + asyncFunction: v(7, 6), + forOf: v(5), + destructuring: v(6), + bigIntLiteral: v(10, 4), + dynamicImport: v(12, 17), + dynamicImportInWorker: v(12, 17), + module: v(12, 17) + }; + } + ], + [ + "electron[X[.Y]]-main/preload/renderer", + "Electron in version X.Y. Script is running in main, preload resp. renderer context.", + /^electron((\d+)(?:\.(\d+))?)?-(main|preload|renderer)$/, + (_, major, minor, context) => { + const v = versionDependent(major, minor); + // see https://node.green/ + https://github.com/electron/releases + return { + node: true, + web: context !== "main", + webworker: false, + browser: false, + electron: true, + nwjs: false, + + electronMain: context === "main", + electronPreload: context === "preload", + electronRenderer: context === "renderer", + + global: true, + nodeBuiltins: true, + // 15.0.0 - Node.js v16.5 + // 14.0.0 - Mode.js v14.17, but prefixes only since v14.18 + nodePrefixForCoreModules: v(15), + + require: true, + document: context === "renderer", + fetchWasm: context === "renderer", + importScripts: false, + importScriptsInWorker: true, + + globalThis: v(5), + const: v(1, 1), + templateLiteral: v(1, 1), + optionalChaining: v(8), + arrowFunction: v(1, 1), + asyncFunction: v(1, 7), + forOf: v(0, 36), + destructuring: v(1, 1), + bigIntLiteral: v(4), + dynamicImport: v(11), + dynamicImportInWorker: v(11), + module: v(11) + }; + } + ], + [ + "nwjs[X[.Y]] / node-webkit[X[.Y]]", + "NW.js in version X.Y.", + /^(?:nwjs|node-webkit)((\d+)(?:\.(\d+))?)?$/, + (_, major, minor) => { + const v = versionDependent(major, minor); + // see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md + return { + node: true, + web: true, + webworker: null, + browser: false, + electron: false, + nwjs: true, + + global: true, + nodeBuiltins: true, + document: false, + importScriptsInWorker: false, + fetchWasm: false, + importScripts: false, + require: false, + + globalThis: v(0, 43), + const: v(0, 15), + templateLiteral: v(0, 13), + optionalChaining: v(0, 44), + arrowFunction: v(0, 15), + asyncFunction: v(0, 21), + forOf: v(0, 13), + destructuring: v(0, 15), + bigIntLiteral: v(0, 32), + dynamicImport: v(0, 43), + dynamicImportInWorker: v(0, 44), + module: v(0, 43) + }; + } + ], + [ + "esX", + "EcmaScript in this version. Examples: es2020, es5.", + /^es(\d+)$/, + (version) => { + let v = Number(version); + if (v < 1000) v += 2009; + return { + const: v >= 2015, + templateLiteral: v >= 2015, + optionalChaining: v >= 2020, + arrowFunction: v >= 2015, + forOf: v >= 2015, + destructuring: v >= 2015, + module: v >= 2015, + asyncFunction: v >= 2017, + globalThis: v >= 2020, + bigIntLiteral: v >= 2020, + dynamicImport: v >= 2020, + dynamicImportInWorker: v >= 2020 + }; + } + ] +]; + +/** + * @param {string} target the target + * @param {string} context the context directory + * @returns {TargetProperties} target properties + */ +const getTargetProperties = (target, context) => { + for (const [, , regExp, handler] of TARGETS) { + const match = regExp.exec(target); + if (match) { + const [, ...args] = match; + const result = handler(...args, context); + if (result) return /** @type {TargetProperties} */ (result); + } + } + throw new Error( + `Unknown target '${target}'. The following targets are supported:\n${TARGETS.map( + ([name, description]) => `* ${name}: ${description}` + ).join("\n")}` + ); +}; + +/** + * @param {TargetProperties[]} targetProperties array of target properties + * @returns {TargetProperties} merged target properties + */ +const mergeTargetProperties = (targetProperties) => { + /** @type {Set} */ + const keys = new Set(); + for (const tp of targetProperties) { + for (const key of Object.keys(tp)) { + keys.add(/** @type {keyof TargetProperties} */ (key)); + } + } + /** @type {TargetProperties} */ + const result = {}; + for (const key of keys) { + let hasTrue = false; + let hasFalse = false; + for (const tp of targetProperties) { + const value = tp[key]; + switch (value) { + case true: + hasTrue = true; + break; + case false: + hasFalse = true; + break; + } + } + if (hasTrue || hasFalse) { + /** @type {TargetProperties} */ + (result)[key] = hasFalse && hasTrue ? null : Boolean(hasTrue); + } + } + return result; +}; + +/** + * @param {string[]} targets the targets + * @param {string} context the context directory + * @returns {TargetProperties} target properties + */ +const getTargetsProperties = (targets, context) => + mergeTargetProperties(targets.map((t) => getTargetProperties(t, context))); + +module.exports.getDefaultTarget = getDefaultTarget; +module.exports.getTargetProperties = getTargetProperties; +module.exports.getTargetsProperties = getTargetsProperties; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerEntryDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerEntryDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..787d99cffac9dda1e3031eb7c6dc63ebf67f6d69 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerEntryDependency.js @@ -0,0 +1,48 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("./ContainerEntryModule").ExposeOptions} ExposeOptions */ +/** @typedef {import("./ContainerEntryModule").ExposesList} ExposesList */ + +class ContainerEntryDependency extends Dependency { + /** + * @param {string} name entry name + * @param {ExposesList} exposes list of exposed modules + * @param {string} shareScope name of the share scope + */ + constructor(name, exposes, shareScope) { + super(); + this.name = name; + this.exposes = exposes; + this.shareScope = shareScope; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `container-entry-${this.name}`; + } + + get type() { + return "container entry"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + ContainerEntryDependency, + "webpack/lib/container/ContainerEntryDependency" +); + +module.exports = ContainerEntryDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerEntryModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerEntryModule.js new file mode 100644 index 0000000000000000000000000000000000000000..37a2298491ebdb8f7e05c5752a3ae536e0c9c9be --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerEntryModule.js @@ -0,0 +1,297 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ + +"use strict"; + +const { OriginalSource, RawSource } = require("webpack-sources"); +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const Module = require("../Module"); +const { JS_TYPES } = require("../ModuleSourceTypesConstants"); +const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); +const makeSerializable = require("../util/makeSerializable"); +const ContainerExposedDependency = require("./ContainerExposedDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").BuildCallback} BuildCallback */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ + +/** + * @typedef {object} ExposeOptions + * @property {string[]} import requests to exposed modules (last one is exported) + * @property {string} name custom chunk name for the exposed module + */ + +/** @typedef {[string, ExposeOptions][]} ExposesList */ + +class ContainerEntryModule extends Module { + /** + * @param {string} name container entry name + * @param {ExposesList} exposes list of exposed modules + * @param {string} shareScope name of the share scope + */ + constructor(name, exposes, shareScope) { + super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null); + this._name = name; + this._exposes = exposes; + this._shareScope = shareScope; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return JS_TYPES; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `container entry (${this._shareScope}) ${JSON.stringify( + this._exposes + )}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return "container entry"; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${ + this._name + }`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + strict: true, + topLevelDeclarations: new Set(["moduleMap", "get", "init"]) + }; + this.buildMeta.exportsType = "namespace"; + + this.clearDependenciesAndBlocks(); + + for (const [name, options] of this._exposes) { + const block = new AsyncDependenciesBlock( + { + name: options.name + }, + { name }, + options.import[options.import.length - 1] + ); + let idx = 0; + for (const request of options.import) { + const dep = new ContainerExposedDependency(name, request); + dep.loc = { + name, + index: idx++ + }; + + block.addDependency(dep); + } + this.addBlock(block); + } + this.addDependency(new StaticExportsDependency(["get", "init"], false)); + + callback(); + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) { + const sources = new Map(); + const runtimeRequirements = new Set([ + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.hasOwnProperty, + RuntimeGlobals.exports + ]); + const getters = []; + + for (const block of this.blocks) { + const { dependencies } = block; + + const modules = dependencies.map((dependency) => { + const dep = /** @type {ContainerExposedDependency} */ (dependency); + return { + name: dep.exposedName, + module: moduleGraph.getModule(dep), + request: dep.userRequest + }; + }); + + let str; + + if (modules.some((m) => !m.module)) { + str = runtimeTemplate.throwMissingModuleErrorBlock({ + request: modules.map((m) => m.request).join(", ") + }); + } else { + str = `return ${runtimeTemplate.blockPromise({ + block, + message: "", + chunkGraph, + runtimeRequirements + })}.then(${runtimeTemplate.returningFunction( + runtimeTemplate.returningFunction( + `(${modules + .map(({ module, request }) => + runtimeTemplate.moduleRaw({ + module, + chunkGraph, + request, + weak: false, + runtimeRequirements + }) + ) + .join(", ")})` + ) + )});`; + } + + getters.push( + `${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction( + "", + str + )}` + ); + } + + const source = Template.asString([ + "var moduleMap = {", + Template.indent(getters.join(",\n")), + "};", + `var get = ${runtimeTemplate.basicFunction("module, getScope", [ + `${RuntimeGlobals.currentRemoteGetScope} = getScope;`, + // reusing the getScope variable to avoid creating a new var (and module is also used later) + "getScope = (", + Template.indent([ + `${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`, + Template.indent([ + "? moduleMap[module]()", + `: Promise.resolve().then(${runtimeTemplate.basicFunction( + "", + "throw new Error('Module \"' + module + '\" does not exist in container.');" + )})` + ]) + ]), + ");", + `${RuntimeGlobals.currentRemoteGetScope} = undefined;`, + "return getScope;" + ])};`, + `var init = ${runtimeTemplate.basicFunction("shareScope, initScope", [ + `if (!${RuntimeGlobals.shareScopeMap}) return;`, + `var name = ${JSON.stringify(this._shareScope)}`, + `var oldScope = ${RuntimeGlobals.shareScopeMap}[name];`, + 'if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");', + `${RuntimeGlobals.shareScopeMap}[name] = shareScope;`, + `return ${RuntimeGlobals.initializeSharing}(name, initScope);` + ])};`, + "", + "// This exports getters to disallow modifications", + `${RuntimeGlobals.definePropertyGetters}(exports, {`, + Template.indent([ + `get: ${runtimeTemplate.returningFunction("get")},`, + `init: ${runtimeTemplate.returningFunction("init")}` + ]), + "});" + ]); + + sources.set( + "javascript", + this.useSourceMap || this.useSimpleSourceMap + ? new OriginalSource(source, "webpack/container-entry") + : new RawSource(source) + ); + + return { + sources, + runtimeRequirements + }; + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return 42; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this._name); + write(this._exposes); + write(this._shareScope); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {ContainerEntryModule} deserialized container entry module + */ + static deserialize(context) { + const { read } = context; + const obj = new ContainerEntryModule(read(), read(), read()); + obj.deserialize(context); + return obj; + } +} + +makeSerializable( + ContainerEntryModule, + "webpack/lib/container/ContainerEntryModule" +); + +module.exports = ContainerEntryModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerEntryModuleFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerEntryModuleFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..cff347bfd1df4408411208a5860922355f0fdbb9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerEntryModuleFactory.js @@ -0,0 +1,27 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ + +"use strict"; + +const ModuleFactory = require("../ModuleFactory"); +const ContainerEntryModule = require("./ContainerEntryModule"); + +/** @typedef {import("../ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ + +module.exports = class ContainerEntryModuleFactory extends ModuleFactory { + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create({ dependencies: [dependency] }, callback) { + const dep = /** @type {ContainerEntryDependency} */ (dependency); + callback(null, { + module: new ContainerEntryModule(dep.name, dep.exposes, dep.shareScope) + }); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerExposedDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerExposedDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..2cbf04a694df33c04a82db90ad1a75fae558f6d8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerExposedDependency.js @@ -0,0 +1,61 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ + +"use strict"; + +const ModuleDependency = require("../dependencies/ModuleDependency"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class ContainerExposedDependency extends ModuleDependency { + /** + * @param {string} exposedName public name + * @param {string} request request to module + */ + constructor(exposedName, request) { + super(request); + this.exposedName = exposedName; + } + + get type() { + return "container exposed"; + } + + get category() { + return "esm"; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `exposed dependency ${this.exposedName}=${this.request}`; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + context.write(this.exposedName); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + this.exposedName = context.read(); + super.deserialize(context); + } +} + +makeSerializable( + ContainerExposedDependency, + "webpack/lib/container/ContainerExposedDependency" +); + +module.exports = ContainerExposedDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7a725dc844c59dca6affc7ab547874858ffd8e98 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerPlugin.js @@ -0,0 +1,119 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ + +"use strict"; + +const createSchemaValidation = require("../util/create-schema-validation"); +const memoize = require("../util/memoize"); +const ContainerEntryDependency = require("./ContainerEntryDependency"); +const ContainerEntryModuleFactory = require("./ContainerEntryModuleFactory"); +const ContainerExposedDependency = require("./ContainerExposedDependency"); +const { parseOptions } = require("./options"); + +/** @typedef {import("../../declarations/plugins/container/ContainerPlugin").ContainerPluginOptions} ContainerPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("./ContainerEntryModule").ExposeOptions} ExposeOptions */ +/** @typedef {import("./ContainerEntryModule").ExposesList} ExposesList */ + +const getModuleFederationPlugin = memoize(() => + require("./ModuleFederationPlugin") +); + +const validate = createSchemaValidation( + require("../../schemas/plugins/container/ContainerPlugin.check"), + () => require("../../schemas/plugins/container/ContainerPlugin.json"), + { + name: "Container Plugin", + baseDataPath: "options" + } +); + +const PLUGIN_NAME = "ContainerPlugin"; + +class ContainerPlugin { + /** + * @param {ContainerPluginOptions} options options + */ + constructor(options) { + validate(options); + + this._options = { + name: options.name, + shareScope: options.shareScope || "default", + library: options.library || { + type: "var", + name: options.name + }, + runtime: options.runtime, + filename: options.filename || undefined, + exposes: /** @type {ExposesList} */ ( + parseOptions( + options.exposes, + (item) => ({ + import: Array.isArray(item) ? item : [item], + name: undefined + }), + (item) => ({ + import: Array.isArray(item.import) ? item.import : [item.import], + name: item.name || undefined + }) + ) + ) + }; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { name, exposes, shareScope, filename, library, runtime } = + this._options; + + if (!compiler.options.output.enabledLibraryTypes.includes(library.type)) { + compiler.options.output.enabledLibraryTypes.push(library.type); + } + + compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { + const hooks = + getModuleFederationPlugin().getCompilationHooks(compilation); + const dep = new ContainerEntryDependency(name, exposes, shareScope); + dep.loc = { name }; + compilation.addEntry( + /** @type {string} */ (compilation.options.context), + dep, + { + name, + filename, + runtime, + library + }, + (error) => { + if (error) return callback(error); + hooks.addContainerEntryDependency.call(dep); + callback(); + } + ); + }); + + compiler.hooks.thisCompilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + ContainerEntryDependency, + new ContainerEntryModuleFactory() + ); + + compilation.dependencyFactories.set( + ContainerExposedDependency, + normalModuleFactory + ); + } + ); + } +} + +module.exports = ContainerPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerReferencePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerReferencePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..95efc51b99d527560afd13f49c5ac2f254b5e1dc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ContainerReferencePlugin.js @@ -0,0 +1,140 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy +*/ + +"use strict"; + +const ExternalsPlugin = require("../ExternalsPlugin"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const createSchemaValidation = require("../util/create-schema-validation"); +const FallbackDependency = require("./FallbackDependency"); +const FallbackItemDependency = require("./FallbackItemDependency"); +const FallbackModuleFactory = require("./FallbackModuleFactory"); +const RemoteModule = require("./RemoteModule"); +const RemoteRuntimeModule = require("./RemoteRuntimeModule"); +const RemoteToExternalDependency = require("./RemoteToExternalDependency"); +const { parseOptions } = require("./options"); + +/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").ContainerReferencePluginOptions} ContainerReferencePluginOptions */ +/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").RemotesConfig} RemotesConfig */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/container/ContainerReferencePlugin.check"), + () => + require("../../schemas/plugins/container/ContainerReferencePlugin.json"), + { + name: "Container Reference Plugin", + baseDataPath: "options" + } +); + +const slashCode = "/".charCodeAt(0); +const PLUGIN_NAME = "ContainerReferencePlugin"; + +class ContainerReferencePlugin { + /** + * @param {ContainerReferencePluginOptions} options options + */ + constructor(options) { + validate(options); + + this._remoteType = options.remoteType; + this._remotes = parseOptions( + options.remotes, + (item) => ({ + external: Array.isArray(item) ? item : [item], + shareScope: options.shareScope || "default" + }), + (item) => ({ + external: Array.isArray(item.external) + ? item.external + : [item.external], + shareScope: item.shareScope || options.shareScope || "default" + }) + ); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _remotes: remotes, _remoteType: remoteType } = this; + + /** @type {Record} */ + const remoteExternals = {}; + for (const [key, config] of remotes) { + let i = 0; + for (const external of config.external) { + if (external.startsWith("internal ")) continue; + remoteExternals[ + `webpack/container/reference/${key}${i ? `/fallback-${i}` : ""}` + ] = external; + i++; + } + } + + new ExternalsPlugin(remoteType, remoteExternals).apply(compiler); + + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RemoteToExternalDependency, + normalModuleFactory + ); + + compilation.dependencyFactories.set( + FallbackItemDependency, + normalModuleFactory + ); + + compilation.dependencyFactories.set( + FallbackDependency, + new FallbackModuleFactory() + ); + + normalModuleFactory.hooks.factorize.tap(PLUGIN_NAME, (data) => { + if (!data.request.includes("!")) { + for (const [key, config] of remotes) { + if ( + data.request.startsWith(`${key}`) && + (data.request.length === key.length || + data.request.charCodeAt(key.length) === slashCode) + ) { + return new RemoteModule( + data.request, + config.external.map((external, i) => + external.startsWith("internal ") + ? external.slice(9) + : `webpack/container/reference/${key}${ + i ? `/fallback-${i}` : "" + }` + ), + `.${data.request.slice(key.length)}`, + config.shareScope + ); + } + } + } + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + set.add(RuntimeGlobals.initializeSharing); + set.add(RuntimeGlobals.shareScopeMap); + compilation.addRuntimeModule(chunk, new RemoteRuntimeModule()); + }); + } + ); + } +} + +module.exports = ContainerReferencePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..088720f5e327b51d0819bfccf93d9696c348139f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackDependency.js @@ -0,0 +1,64 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class FallbackDependency extends Dependency { + /** + * @param {string[]} requests requests + */ + constructor(requests) { + super(); + this.requests = requests; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `fallback ${this.requests.join(" ")}`; + } + + get type() { + return "fallback"; + } + + get category() { + return "esm"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.requests); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {FallbackDependency} deserialize fallback dependency + */ + static deserialize(context) { + const { read } = context; + const obj = new FallbackDependency(read()); + obj.deserialize(context); + return obj; + } +} + +makeSerializable( + FallbackDependency, + "webpack/lib/container/FallbackDependency" +); + +module.exports = FallbackDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackItemDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackItemDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..f09f8cf8c3cad0cee4d20634aa9162d8e96b6efc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackItemDependency.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleDependency = require("../dependencies/ModuleDependency"); +const makeSerializable = require("../util/makeSerializable"); + +class FallbackItemDependency extends ModuleDependency { + /** + * @param {string} request request + */ + constructor(request) { + super(request); + } + + get type() { + return "fallback item"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + FallbackItemDependency, + "webpack/lib/container/FallbackItemDependency" +); + +module.exports = FallbackItemDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackModule.js new file mode 100644 index 0000000000000000000000000000000000000000..be757f0e061d1add75d1a780ebe70e12cfc859ed --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackModule.js @@ -0,0 +1,187 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const Module = require("../Module"); +const { JS_TYPES } = require("../ModuleSourceTypesConstants"); +const { WEBPACK_MODULE_TYPE_FALLBACK } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const makeSerializable = require("../util/makeSerializable"); +const FallbackItemDependency = require("./FallbackItemDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").BuildCallback} BuildCallback */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + +const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); + +class FallbackModule extends Module { + /** + * @param {string[]} requests list of requests to choose one + */ + constructor(requests) { + super(WEBPACK_MODULE_TYPE_FALLBACK); + this.requests = requests; + this._identifier = `fallback ${this.requests.join(" ")}`; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this._identifier; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return this._identifier; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${ + this.requests[0] + }/and ${this.requests.length - 1} more`; + } + + /** + * @param {Chunk} chunk the chunk which condition should be checked + * @param {Compilation} compilation the compilation + * @returns {boolean} true, if the chunk is ok for the module + */ + chunkCondition(chunk, { chunkGraph }) { + return chunkGraph.getNumberOfEntryModules(chunk) > 0; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + strict: true + }; + + this.clearDependenciesAndBlocks(); + for (const request of this.requests) { + this.addDependency(new FallbackItemDependency(request)); + } + + callback(); + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return this.requests.length * 5 + 42; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return JS_TYPES; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { + const ids = this.dependencies.map((dep) => + chunkGraph.getModuleId(/** @type {Module} */ (moduleGraph.getModule(dep))) + ); + const code = Template.asString([ + `var ids = ${JSON.stringify(ids)};`, + "var error, result, i = 0;", + `var loop = ${runtimeTemplate.basicFunction("next", [ + "while(i < ids.length) {", + Template.indent([ + `try { next = ${RuntimeGlobals.require}(ids[i++]); } catch(e) { return handleError(e); }`, + "if(next) return next.then ? next.then(handleResult, handleError) : handleResult(next);" + ]), + "}", + "if(error) throw error;" + ])}`, + `var handleResult = ${runtimeTemplate.basicFunction("result", [ + "if(result) return result;", + "return loop();" + ])};`, + `var handleError = ${runtimeTemplate.basicFunction("e", [ + "error = e;", + "return loop();" + ])};`, + "module.exports = loop();" + ]); + const sources = new Map(); + sources.set("javascript", new RawSource(code)); + return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS }; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.requests); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {FallbackModule} deserialized fallback module + */ + static deserialize(context) { + const { read } = context; + const obj = new FallbackModule(read()); + obj.deserialize(context); + return obj; + } +} + +makeSerializable(FallbackModule, "webpack/lib/container/FallbackModule"); + +module.exports = FallbackModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackModuleFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackModuleFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..9ae5d427f32258a0e1348d37973ddb0ddfd812e0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/FallbackModuleFactory.js @@ -0,0 +1,27 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ + +"use strict"; + +const ModuleFactory = require("../ModuleFactory"); +const FallbackModule = require("./FallbackModule"); + +/** @typedef {import("../ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./FallbackDependency")} FallbackDependency */ + +module.exports = class FallbackModuleFactory extends ModuleFactory { + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create({ dependencies: [dependency] }, callback) { + const dep = /** @type {FallbackDependency} */ (dependency); + callback(null, { + module: new FallbackModule(dep.requests) + }); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/HoistContainerReferencesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/HoistContainerReferencesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..238bb32805b7e6406983b56026c14ff0528336c2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/HoistContainerReferencesPlugin.js @@ -0,0 +1,250 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Zackary Jackson @ScriptedAlchemy +*/ + +"use strict"; + +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const ExternalModule = require("../ExternalModule"); +const { STAGE_ADVANCED } = require("../OptimizationStages"); +const memoize = require("../util/memoize"); +const { forEachRuntime } = require("../util/runtime"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Module")} Module */ + +const getModuleFederationPlugin = memoize(() => + require("./ModuleFederationPlugin") +); + +const PLUGIN_NAME = "HoistContainerReferences"; + +/** + * This class is used to hoist container references in the code. + */ +class HoistContainerReferences { + /** + * Apply the plugin to the compiler. + * @param {Compiler} compiler The webpack compiler instance. + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const hooks = + getModuleFederationPlugin().getCompilationHooks(compilation); + const depsToTrace = new Set(); + const entryExternalsToHoist = new Set(); + hooks.addContainerEntryDependency.tap(PLUGIN_NAME, (dep) => { + depsToTrace.add(dep); + }); + hooks.addFederationRuntimeDependency.tap(PLUGIN_NAME, (dep) => { + depsToTrace.add(dep); + }); + + compilation.hooks.addEntry.tap(PLUGIN_NAME, (entryDep) => { + if (entryDep.type === "entry") { + entryExternalsToHoist.add(entryDep); + } + }); + + // Hook into the optimizeChunks phase + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + // advanced stage is where SplitChunksPlugin runs. + stage: STAGE_ADVANCED + 1 + }, + (_chunks) => { + this.hoistModulesInChunks( + compilation, + depsToTrace, + entryExternalsToHoist + ); + } + ); + }); + } + + /** + * Hoist modules in chunks. + * @param {Compilation} compilation The webpack compilation instance. + * @param {Set} depsToTrace Set of container entry dependencies. + * @param {Set} entryExternalsToHoist Set of container entry dependencies to hoist. + */ + hoistModulesInChunks(compilation, depsToTrace, entryExternalsToHoist) { + const { chunkGraph, moduleGraph } = compilation; + + // loop over entry points + for (const dep of entryExternalsToHoist) { + const entryModule = moduleGraph.getModule(dep); + if (!entryModule) continue; + // get all the external module types and hoist them to the runtime chunk, this will get RemoteModule externals + const allReferencedModules = getAllReferencedModules( + compilation, + entryModule, + "external", + false + ); + + const containerRuntimes = chunkGraph.getModuleRuntimes(entryModule); + const runtimes = new Set(); + + for (const runtimeSpec of containerRuntimes) { + forEachRuntime(runtimeSpec, (runtimeKey) => { + if (runtimeKey) { + runtimes.add(runtimeKey); + } + }); + } + + for (const runtime of runtimes) { + const runtimeChunk = compilation.namedChunks.get(runtime); + if (!runtimeChunk) continue; + + for (const module of allReferencedModules) { + if (!chunkGraph.isModuleInChunk(module, runtimeChunk)) { + chunkGraph.connectChunkAndModule(runtimeChunk, module); + } + } + } + this.cleanUpChunks(compilation, allReferencedModules); + } + + // handle container entry specifically + for (const dep of depsToTrace) { + const containerEntryModule = moduleGraph.getModule(dep); + if (!containerEntryModule) continue; + const allReferencedModules = getAllReferencedModules( + compilation, + containerEntryModule, + "initial", + false + ); + + const allRemoteReferences = getAllReferencedModules( + compilation, + containerEntryModule, + "external", + false + ); + + for (const remote of allRemoteReferences) { + allReferencedModules.add(remote); + } + + const containerRuntimes = + chunkGraph.getModuleRuntimes(containerEntryModule); + const runtimes = new Set(); + + for (const runtimeSpec of containerRuntimes) { + forEachRuntime(runtimeSpec, (runtimeKey) => { + if (runtimeKey) { + runtimes.add(runtimeKey); + } + }); + } + + for (const runtime of runtimes) { + const runtimeChunk = compilation.namedChunks.get(runtime); + if (!runtimeChunk) continue; + + for (const module of allReferencedModules) { + if (!chunkGraph.isModuleInChunk(module, runtimeChunk)) { + chunkGraph.connectChunkAndModule(runtimeChunk, module); + } + } + } + this.cleanUpChunks(compilation, allReferencedModules); + } + } + + /** + * Clean up chunks by disconnecting unused modules. + * @param {Compilation} compilation The webpack compilation instance. + * @param {Set} modules Set of modules to clean up. + */ + cleanUpChunks(compilation, modules) { + const { chunkGraph } = compilation; + for (const module of modules) { + for (const chunk of chunkGraph.getModuleChunks(module)) { + if (!chunk.hasRuntime()) { + chunkGraph.disconnectChunkAndModule(chunk, module); + if ( + chunkGraph.getNumberOfChunkModules(chunk) === 0 && + chunkGraph.getNumberOfEntryModules(chunk) === 0 + ) { + chunkGraph.disconnectChunk(chunk); + compilation.chunks.delete(chunk); + if (chunk.name) { + compilation.namedChunks.delete(chunk.name); + } + } + } + } + } + modules.clear(); + } +} + +/** + * Helper method to collect all referenced modules recursively. + * @param {Compilation} compilation The webpack compilation instance. + * @param {Module} module The module to start collecting from. + * @param {string} type The type of modules to collect ("initial", "external", or "all"). + * @param {boolean} includeInitial Should include the referenced module passed + * @returns {Set} Set of collected modules. + */ +function getAllReferencedModules(compilation, module, type, includeInitial) { + const collectedModules = new Set(includeInitial ? [module] : []); + const visitedModules = new WeakSet([module]); + const stack = [module]; + + while (stack.length > 0) { + const currentModule = stack.pop(); + if (!currentModule) continue; + + const outgoingConnections = + compilation.moduleGraph.getOutgoingConnections(currentModule); + if (outgoingConnections) { + for (const connection of outgoingConnections) { + const connectedModule = connection.module; + + // Skip if module has already been visited + if (!connectedModule || visitedModules.has(connectedModule)) { + continue; + } + + // Handle 'initial' type (skipping async blocks) + if (type === "initial") { + const parentBlock = compilation.moduleGraph.getParentBlock( + /** @type {Dependency} */ + (connection.dependency) + ); + if (parentBlock instanceof AsyncDependenciesBlock) { + continue; + } + } + + // Handle 'external' type (collecting only external modules) + if (type === "external") { + if (connection.module instanceof ExternalModule) { + collectedModules.add(connectedModule); + } + } else { + // Handle 'all' or unspecified types + collectedModules.add(connectedModule); + } + + // Add connected module to the stack and mark it as visited + visitedModules.add(connectedModule); + stack.push(connectedModule); + } + } + } + + return collectedModules; +} + +module.exports = HoistContainerReferences; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ModuleFederationPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ModuleFederationPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..721f8ae8551e492bc1b6c4353995fbfb64c52282 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/ModuleFederationPlugin.js @@ -0,0 +1,132 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy +*/ + +"use strict"; + +const { SyncHook } = require("tapable"); +const isValidExternalsType = require("../../schemas/plugins/container/ExternalsType.check"); +const Compilation = require("../Compilation"); +const SharePlugin = require("../sharing/SharePlugin"); +const createSchemaValidation = require("../util/create-schema-validation"); +const ContainerPlugin = require("./ContainerPlugin"); +const ContainerReferencePlugin = require("./ContainerReferencePlugin"); +const HoistContainerReferences = require("./HoistContainerReferencesPlugin"); + +/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ExternalsType} ExternalsType */ +/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ModuleFederationPluginOptions} ModuleFederationPluginOptions */ +/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").Shared} Shared */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ + +/** + * @typedef {object} CompilationHooks + * @property {SyncHook} addContainerEntryDependency + * @property {SyncHook} addFederationRuntimeDependency + */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/container/ModuleFederationPlugin.check"), + () => require("../../schemas/plugins/container/ModuleFederationPlugin.json"), + { + name: "Module Federation Plugin", + baseDataPath: "options" + } +); + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); +const PLUGIN_NAME = "ModuleFederationPlugin"; + +class ModuleFederationPlugin { + /** + * @param {ModuleFederationPluginOptions} options options + */ + constructor(options) { + validate(options); + + this._options = options; + } + + /** + * Get the compilation hooks associated with this plugin. + * @param {Compilation} compilation The compilation instance. + * @returns {CompilationHooks} The hooks for the compilation. + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (!hooks) { + hooks = { + addContainerEntryDependency: new SyncHook(["dependency"]), + addFederationRuntimeDependency: new SyncHook(["dependency"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _options: options } = this; + const library = options.library || { type: "var", name: options.name }; + const remoteType = + options.remoteType || + (options.library && isValidExternalsType(options.library.type) + ? /** @type {ExternalsType} */ (options.library.type) + : "script"); + if ( + library && + !compiler.options.output.enabledLibraryTypes.includes(library.type) + ) { + compiler.options.output.enabledLibraryTypes.push(library.type); + } + compiler.hooks.afterPlugins.tap(PLUGIN_NAME, () => { + if ( + options.exposes && + (Array.isArray(options.exposes) + ? options.exposes.length > 0 + : Object.keys(options.exposes).length > 0) + ) { + new ContainerPlugin({ + name: /** @type {string} */ (options.name), + library, + filename: options.filename, + runtime: options.runtime, + shareScope: options.shareScope, + exposes: options.exposes + }).apply(compiler); + } + if ( + options.remotes && + (Array.isArray(options.remotes) + ? options.remotes.length > 0 + : Object.keys(options.remotes).length > 0) + ) { + new ContainerReferencePlugin({ + remoteType, + shareScope: options.shareScope, + remotes: options.remotes + }).apply(compiler); + } + if (options.shared) { + new SharePlugin({ + shared: options.shared, + shareScope: options.shareScope + }).apply(compiler); + } + new HoistContainerReferences().apply(compiler); + }); + } +} + +module.exports = ModuleFederationPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/RemoteModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/RemoteModule.js new file mode 100644 index 0000000000000000000000000000000000000000..41b77701e6b52f8bf1ad8bec5c416c286eb5592b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/RemoteModule.js @@ -0,0 +1,186 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const Module = require("../Module"); +const { + REMOTE_AND_SHARE_INIT_TYPES +} = require("../ModuleSourceTypesConstants"); +const { WEBPACK_MODULE_TYPE_REMOTE } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const FallbackDependency = require("./FallbackDependency"); +const RemoteToExternalDependency = require("./RemoteToExternalDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").BuildCallback} BuildCallback */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + +const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); + +class RemoteModule extends Module { + /** + * @param {string} request request string + * @param {string[]} externalRequests list of external requests to containers + * @param {string} internalRequest name of exposed module in container + * @param {string} shareScope the used share scope name + */ + constructor(request, externalRequests, internalRequest, shareScope) { + super(WEBPACK_MODULE_TYPE_REMOTE); + this.request = request; + this.externalRequests = externalRequests; + this.internalRequest = internalRequest; + this.shareScope = shareScope; + this._identifier = `remote (${shareScope}) ${this.externalRequests.join( + " " + )} ${this.internalRequest}`; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this._identifier; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `remote ${this.request}`; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${ + this.request + }`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + strict: true + }; + + this.clearDependenciesAndBlocks(); + if (this.externalRequests.length === 1) { + this.addDependency( + new RemoteToExternalDependency(this.externalRequests[0]) + ); + } else { + this.addDependency(new FallbackDependency(this.externalRequests)); + } + + callback(); + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return 6; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return REMOTE_AND_SHARE_INIT_TYPES; + } + + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + return this.request; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ moduleGraph, chunkGraph }) { + const module = moduleGraph.getModule(this.dependencies[0]); + const id = module && chunkGraph.getModuleId(module); + const sources = new Map(); + sources.set("remote", new RawSource("")); + const data = new Map(); + data.set("share-init", [ + { + shareScope: this.shareScope, + initStage: 20, + init: id === undefined ? "" : `initExternal(${JSON.stringify(id)});` + } + ]); + return { sources, data, runtimeRequirements: RUNTIME_REQUIREMENTS }; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.request); + write(this.externalRequests); + write(this.internalRequest); + write(this.shareScope); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {RemoteModule} deserialized module + */ + static deserialize(context) { + const { read } = context; + const obj = new RemoteModule(read(), read(), read(), read()); + obj.deserialize(context); + return obj; + } +} + +makeSerializable(RemoteModule, "webpack/lib/container/RemoteModule"); + +module.exports = RemoteModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/RemoteRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/RemoteRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..1e871e2da2f898789283d3e045855ddef5041a22 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/RemoteRuntimeModule.js @@ -0,0 +1,144 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Chunk").ChunkId} ChunkId */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("./RemoteModule")} RemoteModule */ + +class RemoteRuntimeModule extends RuntimeModule { + constructor() { + super("remotes loading"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const { runtimeTemplate, moduleGraph } = compilation; + /** @type {Record} */ + const chunkToRemotesMapping = {}; + /** @type {Record} */ + const idToExternalAndNameMapping = {}; + for (const chunk of /** @type {Chunk} */ ( + this.chunk + ).getAllReferencedChunks()) { + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "remote" + ); + if (!modules) continue; + /** @type {ModuleId[]} */ + const remotes = (chunkToRemotesMapping[ + /** @type {ChunkId} */ + (chunk.id) + ] = []); + for (const m of modules) { + const module = /** @type {RemoteModule} */ (m); + const name = module.internalRequest; + const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module)); + const shareScope = module.shareScope; + const dep = module.dependencies[0]; + const externalModule = moduleGraph.getModule(dep); + const externalModuleId = + /** @type {ModuleId} */ + (externalModule && chunkGraph.getModuleId(externalModule)); + remotes.push(id); + idToExternalAndNameMapping[id] = [shareScope, name, externalModuleId]; + } + } + return Template.asString([ + `var chunkMapping = ${JSON.stringify( + chunkToRemotesMapping, + null, + "\t" + )};`, + `var idToExternalAndNameMapping = ${JSON.stringify( + idToExternalAndNameMapping, + null, + "\t" + )};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.remotes = ${runtimeTemplate.basicFunction("chunkId, promises", [ + `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, + Template.indent([ + `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction("id", [ + `var getScope = ${RuntimeGlobals.currentRemoteGetScope};`, + "if(!getScope) getScope = [];", + "var data = idToExternalAndNameMapping[id];", + "if(getScope.indexOf(data) >= 0) return;", + "getScope.push(data);", + "if(data.p) return promises.push(data.p);", + `var onError = ${runtimeTemplate.basicFunction("error", [ + 'if(!error) error = new Error("Container missing");', + 'if(typeof error.message === "string")', + Template.indent( + "error.message += '\\nwhile loading \"' + data[1] + '\" from ' + data[2];" + ), + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("", ["throw error;"])}`, + "data.p = 0;" + ])};`, + `var handleFunction = ${runtimeTemplate.basicFunction( + "fn, arg1, arg2, d, next, first", + [ + "try {", + Template.indent([ + "var promise = fn(arg1, arg2);", + "if(promise && promise.then) {", + Template.indent([ + `var p = promise.then(${runtimeTemplate.returningFunction( + "next(result, d)", + "result" + )}, onError);`, + "if(first) promises.push(data.p = p); else return p;" + ]), + "} else {", + Template.indent(["return next(promise, d, first);"]), + "}" + ]), + "} catch(error) {", + Template.indent(["onError(error);"]), + "}" + ] + )}`, + `var onExternal = ${runtimeTemplate.returningFunction( + `external ? handleFunction(${RuntimeGlobals.initializeSharing}, data[0], 0, external, onInitialized, first) : onError()`, + "external, _, first" + )};`, + `var onInitialized = ${runtimeTemplate.returningFunction( + "handleFunction(external.get, data[1], getScope, 0, onFactory, first)", + "_, external, first" + )};`, + `var onFactory = ${runtimeTemplate.basicFunction("factory", [ + "data.p = 1;", + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + "module.exports = factory();" + ])}` + ])};`, + `handleFunction(${RuntimeGlobals.require}, data[2], 0, 0, onExternal, 1);` + ])});` + ]), + "}" + ])}` + ]); + } +} + +module.exports = RemoteRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/RemoteToExternalDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/RemoteToExternalDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..df7fd1f81580517d20e008e01d332c4c9715a00e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/RemoteToExternalDependency.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleDependency = require("../dependencies/ModuleDependency"); +const makeSerializable = require("../util/makeSerializable"); + +class RemoteToExternalDependency extends ModuleDependency { + /** + * @param {string} request request + */ + constructor(request) { + super(request); + } + + get type() { + return "remote to external"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + RemoteToExternalDependency, + "webpack/lib/container/RemoteToExternalDependency" +); + +module.exports = RemoteToExternalDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/options.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/options.js new file mode 100644 index 0000000000000000000000000000000000000000..953aea64c76efa672997b7ccd3fa9146c1fa36d7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/container/options.js @@ -0,0 +1,105 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @template T + * @typedef {Record} Item + */ + +/** + * @template T + * @typedef {(string | Item)[] | Item} ContainerOptionsFormat + */ + +/** + * @template T + * @template N + * @param {ContainerOptionsFormat} options options passed by the user + * @param {(item: string | string[], itemOrKey: string) => N} normalizeSimple normalize a simple item + * @param {(value: T, key: string) => N} normalizeOptions normalize a complex item + * @param {(item: string, normalized: N) => void} fn processing function + * @returns {void} + */ +const process = (options, normalizeSimple, normalizeOptions, fn) => { + /** + * @param {(string | Item)[]} items items + */ + const array = (items) => { + for (const item of items) { + if (typeof item === "string") { + fn(item, normalizeSimple(item, item)); + } else if (item && typeof item === "object") { + object(item); + } else { + throw new Error("Unexpected options format"); + } + } + }; + /** + * @param {Item} obj an object + */ + const object = (obj) => { + for (const [key, value] of Object.entries(obj)) { + if (typeof value === "string" || Array.isArray(value)) { + fn(key, normalizeSimple(value, key)); + } else { + fn(key, normalizeOptions(value, key)); + } + } + }; + if (!options) { + // Do nothing + } else if (Array.isArray(options)) { + array(options); + } else if (typeof options === "object") { + object(options); + } else { + throw new Error("Unexpected options format"); + } +}; + +/** + * @template T + * @template R + * @param {ContainerOptionsFormat} options options passed by the user + * @param {(item: string | string[], itemOrKey: string) => R} normalizeSimple normalize a simple item + * @param {(value: T, key: string) => R} normalizeOptions normalize a complex item + * @returns {[string, R][]} parsed options + */ +const parseOptions = (options, normalizeSimple, normalizeOptions) => { + /** @type {[string, R][]} */ + const items = []; + process(options, normalizeSimple, normalizeOptions, (key, value) => { + items.push([key, value]); + }); + return items; +}; + +/** + * @template T + * @param {string} scope scope name + * @param {ContainerOptionsFormat} options options passed by the user + * @returns {Record} options to spread or pass + */ +const scope = (scope, options) => { + /** @type {Record} */ + const obj = {}; + process( + options, + (item) => /** @type {string | string[] | T} */ (item), + (item) => /** @type {string | string[] | T} */ (item), + (key, value) => { + obj[ + key.startsWith("./") ? `${scope}${key.slice(1)}` : `${scope}/${key}` + ] = value; + } + ); + return obj; +}; + +module.exports.parseOptions = parseOptions; +module.exports.scope = scope; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssGenerator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..56cbc5d607f4b5f74e70b211b514d26635e31413 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssGenerator.js @@ -0,0 +1,328 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + +"use strict"; + +const { ConcatSource, RawSource, ReplaceSource } = require("webpack-sources"); +const { UsageState } = require("../ExportsInfo"); +const Generator = require("../Generator"); +const InitFragment = require("../InitFragment"); +const { + CSS_TYPE, + CSS_TYPES, + JS_AND_CSS_EXPORT_TYPES, + JS_AND_CSS_TYPES, + JS_TYPE +} = require("../ModuleSourceTypesConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const memoize = require("../util/memoize"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").CssAutoGeneratorOptions} CssAutoGeneratorOptions */ +/** @typedef {import("../../declarations/WebpackOptions").CssGlobalGeneratorOptions} CssGlobalGeneratorOptions */ +/** @typedef {import("../../declarations/WebpackOptions").CssModuleGeneratorOptions} CssModuleGeneratorOptions */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").CssData} CssData */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../util/Hash")} Hash */ + +const getPropertyName = memoize(() => require("../util/propertyName")); + +class CssGenerator extends Generator { + /** + * @param {CssAutoGeneratorOptions | CssGlobalGeneratorOptions | CssModuleGeneratorOptions} options options + * @param {ModuleGraph} moduleGraph the module graph + */ + constructor(options, moduleGraph) { + super(); + this.convention = options.exportsConvention; + this.localIdentName = options.localIdentName; + this.exportsOnly = options.exportsOnly; + this.esModule = options.esModule; + this._moduleGraph = moduleGraph; + } + + /** + * @param {NormalModule} module module for which the bailout reason should be determined + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(module, context) { + if (!this.esModule) { + return "Module is not an ECMAScript module"; + } + + return undefined; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate(module, generateContext) { + const source = + generateContext.type === "javascript" + ? new ReplaceSource(new RawSource("")) + : new ReplaceSource(/** @type {Source} */ (module.originalSource())); + + /** @type {InitFragment[]} */ + const initFragments = []; + /** @type {CssData} */ + const cssData = { + esModule: /** @type {boolean} */ (this.esModule), + exports: new Map() + }; + + /** @type {InitFragment[] | undefined} */ + let chunkInitFragments; + /** @type {DependencyTemplateContext} */ + const templateContext = { + runtimeTemplate: generateContext.runtimeTemplate, + dependencyTemplates: generateContext.dependencyTemplates, + moduleGraph: generateContext.moduleGraph, + chunkGraph: generateContext.chunkGraph, + module, + runtime: generateContext.runtime, + runtimeRequirements: generateContext.runtimeRequirements, + concatenationScope: generateContext.concatenationScope, + codeGenerationResults: + /** @type {CodeGenerationResults} */ + (generateContext.codeGenerationResults), + initFragments, + cssData, + get chunkInitFragments() { + if (!chunkInitFragments) { + const data = + /** @type {NonNullable} */ + (generateContext.getData)(); + chunkInitFragments = data.get("chunkInitFragments"); + if (!chunkInitFragments) { + chunkInitFragments = []; + data.set("chunkInitFragments", chunkInitFragments); + } + } + + return chunkInitFragments; + } + }; + + /** + * @param {Dependency} dependency dependency + */ + const handleDependency = (dependency) => { + const constructor = + /** @type {new (...args: EXPECTED_ANY[]) => Dependency} */ + (dependency.constructor); + const template = generateContext.dependencyTemplates.get(constructor); + if (!template) { + throw new Error( + `No template for dependency: ${dependency.constructor.name}` + ); + } + + template.apply(dependency, source, templateContext); + }; + + for (const dependency of module.dependencies) { + handleDependency(dependency); + } + + switch (generateContext.type) { + case "javascript": { + /** @type {BuildInfo} */ + (module.buildInfo).cssData = cssData; + + generateContext.runtimeRequirements.add(RuntimeGlobals.module); + + if (generateContext.concatenationScope) { + const source = new ConcatSource(); + const usedIdentifiers = new Set(); + const { RESERVED_IDENTIFIER } = getPropertyName(); + for (const [name, v] of cssData.exports) { + const usedName = generateContext.moduleGraph + .getExportInfo(module, name) + .getUsedName(name, generateContext.runtime); + if (!usedName) { + continue; + } + let identifier = Template.toIdentifier(usedName); + + if (RESERVED_IDENTIFIER.has(identifier)) { + identifier = `_${identifier}`; + } + const i = 0; + while (usedIdentifiers.has(identifier)) { + identifier = Template.toIdentifier(name + i); + } + usedIdentifiers.add(identifier); + generateContext.concatenationScope.registerExport(name, identifier); + source.add( + `${ + generateContext.runtimeTemplate.supportsConst() + ? "const" + : "var" + } ${identifier} = ${JSON.stringify(v)};\n` + ); + } + return source; + } + + if ( + cssData.exports.size === 0 && + !(/** @type {BuildMeta} */ (module.buildMeta).isCSSModule) + ) { + return new RawSource(""); + } + + const needNsObj = + this.esModule && + generateContext.moduleGraph + .getExportsInfo(module) + .otherExportsInfo.getUsed(generateContext.runtime) !== + UsageState.Unused; + + if (needNsObj) { + generateContext.runtimeRequirements.add( + RuntimeGlobals.makeNamespaceObject + ); + } + + const exports = []; + + for (const [name, v] of cssData.exports) { + exports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`); + } + + return new RawSource( + `${needNsObj ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${ + module.moduleArgument + }.exports = {\n${exports.join(",\n")}\n}${needNsObj ? ")" : ""};` + ); + } + case "css": { + if (module.presentationalDependencies !== undefined) { + for (const dependency of module.presentationalDependencies) { + handleDependency(dependency); + } + } + + generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules); + + return InitFragment.addToSource(source, initFragments, generateContext); + } + default: + return null; + } + } + + /** + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generateError(error, module, generateContext) { + switch (generateContext.type) { + case "javascript": { + return new RawSource( + `throw new Error(${JSON.stringify(error.message)});` + ); + } + case "css": { + return new RawSource(`/**\n ${error.message} \n**/`); + } + default: + return null; + } + } + + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + // TODO, find a better way to prevent the original module from being removed after concatenation, maybe it is a bug + if (this.exportsOnly) { + return JS_AND_CSS_EXPORT_TYPES; + } + const sourceTypes = new Set(); + const connections = this._moduleGraph.getIncomingConnections(module); + for (const connection of connections) { + if (!connection.originModule) { + continue; + } + if (connection.originModule.type.split("/")[0] !== CSS_TYPE) { + sourceTypes.add(JS_TYPE); + } + } + if (sourceTypes.has(JS_TYPE)) { + return JS_AND_CSS_TYPES; + } + return CSS_TYPES; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + switch (type) { + case "javascript": { + const cssData = /** @type {BuildInfo} */ (module.buildInfo).cssData; + if (!cssData) { + return 42; + } + if (cssData.exports.size === 0) { + if (/** @type {BuildMeta} */ (module.buildMeta).isCSSModule) { + return 42; + } + return 0; + } + const exports = cssData.exports; + const stringifiedExports = JSON.stringify( + [...exports].reduce((obj, [key, value]) => { + obj[key] = value; + return obj; + }, /** @type {Record} */ ({})) + ); + + return stringifiedExports.length + 42; + } + case "css": { + const originalSource = module.originalSource(); + + if (!originalSource) { + return 0; + } + + return originalSource.size(); + } + default: + return 0; + } + } + + /** + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash + */ + updateHash(hash, { module }) { + hash.update(/** @type {boolean} */ (this.esModule).toString()); + } +} + +module.exports = CssGenerator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssLoadingRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssLoadingRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..ce2a9b13d88ba0153a86205e3e990bdc96572a89 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssLoadingRuntimeModule.js @@ -0,0 +1,506 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { SyncWaterfallHook } = require("tapable"); +const Compilation = require("../Compilation"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const compileBooleanMatcher = require("../util/compileBooleanMatcher"); +const { chunkHasCss } = require("./CssModulesPlugin"); + +/** @typedef {import("../../declarations/WebpackOptions").Environment} Environment */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation").RuntimeRequirementsContext} RuntimeRequirementsContext */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ + +/** + * @typedef {object} CssLoadingRuntimeModulePluginHooks + * @property {SyncWaterfallHook<[string, Chunk]>} createStylesheet + * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload + * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class CssLoadingRuntimeModule extends RuntimeModule { + /** + * @param {Compilation} compilation the compilation + * @returns {CssLoadingRuntimeModulePluginHooks} hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + createStylesheet: new SyncWaterfallHook(["source", "chunk"]), + linkPreload: new SyncWaterfallHook(["source", "chunk"]), + linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** + * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super("css loading", 10); + + this._runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { _runtimeRequirements } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunk = /** @type {Chunk} */ (this.chunk); + const { + chunkGraph, + runtimeTemplate, + outputOptions: { + crossOriginLoading, + uniqueName, + chunkLoadTimeout: loadTimeout, + charset + } + } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const conditionMap = chunkGraph.getChunkConditionMap( + /** @type {Chunk} */ (chunk), + /** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {boolean} true, if the chunk has css + */ + (chunk, chunkGraph) => + Boolean(chunkGraph.getChunkModulesIterableBySourceType(chunk, "css")) + ); + const hasCssMatcher = compileBooleanMatcher(conditionMap); + + const withLoading = + _runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && + hasCssMatcher !== false; + /** @type {boolean} */ + const withHmr = _runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + /** @type {Set} */ + const initialChunkIds = new Set(); + for (const c of /** @type {Chunk} */ (chunk).getAllInitialChunks()) { + if (chunkHasCss(c, chunkGraph)) { + initialChunkIds.add(c.id); + } + } + + if (!withLoading && !withHmr) { + return null; + } + + const environment = + /** @type {Environment} */ + (compilation.outputOptions.environment); + const isNeutralPlatform = runtimeTemplate.isNeutralPlatform(); + const withPrefetch = + this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) && + (environment.document || isNeutralPlatform) && + chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasCss); + const withPreload = + this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) && + (environment.document || isNeutralPlatform) && + chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasCss); + + const { linkPreload, linkPrefetch } = + CssLoadingRuntimeModule.getCompilationHooks(compilation); + + const withFetchPriority = _runtimeRequirements.has( + RuntimeGlobals.hasFetchPriority + ); + + const { createStylesheet } = + CssLoadingRuntimeModule.getCompilationHooks(compilation); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css` + : undefined; + + const code = Template.asString([ + "link = document.createElement('link');", + charset ? "link.charset = 'utf-8';" : "", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + uniqueName + ? 'link.setAttribute("data-webpack", uniqueName + ":" + key);' + : "", + withFetchPriority + ? Template.asString([ + "if(fetchPriority) {", + Template.indent( + 'link.setAttribute("fetchpriority", fetchPriority);' + ), + "}" + ]) + : "", + "link.setAttribute(loadingAttribute, 1);", + 'link.rel = "stylesheet";', + "link.href = url;", + crossOriginLoading + ? crossOriginLoading === "use-credentials" + ? 'link.crossOrigin = "use-credentials";' + : Template.asString([ + "if (link.href.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "" + ]); + + return Template.asString([ + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), + "};", + "", + uniqueName + ? `var uniqueName = ${JSON.stringify( + runtimeTemplate.outputOptions.uniqueName + )};` + : "// data-webpack is not used as build has no uniqueName", + withLoading || withHmr + ? Template.asString([ + 'var loadingAttribute = "data-webpack-loading";', + `var loadStylesheet = ${runtimeTemplate.basicFunction( + `chunkId, url, done${ + withFetchPriority ? ", fetchPriority" : "" + }${withHmr ? ", hmr" : ""}`, + [ + 'var link, needAttach, key = "chunk-" + chunkId;', + withHmr ? "if(!hmr) {" : "", + 'var links = document.getElementsByTagName("link");', + "for(var i = 0; i < links.length; i++) {", + Template.indent([ + "var l = links[i];", + `if(l.rel == "stylesheet" && (${ + withHmr + ? 'l.href.startsWith(url) || l.getAttribute("href").startsWith(url)' + : 'l.href == url || l.getAttribute("href") == url' + }${ + uniqueName + ? ' || l.getAttribute("data-webpack") == uniqueName + ":" + key' + : "" + })) { link = l; break; }` + ]), + "}", + "if(!done) return link;", + withHmr ? "}" : "", + "if(!link) {", + Template.indent([ + "needAttach = true;", + createStylesheet.call(code, /** @type {Chunk} */ (this.chunk)) + ]), + "}", + `var onLinkComplete = ${runtimeTemplate.basicFunction( + "prev, event", + Template.asString([ + "link.onerror = link.onload = null;", + "link.removeAttribute(loadingAttribute);", + "clearTimeout(timeout);", + 'if(event && event.type != "load") link.parentNode.removeChild(link)', + "done(event);", + "if(prev) return prev(event);" + ]) + )};`, + "if(link.getAttribute(loadingAttribute)) {", + Template.indent([ + `var timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`, + "link.onerror = onLinkComplete.bind(null, link.onerror);", + "link.onload = onLinkComplete.bind(null, link.onload);" + ]), + "} else onLinkComplete(undefined, { type: 'load', target: link });", // We assume any existing stylesheet is render blocking + withHmr && withFetchPriority + ? 'if (hmr && hmr.getAttribute("fetchpriority")) link.setAttribute("fetchpriority", hmr.getAttribute("fetchpriority"));' + : "", + withHmr ? "hmr ? document.head.insertBefore(link, hmr) :" : "", + "needAttach && document.head.appendChild(link);", + "return link;" + ] + )};` + ]) + : "", + withLoading + ? Template.asString([ + `${fn}.css = ${runtimeTemplate.basicFunction( + `chunkId, promises${withFetchPriority ? " , fetchPriority" : ""}`, + [ + "// css chunk loading", + `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent(["promises.push(installedChunkData[2]);"]), + "} else {", + Template.indent([ + hasCssMatcher === true + ? "if(true) { // all chunks have CSS" + : `if(${hasCssMatcher("chunkId")}) {`, + Template.indent([ + "// setup Promise in chunk cache", + `var promise = new Promise(${runtimeTemplate.expressionFunction( + "installedChunkData = installedChunks[chunkId] = [resolve, reject]", + "resolve, reject" + )});`, + "promises.push(installedChunkData[2] = promise);", + "", + "// start chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + `var loadingEnded = ${runtimeTemplate.basicFunction( + "event", + [ + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, + Template.indent([ + "installedChunkData = installedChunks[chunkId];", + "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", + "if(installedChunkData) {", + Template.indent([ + 'if(event.type !== "load") {', + Template.indent([ + "var errorType = event && event.type;", + "var realHref = event && event.target && event.target.href;", + "error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realHref + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realHref;", + "installedChunkData[1](error);" + ]), + "} else {", + Template.indent([ + "installedChunks[chunkId] = 0;", + "installedChunkData[0]();" + ]), + "}" + ]), + "}" + ]), + "}" + ] + )};`, + isNeutralPlatform + ? "if (typeof document !== 'undefined') {" + : "", + Template.indent([ + `loadStylesheet(chunkId, url, loadingEnded${ + withFetchPriority ? ", fetchPriority" : "" + });` + ]), + isNeutralPlatform + ? "} else { loadingEnded({ type: 'load' }); }" + : "" + ]), + "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ] + )};` + ]) + : "// no chunk loading", + "", + withPrefetch && hasCssMatcher !== false + ? `${ + RuntimeGlobals.prefetchChunkHandlers + }.s = ${runtimeTemplate.basicFunction("chunkId", [ + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasCssMatcher === true ? "true" : hasCssMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + isNeutralPlatform + ? "if (typeof document === 'undefined') return;" + : "", + linkPrefetch.call( + Template.asString([ + "var link = document.createElement('link');", + charset ? "link.charset = 'utf-8';" : "", + crossOriginLoading + ? `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + : "", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + 'link.rel = "prefetch";', + 'link.as = "style";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);` + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no prefetching", + "", + withPreload && hasCssMatcher !== false + ? `${ + RuntimeGlobals.preloadChunkHandlers + }.s = ${runtimeTemplate.basicFunction("chunkId", [ + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasCssMatcher === true ? "true" : hasCssMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + isNeutralPlatform + ? "if (typeof document === 'undefined') return;" + : "", + linkPreload.call( + Template.asString([ + "var link = document.createElement('link');", + charset ? "link.charset = 'utf-8';" : "", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + 'link.rel = "preload";', + 'link.as = "style";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, + crossOriginLoading + ? crossOriginLoading === "use-credentials" + ? 'link.crossOrigin = "use-credentials";' + : Template.asString([ + "if (link.href.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + ), + "}" + ]) + : "" + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no preloaded", + withHmr + ? Template.asString([ + "var oldTags = [];", + "var newTags = [];", + `var applyHandler = ${runtimeTemplate.basicFunction("options", [ + `return { dispose: ${runtimeTemplate.basicFunction("", [ + "while(oldTags.length) {", + Template.indent([ + "var oldTag = oldTags.pop();", + "if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);" + ]), + "}" + ])}, apply: ${runtimeTemplate.basicFunction("", [ + "while(newTags.length) {", + Template.indent([ + "var newTag = newTags.pop();", + "newTag.sheet.disabled = false" + ]), + "}" + ])} };` + ])}`, + `var cssTextKey = ${runtimeTemplate.returningFunction( + `Array.from(link.sheet.cssRules, ${runtimeTemplate.returningFunction( + "r.cssText", + "r" + )}).join()`, + "link" + )};`, + `${ + RuntimeGlobals.hmrDownloadUpdateHandlers + }.css = ${runtimeTemplate.basicFunction( + "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList", + [ + isNeutralPlatform + ? "if (typeof document === 'undefined') return;" + : "", + "applyHandlers.push(applyHandler);", + `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [ + `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, + `var url = ${RuntimeGlobals.publicPath} + filename;`, + "var oldTag = loadStylesheet(chunkId, url);", + "if(!oldTag) return;", + `promises.push(new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + `var link = loadStylesheet(chunkId, url + (url.indexOf("?") < 0 ? "?" : "&") + "hmr=" + Date.now(), ${runtimeTemplate.basicFunction( + "event", + [ + 'if(event.type !== "load") {', + Template.indent([ + "var errorType = event && event.type;", + "var realHref = event && event.target && event.target.href;", + "error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realHref + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realHref;", + "reject(error);" + ]), + "} else {", + Template.indent([ + "try { if(cssTextKey(oldTag) == cssTextKey(link)) { if(link.parentNode) link.parentNode.removeChild(link); return resolve(); } } catch(e) {}", + "link.sheet.disabled = true;", + "oldTags.push(oldTag);", + "newTags.push(link);", + "resolve();" + ]), + "}" + ] + )}, ${withFetchPriority ? "undefined," : ""} oldTag);` + ] + )}));` + ])});` + ] + )}` + ]) + : "// no hmr" + ]); + } +} + +module.exports = CssLoadingRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9c5be4c1387704bdb7f55a1d7c76d1837bf410d2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssModulesPlugin.js @@ -0,0 +1,937 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { SyncHook, SyncWaterfallHook } = require("tapable"); +const { + CachedSource, + ConcatSource, + PrefixSource, + RawSource, + ReplaceSource +} = require("webpack-sources"); +const Compilation = require("../Compilation"); +const CssModule = require("../CssModule"); +const { tryRunOrWebpackError } = require("../HookWebpackError"); +const HotUpdateChunk = require("../HotUpdateChunk"); +const { + CSS_MODULE_TYPE, + CSS_MODULE_TYPE_AUTO, + CSS_MODULE_TYPE_GLOBAL, + CSS_MODULE_TYPE_MODULE +} = require("../ModuleTypeConstants"); +const NormalModule = require("../NormalModule"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const SelfModuleFactory = require("../SelfModuleFactory"); +const Template = require("../Template"); +const WebpackError = require("../WebpackError"); +const CssIcssExportDependency = require("../dependencies/CssIcssExportDependency"); +const CssIcssImportDependency = require("../dependencies/CssIcssImportDependency"); +const CssIcssSymbolDependency = require("../dependencies/CssIcssSymbolDependency"); +const CssImportDependency = require("../dependencies/CssImportDependency"); +const CssLocalIdentifierDependency = require("../dependencies/CssLocalIdentifierDependency"); +const CssSelfLocalIdentifierDependency = require("../dependencies/CssSelfLocalIdentifierDependency"); +const CssUrlDependency = require("../dependencies/CssUrlDependency"); +const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); +const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin"); +const { compareModulesByIdOrIdentifier } = require("../util/comparators"); +const createSchemaValidation = require("../util/create-schema-validation"); +const createHash = require("../util/createHash"); +const { getUndoPath } = require("../util/identifier"); +const memoize = require("../util/memoize"); +const nonNumericOnlyHash = require("../util/nonNumericOnlyHash"); +const removeBOM = require("../util/removeBOM"); +const CssGenerator = require("./CssGenerator"); +const CssParser = require("./CssParser"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../CssModule").Inheritance} Inheritance */ +/** @typedef {import("../CssModule").CSSModuleCreateData} CSSModuleCreateData */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Template").RuntimeTemplate} RuntimeTemplate */ +/** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/memoize")} Memoize */ + +/** + * @typedef {object} RenderContext + * @property {Chunk} chunk the chunk + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {string} uniqueName the unique name + * @property {string} undoPath undo path to css file + * @property {CssModule[]} modules modules + */ + +/** + * @typedef {object} ChunkRenderContext + * @property {Chunk} chunk the chunk + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {string} undoPath undo path to css file + */ + +/** + * @typedef {object} CompilationHooks + * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModulePackage + * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash + */ + +const getCssLoadingRuntimeModule = memoize(() => + require("./CssLoadingRuntimeModule") +); + +/** + * @param {string} name name + * @returns {{ oneOf: [{ $ref: string }], definitions: import("../../schemas/WebpackOptions.json")["definitions"] }} schema + */ +const getSchema = (name) => { + const { definitions } = require("../../schemas/WebpackOptions.json"); + + return { + definitions, + oneOf: [{ $ref: `#/definitions/${name}` }] + }; +}; + +const generatorValidationOptions = { + name: "Css Modules Plugin", + baseDataPath: "generator" +}; +const validateGeneratorOptions = { + css: createSchemaValidation( + require("../../schemas/plugins/css/CssGeneratorOptions.check"), + () => getSchema("CssGeneratorOptions"), + generatorValidationOptions + ), + "css/auto": createSchemaValidation( + require("../../schemas/plugins/css/CssAutoGeneratorOptions.check"), + () => getSchema("CssAutoGeneratorOptions"), + generatorValidationOptions + ), + "css/module": createSchemaValidation( + require("../../schemas/plugins/css/CssModuleGeneratorOptions.check"), + () => getSchema("CssModuleGeneratorOptions"), + generatorValidationOptions + ), + "css/global": createSchemaValidation( + require("../../schemas/plugins/css/CssGlobalGeneratorOptions.check"), + () => getSchema("CssGlobalGeneratorOptions"), + generatorValidationOptions + ) +}; + +const parserValidationOptions = { + name: "Css Modules Plugin", + baseDataPath: "parser" +}; +const validateParserOptions = { + css: createSchemaValidation( + require("../../schemas/plugins/css/CssParserOptions.check"), + () => getSchema("CssParserOptions"), + parserValidationOptions + ), + "css/auto": createSchemaValidation( + require("../../schemas/plugins/css/CssAutoParserOptions.check"), + () => getSchema("CssAutoParserOptions"), + parserValidationOptions + ), + "css/module": createSchemaValidation( + require("../../schemas/plugins/css/CssModuleParserOptions.check"), + () => getSchema("CssModuleParserOptions"), + parserValidationOptions + ), + "css/global": createSchemaValidation( + require("../../schemas/plugins/css/CssGlobalParserOptions.check"), + () => getSchema("CssGlobalParserOptions"), + parserValidationOptions + ) +}; + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +const PLUGIN_NAME = "CssModulesPlugin"; + +class CssModulesPlugin { + /** + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} the attached hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + renderModulePackage: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]), + chunkHash: new SyncHook(["chunk", "hash", "context"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + constructor() { + /** @type {WeakMap} */ + this._moduleFactoryCache = new WeakMap(); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + const hooks = CssModulesPlugin.getCompilationHooks(compilation); + const selfFactory = new SelfModuleFactory(compilation.moduleGraph); + compilation.dependencyFactories.set( + CssImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CssImportDependency, + new CssImportDependency.Template() + ); + compilation.dependencyFactories.set( + CssUrlDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CssUrlDependency, + new CssUrlDependency.Template() + ); + compilation.dependencyTemplates.set( + CssLocalIdentifierDependency, + new CssLocalIdentifierDependency.Template() + ); + compilation.dependencyFactories.set( + CssSelfLocalIdentifierDependency, + selfFactory + ); + compilation.dependencyTemplates.set( + CssSelfLocalIdentifierDependency, + new CssSelfLocalIdentifierDependency.Template() + ); + compilation.dependencyFactories.set( + CssIcssImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CssIcssImportDependency, + new CssIcssImportDependency.Template() + ); + compilation.dependencyTemplates.set( + CssIcssExportDependency, + new CssIcssExportDependency.Template() + ); + compilation.dependencyTemplates.set( + CssIcssSymbolDependency, + new CssIcssSymbolDependency.Template() + ); + compilation.dependencyTemplates.set( + StaticExportsDependency, + new StaticExportsDependency.Template() + ); + for (const type of [ + CSS_MODULE_TYPE, + CSS_MODULE_TYPE_GLOBAL, + CSS_MODULE_TYPE_MODULE, + CSS_MODULE_TYPE_AUTO + ]) { + normalModuleFactory.hooks.createParser + .for(type) + .tap(PLUGIN_NAME, (parserOptions) => { + validateParserOptions[type](parserOptions); + const { url, import: importOption, namedExports } = parserOptions; + + switch (type) { + case CSS_MODULE_TYPE: + return new CssParser({ + importOption, + url, + namedExports + }); + case CSS_MODULE_TYPE_GLOBAL: + return new CssParser({ + defaultMode: "global", + importOption, + url, + namedExports + }); + case CSS_MODULE_TYPE_MODULE: + return new CssParser({ + defaultMode: "local", + importOption, + url, + namedExports + }); + case CSS_MODULE_TYPE_AUTO: + return new CssParser({ + defaultMode: "auto", + importOption, + url, + namedExports + }); + } + }); + normalModuleFactory.hooks.createGenerator + .for(type) + .tap(PLUGIN_NAME, (generatorOptions) => { + validateGeneratorOptions[type](generatorOptions); + + return new CssGenerator( + generatorOptions, + compilation.moduleGraph + ); + }); + normalModuleFactory.hooks.createModuleClass + .for(type) + .tap(PLUGIN_NAME, (createData, resolveData) => { + if (resolveData.dependencies.length > 0) { + // When CSS is imported from CSS there is only one dependency + const dependency = resolveData.dependencies[0]; + + if (dependency instanceof CssImportDependency) { + const parent = + /** @type {CssModule} */ + (compilation.moduleGraph.getParentModule(dependency)); + + if (parent instanceof CssModule) { + /** @type {import("../CssModule").Inheritance | undefined} */ + let inheritance; + + if ( + parent.cssLayer !== undefined || + parent.supports || + parent.media + ) { + if (!inheritance) { + inheritance = []; + } + + inheritance.push([ + parent.cssLayer, + parent.supports, + parent.media + ]); + } + + if (parent.inheritance) { + if (!inheritance) { + inheritance = []; + } + + inheritance.push(...parent.inheritance); + } + + return new CssModule( + /** @type {CSSModuleCreateData} */ + ({ + ...createData, + cssLayer: dependency.layer, + supports: dependency.supports, + media: dependency.media, + inheritance + }) + ); + } + + return new CssModule( + /** @type {CSSModuleCreateData} */ + ({ + ...createData, + cssLayer: dependency.layer, + supports: dependency.supports, + media: dependency.media + }) + ); + } + } + + return new CssModule( + /** @type {CSSModuleCreateData} */ + (createData) + ); + }); + + NormalModule.getCompilationHooks(compilation).processResult.tap( + PLUGIN_NAME, + (result, module) => { + if (module.type === type) { + const [source, ...rest] = result; + + return [removeBOM(source), ...rest]; + } + + return result; + } + ); + } + + JavascriptModulesPlugin.getCompilationHooks( + compilation + ).renderModuleContent.tap(PLUGIN_NAME, (source, module) => { + if (module instanceof CssModule && module.hot) { + const cssData = /** @type {BuildInfo} */ (module.buildInfo).cssData; + if (!cssData) { + return source; + } + const exports = cssData.exports; + const stringifiedExports = JSON.stringify( + JSON.stringify( + [...exports].reduce((obj, [key, value]) => { + obj[key] = value; + return obj; + }, /** @type {Record} */ ({})) + ) + ); + + const hmrCode = Template.asString([ + "", + `var __webpack_css_exports__ = ${stringifiedExports};`, + "// only invalidate when locals change", + "if (module.hot.data && module.hot.data.__webpack_css_exports__ && module.hot.data.__webpack_css_exports__ != __webpack_css_exports__) {", + Template.indent("module.hot.invalidate();"), + "} else {", + Template.indent("module.hot.accept();"), + "}", + "module.hot.dispose(function(data) { data.__webpack_css_exports__ = __webpack_css_exports__; });" + ]); + + return new ConcatSource(source, "\n", new RawSource(hmrCode)); + } + + return source; + }); + const orderedCssModulesPerChunk = new WeakMap(); + compilation.hooks.afterCodeGeneration.tap(PLUGIN_NAME, () => { + const { chunkGraph } = compilation; + for (const chunk of compilation.chunks) { + if (CssModulesPlugin.chunkHasCss(chunk, chunkGraph)) { + orderedCssModulesPerChunk.set( + chunk, + this.getOrderedChunkCssModules(chunk, chunkGraph, compilation) + ); + } + } + }); + compilation.hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash, context) => { + hooks.chunkHash.call(chunk, hash, context); + }); + compilation.hooks.contentHash.tap(PLUGIN_NAME, (chunk) => { + const { + chunkGraph, + codeGenerationResults, + moduleGraph, + runtimeTemplate, + outputOptions: { + hashSalt, + hashDigest, + hashDigestLength, + hashFunction + } + } = compilation; + const hash = createHash(/** @type {HashFunction} */ (hashFunction)); + if (hashSalt) hash.update(hashSalt); + hooks.chunkHash.call(chunk, hash, { + chunkGraph, + codeGenerationResults, + moduleGraph, + runtimeTemplate + }); + const modules = orderedCssModulesPerChunk.get(chunk); + if (modules) { + for (const module of modules) { + hash.update(chunkGraph.getModuleHash(module, chunk.runtime)); + } + } + const digest = /** @type {string} */ (hash.digest(hashDigest)); + chunk.contentHash.css = nonNumericOnlyHash( + digest, + /** @type {number} */ + (hashDigestLength) + ); + }); + compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => { + const { chunkGraph } = compilation; + const { hash, chunk, codeGenerationResults, runtimeTemplate } = + options; + + if (chunk instanceof HotUpdateChunk) return result; + + /** @type {CssModule[] | undefined} */ + const modules = orderedCssModulesPerChunk.get(chunk); + if (modules !== undefined) { + const { path: filename, info } = compilation.getPathWithInfo( + CssModulesPlugin.getChunkFilenameTemplate( + chunk, + compilation.outputOptions + ), + { + hash, + runtime: chunk.runtime, + chunk, + contentHashType: "css" + } + ); + const undoPath = getUndoPath( + filename, + /** @type {string} */ + (compilation.outputOptions.path), + false + ); + result.push({ + render: () => + this.renderChunk( + { + chunk, + chunkGraph, + codeGenerationResults, + uniqueName: + /** @type {string} */ + (compilation.outputOptions.uniqueName), + undoPath, + modules, + runtimeTemplate + }, + hooks + ), + filename, + info, + identifier: `css${chunk.id}`, + hash: chunk.contentHash.css + }); + } + return result; + }); + const globalChunkLoading = compilation.outputOptions.chunkLoading; + /** + * @param {Chunk} chunk the chunk + * @returns {boolean} true, when enabled + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === "jsonp" || chunkLoading === "import"; + }; + const onceForChunkSet = new WeakSet(); + /** + * @param {Chunk} chunk chunk to check + * @param {Set} set runtime requirements + */ + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + + set.add(RuntimeGlobals.makeNamespaceObject); + + const CssLoadingRuntimeModule = getCssLoadingRuntimeModule(); + compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set)); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hasCssModules) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + (m) => + m.type === CSS_MODULE_TYPE || + m.type === CSS_MODULE_TYPE_GLOBAL || + m.type === CSS_MODULE_TYPE_MODULE || + m.type === CSS_MODULE_TYPE_AUTO + ) + ) { + return; + } + + set.add(RuntimeGlobals.hasOwnProperty); + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkCssFilename); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + (m) => + m.type === CSS_MODULE_TYPE || + m.type === CSS_MODULE_TYPE_GLOBAL || + m.type === CSS_MODULE_TYPE_MODULE || + m.type === CSS_MODULE_TYPE_AUTO + ) + ) { + return; + } + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkCssFilename); + }); + } + ); + } + + /** + * @param {Chunk} chunk chunk + * @param {Iterable} modules unordered modules + * @param {Compilation} compilation compilation + * @returns {Module[]} ordered modules + */ + getModulesInOrder(chunk, modules, compilation) { + if (!modules) return []; + + /** @type {Module[]} */ + const modulesList = [...modules]; + + // Get ordered list of modules per chunk group + // Lists are in reverse order to allow to use Array.pop() + const modulesByChunkGroup = Array.from( + chunk.groupsIterable, + (chunkGroup) => { + const sortedModules = modulesList + .map((module) => ({ + module, + index: chunkGroup.getModulePostOrderIndex(module) + })) + .filter((item) => item.index !== undefined) + .sort( + (a, b) => + /** @type {number} */ (b.index) - /** @type {number} */ (a.index) + ) + .map((item) => item.module); + + return { list: sortedModules, set: new Set(sortedModules) }; + } + ); + + if (modulesByChunkGroup.length === 1) { + return modulesByChunkGroup[0].list.reverse(); + } + + const boundCompareModulesByIdOrIdentifier = compareModulesByIdOrIdentifier( + compilation.chunkGraph + ); + + /** + * @param {{ list: Module[] }} a a + * @param {{ list: Module[] }} b b + * @returns {-1 | 0 | 1} result + */ + const compareModuleLists = ({ list: a }, { list: b }) => { + if (a.length === 0) { + return b.length === 0 ? 0 : 1; + } + if (b.length === 0) return -1; + return boundCompareModulesByIdOrIdentifier( + a[a.length - 1], + b[b.length - 1] + ); + }; + + modulesByChunkGroup.sort(compareModuleLists); + + /** @type {Module[]} */ + const finalModules = []; + + for (;;) { + const failedModules = new Set(); + const list = modulesByChunkGroup[0].list; + if (list.length === 0) { + // done, everything empty + break; + } + /** @type {Module} */ + let selectedModule = list[list.length - 1]; + let hasFailed; + outer: for (;;) { + for (const { list, set } of modulesByChunkGroup) { + if (list.length === 0) continue; + const lastModule = list[list.length - 1]; + if (lastModule === selectedModule) continue; + if (!set.has(selectedModule)) continue; + failedModules.add(selectedModule); + if (failedModules.has(lastModule)) { + // There is a conflict, try other alternatives + hasFailed = lastModule; + continue; + } + selectedModule = lastModule; + hasFailed = false; + continue outer; // restart + } + break; + } + if (hasFailed) { + // There is a not resolve-able conflict with the selectedModule + // TODO print better warning + compilation.warnings.push( + new WebpackError( + `chunk ${chunk.name || chunk.id}\nConflicting order between ${ + /** @type {Module} */ + (hasFailed).readableIdentifier(compilation.requestShortener) + } and ${selectedModule.readableIdentifier( + compilation.requestShortener + )}` + ) + ); + selectedModule = /** @type {Module} */ (hasFailed); + } + // Insert the selected module into the final modules list + finalModules.push(selectedModule); + // Remove the selected module from all lists + for (const { list, set } of modulesByChunkGroup) { + const lastModule = list[list.length - 1]; + if (lastModule === selectedModule) { + list.pop(); + } else if (hasFailed && set.has(selectedModule)) { + const idx = list.indexOf(selectedModule); + if (idx >= 0) list.splice(idx, 1); + } + } + modulesByChunkGroup.sort(compareModuleLists); + } + return finalModules; + } + + /** + * @param {Chunk} chunk chunk + * @param {ChunkGraph} chunkGraph chunk graph + * @param {Compilation} compilation compilation + * @returns {Module[]} ordered css modules + */ + getOrderedChunkCssModules(chunk, chunkGraph, compilation) { + return [ + ...this.getModulesInOrder( + chunk, + /** @type {Iterable} */ + ( + chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "css-import", + compareModulesByIdOrIdentifier(chunkGraph) + ) + ), + compilation + ), + ...this.getModulesInOrder( + chunk, + /** @type {Iterable} */ + ( + chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "css", + compareModulesByIdOrIdentifier(chunkGraph) + ) + ), + compilation + ) + ]; + } + + /** + * @param {CssModule} module css module + * @param {ChunkRenderContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @returns {Source} css module source + */ + renderModule(module, renderContext, hooks) { + const { codeGenerationResults, chunk, undoPath } = renderContext; + const codeGenResult = codeGenerationResults.get(module, chunk.runtime); + const moduleSourceContent = + /** @type {Source} */ + ( + codeGenResult.sources.get("css") || + codeGenResult.sources.get("css-import") + ); + const cacheEntry = this._moduleFactoryCache.get(moduleSourceContent); + + /** @type {Inheritance} */ + const inheritance = [[module.cssLayer, module.supports, module.media]]; + if (module.inheritance) { + inheritance.push(...module.inheritance); + } + + let source; + if ( + cacheEntry && + cacheEntry.undoPath === undoPath && + cacheEntry.inheritance.every(([layer, supports, media], i) => { + const item = inheritance[i]; + if (Array.isArray(item)) { + return layer === item[0] && supports === item[1] && media === item[2]; + } + return false; + }) + ) { + source = cacheEntry.source; + } else { + const moduleSourceCode = + /** @type {string} */ + (moduleSourceContent.source()); + const publicPathAutoRegex = new RegExp( + CssUrlDependency.PUBLIC_PATH_AUTO, + "g" + ); + /** @type {Source} */ + let moduleSource = new ReplaceSource(moduleSourceContent); + let match; + while ((match = publicPathAutoRegex.exec(moduleSourceCode))) { + /** @type {ReplaceSource} */ (moduleSource).replace( + match.index, + (match.index += match[0].length - 1), + undoPath + ); + } + + for (let i = 0; i < inheritance.length; i++) { + const layer = inheritance[i][0]; + const supports = inheritance[i][1]; + const media = inheritance[i][2]; + + if (media) { + moduleSource = new ConcatSource( + `@media ${media} {\n`, + new PrefixSource("\t", moduleSource), + "}\n" + ); + } + + if (supports) { + moduleSource = new ConcatSource( + `@supports (${supports}) {\n`, + new PrefixSource("\t", moduleSource), + "}\n" + ); + } + + // Layer can be anonymous + if (layer !== undefined && layer !== null) { + moduleSource = new ConcatSource( + `@layer${layer ? ` ${layer}` : ""} {\n`, + new PrefixSource("\t", moduleSource), + "}\n" + ); + } + } + + if (moduleSource) { + moduleSource = new ConcatSource(moduleSource, "\n"); + } + + source = new CachedSource(moduleSource); + this._moduleFactoryCache.set(moduleSourceContent, { + inheritance, + undoPath, + source + }); + } + + return tryRunOrWebpackError( + () => hooks.renderModulePackage.call(source, module, renderContext), + "CssModulesPlugin.getCompilationHooks().renderModulePackage" + ); + } + + /** + * @param {RenderContext} renderContext the render context + * @param {CompilationHooks} hooks hooks + * @returns {Source} generated source + */ + renderChunk( + { + undoPath, + chunk, + chunkGraph, + codeGenerationResults, + modules, + runtimeTemplate + }, + hooks + ) { + const source = new ConcatSource(); + for (const module of modules) { + try { + const moduleSource = this.renderModule( + module, + { + undoPath, + chunk, + chunkGraph, + codeGenerationResults, + runtimeTemplate + }, + hooks + ); + source.add(moduleSource); + } catch (err) { + /** @type {Error} */ + (err).message += `\nduring rendering of css ${module.identifier()}`; + throw err; + } + } + chunk.rendered = true; + return source; + } + + /** + * @param {Chunk} chunk chunk + * @param {OutputOptions} outputOptions output options + * @returns {TemplatePath} used filename template + */ + static getChunkFilenameTemplate(chunk, outputOptions) { + if (chunk.cssFilenameTemplate) { + return chunk.cssFilenameTemplate; + } else if (chunk.canBeInitial()) { + return /** @type {TemplatePath} */ (outputOptions.cssFilename); + } + return /** @type {TemplatePath} */ (outputOptions.cssChunkFilename); + } + + /** + * @param {Chunk} chunk chunk + * @param {ChunkGraph} chunkGraph chunk graph + * @returns {boolean} true, when the chunk has css + */ + static chunkHasCss(chunk, chunkGraph) { + return ( + Boolean(chunkGraph.getChunkModulesIterableBySourceType(chunk, "css")) || + Boolean( + chunkGraph.getChunkModulesIterableBySourceType(chunk, "css-import") + ) + ); + } +} + +module.exports = CssModulesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssParser.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssParser.js new file mode 100644 index 0000000000000000000000000000000000000000..b8b430bc7a7436b2fbf72056211ad39d10faa975 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/CssParser.js @@ -0,0 +1,1624 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const vm = require("vm"); +const CommentCompilationWarning = require("../CommentCompilationWarning"); +const ModuleDependencyWarning = require("../ModuleDependencyWarning"); +const { CSS_MODULE_TYPE_AUTO } = require("../ModuleTypeConstants"); +const Parser = require("../Parser"); +const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); +const WebpackError = require("../WebpackError"); +const ConstDependency = require("../dependencies/ConstDependency"); +const CssIcssExportDependency = require("../dependencies/CssIcssExportDependency"); +const CssIcssImportDependency = require("../dependencies/CssIcssImportDependency"); +const CssIcssSymbolDependency = require("../dependencies/CssIcssSymbolDependency"); +const CssImportDependency = require("../dependencies/CssImportDependency"); +const CssLocalIdentifierDependency = require("../dependencies/CssLocalIdentifierDependency"); +const CssSelfLocalIdentifierDependency = require("../dependencies/CssSelfLocalIdentifierDependency"); +const CssUrlDependency = require("../dependencies/CssUrlDependency"); +const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); +const binarySearchBounds = require("../util/binarySearchBounds"); +const { parseResource } = require("../util/identifier"); +const { + createMagicCommentContext, + webpackCommentRegExp +} = require("../util/magicComment"); +const walkCssTokens = require("./walkCssTokens"); + +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +/** @typedef {import("./walkCssTokens").CssTokenCallbacks} CssTokenCallbacks */ + +/** @typedef {[number, number]} Range */ +/** @typedef {{ line: number, column: number }} Position */ +/** @typedef {{ value: string, range: Range, loc: { start: Position, end: Position } }} Comment */ + +const CC_COLON = ":".charCodeAt(0); +const CC_SLASH = "/".charCodeAt(0); +const CC_LEFT_PARENTHESIS = "(".charCodeAt(0); +const CC_RIGHT_PARENTHESIS = ")".charCodeAt(0); +const CC_LOWER_F = "f".charCodeAt(0); +const CC_UPPER_F = "F".charCodeAt(0); + +// https://www.w3.org/TR/css-syntax-3/#newline +// We don't have `preprocessing` stage, so we need specify all of them +const STRING_MULTILINE = /\\[\n\r\f]/g; +// https://www.w3.org/TR/css-syntax-3/#whitespace +const TRIM_WHITE_SPACES = /(^[ \t\n\r\f]*|[ \t\n\r\f]*$)/g; +const UNESCAPE = /\\([0-9a-fA-F]{1,6}[ \t\n\r\f]?|[\s\S])/g; +const IMAGE_SET_FUNCTION = /^(-\w+-)?image-set$/i; +const OPTIONALLY_VENDOR_PREFIXED_KEYFRAMES_AT_RULE = /^@(-\w+-)?keyframes$/; +const OPTIONALLY_VENDOR_PREFIXED_ANIMATION_PROPERTY = + /^(-\w+-)?animation(-name)?$/i; +const IS_MODULES = /\.module(s)?\.[^.]+$/i; +const CSS_COMMENT = /\/\*((?!\*\/).*?)\*\//g; + +/** + * @param {string} str url string + * @param {boolean} isString is url wrapped in quotes + * @returns {string} normalized url + */ +const normalizeUrl = (str, isString) => { + // Remove extra spaces and newlines: + // `url("im\ + // g.png")` + if (isString) { + str = str.replace(STRING_MULTILINE, ""); + } + + str = str + // Remove unnecessary spaces from `url(" img.png ")` + .replace(TRIM_WHITE_SPACES, "") + // Unescape + .replace(UNESCAPE, (match) => { + if (match.length > 2) { + return String.fromCharCode(Number.parseInt(match.slice(1).trim(), 16)); + } + return match[1]; + }); + + if (/^data:/i.test(str)) { + return str; + } + + if (str.includes("%")) { + // Convert `url('%2E/img.png')` -> `url('./img.png')` + try { + str = decodeURIComponent(str); + } catch (_err) { + // Ignore + } + } + + return str; +}; + +// eslint-disable-next-line no-useless-escape +const regexSingleEscape = /[ -,.\/:-@[\]\^`{-~]/; +const regexExcessiveSpaces = + /(^|\\+)?(\\[A-F0-9]{1,6})\u0020(?![a-fA-F0-9\u0020])/g; + +/** + * @param {string} str string + * @returns {string} escaped identifier + */ +const escapeIdentifier = (str) => { + let output = ""; + let counter = 0; + + while (counter < str.length) { + const character = str.charAt(counter++); + + let value; + + // eslint-disable-next-line no-control-regex + if (/[\t\n\f\r\u000B]/.test(character)) { + const codePoint = character.charCodeAt(0); + + value = `\\${codePoint.toString(16).toUpperCase()} `; + } else if (character === "\\" || regexSingleEscape.test(character)) { + value = `\\${character}`; + } else { + value = character; + } + + output += value; + } + + const firstChar = str.charAt(0); + + if (/^-[-\d]/.test(output)) { + output = `\\-${output.slice(1)}`; + } else if (/\d/.test(firstChar)) { + output = `\\3${firstChar} ${output.slice(1)}`; + } + + // Remove spaces after `\HEX` escapes that are not followed by a hex digit, + // since they’re redundant. Note that this is only possible if the escape + // sequence isn’t preceded by an odd number of backslashes. + output = output.replace(regexExcessiveSpaces, ($0, $1, $2) => { + if ($1 && $1.length % 2) { + // It’s not safe to remove the space, so don’t. + return $0; + } + + // Strip the space. + return ($1 || "") + $2; + }); + + return output; +}; + +const CONTAINS_ESCAPE = /\\/; + +/** + * @param {string} str string + * @returns {[string, number] | undefined} hex + */ +const gobbleHex = (str) => { + const lower = str.toLowerCase(); + let hex = ""; + let spaceTerminated = false; + + for (let i = 0; i < 6 && lower[i] !== undefined; i++) { + const code = lower.charCodeAt(i); + // check to see if we are dealing with a valid hex char [a-f|0-9] + const valid = (code >= 97 && code <= 102) || (code >= 48 && code <= 57); + // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point + spaceTerminated = code === 32; + if (!valid) break; + hex += lower[i]; + } + + if (hex.length === 0) return undefined; + + const codePoint = Number.parseInt(hex, 16); + const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff; + + // Add special case for + // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point" + // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point + if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10ffff) { + return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)]; + } + + return [ + String.fromCodePoint(codePoint), + hex.length + (spaceTerminated ? 1 : 0) + ]; +}; + +/** + * @param {string} str string + * @returns {string} unescaped string + */ +const unescapeIdentifier = (str) => { + const needToProcess = CONTAINS_ESCAPE.test(str); + if (!needToProcess) return str; + let ret = ""; + for (let i = 0; i < str.length; i++) { + if (str[i] === "\\") { + const gobbled = gobbleHex(str.slice(i + 1, i + 7)); + if (gobbled !== undefined) { + ret += gobbled[0]; + i += gobbled[1]; + continue; + } + // Retain a pair of \\ if double escaped `\\\\` + // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e + if (str[i + 1] === "\\") { + ret += "\\"; + i += 1; + continue; + } + // if \\ is at the end of the string retain it + // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb + if (str.length === i + 1) { + ret += str[i]; + } + continue; + } + ret += str[i]; + } + + return ret; +}; + +class LocConverter { + /** + * @param {string} input input + */ + constructor(input) { + this._input = input; + this.line = 1; + this.column = 0; + this.pos = 0; + } + + /** + * @param {number} pos position + * @returns {LocConverter} location converter + */ + get(pos) { + if (this.pos !== pos) { + if (this.pos < pos) { + const str = this._input.slice(this.pos, pos); + let i = str.lastIndexOf("\n"); + if (i === -1) { + this.column += str.length; + } else { + this.column = str.length - i - 1; + this.line++; + while (i > 0 && (i = str.lastIndexOf("\n", i - 1)) !== -1) { + this.line++; + } + } + } else { + let i = this._input.lastIndexOf("\n", this.pos); + while (i >= pos) { + this.line--; + i = i > 0 ? this._input.lastIndexOf("\n", i - 1) : -1; + } + this.column = pos - i; + } + this.pos = pos; + } + return this; + } +} + +const EMPTY_COMMENT_OPTIONS = { + options: null, + errors: null +}; + +const CSS_MODE_TOP_LEVEL = 0; +const CSS_MODE_IN_BLOCK = 1; + +const eatUntilSemi = walkCssTokens.eatUntil(";"); +const eatUntilLeftCurly = walkCssTokens.eatUntil("{"); +const eatSemi = walkCssTokens.eatUntil(";"); + +/** + * @typedef {object} CssParserOptions + * @property {boolean=} importOption need handle `@import` + * @property {boolean=} url need handle URLs + * @property {("pure" | "global" | "local" | "auto")=} defaultMode default mode + * @property {boolean=} namedExports is named exports + */ + +class CssParser extends Parser { + /** + * @param {CssParserOptions=} options options + */ + constructor({ + defaultMode = "pure", + importOption = true, + url = true, + namedExports = true + } = {}) { + super(); + this.defaultMode = defaultMode; + this.import = importOption; + this.url = url; + this.namedExports = namedExports; + /** @type {Comment[] | undefined} */ + this.comments = undefined; + this.magicCommentContext = createMagicCommentContext(); + } + + /** + * @param {ParserState} state parser state + * @param {string} message warning message + * @param {LocConverter} locConverter location converter + * @param {number} start start offset + * @param {number} end end offset + */ + _emitWarning(state, message, locConverter, start, end) { + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + + state.current.addWarning( + new ModuleDependencyWarning(state.module, new WebpackError(message), { + start: { line: sl, column: sc }, + end: { line: el, column: ec } + }) + ); + } + + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (Buffer.isBuffer(source)) { + source = source.toString("utf8"); + } else if (typeof source === "object") { + throw new Error("webpackAst is unexpected for the CssParser"); + } + if (source[0] === "\uFEFF") { + source = source.slice(1); + } + + let mode = this.defaultMode; + + const module = state.module; + + if ( + mode === "auto" && + module.type === CSS_MODULE_TYPE_AUTO && + IS_MODULES.test( + parseResource(module.matchResource || module.resource).path + ) + ) { + mode = "local"; + } + + const isModules = mode === "global" || mode === "local"; + + /** @type {BuildMeta} */ + (module.buildMeta).isCSSModule = isModules; + + const locConverter = new LocConverter(source); + + /** @type {number} */ + let scope = CSS_MODE_TOP_LEVEL; + /** @type {boolean} */ + let allowImportAtRule = true; + /** @type [string, number, number][] */ + const balanced = []; + let lastTokenEndForComments = 0; + + /** @type {boolean} */ + let isNextRulePrelude = isModules; + /** @type {number} */ + let blockNestingLevel = 0; + /** @type {"local" | "global" | undefined} */ + let modeData; + /** @type {boolean} */ + let inAnimationProperty = false; + /** @type {[number, number, boolean] | undefined} */ + let lastIdentifier; + /** @type {Set} */ + const declaredCssVariables = new Set(); + /** @typedef {{ path?: string, value: string }} IcssDefinition */ + /** @type {Map} */ + const icssDefinitions = new Map(); + + /** + * @param {string} input input + * @param {number} pos position + * @returns {boolean} true, when next is nested syntax + */ + const isNextNestedSyntax = (input, pos) => { + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + + if (input[pos] === "}") { + return false; + } + + // According spec only identifier can be used as a property name + const isIdentifier = walkCssTokens.isIdentStartCodePoint( + input.charCodeAt(pos) + ); + + return !isIdentifier; + }; + /** + * @returns {boolean} true, when in local scope + */ + const isLocalMode = () => + modeData === "local" || (mode === "local" && modeData === undefined); + + /** + * @param {string} input input + * @param {number} pos start position + * @param {(input: string, pos: number) => number} eater eater + * @returns {[number,string]} new position and text + */ + const eatText = (input, pos, eater) => { + let text = ""; + for (;;) { + if (input.charCodeAt(pos) === CC_SLASH) { + const newPos = walkCssTokens.eatComments(input, pos); + if (pos !== newPos) { + pos = newPos; + if (pos === input.length) break; + } else { + text += "/"; + pos++; + if (pos === input.length) break; + } + } + const newPos = eater(input, pos); + if (pos !== newPos) { + text += input.slice(pos, newPos); + pos = newPos; + } else { + break; + } + if (pos === input.length) break; + } + return [pos, text.trimEnd()]; + }; + + /** + * @param {0 | 1} type import or export + * @param {string} input input + * @param {number} pos start position + * @returns {number} position after parse + */ + const parseImportOrExport = (type, input, pos) => { + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + /** @type {string | undefined} */ + let importPath; + if (type === 0) { + let cc = input.charCodeAt(pos); + if (cc !== CC_LEFT_PARENTHESIS) { + this._emitWarning( + state, + `Unexpected '${input[pos]}' at ${pos} during parsing of ':import' (expected '(')`, + locConverter, + pos, + pos + ); + return pos; + } + pos++; + const stringStart = pos; + const str = walkCssTokens.eatString(input, pos); + if (!str) { + this._emitWarning( + state, + `Unexpected '${input[pos]}' at ${pos} during parsing of ':import' (expected string)`, + locConverter, + stringStart, + pos + ); + return pos; + } + importPath = input.slice(str[0] + 1, str[1] - 1); + pos = str[1]; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + cc = input.charCodeAt(pos); + if (cc !== CC_RIGHT_PARENTHESIS) { + this._emitWarning( + state, + `Unexpected '${input[pos]}' at ${pos} during parsing of ':import' (expected ')')`, + locConverter, + pos, + pos + ); + return pos; + } + pos++; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + } + + /** + * @param {string} name name + * @param {string} value value + * @param {number} start start of position + * @param {number} end end of position + */ + const createDep = (name, value, start, end) => { + if (type === 0) { + icssDefinitions.set(name, { + path: /** @type {string} */ (importPath), + value + }); + } else if (type === 1) { + const dep = new CssIcssExportDependency(name, value); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + }; + + let needTerminate = false; + let balanced = 0; + /** @type {undefined | 0 | 1 | 2} */ + let scope; + + /** @typedef {[number, number]} Name */ + + /** @type {Name | undefined} */ + let name; + /** @type {number | undefined} */ + let value; + + /** @type {CssTokenCallbacks} */ + const callbacks = { + leftCurlyBracket: (_input, _start, end) => { + balanced++; + + if (scope === undefined) { + scope = 0; + } + + return end; + }, + rightCurlyBracket: (_input, _start, end) => { + balanced--; + + if (scope === 2) { + const [nameStart, nameEnd] = /** @type {Name} */ (name); + createDep( + input.slice(nameStart, nameEnd), + input.slice(value, end - 1).trim(), + nameEnd, + end - 1 + ); + scope = 0; + } + + if (balanced === 0 && scope === 0) { + needTerminate = true; + } + + return end; + }, + identifier: (_input, start, end) => { + if (scope === 0) { + name = [start, end]; + scope = 1; + } + + return end; + }, + colon: (_input, _start, end) => { + if (scope === 1) { + scope = 2; + value = walkCssTokens.eatWhitespace(input, end); + return value; + } + + return end; + }, + semicolon: (input, _start, end) => { + if (scope === 2) { + const [nameStart, nameEnd] = /** @type {Name} */ (name); + createDep( + input.slice(nameStart, nameEnd), + input.slice(value, end - 1), + nameEnd, + end - 1 + ); + scope = 0; + } + + return end; + }, + needTerminate: () => needTerminate + }; + + pos = walkCssTokens(input, pos, callbacks); + pos = walkCssTokens.eatWhiteLine(input, pos); + + return pos; + }; + const eatPropertyName = walkCssTokens.eatUntil(":{};"); + /** + * @param {string} input input + * @param {number} pos name start position + * @param {number} end name end position + * @returns {number} position after handling + */ + const processLocalDeclaration = (input, pos, end) => { + modeData = undefined; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + const propertyNameStart = pos; + const [propertyNameEnd, propertyName] = eatText( + input, + pos, + eatPropertyName + ); + if (input.charCodeAt(propertyNameEnd) !== CC_COLON) return end; + pos = propertyNameEnd + 1; + if (propertyName.startsWith("--") && propertyName.length >= 3) { + // CSS Variable + const { line: sl, column: sc } = locConverter.get(propertyNameStart); + const { line: el, column: ec } = locConverter.get(propertyNameEnd); + const name = unescapeIdentifier(propertyName.slice(2)); + const dep = new CssLocalIdentifierDependency( + name, + [propertyNameStart, propertyNameEnd], + "--" + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + declaredCssVariables.add(name); + } else if ( + OPTIONALLY_VENDOR_PREFIXED_ANIMATION_PROPERTY.test(propertyName) + ) { + inAnimationProperty = true; + } + return pos; + }; + /** + * @param {string} input input + */ + const processDeclarationValueDone = (input) => { + if (inAnimationProperty && lastIdentifier) { + const { line: sl, column: sc } = locConverter.get(lastIdentifier[0]); + const { line: el, column: ec } = locConverter.get(lastIdentifier[1]); + const name = unescapeIdentifier( + lastIdentifier[2] + ? input.slice(lastIdentifier[0], lastIdentifier[1]) + : input.slice(lastIdentifier[0] + 1, lastIdentifier[1] - 1) + ); + const dep = new CssSelfLocalIdentifierDependency(name, [ + lastIdentifier[0], + lastIdentifier[1] + ]); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + lastIdentifier = undefined; + } + }; + + /** + * @param {string} input input + * @param {number} start start + * @param {number} end end + * @returns {number} end + */ + const comment = (input, start, end) => { + if (!this.comments) this.comments = []; + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + + /** @type {Comment} */ + const comment = { + value: input.slice(start + 2, end - 2), + range: [start, end], + loc: { + start: { line: sl, column: sc }, + end: { line: el, column: ec } + } + }; + this.comments.push(comment); + return end; + }; + + walkCssTokens(source, 0, { + comment, + leftCurlyBracket: (input, start, end) => { + switch (scope) { + case CSS_MODE_TOP_LEVEL: { + allowImportAtRule = false; + scope = CSS_MODE_IN_BLOCK; + + if (isModules) { + blockNestingLevel = 1; + isNextRulePrelude = isNextNestedSyntax(input, end); + } + + break; + } + case CSS_MODE_IN_BLOCK: { + if (isModules) { + blockNestingLevel++; + isNextRulePrelude = isNextNestedSyntax(input, end); + } + break; + } + } + return end; + }, + rightCurlyBracket: (input, start, end) => { + switch (scope) { + case CSS_MODE_IN_BLOCK: { + if (--blockNestingLevel === 0) { + scope = CSS_MODE_TOP_LEVEL; + + if (isModules) { + isNextRulePrelude = true; + modeData = undefined; + } + } else if (isModules) { + if (isLocalMode()) { + processDeclarationValueDone(input); + inAnimationProperty = false; + } + + isNextRulePrelude = isNextNestedSyntax(input, end); + } + break; + } + } + return end; + }, + url: (input, start, end, contentStart, contentEnd) => { + if (!this.url) { + return end; + } + + const { options, errors: commentErrors } = this.parseCommentOptions([ + lastTokenEndForComments, + end + ]); + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); + } + } + if (options && options.webpackIgnore !== undefined) { + if (typeof options.webpackIgnore !== "boolean") { + const { line: sl, column: sc } = locConverter.get( + lastTokenEndForComments + ); + const { line: el, column: ec } = locConverter.get(end); + + state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`, + { + start: { line: sl, column: sc }, + end: { line: el, column: ec } + } + ) + ); + } else if (options.webpackIgnore) { + return end; + } + } + const value = normalizeUrl( + input.slice(contentStart, contentEnd), + false + ); + // Ignore `url()`, `url('')` and `url("")`, they are valid by spec + if (value.length === 0) return end; + const dep = new CssUrlDependency(value, [start, end], "url"); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + module.addCodeGenerationDependency(dep); + return end; + }, + string: (_input, start, end) => { + switch (scope) { + case CSS_MODE_IN_BLOCK: { + if (inAnimationProperty && balanced.length === 0) { + lastIdentifier = [start, end, false]; + } + } + } + return end; + }, + atKeyword: (input, start, end) => { + const name = input.slice(start, end).toLowerCase(); + + switch (name) { + case "@namespace": { + this._emitWarning( + state, + "'@namespace' is not supported in bundled CSS", + locConverter, + start, + end + ); + + return eatUntilSemi(input, start); + } + case "@import": { + if (!this.import) { + return eatSemi(input, end); + } + + if (!allowImportAtRule) { + this._emitWarning( + state, + "Any '@import' rules must precede all other rules", + locConverter, + start, + end + ); + return end; + } + + const tokens = walkCssTokens.eatImportTokens(input, end, { + comment + }); + if (!tokens[3]) return end; + const semi = tokens[3][1]; + if (!tokens[0]) { + this._emitWarning( + state, + `Expected URL in '${input.slice(start, semi)}'`, + locConverter, + start, + semi + ); + return end; + } + + const urlToken = tokens[0]; + const url = normalizeUrl( + input.slice(urlToken[2], urlToken[3]), + true + ); + const newline = walkCssTokens.eatWhiteLine(input, semi); + const { options, errors: commentErrors } = this.parseCommentOptions( + [end, urlToken[1]] + ); + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); + } + } + if (options && options.webpackIgnore !== undefined) { + if (typeof options.webpackIgnore !== "boolean") { + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(newline); + + state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`, + { + start: { line: sl, column: sc }, + end: { line: el, column: ec } + } + ) + ); + } else if (options.webpackIgnore) { + return newline; + } + } + if (url.length === 0) { + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(newline); + const dep = new ConstDependency("", [start, newline]); + module.addPresentationalDependency(dep); + dep.setLoc(sl, sc, el, ec); + + return newline; + } + + let layer; + + if (tokens[1]) { + layer = input.slice(tokens[1][0] + 6, tokens[1][1] - 1).trim(); + } + + let supports; + + if (tokens[2]) { + supports = input.slice(tokens[2][0] + 9, tokens[2][1] - 1).trim(); + } + + const last = tokens[2] || tokens[1] || tokens[0]; + const mediaStart = walkCssTokens.eatWhitespaceAndComments( + input, + last[1] + ); + + let media; + + if (mediaStart !== semi - 1) { + media = input.slice(mediaStart, semi - 1).trim(); + } + + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(newline); + const dep = new CssImportDependency( + url, + [start, newline], + layer, + supports && supports.length > 0 ? supports : undefined, + media && media.length > 0 ? media : undefined + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + + return newline; + } + default: { + if (isModules) { + if (name === "@value") { + const semi = eatUntilSemi(input, end); + const atRuleEnd = semi + 1; + const params = input.slice(end, semi); + let [alias, from] = params.split(/\s*from\s*/); + + if (from) { + const aliases = alias + .replace(CSS_COMMENT, " ") + .trim() + .replace(/^\(|\)$/g, "") + .split(/\s*,\s*/); + + from = from.replace(CSS_COMMENT, "").trim(); + + const isExplicitImport = from[0] === "'" || from[0] === '"'; + + if (isExplicitImport) { + from = from.slice(1, -1); + } + + for (const alias of aliases) { + const [name, aliasName] = alias.split(/\s*as\s*/); + + icssDefinitions.set(aliasName || name, { + value: name, + path: from + }); + } + } else { + const ident = walkCssTokens.eatIdentSequence(alias, 0); + + if (!ident) { + this._emitWarning( + state, + `Broken '@value' at-rule: ${input.slice( + start, + atRuleEnd + )}'`, + locConverter, + start, + atRuleEnd + ); + + const dep = new ConstDependency("", [start, atRuleEnd]); + module.addPresentationalDependency(dep); + return atRuleEnd; + } + + const pos = walkCssTokens.eatWhitespaceAndComments( + alias, + ident[1] + ); + + const name = alias.slice(ident[0], ident[1]); + let value = + alias.charCodeAt(pos) === CC_COLON + ? alias.slice(pos + 1) + : alias.slice(ident[1]); + + if (value && !/^\s+$/.test(value)) { + value = value.trim(); + } + + if (icssDefinitions.has(value)) { + const def = + /** @type {IcssDefinition} */ + (icssDefinitions.get(value)); + + value = def.value; + } + + icssDefinitions.set(name, { value }); + + const dep = new CssIcssExportDependency(name, value); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + + const dep = new ConstDependency("", [start, atRuleEnd]); + module.addPresentationalDependency(dep); + return atRuleEnd; + } else if ( + OPTIONALLY_VENDOR_PREFIXED_KEYFRAMES_AT_RULE.test(name) && + isLocalMode() + ) { + const ident = walkCssTokens.eatIdentSequenceOrString( + input, + end + ); + if (!ident) return end; + const name = unescapeIdentifier( + ident[2] === true + ? input.slice(ident[0], ident[1]) + : input.slice(ident[0] + 1, ident[1] - 1) + ); + const { line: sl, column: sc } = locConverter.get(ident[0]); + const { line: el, column: ec } = locConverter.get(ident[1]); + const dep = new CssLocalIdentifierDependency(name, [ + ident[0], + ident[1] + ]); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + return ident[1]; + } else if (name === "@property" && isLocalMode()) { + const ident = walkCssTokens.eatIdentSequence(input, end); + if (!ident) return end; + let name = input.slice(ident[0], ident[1]); + if (!name.startsWith("--") || name.length < 3) return end; + name = unescapeIdentifier(name.slice(2)); + declaredCssVariables.add(name); + const { line: sl, column: sc } = locConverter.get(ident[0]); + const { line: el, column: ec } = locConverter.get(ident[1]); + const dep = new CssLocalIdentifierDependency( + name, + [ident[0], ident[1]], + "--" + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + return ident[1]; + } else if (name === "@scope") { + isNextRulePrelude = true; + return end; + } + + isNextRulePrelude = false; + } + } + } + + return end; + }, + semicolon: (input, start, end) => { + if (isModules && scope === CSS_MODE_IN_BLOCK) { + if (isLocalMode()) { + processDeclarationValueDone(input); + inAnimationProperty = false; + } + + isNextRulePrelude = isNextNestedSyntax(input, end); + } + return end; + }, + identifier: (input, start, end) => { + if (isModules) { + const name = input.slice(start, end); + + if (icssDefinitions.has(name)) { + let { path, value } = + /** @type {IcssDefinition} */ + (icssDefinitions.get(name)); + + if (path) { + if (icssDefinitions.has(path)) { + const definition = + /** @type {IcssDefinition} */ + (icssDefinitions.get(path)); + + path = definition.value.slice(1, -1); + } + + const dep = new CssIcssImportDependency(path, value, [ + start, + end - 1 + ]); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end - 1); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } else { + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + const dep = new CssIcssSymbolDependency(name, value, [ + start, + end + ]); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + + return end; + } + + switch (scope) { + case CSS_MODE_IN_BLOCK: { + if (isLocalMode()) { + // Handle only top level values and not inside functions + if (inAnimationProperty && balanced.length === 0) { + lastIdentifier = [start, end, true]; + } else { + return processLocalDeclaration(input, start, end); + } + } + break; + } + } + } + + return end; + }, + delim: (input, start, end) => { + if (isNextRulePrelude && isLocalMode()) { + const ident = walkCssTokens.skipCommentsAndEatIdentSequence( + input, + end + ); + if (!ident) return end; + const name = unescapeIdentifier(input.slice(ident[0], ident[1])); + const dep = new CssLocalIdentifierDependency(name, [ + ident[0], + ident[1] + ]); + const { line: sl, column: sc } = locConverter.get(ident[0]); + const { line: el, column: ec } = locConverter.get(ident[1]); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + return ident[1]; + } + + return end; + }, + hash: (input, start, end, isID) => { + if (isNextRulePrelude && isLocalMode() && isID) { + const valueStart = start + 1; + const name = unescapeIdentifier(input.slice(valueStart, end)); + const dep = new CssLocalIdentifierDependency(name, [valueStart, end]); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + + return end; + }, + colon: (input, start, end) => { + if (isModules) { + const ident = walkCssTokens.skipCommentsAndEatIdentSequence( + input, + end + ); + if (!ident) return end; + const name = input.slice(ident[0], ident[1]).toLowerCase(); + + switch (scope) { + case CSS_MODE_TOP_LEVEL: { + if (name === "import") { + const pos = parseImportOrExport(0, input, ident[1]); + const dep = new ConstDependency("", [start, pos]); + module.addPresentationalDependency(dep); + return pos; + } else if (name === "export") { + const pos = parseImportOrExport(1, input, ident[1]); + const dep = new ConstDependency("", [start, pos]); + module.addPresentationalDependency(dep); + return pos; + } + } + // falls through + default: { + if (isNextRulePrelude) { + const isFn = input.charCodeAt(ident[1]) === CC_LEFT_PARENTHESIS; + + if (isFn && name === "local") { + const end = ident[1] + 1; + modeData = "local"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + balanced.push([":local", start, end]); + return end; + } else if (name === "local") { + modeData = "local"; + // Eat extra whitespace + end = walkCssTokens.eatWhitespace(input, ident[1]); + + if (ident[1] === end) { + this._emitWarning( + state, + `Missing whitespace after ':local' in '${input.slice( + start, + eatUntilLeftCurly(input, end) + 1 + )}'`, + locConverter, + start, + end + ); + } + + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + return end; + } else if (isFn && name === "global") { + const end = ident[1] + 1; + modeData = "global"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + balanced.push([":global", start, end]); + return end; + } else if (name === "global") { + modeData = "global"; + // Eat extra whitespace + end = walkCssTokens.eatWhitespace(input, ident[1]); + + if (ident[1] === end) { + this._emitWarning( + state, + `Missing whitespace after ':global' in '${input.slice( + start, + eatUntilLeftCurly(input, end) + 1 + )}'`, + locConverter, + start, + end + ); + } + + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + return end; + } + } + } + } + } + + lastTokenEndForComments = end; + + return end; + }, + function: (input, start, end) => { + const name = input + .slice(start, end - 1) + .replace(/\\/g, "") + .toLowerCase(); + + balanced.push([name, start, end]); + + switch (name) { + case "src": + case "url": { + if (!this.url) { + return end; + } + + const string = walkCssTokens.eatString(input, end); + if (!string) return end; + const { options, errors: commentErrors } = this.parseCommentOptions( + [lastTokenEndForComments, end] + ); + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); + } + } + if (options && options.webpackIgnore !== undefined) { + if (typeof options.webpackIgnore !== "boolean") { + const { line: sl, column: sc } = locConverter.get(string[0]); + const { line: el, column: ec } = locConverter.get(string[1]); + + state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`, + { + start: { line: sl, column: sc }, + end: { line: el, column: ec } + } + ) + ); + } else if (options.webpackIgnore) { + return end; + } + } + const value = normalizeUrl( + input.slice(string[0] + 1, string[1] - 1), + true + ); + // Ignore `url()`, `url('')` and `url("")`, they are valid by spec + if (value.length === 0) return end; + const isUrl = name === "url" || name === "src"; + const dep = new CssUrlDependency( + value, + [string[0], string[1]], + isUrl ? "string" : "url" + ); + const { line: sl, column: sc } = locConverter.get(string[0]); + const { line: el, column: ec } = locConverter.get(string[1]); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + module.addCodeGenerationDependency(dep); + return string[1]; + } + default: { + if (this.url && IMAGE_SET_FUNCTION.test(name)) { + lastTokenEndForComments = end; + const values = walkCssTokens.eatImageSetStrings(input, end, { + comment + }); + if (values.length === 0) return end; + for (const [index, string] of values.entries()) { + const value = normalizeUrl( + input.slice(string[0] + 1, string[1] - 1), + true + ); + if (value.length === 0) return end; + const { options, errors: commentErrors } = + this.parseCommentOptions([ + index === 0 ? start : values[index - 1][1], + string[1] + ]); + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); + } + } + if (options && options.webpackIgnore !== undefined) { + if (typeof options.webpackIgnore !== "boolean") { + const { line: sl, column: sc } = locConverter.get( + string[0] + ); + const { line: el, column: ec } = locConverter.get( + string[1] + ); + + state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`, + { + start: { line: sl, column: sc }, + end: { line: el, column: ec } + } + ) + ); + } else if (options.webpackIgnore) { + continue; + } + } + const dep = new CssUrlDependency( + value, + [string[0], string[1]], + "url" + ); + const { line: sl, column: sc } = locConverter.get(string[0]); + const { line: el, column: ec } = locConverter.get(string[1]); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + module.addCodeGenerationDependency(dep); + } + // Can contain `url()` inside, so let's return end to allow parse them + return end; + } else if (isLocalMode()) { + // Don't rename animation name when we have `var()` function + if (inAnimationProperty && balanced.length === 1) { + lastIdentifier = undefined; + } + + if (name === "var") { + const customIdent = walkCssTokens.eatIdentSequence(input, end); + if (!customIdent) return end; + let name = input.slice(customIdent[0], customIdent[1]); + // A custom property is any property whose name starts with two dashes (U+002D HYPHEN-MINUS), like --foo. + // The production corresponds to this: + // it’s defined as any (a valid identifier that starts with two dashes), + // except -- itself, which is reserved for future use by CSS. + if (!name.startsWith("--") || name.length < 3) return end; + name = unescapeIdentifier( + input.slice(customIdent[0] + 2, customIdent[1]) + ); + const afterCustomIdent = walkCssTokens.eatWhitespaceAndComments( + input, + customIdent[1] + ); + if ( + input.charCodeAt(afterCustomIdent) === CC_LOWER_F || + input.charCodeAt(afterCustomIdent) === CC_UPPER_F + ) { + const fromWord = walkCssTokens.eatIdentSequence( + input, + afterCustomIdent + ); + if ( + !fromWord || + input.slice(fromWord[0], fromWord[1]).toLowerCase() !== + "from" + ) { + return end; + } + const from = walkCssTokens.eatIdentSequenceOrString( + input, + walkCssTokens.eatWhitespaceAndComments(input, fromWord[1]) + ); + if (!from) { + return end; + } + const path = input.slice(from[0], from[1]); + if (from[2] === true && path === "global") { + const dep = new ConstDependency("", [ + customIdent[1], + from[1] + ]); + module.addPresentationalDependency(dep); + return end; + } else if (from[2] === false) { + const dep = new CssIcssImportDependency( + path.slice(1, -1), + name, + [customIdent[0], from[1] - 1] + ); + const { line: sl, column: sc } = locConverter.get( + customIdent[0] + ); + const { line: el, column: ec } = locConverter.get( + from[1] - 1 + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + } else { + const { line: sl, column: sc } = locConverter.get( + customIdent[0] + ); + const { line: el, column: ec } = locConverter.get( + customIdent[1] + ); + const dep = new CssSelfLocalIdentifierDependency( + name, + [customIdent[0], customIdent[1]], + "--", + declaredCssVariables + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + return end; + } + } + } + } + } + + return end; + }, + leftParenthesis: (input, start, end) => { + balanced.push(["(", start, end]); + + return end; + }, + rightParenthesis: (input, start, end) => { + const popped = balanced.pop(); + + if ( + isModules && + popped && + (popped[0] === ":local" || popped[0] === ":global") + ) { + modeData = balanced[balanced.length - 1] + ? /** @type {"local" | "global"} */ + (balanced[balanced.length - 1][0]) + : undefined; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } + + return end; + }, + comma: (input, start, end) => { + if (isModules) { + // Reset stack for `:global .class :local .class-other` selector after + modeData = undefined; + + if (scope === CSS_MODE_IN_BLOCK && isLocalMode()) { + processDeclarationValueDone(input); + } + } + + lastTokenEndForComments = start; + + return end; + } + }); + + /** @type {BuildInfo} */ + (module.buildInfo).strict = true; + /** @type {BuildMeta} */ + (module.buildMeta).exportsType = this.namedExports + ? "namespace" + : "default"; + + if (!this.namedExports) { + /** @type {BuildMeta} */ + (module.buildMeta).defaultObject = "redirect"; + } + + module.addDependency(new StaticExportsDependency([], true)); + return state; + } + + /** + * @param {Range} range range + * @returns {Comment[]} comments in the range + */ + getComments(range) { + if (!this.comments) return []; + const [rangeStart, rangeEnd] = range; + /** + * @param {Comment} comment comment + * @param {number} needle needle + * @returns {number} compared + */ + const compare = (comment, needle) => + /** @type {Range} */ (comment.range)[0] - needle; + const comments = /** @type {Comment[]} */ (this.comments); + let idx = binarySearchBounds.ge(comments, rangeStart, compare); + /** @type {Comment[]} */ + const commentsInRange = []; + while ( + comments[idx] && + /** @type {Range} */ (comments[idx].range)[1] <= rangeEnd + ) { + commentsInRange.push(comments[idx]); + idx++; + } + + return commentsInRange; + } + + /** + * @param {Range} range range of the comment + * @returns {{ options: Record | null, errors: (Error & { comment: Comment })[] | null }} result + */ + parseCommentOptions(range) { + const comments = this.getComments(range); + if (comments.length === 0) { + return EMPTY_COMMENT_OPTIONS; + } + /** @type {Record } */ + const options = {}; + /** @type {(Error & { comment: Comment })[]} */ + const errors = []; + for (const comment of comments) { + const { value } = comment; + if (value && webpackCommentRegExp.test(value)) { + // try compile only if webpack options comment is present + try { + for (let [key, val] of Object.entries( + vm.runInContext( + `(function(){return {${value}};})()`, + this.magicCommentContext + ) + )) { + if (typeof val === "object" && val !== null) { + val = + val.constructor.name === "RegExp" + ? new RegExp(val) + : JSON.parse(JSON.stringify(val)); + } + options[key] = val; + } + } catch (err) { + const newErr = new Error(String(/** @type {Error} */ (err).message)); + newErr.stack = String(/** @type {Error} */ (err).stack); + Object.assign(newErr, { comment }); + errors.push(/** @type (Error & { comment: Comment }) */ (newErr)); + } + } + } + return { options, errors }; + } +} + +module.exports = CssParser; +module.exports.escapeIdentifier = escapeIdentifier; +module.exports.unescapeIdentifier = unescapeIdentifier; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/walkCssTokens.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/walkCssTokens.js new file mode 100644 index 0000000000000000000000000000000000000000..bfdc05b10e2c03e15a3f87afc1da9e4dfe3f5a9e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/css/walkCssTokens.js @@ -0,0 +1,1623 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @typedef {object} CssTokenCallbacks + * @property {((input: string, start: number, end: number, innerStart: number, innerEnd: number) => number)=} url + * @property {((input: string, start: number, end: number) => number)=} comment + * @property {((input: string, start: number, end: number) => number)=} string + * @property {((input: string, start: number, end: number) => number)=} leftParenthesis + * @property {((input: string, start: number, end: number) => number)=} rightParenthesis + * @property {((input: string, start: number, end: number) => number)=} function + * @property {((input: string, start: number, end: number) => number)=} colon + * @property {((input: string, start: number, end: number) => number)=} atKeyword + * @property {((input: string, start: number, end: number) => number)=} delim + * @property {((input: string, start: number, end: number) => number)=} identifier + * @property {((input: string, start: number, end: number, isId: boolean) => number)=} hash + * @property {((input: string, start: number, end: number) => number)=} leftCurlyBracket + * @property {((input: string, start: number, end: number) => number)=} rightCurlyBracket + * @property {((input: string, start: number, end: number) => number)=} semicolon + * @property {((input: string, start: number, end: number) => number)=} comma + * @property {(() => boolean)=} needTerminate + */ + +/** @typedef {(input: string, pos: number, callbacks: CssTokenCallbacks) => number} CharHandler */ + +// spec: https://drafts.csswg.org/css-syntax/ + +const CC_LINE_FEED = "\n".charCodeAt(0); +const CC_CARRIAGE_RETURN = "\r".charCodeAt(0); +const CC_FORM_FEED = "\f".charCodeAt(0); + +const CC_TAB = "\t".charCodeAt(0); +const CC_SPACE = " ".charCodeAt(0); + +const CC_SOLIDUS = "/".charCodeAt(0); +const CC_REVERSE_SOLIDUS = "\\".charCodeAt(0); +const CC_ASTERISK = "*".charCodeAt(0); + +const CC_LEFT_PARENTHESIS = "(".charCodeAt(0); +const CC_RIGHT_PARENTHESIS = ")".charCodeAt(0); +const CC_LEFT_CURLY = "{".charCodeAt(0); +const CC_RIGHT_CURLY = "}".charCodeAt(0); +const CC_LEFT_SQUARE = "[".charCodeAt(0); +const CC_RIGHT_SQUARE = "]".charCodeAt(0); + +const CC_QUOTATION_MARK = '"'.charCodeAt(0); +const CC_APOSTROPHE = "'".charCodeAt(0); + +const CC_FULL_STOP = ".".charCodeAt(0); +const CC_COLON = ":".charCodeAt(0); +const CC_SEMICOLON = ";".charCodeAt(0); +const CC_COMMA = ",".charCodeAt(0); +const CC_PERCENTAGE = "%".charCodeAt(0); +const CC_AT_SIGN = "@".charCodeAt(0); + +const CC_LOW_LINE = "_".charCodeAt(0); +const CC_LOWER_A = "a".charCodeAt(0); +const CC_LOWER_F = "f".charCodeAt(0); +const CC_LOWER_E = "e".charCodeAt(0); +const CC_LOWER_U = "u".charCodeAt(0); +const CC_LOWER_Z = "z".charCodeAt(0); +const CC_UPPER_A = "A".charCodeAt(0); +const CC_UPPER_F = "F".charCodeAt(0); +const CC_UPPER_E = "E".charCodeAt(0); +const CC_UPPER_U = "E".charCodeAt(0); +const CC_UPPER_Z = "Z".charCodeAt(0); +const CC_0 = "0".charCodeAt(0); +const CC_9 = "9".charCodeAt(0); + +const CC_NUMBER_SIGN = "#".charCodeAt(0); +const CC_PLUS_SIGN = "+".charCodeAt(0); +const CC_HYPHEN_MINUS = "-".charCodeAt(0); + +const CC_LESS_THAN_SIGN = "<".charCodeAt(0); +const CC_GREATER_THAN_SIGN = ">".charCodeAt(0); + +/** @type {CharHandler} */ +const consumeSpace = (input, pos, _callbacks) => { + // Consume as much whitespace as possible. + while (_isWhiteSpace(input.charCodeAt(pos))) { + pos++; + } + + // Return a . + return pos; +}; + +// U+000A LINE FEED. Note that U+000D CARRIAGE RETURN and U+000C FORM FEED are not included in this definition, +// as they are converted to U+000A LINE FEED during preprocessing. +// +// Replace any U+000D CARRIAGE RETURN (CR) code points, U+000C FORM FEED (FF) code points, or pairs of U+000D CARRIAGE RETURN (CR) followed by U+000A LINE FEED (LF) in input by a single U+000A LINE FEED (LF) code point. + +/** + * @param {number} cc char code + * @returns {boolean} true, if cc is a newline + */ +const _isNewline = (cc) => + cc === CC_LINE_FEED || cc === CC_CARRIAGE_RETURN || cc === CC_FORM_FEED; + +/** + * @param {number} cc char code + * @param {string} input input + * @param {number} pos position + * @returns {number} position + */ +const consumeExtraNewline = (cc, input, pos) => { + if (cc === CC_CARRIAGE_RETURN && input.charCodeAt(pos) === CC_LINE_FEED) { + pos++; + } + + return pos; +}; + +/** + * @param {number} cc char code + * @returns {boolean} true, if cc is a space (U+0009 CHARACTER TABULATION or U+0020 SPACE) + */ +const _isSpace = (cc) => cc === CC_TAB || cc === CC_SPACE; + +/** + * @param {number} cc char code + * @returns {boolean} true, if cc is a whitespace + */ +const _isWhiteSpace = (cc) => _isNewline(cc) || _isSpace(cc); + +/** + * ident-start code point + * + * A letter, a non-ASCII code point, or U+005F LOW LINE (_). + * @param {number} cc char code + * @returns {boolean} true, if cc is a start code point of an identifier + */ +const isIdentStartCodePoint = (cc) => + (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || + (cc >= CC_UPPER_A && cc <= CC_UPPER_Z) || + cc === CC_LOW_LINE || + cc >= 0x80; + +/** @type {CharHandler} */ +const consumeDelimToken = (input, pos, _callbacks) => + // Return a with its value set to the current input code point. + pos; + +/** @type {CharHandler} */ +const consumeComments = (input, pos, callbacks) => { + // This section describes how to consume comments from a stream of code points. It returns nothing. + // If the next two input code point are U+002F SOLIDUS (/) followed by a U+002A ASTERISK (*), + // consume them and all following code points up to and including the first U+002A ASTERISK (*) + // followed by a U+002F SOLIDUS (/), or up to an EOF code point. + // Return to the start of this step. + while ( + input.charCodeAt(pos) === CC_SOLIDUS && + input.charCodeAt(pos + 1) === CC_ASTERISK + ) { + const start = pos; + pos += 2; + + for (;;) { + if (pos === input.length) { + // If the preceding paragraph ended by consuming an EOF code point, this is a parse error. + return pos; + } + + if ( + input.charCodeAt(pos) === CC_ASTERISK && + input.charCodeAt(pos + 1) === CC_SOLIDUS + ) { + pos += 2; + + if (callbacks.comment) { + pos = callbacks.comment(input, start, pos); + } + + break; + } + + pos++; + } + } + + return pos; +}; + +/** + * @param {number} cc char code + * @returns {boolean} true, if cc is a hex digit + */ +const _isHexDigit = (cc) => + _isDigit(cc) || + (cc >= CC_UPPER_A && cc <= CC_UPPER_F) || + (cc >= CC_LOWER_A && cc <= CC_LOWER_F); + +/** + * @param {string} input input + * @param {number} pos position + * @returns {number} position + */ +const _consumeAnEscapedCodePoint = (input, pos) => { + // This section describes how to consume an escaped code point. + // It assumes that the U+005C REVERSE SOLIDUS (\) has already been consumed and that the next input code point has already been verified to be part of a valid escape. + // It will return a code point. + + // Consume the next input code point. + const cc = input.charCodeAt(pos); + pos++; + + // EOF + // This is a parse error. Return U+FFFD REPLACEMENT CHARACTER (�). + if (pos === input.length) { + return pos; + } + + // hex digit + // Consume as many hex digits as possible, but no more than 5. + // Note that this means 1-6 hex digits have been consumed in total. + // If the next input code point is whitespace, consume it as well. + // Interpret the hex digits as a hexadecimal number. + // If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point, return U+FFFD REPLACEMENT CHARACTER (�). + // Otherwise, return the code point with that value. + if (_isHexDigit(cc)) { + for (let i = 0; i < 5; i++) { + if (_isHexDigit(input.charCodeAt(pos))) { + pos++; + } + } + + const cc = input.charCodeAt(pos); + + if (_isWhiteSpace(cc)) { + pos++; + pos = consumeExtraNewline(cc, input, pos); + } + + return pos; + } + + // anything else + // Return the current input code point. + return pos; +}; + +/** @type {CharHandler} */ +const consumeAStringToken = (input, pos, callbacks) => { + // This section describes how to consume a string token from a stream of code points. + // It returns either a or . + // + // This algorithm may be called with an ending code point, which denotes the code point that ends the string. + // If an ending code point is not specified, the current input code point is used. + const start = pos - 1; + const endingCodePoint = input.charCodeAt(pos - 1); + + // Initially create a with its value set to the empty string. + + // Repeatedly consume the next input code point from the stream: + for (;;) { + // EOF + // This is a parse error. Return the . + if (pos === input.length) { + if (callbacks.string !== undefined) { + return callbacks.string(input, start, pos); + } + + return pos; + } + + const cc = input.charCodeAt(pos); + pos++; + + // ending code point + // Return the . + if (cc === endingCodePoint) { + if (callbacks.string !== undefined) { + return callbacks.string(input, start, pos); + } + + return pos; + } + // newline + // This is a parse error. + // Reconsume the current input code point, create a , and return it. + else if (_isNewline(cc)) { + pos--; + // bad string + return pos; + } + // U+005C REVERSE SOLIDUS (\) + else if (cc === CC_REVERSE_SOLIDUS) { + // If the next input code point is EOF, do nothing. + if (pos === input.length) { + return pos; + } + // Otherwise, if the next input code point is a newline, consume it. + else if (_isNewline(input.charCodeAt(pos))) { + const cc = input.charCodeAt(pos); + pos++; + pos = consumeExtraNewline(cc, input, pos); + } + // Otherwise, (the stream starts with a valid escape) consume an escaped code point and append the returned code point to the ’s value. + else if (_ifTwoCodePointsAreValidEscape(input, pos)) { + pos = _consumeAnEscapedCodePoint(input, pos); + } + } + // anything else + // Append the current input code point to the ’s value. + else { + // Append + } + } +}; + +/** + * @param {number} cc char code + * @param {number} q char code + * @returns {boolean} is non-ASCII code point + */ +const isNonASCIICodePoint = (cc, q) => + // Simplify + cc > 0x80; + +/** + * @param {number} cc char code + * @returns {boolean} is letter + */ +const isLetter = (cc) => + (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || + (cc >= CC_UPPER_A && cc <= CC_UPPER_Z); + +/** + * @param {number} cc char code + * @param {number} q char code + * @returns {boolean} is identifier start code + */ +const _isIdentStartCodePoint = (cc, q) => + isLetter(cc) || isNonASCIICodePoint(cc, q) || cc === CC_LOW_LINE; + +/** + * @param {number} cc char code + * @param {number} q char code + * @returns {boolean} is identifier code + */ +const _isIdentCodePoint = (cc, q) => + _isIdentStartCodePoint(cc, q) || _isDigit(cc) || cc === CC_HYPHEN_MINUS; +/** + * @param {number} cc char code + * @returns {boolean} is digit + */ +const _isDigit = (cc) => cc >= CC_0 && cc <= CC_9; + +/** + * @param {string} input input + * @param {number} pos position + * @param {number=} f first code point + * @param {number=} s second code point + * @returns {boolean} true if two code points are a valid escape + */ +const _ifTwoCodePointsAreValidEscape = (input, pos, f, s) => { + // This section describes how to check if two code points are a valid escape. + // The algorithm described here can be called explicitly with two code points, or can be called with the input stream itself. + // In the latter case, the two code points in question are the current input code point and the next input code point, in that order. + + // Note: This algorithm will not consume any additional code point. + const first = f || input.charCodeAt(pos - 1); + const second = s || input.charCodeAt(pos); + + // If the first code point is not U+005C REVERSE SOLIDUS (\), return false. + if (first !== CC_REVERSE_SOLIDUS) return false; + // Otherwise, if the second code point is a newline, return false. + if (_isNewline(second)) return false; + // Otherwise, return true. + return true; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @param {number=} f first + * @param {number=} s second + * @param {number=} t third + * @returns {boolean} true, if input at pos starts an identifier + */ +const _ifThreeCodePointsWouldStartAnIdentSequence = (input, pos, f, s, t) => { + // This section describes how to check if three code points would start an ident sequence. + // The algorithm described here can be called explicitly with three code points, or can be called with the input stream itself. + // In the latter case, the three code points in question are the current input code point and the next two input code points, in that order. + + // Note: This algorithm will not consume any additional code points. + + const first = f || input.charCodeAt(pos - 1); + const second = s || input.charCodeAt(pos); + const third = t || input.charCodeAt(pos + 1); + + // Look at the first code point: + + // U+002D HYPHEN-MINUS + if (first === CC_HYPHEN_MINUS) { + // If the second code point is an ident-start code point or a U+002D HYPHEN-MINUS + // or a U+002D HYPHEN-MINUS, or the second and third code points are a valid escape, return true. + if ( + _isIdentStartCodePoint(second, pos) || + second === CC_HYPHEN_MINUS || + _ifTwoCodePointsAreValidEscape(input, pos, second, third) + ) { + return true; + } + return false; + } + // ident-start code point + else if (_isIdentStartCodePoint(first, pos - 1)) { + return true; + } + // U+005C REVERSE SOLIDUS (\) + // If the first and second code points are a valid escape, return true. Otherwise, return false. + else if (first === CC_REVERSE_SOLIDUS) { + if (_ifTwoCodePointsAreValidEscape(input, pos, first, second)) { + return true; + } + + return false; + } + // anything else + // Return false. + return false; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @param {number=} f first + * @param {number=} s second + * @param {number=} t third + * @returns {boolean} true, if input at pos starts an identifier + */ +const _ifThreeCodePointsWouldStartANumber = (input, pos, f, s, t) => { + // This section describes how to check if three code points would start a number. + // The algorithm described here can be called explicitly with three code points, or can be called with the input stream itself. + // In the latter case, the three code points in question are the current input code point and the next two input code points, in that order. + + // Note: This algorithm will not consume any additional code points. + + const first = f || input.charCodeAt(pos - 1); + const second = s || input.charCodeAt(pos); + const third = t || input.charCodeAt(pos); + + // Look at the first code point: + + // U+002B PLUS SIGN (+) + // U+002D HYPHEN-MINUS (-) + // + // If the second code point is a digit, return true. + // Otherwise, if the second code point is a U+002E FULL STOP (.) and the third code point is a digit, return true. + // Otherwise, return false. + if (first === CC_PLUS_SIGN || first === CC_HYPHEN_MINUS) { + if (_isDigit(second)) { + return true; + } else if (second === CC_FULL_STOP && _isDigit(third)) { + return true; + } + + return false; + } + // U+002E FULL STOP (.) + // If the second code point is a digit, return true. Otherwise, return false. + else if (first === CC_FULL_STOP) { + if (_isDigit(second)) { + return true; + } + + return false; + } + // digit + // Return true. + else if (_isDigit(first)) { + return true; + } + + // anything else + // Return false. + return false; +}; + +/** @type {CharHandler} */ +const consumeNumberSign = (input, pos, callbacks) => { + // If the next input code point is an ident code point or the next two input code points are a valid escape, then: + // - Create a . + // - If the next 3 input code points would start an ident sequence, set the ’s type flag to "id". + // - Consume an ident sequence, and set the ’s value to the returned string. + // - Return the . + const start = pos - 1; + const first = input.charCodeAt(pos); + const second = input.charCodeAt(pos + 1); + + if ( + _isIdentCodePoint(first, pos - 1) || + _ifTwoCodePointsAreValidEscape(input, pos, first, second) + ) { + const third = input.charCodeAt(pos + 2); + let isId = false; + + if ( + _ifThreeCodePointsWouldStartAnIdentSequence( + input, + pos, + first, + second, + third + ) + ) { + isId = true; + } + + pos = _consumeAnIdentSequence(input, pos, callbacks); + + if (callbacks.hash !== undefined) { + return callbacks.hash(input, start, pos, isId); + } + + return pos; + } + + // Otherwise, return a with its value set to the current input code point. + return pos; +}; + +/** @type {CharHandler} */ +const consumeHyphenMinus = (input, pos, callbacks) => { + // If the input stream starts with a number, reconsume the current input code point, consume a numeric token, and return it. + if (_ifThreeCodePointsWouldStartANumber(input, pos)) { + pos--; + return consumeANumericToken(input, pos, callbacks); + } + // Otherwise, if the next 2 input code points are U+002D HYPHEN-MINUS U+003E GREATER-THAN SIGN (->), consume them and return a . + else if ( + input.charCodeAt(pos) === CC_HYPHEN_MINUS && + input.charCodeAt(pos + 1) === CC_GREATER_THAN_SIGN + ) { + return pos + 2; + } + // Otherwise, if the input stream starts with an ident sequence, reconsume the current input code point, consume an ident-like token, and return it. + else if (_ifThreeCodePointsWouldStartAnIdentSequence(input, pos)) { + pos--; + return consumeAnIdentLikeToken(input, pos, callbacks); + } + + // Otherwise, return a with its value set to the current input code point. + return pos; +}; + +/** @type {CharHandler} */ +const consumeFullStop = (input, pos, callbacks) => { + const start = pos - 1; + + // If the input stream starts with a number, reconsume the current input code point, consume a numeric token, and return it. + if (_ifThreeCodePointsWouldStartANumber(input, pos)) { + pos--; + return consumeANumericToken(input, pos, callbacks); + } + + // Otherwise, return a with its value set to the current input code point. + if (callbacks.delim !== undefined) { + return callbacks.delim(input, start, pos); + } + + return pos; +}; + +/** @type {CharHandler} */ +const consumePlusSign = (input, pos, callbacks) => { + // If the input stream starts with a number, reconsume the current input code point, consume a numeric token, and return it. + if (_ifThreeCodePointsWouldStartANumber(input, pos)) { + pos--; + return consumeANumericToken(input, pos, callbacks); + } + + // Otherwise, return a with its value set to the current input code point. + return pos; +}; + +/** @type {CharHandler} */ +const _consumeANumber = (input, pos) => { + // This section describes how to consume a number from a stream of code points. + // It returns a numeric value, and a type which is either "integer" or "number". + + // Execute the following steps in order: + // Initially set type to "integer". Let repr be the empty string. + + // If the next input code point is U+002B PLUS SIGN (+) or U+002D HYPHEN-MINUS (-), consume it and append it to repr. + if ( + input.charCodeAt(pos) === CC_HYPHEN_MINUS || + input.charCodeAt(pos) === CC_PLUS_SIGN + ) { + pos++; + } + + // While the next input code point is a digit, consume it and append it to repr. + while (_isDigit(input.charCodeAt(pos))) { + pos++; + } + + // If the next 2 input code points are U+002E FULL STOP (.) followed by a digit, then: + // 1. Consume the next input code point and append it to number part. + // 2. While the next input code point is a digit, consume it and append it to number part. + // 3. Set type to "number". + if ( + input.charCodeAt(pos) === CC_FULL_STOP && + _isDigit(input.charCodeAt(pos + 1)) + ) { + pos++; + + while (_isDigit(input.charCodeAt(pos))) { + pos++; + } + } + + // If the next 2 or 3 input code points are U+0045 LATIN CAPITAL LETTER E (E) or U+0065 LATIN SMALL LETTER E (e), optionally followed by U+002D HYPHEN-MINUS (-) or U+002B PLUS SIGN (+), followed by a digit, then: + // 1. Consume the next input code point. + // 2. If the next input code point is "+" or "-", consume it and append it to exponent part. + // 3. While the next input code point is a digit, consume it and append it to exponent part. + // 4. Set type to "number". + if ( + (input.charCodeAt(pos) === CC_LOWER_E || + input.charCodeAt(pos) === CC_UPPER_E) && + (((input.charCodeAt(pos + 1) === CC_HYPHEN_MINUS || + input.charCodeAt(pos + 1) === CC_PLUS_SIGN) && + _isDigit(input.charCodeAt(pos + 2))) || + _isDigit(input.charCodeAt(pos + 1))) + ) { + pos++; + + if ( + input.charCodeAt(pos) === CC_PLUS_SIGN || + input.charCodeAt(pos) === CC_HYPHEN_MINUS + ) { + pos++; + } + + while (_isDigit(input.charCodeAt(pos))) { + pos++; + } + } + + // Let value be the result of interpreting number part as a base-10 number. + + // If exponent part is non-empty, interpret it as a base-10 integer, then raise 10 to the power of the result, multiply it by value, and set value to that result. + + // Return value and type. + return pos; +}; + +/** @type {CharHandler} */ +const consumeANumericToken = (input, pos, callbacks) => { + // This section describes how to consume a numeric token from a stream of code points. + // It returns either a , , or . + + // Consume a number and let number be the result. + pos = _consumeANumber(input, pos, callbacks); + + // If the next 3 input code points would start an ident sequence, then: + // + // - Create a with the same value and type flag as number, and a unit set initially to the empty string. + // - Consume an ident sequence. Set the ’s unit to the returned value. + // - Return the . + + const first = input.charCodeAt(pos); + const second = input.charCodeAt(pos + 1); + const third = input.charCodeAt(pos + 2); + + if ( + _ifThreeCodePointsWouldStartAnIdentSequence( + input, + pos, + first, + second, + third + ) + ) { + return _consumeAnIdentSequence(input, pos, callbacks); + } + // Otherwise, if the next input code point is U+0025 PERCENTAGE SIGN (%), consume it. + // Create a with the same value as number, and return it. + else if (first === CC_PERCENTAGE) { + return pos + 1; + } + + // Otherwise, create a with the same value and type flag as number, and return it. + return pos; +}; + +/** @type {CharHandler} */ +const consumeColon = (input, pos, callbacks) => { + // Return a . + if (callbacks.colon !== undefined) { + return callbacks.colon(input, pos - 1, pos); + } + return pos; +}; + +/** @type {CharHandler} */ +const consumeLeftParenthesis = (input, pos, callbacks) => { + // Return a <(-token>. + if (callbacks.leftParenthesis !== undefined) { + return callbacks.leftParenthesis(input, pos - 1, pos); + } + return pos; +}; + +/** @type {CharHandler} */ +const consumeRightParenthesis = (input, pos, callbacks) => { + // Return a <)-token>. + if (callbacks.rightParenthesis !== undefined) { + return callbacks.rightParenthesis(input, pos - 1, pos); + } + return pos; +}; + +/** @type {CharHandler} */ +const consumeLeftSquareBracket = (input, pos, _callbacks) => + // Return a <]-token>. + pos; + +/** @type {CharHandler} */ +const consumeRightSquareBracket = (input, pos, _callbacks) => + // Return a <]-token>. + pos; + +/** @type {CharHandler} */ +const consumeLeftCurlyBracket = (input, pos, callbacks) => { + // Return a <{-token>. + if (callbacks.leftCurlyBracket !== undefined) { + return callbacks.leftCurlyBracket(input, pos - 1, pos); + } + return pos; +}; + +/** @type {CharHandler} */ +const consumeRightCurlyBracket = (input, pos, callbacks) => { + // Return a <}-token>. + if (callbacks.rightCurlyBracket !== undefined) { + return callbacks.rightCurlyBracket(input, pos - 1, pos); + } + return pos; +}; + +/** @type {CharHandler} */ +const consumeSemicolon = (input, pos, callbacks) => { + // Return a . + if (callbacks.semicolon !== undefined) { + return callbacks.semicolon(input, pos - 1, pos); + } + return pos; +}; + +/** @type {CharHandler} */ +const consumeComma = (input, pos, callbacks) => { + // Return a . + if (callbacks.comma !== undefined) { + return callbacks.comma(input, pos - 1, pos); + } + return pos; +}; + +/** @type {CharHandler} */ +const _consumeAnIdentSequence = (input, pos) => { + // This section describes how to consume an ident sequence from a stream of code points. + // It returns a string containing the largest name that can be formed from adjacent code points in the stream, starting from the first. + + // Note: This algorithm does not do the verification of the first few code points that are necessary to ensure the returned code points would constitute an . + // If that is the intended use, ensure that the stream starts with an ident sequence before calling this algorithm. + + // Let result initially be an empty string. + + // Repeatedly consume the next input code point from the stream: + for (;;) { + const cc = input.charCodeAt(pos); + pos++; + + // ident code point + // Append the code point to result. + if (_isIdentCodePoint(cc, pos - 1)) { + // Nothing + } + // the stream starts with a valid escape + // Consume an escaped code point. Append the returned code point to result. + else if (_ifTwoCodePointsAreValidEscape(input, pos)) { + pos = _consumeAnEscapedCodePoint(input, pos); + } + // anything else + // Reconsume the current input code point. Return result. + else { + return pos - 1; + } + } +}; + +/** + * @param {number} cc char code + * @returns {boolean} true, when cc is the non-printable code point, otherwise false + */ +const _isNonPrintableCodePoint = (cc) => + (cc >= 0x00 && cc <= 0x08) || + cc === 0x0b || + (cc >= 0x0e && cc <= 0x1f) || + cc === 0x7f; + +/** + * @param {string} input input + * @param {number} pos position + * @returns {number} position + */ +const consumeTheRemnantsOfABadUrl = (input, pos) => { + // This section describes how to consume the remnants of a bad url from a stream of code points, + // "cleaning up" after the tokenizer realizes that it’s in the middle of a rather than a . + // It returns nothing; its sole use is to consume enough of the input stream to reach a recovery point where normal tokenizing can resume. + + // Repeatedly consume the next input code point from the stream: + for (;;) { + // EOF + // Return. + if (pos === input.length) { + return pos; + } + + const cc = input.charCodeAt(pos); + pos++; + + // U+0029 RIGHT PARENTHESIS ()) + // Return. + if (cc === CC_RIGHT_PARENTHESIS) { + return pos; + } + // the input stream starts with a valid escape + // Consume an escaped code point. + // This allows an escaped right parenthesis ("\)") to be encountered without ending the . + // This is otherwise identical to the "anything else" clause. + else if (_ifTwoCodePointsAreValidEscape(input, pos)) { + pos = _consumeAnEscapedCodePoint(input, pos); + } + // anything else + // Do nothing. + else { + // Do nothing. + } + } +}; + +/** + * @param {string} input input + * @param {number} pos position + * @param {number} fnStart start + * @param {CssTokenCallbacks} callbacks callbacks + * @returns {pos} pos + */ +const consumeAUrlToken = (input, pos, fnStart, callbacks) => { + // This section describes how to consume a url token from a stream of code points. + // It returns either a or a . + + // Note: This algorithm assumes that the initial "url(" has already been consumed. + // This algorithm also assumes that it’s being called to consume an "unquoted" value, like url(foo). + // A quoted value, like url("foo"), is parsed as a . + // Consume an ident-like token automatically handles this distinction; this algorithm shouldn’t be called directly otherwise. + + // Initially create a with its value set to the empty string. + + // Consume as much whitespace as possible. + while (_isWhiteSpace(input.charCodeAt(pos))) { + pos++; + } + + const contentStart = pos; + + // Repeatedly consume the next input code point from the stream: + for (;;) { + // EOF + // This is a parse error. Return the . + if (pos === input.length) { + if (callbacks.url !== undefined) { + return callbacks.url(input, fnStart, pos, contentStart, pos - 1); + } + + return pos; + } + + const cc = input.charCodeAt(pos); + pos++; + + // U+0029 RIGHT PARENTHESIS ()) + // Return the . + if (cc === CC_RIGHT_PARENTHESIS) { + if (callbacks.url !== undefined) { + return callbacks.url(input, fnStart, pos, contentStart, pos - 1); + } + + return pos; + } + // whitespace + // Consume as much whitespace as possible. + // If the next input code point is U+0029 RIGHT PARENTHESIS ()) or EOF, consume it and return the + // (if EOF was encountered, this is a parse error); otherwise, consume the remnants of a bad url, create a , and return it. + else if (_isWhiteSpace(cc)) { + const end = pos - 1; + + while (_isWhiteSpace(input.charCodeAt(pos))) { + pos++; + } + + if (pos === input.length) { + if (callbacks.url !== undefined) { + return callbacks.url(input, fnStart, pos, contentStart, end); + } + + return pos; + } + + if (input.charCodeAt(pos) === CC_RIGHT_PARENTHESIS) { + pos++; + + if (callbacks.url !== undefined) { + return callbacks.url(input, fnStart, pos, contentStart, end); + } + + return pos; + } + + // Don't handle bad urls + return consumeTheRemnantsOfABadUrl(input, pos); + } + // U+0022 QUOTATION MARK (") + // U+0027 APOSTROPHE (') + // U+0028 LEFT PARENTHESIS (() + // non-printable code point + // This is a parse error. Consume the remnants of a bad url, create a , and return it. + else if ( + cc === CC_QUOTATION_MARK || + cc === CC_APOSTROPHE || + cc === CC_LEFT_PARENTHESIS || + _isNonPrintableCodePoint(cc) + ) { + // Don't handle bad urls + return consumeTheRemnantsOfABadUrl(input, pos); + } + // // U+005C REVERSE SOLIDUS (\) + // // If the stream starts with a valid escape, consume an escaped code point and append the returned code point to the ’s value. + // // Otherwise, this is a parse error. Consume the remnants of a bad url, create a , and return it. + else if (cc === CC_REVERSE_SOLIDUS) { + if (_ifTwoCodePointsAreValidEscape(input, pos)) { + pos = _consumeAnEscapedCodePoint(input, pos); + } else { + // Don't handle bad urls + return consumeTheRemnantsOfABadUrl(input, pos); + } + } + // anything else + // Append the current input code point to the ’s value. + else { + // Nothing + } + } +}; + +/** @type {CharHandler} */ +const consumeAnIdentLikeToken = (input, pos, callbacks) => { + const start = pos; + // This section describes how to consume an ident-like token from a stream of code points. + // It returns an , , , or . + pos = _consumeAnIdentSequence(input, pos, callbacks); + + // If string’s value is an ASCII case-insensitive match for "url", and the next input code point is U+0028 LEFT PARENTHESIS ((), consume it. + // While the next two input code points are whitespace, consume the next input code point. + // If the next one or two input code points are U+0022 QUOTATION MARK ("), U+0027 APOSTROPHE ('), or whitespace followed by U+0022 QUOTATION MARK (") or U+0027 APOSTROPHE ('), then create a with its value set to string and return it. + // Otherwise, consume a url token, and return it. + if ( + input.slice(start, pos).toLowerCase() === "url" && + input.charCodeAt(pos) === CC_LEFT_PARENTHESIS + ) { + pos++; + const end = pos; + + while ( + _isWhiteSpace(input.charCodeAt(pos)) && + _isWhiteSpace(input.charCodeAt(pos + 1)) + ) { + pos++; + } + + if ( + input.charCodeAt(pos) === CC_QUOTATION_MARK || + input.charCodeAt(pos) === CC_APOSTROPHE || + (_isWhiteSpace(input.charCodeAt(pos)) && + (input.charCodeAt(pos + 1) === CC_QUOTATION_MARK || + input.charCodeAt(pos + 1) === CC_APOSTROPHE)) + ) { + if (callbacks.function !== undefined) { + return callbacks.function(input, start, end); + } + + return pos; + } + + return consumeAUrlToken(input, pos, start, callbacks); + } + + // Otherwise, if the next input code point is U+0028 LEFT PARENTHESIS ((), consume it. + // Create a with its value set to string and return it. + if (input.charCodeAt(pos) === CC_LEFT_PARENTHESIS) { + pos++; + + if (callbacks.function !== undefined) { + return callbacks.function(input, start, pos); + } + + return pos; + } + + // Otherwise, create an with its value set to string and return it. + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); + } + + return pos; +}; + +/** @type {CharHandler} */ +const consumeLessThan = (input, pos, _callbacks) => { + // If the next 3 input code points are U+0021 EXCLAMATION MARK U+002D HYPHEN-MINUS U+002D HYPHEN-MINUS (!--), consume them and return a . + if (input.slice(pos, pos + 3) === "!--") { + return pos + 3; + } + + // Otherwise, return a with its value set to the current input code point. + return pos; +}; + +/** @type {CharHandler} */ +const consumeCommercialAt = (input, pos, callbacks) => { + const start = pos - 1; + + // If the next 3 input code points would start an ident sequence, consume an ident sequence, create an with its value set to the returned value, and return it. + if ( + _ifThreeCodePointsWouldStartAnIdentSequence( + input, + pos, + input.charCodeAt(pos), + input.charCodeAt(pos + 1), + input.charCodeAt(pos + 2) + ) + ) { + pos = _consumeAnIdentSequence(input, pos, callbacks); + + if (callbacks.atKeyword !== undefined) { + pos = callbacks.atKeyword(input, start, pos); + } + + return pos; + } + + // Otherwise, return a with its value set to the current input code point. + return pos; +}; + +/** @type {CharHandler} */ +const consumeReverseSolidus = (input, pos, callbacks) => { + // If the input stream starts with a valid escape, reconsume the current input code point, consume an ident-like token, and return it. + if (_ifTwoCodePointsAreValidEscape(input, pos)) { + pos--; + return consumeAnIdentLikeToken(input, pos, callbacks); + } + + // Otherwise, this is a parse error. Return a with its value set to the current input code point. + return pos; +}; + +/** @type {CharHandler} */ +const consumeAToken = (input, pos, callbacks) => { + const cc = input.charCodeAt(pos - 1); + + // https://drafts.csswg.org/css-syntax/#consume-token + switch (cc) { + // whitespace + case CC_LINE_FEED: + case CC_CARRIAGE_RETURN: + case CC_FORM_FEED: + case CC_TAB: + case CC_SPACE: + return consumeSpace(input, pos, callbacks); + // U+0022 QUOTATION MARK (") + case CC_QUOTATION_MARK: + return consumeAStringToken(input, pos, callbacks); + // U+0023 NUMBER SIGN (#) + case CC_NUMBER_SIGN: + return consumeNumberSign(input, pos, callbacks); + // U+0027 APOSTROPHE (') + case CC_APOSTROPHE: + return consumeAStringToken(input, pos, callbacks); + // U+0028 LEFT PARENTHESIS (() + case CC_LEFT_PARENTHESIS: + return consumeLeftParenthesis(input, pos, callbacks); + // U+0029 RIGHT PARENTHESIS ()) + case CC_RIGHT_PARENTHESIS: + return consumeRightParenthesis(input, pos, callbacks); + // U+002B PLUS SIGN (+) + case CC_PLUS_SIGN: + return consumePlusSign(input, pos, callbacks); + // U+002C COMMA (,) + case CC_COMMA: + return consumeComma(input, pos, callbacks); + // U+002D HYPHEN-MINUS (-) + case CC_HYPHEN_MINUS: + return consumeHyphenMinus(input, pos, callbacks); + // U+002E FULL STOP (.) + case CC_FULL_STOP: + return consumeFullStop(input, pos, callbacks); + // U+003A COLON (:) + case CC_COLON: + return consumeColon(input, pos, callbacks); + // U+003B SEMICOLON (;) + case CC_SEMICOLON: + return consumeSemicolon(input, pos, callbacks); + // U+003C LESS-THAN SIGN (<) + case CC_LESS_THAN_SIGN: + return consumeLessThan(input, pos, callbacks); + // U+0040 COMMERCIAL AT (@) + case CC_AT_SIGN: + return consumeCommercialAt(input, pos, callbacks); + // U+005B LEFT SQUARE BRACKET ([) + case CC_LEFT_SQUARE: + return consumeLeftSquareBracket(input, pos, callbacks); + // U+005C REVERSE SOLIDUS (\) + case CC_REVERSE_SOLIDUS: + return consumeReverseSolidus(input, pos, callbacks); + // U+005D RIGHT SQUARE BRACKET (]) + case CC_RIGHT_SQUARE: + return consumeRightSquareBracket(input, pos, callbacks); + // U+007B LEFT CURLY BRACKET ({) + case CC_LEFT_CURLY: + return consumeLeftCurlyBracket(input, pos, callbacks); + // U+007D RIGHT CURLY BRACKET (}) + case CC_RIGHT_CURLY: + return consumeRightCurlyBracket(input, pos, callbacks); + default: + // digit + // Reconsume the current input code point, consume a numeric token, and return it. + if (_isDigit(cc)) { + pos--; + return consumeANumericToken(input, pos, callbacks); + } else if (cc === CC_LOWER_U || cc === CC_UPPER_U) { + // If unicode ranges allowed is true and the input stream would start a unicode-range, + // reconsume the current input code point, consume a unicode-range token, and return it. + // Skip now + // if (_ifThreeCodePointsWouldStartAUnicodeRange(input, pos)) { + // pos--; + // return consumeAUnicodeRangeToken(input, pos, callbacks); + // } + + // Otherwise, reconsume the current input code point, consume an ident-like token, and return it. + pos--; + return consumeAnIdentLikeToken(input, pos, callbacks); + } + // ident-start code point + // Reconsume the current input code point, consume an ident-like token, and return it. + else if (isIdentStartCodePoint(cc)) { + pos--; + return consumeAnIdentLikeToken(input, pos, callbacks); + } + + // EOF, but we don't have it + + // anything else + // Return a with its value set to the current input code point. + return consumeDelimToken(input, pos, callbacks); + } +}; + +/** + * @param {string} input input css + * @param {number=} pos pos + * @param {CssTokenCallbacks=} callbacks callbacks + * @returns {number} pos + */ +module.exports = (input, pos = 0, callbacks = {}) => { + // This section describes how to consume a token from a stream of code points. It will return a single token of any type. + while (pos < input.length) { + // Consume comments. + pos = consumeComments(input, pos, callbacks); + + // Consume the next input code point. + pos++; + pos = consumeAToken(input, pos, callbacks); + + if (callbacks.needTerminate && callbacks.needTerminate()) { + break; + } + } + + return pos; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @returns {number} position after comments + */ +const eatComments = (input, pos) => { + for (;;) { + const originalPos = pos; + pos = consumeComments(input, pos, {}); + if (originalPos === pos) { + break; + } + } + + return pos; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @returns {number} position after whitespace + */ +const eatWhitespace = (input, pos) => { + while (_isWhiteSpace(input.charCodeAt(pos))) { + pos++; + } + + return pos; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @returns {number} position after whitespace and comments + */ +const eatWhitespaceAndComments = (input, pos) => { + for (;;) { + const originalPos = pos; + pos = consumeComments(input, pos, {}); + while (_isWhiteSpace(input.charCodeAt(pos))) { + pos++; + } + if (originalPos === pos) { + break; + } + } + + return pos; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @returns {number} position after whitespace + */ +const eatWhiteLine = (input, pos) => { + for (;;) { + const cc = input.charCodeAt(pos); + if (_isSpace(cc)) { + pos++; + continue; + } + if (_isNewline(cc)) pos++; + pos = consumeExtraNewline(cc, input, pos); + break; + } + + return pos; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @returns {[number, number] | undefined} positions of ident sequence + */ +const skipCommentsAndEatIdentSequence = (input, pos) => { + pos = eatComments(input, pos); + + const start = pos; + + if ( + _ifThreeCodePointsWouldStartAnIdentSequence( + input, + pos, + input.charCodeAt(pos), + input.charCodeAt(pos + 1), + input.charCodeAt(pos + 2) + ) + ) { + return [start, _consumeAnIdentSequence(input, pos, {})]; + } + + return undefined; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @returns {[number, number] | undefined} positions of ident sequence + */ +const eatString = (input, pos) => { + pos = eatWhitespaceAndComments(input, pos); + + const start = pos; + + if ( + input.charCodeAt(pos) === CC_QUOTATION_MARK || + input.charCodeAt(pos) === CC_APOSTROPHE + ) { + return [start, consumeAStringToken(input, pos + 1, {})]; + } + + return undefined; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @param {CssTokenCallbacks} cbs callbacks + * @returns {[number, number][]} positions of ident sequence + */ +const eatImageSetStrings = (input, pos, cbs) => { + /** @type {[number, number][]} */ + const result = []; + + let isFirst = true; + let needStop = false; + // We already in `func(` token + let balanced = 1; + + /** @type {CssTokenCallbacks} */ + const callbacks = { + ...cbs, + string: (_input, start, end) => { + if (isFirst && balanced === 1) { + result.push([start, end]); + isFirst = false; + } + + return end; + }, + comma: (_input, _start, end) => { + if (balanced === 1) { + isFirst = true; + } + + return end; + }, + leftParenthesis: (input, start, end) => { + balanced++; + + return end; + }, + function: (_input, start, end) => { + balanced++; + + return end; + }, + rightParenthesis: (_input, _start, end) => { + balanced--; + + if (balanced === 0) { + needStop = true; + } + + return end; + } + }; + + while (pos < input.length) { + // Consume comments. + pos = consumeComments(input, pos, callbacks); + + // Consume the next input code point. + pos++; + pos = consumeAToken(input, pos, callbacks); + + if (needStop) { + break; + } + } + + return result; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @param {CssTokenCallbacks} cbs callbacks + * @returns {[[number, number, number, number] | undefined, [number, number] | undefined, [number, number] | undefined, [number, number] | undefined]} positions of top level tokens + */ +const eatImportTokens = (input, pos, cbs) => { + const result = + /** @type {[[number, number, number, number] | undefined, [number, number] | undefined, [number, number] | undefined, [number, number] | undefined]} */ + (Array.from({ length: 4 })); + + /** @type {0 | 1 | 2 | undefined} */ + let scope; + let needStop = false; + let balanced = 0; + + /** @type {CssTokenCallbacks} */ + const callbacks = { + ...cbs, + url: (_input, start, end, contentStart, contentEnd) => { + if ( + result[0] === undefined && + balanced === 0 && + result[1] === undefined && + result[2] === undefined && + result[3] === undefined + ) { + result[0] = [start, end, contentStart, contentEnd]; + scope = undefined; + } + + return end; + }, + string: (_input, start, end) => { + if ( + balanced === 0 && + result[0] === undefined && + result[1] === undefined && + result[2] === undefined && + result[3] === undefined + ) { + result[0] = [start, end, start + 1, end - 1]; + scope = undefined; + } else if (result[0] !== undefined && scope === 0) { + result[0][2] = start + 1; + result[0][3] = end - 1; + } + + return end; + }, + leftParenthesis: (_input, _start, end) => { + balanced++; + + return end; + }, + rightParenthesis: (_input, _start, end) => { + balanced--; + + if (balanced === 0 && scope !== undefined) { + /** @type {[number, number]} */ + (result[scope])[1] = end; + scope = undefined; + } + + return end; + }, + function: (input, start, end) => { + if (balanced === 0) { + const name = input + .slice(start, end - 1) + .replace(/\\/g, "") + .toLowerCase(); + + if ( + name === "url" && + result[0] === undefined && + result[1] === undefined && + result[2] === undefined && + result[3] === undefined + ) { + scope = 0; + result[scope] = [start, end + 1, end + 1, end + 1]; + } else if ( + name === "layer" && + result[1] === undefined && + result[2] === undefined + ) { + scope = 1; + result[scope] = [start, end]; + } else if (name === "supports" && result[2] === undefined) { + scope = 2; + result[scope] = [start, end]; + } else { + scope = undefined; + } + } + + balanced++; + + return end; + }, + identifier: (input, start, end) => { + if ( + balanced === 0 && + result[1] === undefined && + result[2] === undefined + ) { + const name = input.slice(start, end).replace(/\\/g, "").toLowerCase(); + + if (name === "layer") { + result[1] = [start, end]; + scope = undefined; + } + } + + return end; + }, + semicolon: (_input, start, end) => { + if (balanced === 0) { + needStop = true; + result[3] = [start, end]; + } + + return end; + } + }; + + while (pos < input.length) { + // Consume comments. + pos = consumeComments(input, pos, callbacks); + + // Consume the next input code point. + pos++; + pos = consumeAToken(input, pos, callbacks); + + if (needStop) { + break; + } + } + + return result; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @returns {[number, number] | undefined} positions of ident sequence + */ +const eatIdentSequence = (input, pos) => { + pos = eatWhitespaceAndComments(input, pos); + + const start = pos; + + if ( + _ifThreeCodePointsWouldStartAnIdentSequence( + input, + pos, + input.charCodeAt(pos), + input.charCodeAt(pos + 1), + input.charCodeAt(pos + 2) + ) + ) { + return [start, _consumeAnIdentSequence(input, pos, {})]; + } + + return undefined; +}; + +/** + * @param {string} input input + * @param {number} pos position + * @returns {[number, number, boolean] | undefined} positions of ident sequence or string + */ +const eatIdentSequenceOrString = (input, pos) => { + pos = eatWhitespaceAndComments(input, pos); + + const start = pos; + + if ( + input.charCodeAt(pos) === CC_QUOTATION_MARK || + input.charCodeAt(pos) === CC_APOSTROPHE + ) { + return [start, consumeAStringToken(input, pos + 1, {}), false]; + } else if ( + _ifThreeCodePointsWouldStartAnIdentSequence( + input, + pos, + input.charCodeAt(pos), + input.charCodeAt(pos + 1), + input.charCodeAt(pos + 2) + ) + ) { + return [start, _consumeAnIdentSequence(input, pos, {}), true]; + } + + return undefined; +}; + +/** + * @param {string} chars characters + * @returns {(input: string, pos: number) => number} function to eat characters + */ +const eatUntil = (chars) => { + const charCodes = Array.from({ length: chars.length }, (_, i) => + chars.charCodeAt(i) + ); + const arr = Array.from( + { length: charCodes.reduce((a, b) => Math.max(a, b), 0) + 1 }, + () => false + ); + for (const cc of charCodes) { + arr[cc] = true; + } + + return (input, pos) => { + for (;;) { + const cc = input.charCodeAt(pos); + if (cc < arr.length && arr[cc]) { + return pos; + } + pos++; + if (pos === input.length) return pos; + } + }; +}; + +module.exports.eatComments = eatComments; +module.exports.eatIdentSequence = eatIdentSequence; +module.exports.eatIdentSequenceOrString = eatIdentSequenceOrString; +module.exports.eatImageSetStrings = eatImageSetStrings; +module.exports.eatImportTokens = eatImportTokens; +module.exports.eatString = eatString; +module.exports.eatUntil = eatUntil; +module.exports.eatWhiteLine = eatWhiteLine; +module.exports.eatWhitespace = eatWhitespace; +module.exports.eatWhitespaceAndComments = eatWhitespaceAndComments; +module.exports.isIdentStartCodePoint = isIdentStartCodePoint; +module.exports.skipCommentsAndEatIdentSequence = + skipCommentsAndEatIdentSequence; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/debug/ProfilingPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/debug/ProfilingPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..eff5240ae097a724825583c752ef69f3514f47b1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/debug/ProfilingPlugin.js @@ -0,0 +1,561 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const { Tracer } = require("chrome-trace-event"); +const { + CSS_MODULES, + JAVASCRIPT_MODULES, + JSON_MODULE_TYPE, + WEBASSEMBLY_MODULES +} = require("../ModuleTypeConstants"); +const createSchemaValidation = require("../util/create-schema-validation"); +const { dirname, mkdirpSync } = require("../util/fs"); + +/** @typedef {import("inspector").Session} Session */ +/** @typedef {import("tapable").FullTap} FullTap */ +/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../ContextModuleFactory")} ContextModuleFactory */ +/** @typedef {import("../ModuleFactory")} ModuleFactory */ +/** @typedef {import("../NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("../Parser")} Parser */ +/** @typedef {import("../ResolverFactory")} ResolverFactory */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/debug/ProfilingPlugin.check"), + () => require("../../schemas/plugins/debug/ProfilingPlugin.json"), + { + name: "Profiling Plugin", + baseDataPath: "options" + } +); + +/** @typedef {{ Session: typeof import("inspector").Session }} Inspector */ + +/** @type {Inspector | undefined} */ +let inspector; + +try { + // eslint-disable-next-line n/no-unsupported-features/node-builtins + inspector = require("inspector"); +} catch (_err) { + // eslint-disable-next-line no-console + console.log("Unable to CPU profile in < node 8.0"); +} + +class Profiler { + /** + * @param {Inspector} inspector inspector + */ + constructor(inspector) { + /** @type {undefined | Session} */ + this.session = undefined; + this.inspector = inspector; + this._startTime = 0; + } + + hasSession() { + return this.session !== undefined; + } + + startProfiling() { + if (this.inspector === undefined) { + return Promise.resolve(); + } + + try { + this.session = new /** @type {Inspector} */ (inspector).Session(); + /** @type {Session} */ + (this.session).connect(); + } catch (_) { + this.session = undefined; + return Promise.resolve(); + } + + const hrtime = process.hrtime(); + this._startTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); + + return Promise.all([ + this.sendCommand("Profiler.setSamplingInterval", { + interval: 100 + }), + this.sendCommand("Profiler.enable"), + this.sendCommand("Profiler.start") + ]); + } + + /** + * @param {string} method method name + * @param {EXPECTED_OBJECT=} params params + * @returns {Promise} Promise for the result + */ + sendCommand(method, params) { + if (this.hasSession()) { + return new Promise((res, rej) => { + /** @type {Session} */ + (this.session).post(method, params, (err, params) => { + if (err !== null) { + rej(err); + } else { + res(params); + } + }); + }); + } + return Promise.resolve(); + } + + destroy() { + if (this.hasSession()) { + /** @type {Session} */ + (this.session).disconnect(); + } + + return Promise.resolve(); + } + + stopProfiling() { + return this.sendCommand("Profiler.stop").then(({ profile }) => { + const hrtime = process.hrtime(); + const endTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); + // Avoid coverage problems due indirect changes + /* istanbul ignore next */ + if (profile.startTime < this._startTime || profile.endTime > endTime) { + // In some cases timestamps mismatch and we need to adjust them + // Both process.hrtime and the inspector timestamps claim to be relative + // to a unknown point in time. But they do not guarantee that this is the + // same point in time. + const duration = profile.endTime - profile.startTime; + const ownDuration = endTime - this._startTime; + const untracked = Math.max(0, ownDuration - duration); + profile.startTime = this._startTime + untracked / 2; + profile.endTime = endTime - untracked / 2; + } + return { profile }; + }); + } +} + +/** + * an object that wraps Tracer and Profiler with a counter + * @typedef {object} Trace + * @property {Tracer} trace instance of Tracer + * @property {number} counter Counter + * @property {Profiler} profiler instance of Profiler + * @property {(callback: (err?: null | Error) => void) => void} end the end function + */ + +/** + * @param {IntermediateFileSystem} fs filesystem used for output + * @param {string} outputPath The location where to write the log. + * @returns {Trace} The trace object + */ +const createTrace = (fs, outputPath) => { + const trace = new Tracer(); + const profiler = new Profiler(/** @type {Inspector} */ (inspector)); + if (/\/|\\/.test(outputPath)) { + const dirPath = dirname(fs, outputPath); + mkdirpSync(fs, dirPath); + } + const fsStream = fs.createWriteStream(outputPath); + + let counter = 0; + + trace.pipe(fsStream); + // These are critical events that need to be inserted so that tools like + // chrome dev tools can load the profile. + trace.instantEvent({ + name: "TracingStartedInPage", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1", + page: "0xfff", + frames: [ + { + frame: "0xfff", + url: "webpack", + name: "" + } + ] + } + } + }); + + trace.instantEvent({ + name: "TracingStartedInBrowser", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1" + } + } + }); + + return { + trace, + counter, + profiler, + end: (callback) => { + trace.push("]"); + // Wait until the write stream finishes. + fsStream.on("close", () => { + callback(); + }); + // Tear down the readable trace stream. + trace.push(null); + } + }; +}; + +const PLUGIN_NAME = "ProfilingPlugin"; + +class ProfilingPlugin { + /** + * @param {ProfilingPluginOptions=} options options object + */ + constructor(options = {}) { + validate(options); + this.outputPath = options.outputPath || "events.json"; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const tracer = createTrace( + /** @type {IntermediateFileSystem} */ + (compiler.intermediateFileSystem), + this.outputPath + ); + tracer.profiler.startProfiling(); + + // Compiler Hooks + for (const hookName of Object.keys(compiler.hooks)) { + const hook = + compiler.hooks[/** @type {keyof Compiler["hooks"]} */ (hookName)]; + if (hook) { + hook.intercept(makeInterceptorFor("Compiler", tracer)(hookName)); + } + } + + for (const hookName of Object.keys(compiler.resolverFactory.hooks)) { + const hook = + compiler.resolverFactory.hooks[ + /** @type {keyof ResolverFactory["hooks"]} */ + (hookName) + ]; + if (hook) { + hook.intercept(makeInterceptorFor("Resolver", tracer)(hookName)); + } + } + + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory, contextModuleFactory }) => { + interceptAllHooksFor(compilation, tracer, "Compilation"); + interceptAllHooksFor( + normalModuleFactory, + tracer, + "Normal Module Factory" + ); + interceptAllHooksFor( + contextModuleFactory, + tracer, + "Context Module Factory" + ); + interceptAllParserHooks(normalModuleFactory, tracer); + interceptAllGeneratorHooks(normalModuleFactory, tracer); + interceptAllJavascriptModulesPluginHooks(compilation, tracer); + interceptAllCssModulesPluginHooks(compilation, tracer); + } + ); + + // We need to write out the CPU profile when we are all done. + compiler.hooks.done.tapAsync( + { + name: PLUGIN_NAME, + stage: Infinity + }, + (stats, callback) => { + if (compiler.watchMode) return callback(); + tracer.profiler.stopProfiling().then((parsedResults) => { + if (parsedResults === undefined) { + tracer.profiler.destroy(); + tracer.end(callback); + return; + } + + const cpuStartTime = parsedResults.profile.startTime; + const cpuEndTime = parsedResults.profile.endTime; + + tracer.trace.completeEvent({ + name: "TaskQueueManager::ProcessTaskFromWorkQueue", + id: ++tracer.counter, + cat: ["toplevel"], + ts: cpuStartTime, + args: { + // eslint-disable-next-line camelcase + src_file: "../../ipc/ipc_moji_bootstrap.cc", + // eslint-disable-next-line camelcase + src_func: "Accept" + } + }); + + tracer.trace.completeEvent({ + name: "EvaluateScript", + id: ++tracer.counter, + cat: ["devtools.timeline"], + ts: cpuStartTime, + dur: cpuEndTime - cpuStartTime, + args: { + data: { + url: "webpack", + lineNumber: 1, + columnNumber: 1, + frame: "0xFFF" + } + } + }); + + tracer.trace.instantEvent({ + name: "CpuProfile", + id: ++tracer.counter, + cat: ["disabled-by-default-devtools.timeline"], + ts: cpuEndTime, + args: { + data: { + cpuProfile: parsedResults.profile + } + } + }); + + tracer.profiler.destroy(); + tracer.end(callback); + }); + } + ); + } +} + +/** + * @param {EXPECTED_ANY & { hooks: TODO }} instance instance + * @param {Trace} tracer tracer + * @param {string} logLabel log label + */ +const interceptAllHooksFor = (instance, tracer, logLabel) => { + if (Reflect.has(instance, "hooks")) { + for (const hookName of Object.keys(instance.hooks)) { + const hook = instance.hooks[hookName]; + if (hook && !hook._fakeHook) { + hook.intercept(makeInterceptorFor(logLabel, tracer)(hookName)); + } + } + } +}; + +/** + * @param {NormalModuleFactory} moduleFactory normal module factory + * @param {Trace} tracer tracer + */ +const interceptAllParserHooks = (moduleFactory, tracer) => { + const moduleTypes = [ + ...JAVASCRIPT_MODULES, + JSON_MODULE_TYPE, + ...WEBASSEMBLY_MODULES, + ...CSS_MODULES + ]; + + for (const moduleType of moduleTypes) { + moduleFactory.hooks.parser + .for(moduleType) + .tap(PLUGIN_NAME, (parser, _parserOpts) => { + interceptAllHooksFor(parser, tracer, "Parser"); + }); + } +}; + +/** + * @param {NormalModuleFactory} moduleFactory normal module factory + * @param {Trace} tracer tracer + */ +const interceptAllGeneratorHooks = (moduleFactory, tracer) => { + const moduleTypes = [ + ...JAVASCRIPT_MODULES, + JSON_MODULE_TYPE, + ...WEBASSEMBLY_MODULES, + ...CSS_MODULES + ]; + + for (const moduleType of moduleTypes) { + moduleFactory.hooks.generator + .for(moduleType) + .tap(PLUGIN_NAME, (parser, _parserOpts) => { + interceptAllHooksFor(parser, tracer, "Generator"); + }); + } +}; + +/** + * @param {Compilation} compilation compilation + * @param {Trace} tracer tracer + */ +const interceptAllJavascriptModulesPluginHooks = (compilation, tracer) => { + interceptAllHooksFor( + { + hooks: + require("../javascript/JavascriptModulesPlugin").getCompilationHooks( + compilation + ) + }, + tracer, + "JavascriptModulesPlugin" + ); +}; + +/** + * @param {Compilation} compilation compilation + * @param {Trace} tracer tracer + */ +const interceptAllCssModulesPluginHooks = (compilation, tracer) => { + interceptAllHooksFor( + { + hooks: require("../css/CssModulesPlugin").getCompilationHooks(compilation) + }, + tracer, + "CssModulesPlugin" + ); +}; + +/** @typedef {(...args: EXPECTED_ANY[]) => EXPECTED_ANY | Promise<(...args: EXPECTED_ANY[]) => EXPECTED_ANY>} PluginFunction */ + +/** + * @param {string} instance instance + * @param {Trace} tracer tracer + * @returns {(hookName: string) => TODO} interceptor + */ +const makeInterceptorFor = (instance, tracer) => (hookName) => ({ + /** + * @param {FullTap} tapInfo tap info + * @returns {FullTap} modified full tap + */ + register: (tapInfo) => { + const { name, type, fn: internalFn } = tapInfo; + const newFn = + // Don't tap our own hooks to ensure stream can close cleanly + name === PLUGIN_NAME + ? internalFn + : makeNewProfiledTapFn(hookName, tracer, { + name, + type, + fn: /** @type {PluginFunction} */ (internalFn) + }); + return { ...tapInfo, fn: newFn }; + } +}); + +/** + * @param {string} hookName Name of the hook to profile. + * @param {Trace} tracer The trace object. + * @param {object} options Options for the profiled fn. + * @param {string} options.name Plugin name + * @param {"sync" | "async" | "promise"} options.type Plugin type (sync | async | promise) + * @param {PluginFunction} options.fn Plugin function + * @returns {PluginFunction} Chainable hooked function. + */ +const makeNewProfiledTapFn = (hookName, tracer, { name, type, fn }) => { + const defaultCategory = ["blink.user_timing"]; + + switch (type) { + case "promise": + return (...args) => { + const id = ++tracer.counter; + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + const promise = + /** @type {Promise<(...args: EXPECTED_ANY[]) => EXPECTED_ANY>} */ + (fn(...args)); + return promise.then((r) => { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + return r; + }); + }; + case "async": + return (...args) => { + const id = ++tracer.counter; + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + const callback = args.pop(); + fn( + ...args, + /** + * @param {...EXPECTED_ANY[]} r result + */ + (...r) => { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + callback(...r); + } + ); + }; + case "sync": + return (...args) => { + const id = ++tracer.counter; + // Do not instrument ourself due to the CPU + // profile needing to be the last event in the trace. + if (name === PLUGIN_NAME) { + return fn(...args); + } + + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + let r; + try { + r = fn(...args); + } catch (err) { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + throw err; + } + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + return r; + }; + default: + return fn; + } +}; + +module.exports = ProfilingPlugin; +module.exports.Profiler = Profiler; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDDefineDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDDefineDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..4acb15252716afa855a6e2dbde7e7bb88d72d7d2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDDefineDependency.js @@ -0,0 +1,265 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** @type {Record} */ +const DEFINITIONS = { + f: { + definition: "var __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, ${RuntimeGlobals.require}, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [ + RuntimeGlobals.require, + RuntimeGlobals.exports, + RuntimeGlobals.module + ] + }, + o: { + definition: "", + content: "!(module.exports = #)", + requests: [RuntimeGlobals.module] + }, + of: { + definition: + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, ${RuntimeGlobals.require}, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [ + RuntimeGlobals.require, + RuntimeGlobals.exports, + RuntimeGlobals.module + ] + }, + af: { + definition: + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [RuntimeGlobals.exports, RuntimeGlobals.module] + }, + ao: { + definition: "", + content: "!(#, module.exports = #)", + requests: [RuntimeGlobals.module] + }, + aof: { + definition: + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [RuntimeGlobals.exports, RuntimeGlobals.module] + }, + lf: { + definition: "var XXX, XXXmodule;", + content: `!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = (#).call(XXXmodule.exports, ${RuntimeGlobals.require}, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))`, + requests: [RuntimeGlobals.require, RuntimeGlobals.module] + }, + lo: { + definition: "var XXX;", + content: "!(XXX = #)", + requests: [] + }, + lof: { + definition: "var XXX, XXXfactory, XXXmodule;", + content: `!(XXXfactory = (#), (typeof XXXfactory === 'function' ? ((XXXmodule = { id: YYY, exports: {}, loaded: false }), (XXX = XXXfactory.call(XXXmodule.exports, ${RuntimeGlobals.require}, XXXmodule.exports, XXXmodule)), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports)) : XXX = XXXfactory))`, + requests: [RuntimeGlobals.require, RuntimeGlobals.module] + }, + laf: { + definition: "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX, XXXexports;", + content: + "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = (#).apply(XXXexports = {}, __WEBPACK_AMD_DEFINE_ARRAY__), XXX === undefined && (XXX = XXXexports))", + requests: [] + }, + lao: { + definition: "var XXX;", + content: "!(#, XXX = #)", + requests: [] + }, + laof: { + definition: "var XXXarray, XXXfactory, XXXexports, XXX;", + content: `!(XXXarray = #, XXXfactory = (#), + (typeof XXXfactory === 'function' ? + ((XXX = XXXfactory.apply(XXXexports = {}, XXXarray)), XXX === undefined && (XXX = XXXexports)) : + (XXX = XXXfactory) + ))`, + requests: [] + } +}; + +class AMDDefineDependency extends NullDependency { + /** + * @param {Range} range range + * @param {Range | null} arrayRange array range + * @param {Range | null} functionRange function range + * @param {Range | null} objectRange object range + * @param {string | null} namedModule true, when define is called with a name + */ + constructor(range, arrayRange, functionRange, objectRange, namedModule) { + super(); + this.range = range; + this.arrayRange = arrayRange; + this.functionRange = functionRange; + this.objectRange = objectRange; + this.namedModule = namedModule; + this.localModule = null; + } + + get type() { + return "amd define"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + write(this.arrayRange); + write(this.functionRange); + write(this.objectRange); + write(this.namedModule); + write(this.localModule); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.range = read(); + this.arrayRange = read(); + this.functionRange = read(); + this.objectRange = read(); + this.namedModule = read(); + this.localModule = read(); + super.deserialize(context); + } +} + +makeSerializable( + AMDDefineDependency, + "webpack/lib/dependencies/AMDDefineDependency" +); + +AMDDefineDependency.Template = class AMDDefineDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { runtimeRequirements }) { + const dep = /** @type {AMDDefineDependency} */ (dependency); + const branch = this.branch(dep); + const { definition, content, requests } = DEFINITIONS[branch]; + for (const req of requests) { + runtimeRequirements.add(req); + } + this.replace(dep, source, definition, content); + } + + /** + * @param {AMDDefineDependency} dependency dependency + * @returns {string} variable name + */ + localModuleVar(dependency) { + return ( + dependency.localModule && + dependency.localModule.used && + dependency.localModule.variableName() + ); + } + + /** + * @param {AMDDefineDependency} dependency dependency + * @returns {string} branch + */ + branch(dependency) { + const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; + const arrayRange = dependency.arrayRange ? "a" : ""; + const objectRange = dependency.objectRange ? "o" : ""; + const functionRange = dependency.functionRange ? "f" : ""; + return localModuleVar + arrayRange + objectRange + functionRange; + } + + /** + * @param {AMDDefineDependency} dependency dependency + * @param {ReplaceSource} source source + * @param {string} definition definition + * @param {string} text text + */ + replace(dependency, source, definition, text) { + const localModuleVar = this.localModuleVar(dependency); + if (localModuleVar) { + text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); + definition = definition.replace( + /XXX/g, + localModuleVar.replace(/\$/g, "$$$$") + ); + } + + if (dependency.namedModule) { + text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); + } + + const texts = text.split("#"); + + if (definition) source.insert(0, definition); + + let current = dependency.range[0]; + if (dependency.arrayRange) { + source.replace( + current, + dependency.arrayRange[0] - 1, + /** @type {string} */ (texts.shift()) + ); + current = dependency.arrayRange[1]; + } + + if (dependency.objectRange) { + source.replace( + current, + dependency.objectRange[0] - 1, + /** @type {string} */ (texts.shift()) + ); + current = dependency.objectRange[1]; + } else if (dependency.functionRange) { + source.replace( + current, + dependency.functionRange[0] - 1, + /** @type {string} */ (texts.shift()) + ); + current = dependency.functionRange[1]; + } + source.replace( + current, + dependency.range[1] - 1, + /** @type {string} */ (texts.shift()) + ); + if (texts.length > 0) throw new Error("Implementation error"); + } +}; + +module.exports = AMDDefineDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDDefineDependencyParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDDefineDependencyParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..56cab2a8219608eeb5232755eff45c1c2cebefaf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDDefineDependencyParserPlugin.js @@ -0,0 +1,503 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const AMDDefineDependency = require("./AMDDefineDependency"); +const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); +const AMDRequireContextDependency = require("./AMDRequireContextDependency"); +const AMDRequireItemDependency = require("./AMDRequireItemDependency"); +const ConstDependency = require("./ConstDependency"); +const ContextDependencyHelpers = require("./ContextDependencyHelpers"); +const DynamicExports = require("./DynamicExports"); +const LocalModuleDependency = require("./LocalModuleDependency"); +const { addLocalModule, getLocalModule } = require("./LocalModulesHelpers"); + +/** @typedef {import("estree").ArrowFunctionExpression} ArrowFunctionExpression */ +/** @typedef {import("estree").CallExpression} CallExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").FunctionExpression} FunctionExpression */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").Literal} Literal */ +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("estree").ObjectExpression} ObjectExpression */ +/** @typedef {import("estree").SimpleCallExpression} SimpleCallExpression */ +/** @typedef {import("estree").SpreadElement} SpreadElement */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +/** + * @param {Expression | SpreadElement} expr expression + * @returns {expr is CallExpression} true if it's a bound function expression + */ +const isBoundFunctionExpression = (expr) => { + if (expr.type !== "CallExpression") return false; + if (expr.callee.type !== "MemberExpression") return false; + if (expr.callee.computed) return false; + if (expr.callee.object.type !== "FunctionExpression") return false; + if (expr.callee.property.type !== "Identifier") return false; + if (expr.callee.property.name !== "bind") return false; + return true; +}; + +/** @typedef {FunctionExpression | ArrowFunctionExpression} UnboundFunctionExpression */ + +/** + * @param {Expression | SpreadElement} expr expression + * @returns {expr is FunctionExpression | ArrowFunctionExpression} true when unbound function expression + */ +const isUnboundFunctionExpression = (expr) => { + if (expr.type === "FunctionExpression") return true; + if (expr.type === "ArrowFunctionExpression") return true; + return false; +}; + +/** + * @param {Expression | SpreadElement} expr expression + * @returns {expr is FunctionExpression | ArrowFunctionExpression | CallExpression} true when callable + */ +const isCallable = (expr) => { + if (isUnboundFunctionExpression(expr)) return true; + if (isBoundFunctionExpression(expr)) return true; + return false; +}; + +const PLUGIN_NAME = "AMDDefineDependencyParserPlugin"; + +class AMDDefineDependencyParserPlugin { + /** + * @param {JavascriptParserOptions} options parserOptions + */ + constructor(options) { + this.options = options; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + parser.hooks.call + .for("define") + .tap(PLUGIN_NAME, this.processCallDefine.bind(this, parser)); + } + + /** + * @param {JavascriptParser} parser the parser + * @param {CallExpression} expr call expression + * @param {BasicEvaluatedExpression} param param + * @param {Record} identifiers identifiers + * @param {string=} namedModule named module + * @returns {boolean | undefined} result + */ + processArray(parser, expr, param, identifiers, namedModule) { + if (param.isArray()) { + const items = /** @type {BasicEvaluatedExpression[]} */ (param.items); + for (const [idx, item] of items.entries()) { + if ( + item.isString() && + ["require", "module", "exports"].includes( + /** @type {string} */ (item.string) + ) + ) { + identifiers[/** @type {number} */ (idx)] = + /** @type {string} */ + (item.string); + } + const result = this.processItem(parser, expr, item, namedModule); + if (result === undefined) { + this.processContext(parser, expr, item); + } + } + return true; + } else if (param.isConstArray()) { + /** @type {(string | LocalModuleDependency | AMDRequireItemDependency)[]} */ + const deps = []; + const array = /** @type {string[]} */ (param.array); + for (const [idx, request] of array.entries()) { + let dep; + let localModule; + if (request === "require") { + identifiers[idx] = request; + dep = RuntimeGlobals.require; + } else if (["exports", "module"].includes(request)) { + identifiers[idx] = request; + dep = request; + } else if ((localModule = getLocalModule(parser.state, request))) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + } + deps.push(dep); + } + const dep = this.newRequireArrayDependency( + deps, + /** @type {Range} */ (param.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + + /** + * @param {JavascriptParser} parser the parser + * @param {CallExpression} expr call expression + * @param {BasicEvaluatedExpression} param param + * @param {string=} namedModule named module + * @returns {boolean | undefined} result + */ + processItem(parser, expr, param, namedModule) { + if (param.isConditional()) { + const options = /** @type {BasicEvaluatedExpression[]} */ (param.options); + for (const item of options) { + const result = this.processItem(parser, expr, item); + if (result === undefined) { + this.processContext(parser, expr, item); + } + } + + return true; + } else if (param.isString()) { + let dep; + let localModule; + + if (param.string === "require") { + dep = new ConstDependency( + RuntimeGlobals.require, + /** @type {Range} */ (param.range), + [RuntimeGlobals.require] + ); + } else if (param.string === "exports") { + dep = new ConstDependency( + "exports", + /** @type {Range} */ (param.range), + [RuntimeGlobals.exports] + ); + } else if (param.string === "module") { + dep = new ConstDependency( + "module", + /** @type {Range} */ (param.range), + [RuntimeGlobals.module] + ); + } else if ( + (localModule = getLocalModule( + parser.state, + /** @type {string} */ (param.string), + namedModule + )) + ) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency( + /** @type {string} */ (param.string), + param.range + ); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + } + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + + /** + * @param {JavascriptParser} parser the parser + * @param {CallExpression} expr call expression + * @param {BasicEvaluatedExpression} param param + * @returns {boolean | undefined} result + */ + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + /** @type {Range} */ (param.range), + param, + expr, + this.options, + { + category: "amd" + }, + parser + ); + if (!dep) return; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + } + + /** + * @param {JavascriptParser} parser the parser + * @param {CallExpression} expr call expression + * @returns {boolean | undefined} result + */ + processCallDefine(parser, expr) { + /** @type {Expression | SpreadElement | undefined} */ + let array; + /** @type {FunctionExpression | ArrowFunctionExpression | CallExpression | Identifier | undefined} */ + let fn; + /** @type {ObjectExpression | Identifier | undefined} */ + let obj; + /** @type {string | undefined} */ + let namedModule; + switch (expr.arguments.length) { + case 1: + if (isCallable(expr.arguments[0])) { + // define(f() {…}) + fn = expr.arguments[0]; + } else if (expr.arguments[0].type === "ObjectExpression") { + // define({…}) + obj = expr.arguments[0]; + } else { + // define(expr) + // unclear if function or object + obj = fn = /** @type {Identifier} */ (expr.arguments[0]); + } + break; + case 2: + if (expr.arguments[0].type === "Literal") { + namedModule = /** @type {string} */ (expr.arguments[0].value); + // define("…", …) + if (isCallable(expr.arguments[1])) { + // define("…", f() {…}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define("…", {…}) + obj = expr.arguments[1]; + } else { + // define("…", expr) + // unclear if function or object + obj = fn = /** @type {Identifier} */ (expr.arguments[1]); + } + } else { + array = expr.arguments[0]; + if (isCallable(expr.arguments[1])) { + // define([…], f() {}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define([…], {…}) + obj = expr.arguments[1]; + } else { + // define([…], expr) + // unclear if function or object + obj = fn = /** @type {Identifier} */ (expr.arguments[1]); + } + } + break; + case 3: + // define("…", […], f() {…}) + namedModule = + /** @type {string} */ + ( + /** @type {Literal} */ + (expr.arguments[0]).value + ); + array = expr.arguments[1]; + if (isCallable(expr.arguments[2])) { + // define("…", […], f() {}) + fn = expr.arguments[2]; + } else if (expr.arguments[2].type === "ObjectExpression") { + // define("…", […], {…}) + obj = expr.arguments[2]; + } else { + // define("…", […], expr) + // unclear if function or object + obj = fn = /** @type {Identifier} */ (expr.arguments[2]); + } + break; + default: + return; + } + DynamicExports.bailout(parser.state); + /** @type {Identifier[] | null} */ + let fnParams = null; + let fnParamsOffset = 0; + if (fn) { + if (isUnboundFunctionExpression(fn)) { + fnParams = + /** @type {Identifier[]} */ + (fn.params); + } else if (isBoundFunctionExpression(fn)) { + const object = + /** @type {FunctionExpression} */ + (/** @type {MemberExpression} */ (fn.callee).object); + + fnParams = + /** @type {Identifier[]} */ + (object.params); + fnParamsOffset = fn.arguments.length - 1; + if (fnParamsOffset < 0) { + fnParamsOffset = 0; + } + } + } + const fnRenames = new Map(); + if (array) { + /** @type {Record} */ + const identifiers = {}; + const param = parser.evaluateExpression(array); + const result = this.processArray( + parser, + expr, + param, + identifiers, + namedModule + ); + if (!result) return; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); + return false; + } + return true; + }); + } + } else { + const identifiers = ["require", "exports", "module"]; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); + return false; + } + return true; + }); + } + } + /** @type {boolean | undefined} */ + let inTry; + if (fn && isUnboundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope(/** @type {Identifier[]} */ (fnParams), () => { + for (const [name, varInfo] of fnRenames) { + parser.setVariable(name, varInfo); + } + parser.scope.inTry = /** @type {boolean} */ (inTry); + if (fn.body.type === "BlockStatement") { + parser.detectMode(fn.body.body); + const prev = parser.prevStatement; + parser.preWalkStatement(fn.body); + parser.prevStatement = prev; + parser.walkStatement(fn.body); + } else { + parser.walkExpression(fn.body); + } + }); + } else if (fn && isBoundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + + const object = + /** @type {FunctionExpression} */ + (/** @type {MemberExpression} */ (fn.callee).object); + + parser.inScope( + /** @type {Identifier[]} */ + (object.params).filter( + (i) => !["require", "module", "exports"].includes(i.name) + ), + () => { + for (const [name, varInfo] of fnRenames) { + parser.setVariable(name, varInfo); + } + parser.scope.inTry = /** @type {boolean} */ (inTry); + + if (object.body.type === "BlockStatement") { + parser.detectMode(object.body.body); + const prev = parser.prevStatement; + parser.preWalkStatement(object.body); + parser.prevStatement = prev; + parser.walkStatement(object.body); + } else { + parser.walkExpression( + /** @type {TODO} */ + (object.body) + ); + } + } + ); + if (fn.arguments) { + parser.walkExpressions(fn.arguments); + } + } else if (fn || obj) { + parser.walkExpression( + /** @type {FunctionExpression | ArrowFunctionExpression | CallExpression | ObjectExpression | Identifier} */ + (fn || obj) + ); + } + + const dep = this.newDefineDependency( + /** @type {Range} */ (expr.range), + array ? /** @type {Range} */ (array.range) : null, + fn ? /** @type {Range} */ (fn.range) : null, + obj ? /** @type {Range} */ (obj.range) : null, + namedModule || null + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + if (namedModule) { + dep.localModule = addLocalModule(parser.state, namedModule); + } + parser.state.module.addPresentationalDependency(dep); + return true; + } + + /** + * @param {Range} range range + * @param {Range | null} arrayRange array range + * @param {Range | null} functionRange function range + * @param {Range | null} objectRange object range + * @param {string | null} namedModule true, when define is called with a name + * @returns {AMDDefineDependency} AMDDefineDependency + */ + newDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ) { + return new AMDDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ); + } + + /** + * @param {(string | LocalModuleDependency | AMDRequireItemDependency)[]} depsArray deps array + * @param {Range} range range + * @returns {AMDRequireArrayDependency} AMDRequireArrayDependency + */ + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } + + /** + * @param {string} request request + * @param {Range=} range range + * @returns {AMDRequireItemDependency} AMDRequireItemDependency + */ + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } +} + +module.exports = AMDDefineDependencyParserPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..add34161d7da8daf8b3de98cbe9cafb117a9f15a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDPlugin.js @@ -0,0 +1,243 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC +} = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const { + approve, + evaluateToIdentifier, + evaluateToString, + toConstantDependency +} = require("../javascript/JavascriptParserHelpers"); + +const AMDDefineDependency = require("./AMDDefineDependency"); +const AMDDefineDependencyParserPlugin = require("./AMDDefineDependencyParserPlugin"); +const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); +const AMDRequireContextDependency = require("./AMDRequireContextDependency"); +const AMDRequireDependenciesBlockParserPlugin = require("./AMDRequireDependenciesBlockParserPlugin"); +const AMDRequireDependency = require("./AMDRequireDependency"); +const AMDRequireItemDependency = require("./AMDRequireItemDependency"); +const { + AMDDefineRuntimeModule, + AMDOptionsRuntimeModule +} = require("./AMDRuntimeModules"); +const ConstDependency = require("./ConstDependency"); +const LocalModuleDependency = require("./LocalModuleDependency"); +const UnsupportedDependency = require("./UnsupportedDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").Amd} Amd */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "AMDPlugin"; + +/** @typedef {Exclude} AmdOptions */ + +class AMDPlugin { + /** + * @param {AmdOptions} amdOptions the AMD options + */ + constructor(amdOptions) { + this.amdOptions = amdOptions; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const amdOptions = this.amdOptions; + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyTemplates.set( + AMDRequireDependency, + new AMDRequireDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDRequireItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireItemDependency, + new AMDRequireItemDependency.Template() + ); + + compilation.dependencyTemplates.set( + AMDRequireArrayDependency, + new AMDRequireArrayDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireContextDependency, + new AMDRequireContextDependency.Template() + ); + + compilation.dependencyTemplates.set( + AMDDefineDependency, + new AMDDefineDependency.Template() + ); + + compilation.dependencyTemplates.set( + UnsupportedDependency, + new UnsupportedDependency.Template() + ); + + compilation.dependencyTemplates.set( + LocalModuleDependency, + new LocalModuleDependency.Template() + ); + + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.amdDefine) + .tap(PLUGIN_NAME, (module, set) => { + set.add(RuntimeGlobals.require); + }); + + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.amdOptions) + .tap(PLUGIN_NAME, (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.amdDefine) + .tap(PLUGIN_NAME, (chunk, _set) => { + compilation.addRuntimeModule(chunk, new AMDDefineRuntimeModule()); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.amdOptions) + .tap(PLUGIN_NAME, (chunk, _set) => { + compilation.addRuntimeModule( + chunk, + new AMDOptionsRuntimeModule(amdOptions) + ); + }); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if (parserOptions.amd !== undefined && !parserOptions.amd) return; + + /** + * @param {string} optionExpr option expression + * @param {string} rootName root name + * @param {() => string[]} getMembers callback + */ + const tapOptionsHooks = (optionExpr, rootName, getMembers) => { + parser.hooks.expression + .for(optionExpr) + .tap( + PLUGIN_NAME, + toConstantDependency(parser, RuntimeGlobals.amdOptions, [ + RuntimeGlobals.amdOptions + ]) + ); + parser.hooks.evaluateIdentifier + .for(optionExpr) + .tap(PLUGIN_NAME, (expr) => + evaluateToIdentifier( + optionExpr, + rootName, + getMembers, + true + )(expr) + ); + parser.hooks.evaluateTypeof + .for(optionExpr) + .tap(PLUGIN_NAME, evaluateToString("object")); + parser.hooks.typeof + .for(optionExpr) + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("object")) + ); + }; + + new AMDRequireDependenciesBlockParserPlugin(parserOptions).apply( + parser + ); + new AMDDefineDependencyParserPlugin(parserOptions).apply(parser); + + tapOptionsHooks("define.amd", "define", () => ["amd"]); + tapOptionsHooks("require.amd", "require", () => ["amd"]); + tapOptionsHooks( + "__webpack_amd_options__", + "__webpack_amd_options__", + () => [] + ); + + parser.hooks.expression.for("define").tap(PLUGIN_NAME, (expr) => { + const dep = new ConstDependency( + RuntimeGlobals.amdDefine, + /** @type {Range} */ (expr.range), + [RuntimeGlobals.amdDefine] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.typeof + .for("define") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for("define") + .tap(PLUGIN_NAME, evaluateToString("function")); + parser.hooks.canRename.for("define").tap(PLUGIN_NAME, approve); + parser.hooks.rename.for("define").tap(PLUGIN_NAME, (expr) => { + const dep = new ConstDependency( + RuntimeGlobals.amdDefine, + /** @type {Range} */ (expr.range), + [RuntimeGlobals.amdDefine] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return false; + }); + parser.hooks.typeof + .for("require") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for("require") + .tap(PLUGIN_NAME, evaluateToString("function")); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = AMDPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireArrayDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireArrayDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..0740025fefac5340b0fb55237aa0e79e0d5dfef6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireArrayDependency.js @@ -0,0 +1,124 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DependencyTemplate = require("../DependencyTemplate"); +const makeSerializable = require("../util/makeSerializable"); +const LocalModuleDependency = require("./LocalModuleDependency"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./AMDRequireItemDependency")} AMDRequireItemDependency */ + +class AMDRequireArrayDependency extends NullDependency { + /** + * @param {(string | LocalModuleDependency | AMDRequireItemDependency)[]} depsArray deps array + * @param {Range} range range + */ + constructor(depsArray, range) { + super(); + + this.depsArray = depsArray; + this.range = range; + } + + get type() { + return "amd require array"; + } + + get category() { + return "amd"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.depsArray); + write(this.range); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.depsArray = read(); + this.range = read(); + + super.deserialize(context); + } +} + +makeSerializable( + AMDRequireArrayDependency, + "webpack/lib/dependencies/AMDRequireArrayDependency" +); + +AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate extends ( + DependencyTemplate +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {AMDRequireArrayDependency} */ (dependency); + const content = this.getContent(dep, templateContext); + source.replace(dep.range[0], dep.range[1] - 1, content); + } + + /** + * @param {AMDRequireArrayDependency} dep the dependency for which the template should be applied + * @param {DependencyTemplateContext} templateContext the context object + * @returns {string} content + */ + getContent(dep, templateContext) { + const requires = dep.depsArray.map((dependency) => + this.contentForDependency(dependency, templateContext) + ); + return `[${requires.join(", ")}]`; + } + + /** + * @param {string | LocalModuleDependency | AMDRequireItemDependency} dep the dependency for which the template should be applied + * @param {DependencyTemplateContext} templateContext the context object + * @returns {string} content + */ + contentForDependency( + dep, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + if (typeof dep === "string") { + return dep; + } + + if (dep instanceof LocalModuleDependency) { + return dep.localModule.variableName(); + } + + return runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + runtimeRequirements + }); + } +}; + +module.exports = AMDRequireArrayDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireContextDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireContextDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..91f30c41b897feb5d421b54be09177a6d99f49a9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireContextDependency.js @@ -0,0 +1,69 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ContextDependency = require("./ContextDependency"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ + +class AMDRequireContextDependency extends ContextDependency { + /** + * @param {ContextDependencyOptions} options options + * @param {Range} range range + * @param {Range} valueRange value range + */ + constructor(options, range, valueRange) { + super(options); + + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "amd require context"; + } + + get category() { + return "amd"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.range); + write(this.valueRange); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.range = read(); + this.valueRange = read(); + + super.deserialize(context); + } +} + +makeSerializable( + AMDRequireContextDependency, + "webpack/lib/dependencies/AMDRequireContextDependency" +); + +AMDRequireContextDependency.Template = require("./ContextDependencyTemplateAsRequireCall"); + +module.exports = AMDRequireContextDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlock.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlock.js new file mode 100644 index 0000000000000000000000000000000000000000..615660c3c9e4d2fefad4bf4f88f61ee99f02ff81 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlock.js @@ -0,0 +1,28 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ + +class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { + /** + * @param {DependencyLocation} loc location info + * @param {string=} request request + */ + constructor(loc, request) { + super(null, loc, request); + } +} + +makeSerializable( + AMDRequireDependenciesBlock, + "webpack/lib/dependencies/AMDRequireDependenciesBlock" +); + +module.exports = AMDRequireDependenciesBlock; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..0d28b8b9f17b321a1850f989847cebc27158ba14 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js @@ -0,0 +1,420 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); +const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); +const AMDRequireContextDependency = require("./AMDRequireContextDependency"); +const AMDRequireDependenciesBlock = require("./AMDRequireDependenciesBlock"); +const AMDRequireDependency = require("./AMDRequireDependency"); +const AMDRequireItemDependency = require("./AMDRequireItemDependency"); +const ConstDependency = require("./ConstDependency"); +const ContextDependencyHelpers = require("./ContextDependencyHelpers"); +const LocalModuleDependency = require("./LocalModuleDependency"); +const { getLocalModule } = require("./LocalModulesHelpers"); +const UnsupportedDependency = require("./UnsupportedDependency"); +const getFunctionExpression = require("./getFunctionExpression"); + +/** @typedef {import("estree").CallExpression} CallExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").SourceLocation} SourceLocation */ +/** @typedef {import("estree").SpreadElement} SpreadElement */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "AMDRequireDependenciesBlockParserPlugin"; + +class AMDRequireDependenciesBlockParserPlugin { + /** + * @param {JavascriptParserOptions} options parserOptions + */ + constructor(options) { + this.options = options; + } + + /** + * @param {JavascriptParser} parser the parser + * @param {Expression | SpreadElement} expression expression + * @returns {boolean} need bind this + */ + processFunctionArgument(parser, expression) { + let bindThis = true; + const fnData = getFunctionExpression(expression); + if (fnData) { + parser.inScope( + fnData.fn.params.filter( + (i) => + !["require", "module", "exports"].includes( + /** @type {Identifier} */ (i).name + ) + ), + () => { + if (fnData.fn.body.type === "BlockStatement") { + parser.walkStatement(fnData.fn.body); + } else { + parser.walkExpression(fnData.fn.body); + } + } + ); + parser.walkExpressions(fnData.expressions); + if (fnData.needThis === false) { + bindThis = false; + } + } else { + parser.walkExpression(expression); + } + return bindThis; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + parser.hooks.call + .for("require") + .tap(PLUGIN_NAME, this.processCallRequire.bind(this, parser)); + } + + /** + * @param {JavascriptParser} parser the parser + * @param {CallExpression} expr call expression + * @param {BasicEvaluatedExpression} param param + * @returns {boolean | undefined} result + */ + processArray(parser, expr, param) { + if (param.isArray()) { + for (const p of /** @type {BasicEvaluatedExpression[]} */ (param.items)) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isConstArray()) { + /** @type {(string | LocalModuleDependency | AMDRequireItemDependency)[]} */ + const deps = []; + for (const request of /** @type {EXPECTED_ANY[]} */ (param.array)) { + let dep; + let localModule; + if (request === "require") { + dep = RuntimeGlobals.require; + } else if (["exports", "module"].includes(request)) { + dep = request; + } else if ((localModule = getLocalModule(parser.state, request))) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + } + deps.push(dep); + } + const dep = this.newRequireArrayDependency( + deps, + /** @type {Range} */ + (param.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + + /** + * @param {JavascriptParser} parser the parser + * @param {CallExpression} expr call expression + * @param {BasicEvaluatedExpression} param param + * @returns {boolean | undefined} result + */ + processItem(parser, expr, param) { + if (param.isConditional()) { + for (const p of /** @type {BasicEvaluatedExpression[]} */ ( + param.options + )) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isString()) { + let dep; + let localModule; + if (param.string === "require") { + dep = new ConstDependency( + RuntimeGlobals.require, + /** @type {Range} */ + (param.range), + [RuntimeGlobals.require] + ); + } else if (param.string === "module") { + dep = new ConstDependency( + parser.state.module.moduleArgument, + /** @type {Range} */ + (param.range), + [RuntimeGlobals.module] + ); + } else if (param.string === "exports") { + dep = new ConstDependency( + parser.state.module.exportsArgument, + /** @type {Range} */ + (param.range), + [RuntimeGlobals.exports] + ); + } else if ( + (localModule = getLocalModule( + parser.state, + /** @type {string} */ + (param.string) + )) + ) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency( + /** @type {string} */ + (param.string), + param.range + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + } + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + + /** + * @param {JavascriptParser} parser the parser + * @param {CallExpression} expr call expression + * @param {BasicEvaluatedExpression} param param + * @returns {boolean | undefined} result + */ + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + /** @type {Range} */ + (param.range), + param, + expr, + this.options, + { + category: "amd" + }, + parser + ); + if (!dep) return; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + } + + /** + * @param {BasicEvaluatedExpression} param param + * @returns {string | undefined} result + */ + processArrayForRequestString(param) { + if (param.isArray()) { + const result = + /** @type {BasicEvaluatedExpression[]} */ + (param.items).map((item) => this.processItemForRequestString(item)); + if (result.every(Boolean)) return result.join(" "); + } else if (param.isConstArray()) { + return /** @type {string[]} */ (param.array).join(" "); + } + } + + /** + * @param {BasicEvaluatedExpression} param param + * @returns {string | undefined} result + */ + processItemForRequestString(param) { + if (param.isConditional()) { + const result = + /** @type {BasicEvaluatedExpression[]} */ + (param.options).map((item) => this.processItemForRequestString(item)); + if (result.every(Boolean)) return result.join("|"); + } else if (param.isString()) { + return param.string; + } + } + + /** + * @param {JavascriptParser} parser the parser + * @param {CallExpression} expr call expression + * @returns {boolean | undefined} result + */ + processCallRequire(parser, expr) { + /** @type {BasicEvaluatedExpression | undefined} */ + let param; + /** @type {AMDRequireDependenciesBlock | undefined | null} */ + let depBlock; + /** @type {AMDRequireDependency | undefined} */ + let dep; + /** @type {boolean | undefined} */ + let result; + + const old = parser.state.current; + + if (expr.arguments.length >= 1) { + param = parser.evaluateExpression( + /** @type {Expression} */ (expr.arguments[0]) + ); + depBlock = this.newRequireDependenciesBlock( + /** @type {DependencyLocation} */ (expr.loc), + this.processArrayForRequestString(param) + ); + dep = this.newRequireDependency( + /** @type {Range} */ (expr.range), + /** @type {Range} */ (param.range), + expr.arguments.length > 1 + ? /** @type {Range} */ (expr.arguments[1].range) + : null, + expr.arguments.length > 2 + ? /** @type {Range} */ (expr.arguments[2].range) + : null + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + depBlock.addDependency(dep); + + parser.state.current = /** @type {TODO} */ (depBlock); + } + + if (expr.arguments.length === 1) { + parser.inScope([], () => { + result = this.processArray( + parser, + expr, + /** @type {BasicEvaluatedExpression} */ + (param) + ); + }); + parser.state.current = old; + if (!result) return; + parser.state.current.addBlock( + /** @type {AMDRequireDependenciesBlock} */ + (depBlock) + ); + return true; + } + + if (expr.arguments.length === 2 || expr.arguments.length === 3) { + try { + parser.inScope([], () => { + result = this.processArray( + parser, + expr, + /** @type {BasicEvaluatedExpression} */ + (param) + ); + }); + if (!result) { + const dep = new UnsupportedDependency( + "unsupported", + /** @type {Range} */ + (expr.range) + ); + old.addPresentationalDependency(dep); + if (parser.state.module) { + parser.state.module.addError( + new UnsupportedFeatureWarning( + `Cannot statically analyse 'require(…, …)' in line ${ + /** @type {SourceLocation} */ (expr.loc).start.line + }`, + /** @type {DependencyLocation} */ + (expr.loc) + ) + ); + } + depBlock = null; + return true; + } + /** @type {AMDRequireDependency} */ + (dep).functionBindThis = this.processFunctionArgument( + parser, + expr.arguments[1] + ); + if (expr.arguments.length === 3) { + /** @type {AMDRequireDependency} */ + (dep).errorCallbackBindThis = this.processFunctionArgument( + parser, + expr.arguments[2] + ); + } + } finally { + parser.state.current = old; + if (depBlock) parser.state.current.addBlock(depBlock); + } + return true; + } + } + + /** + * @param {DependencyLocation} loc location + * @param {string=} request request + * @returns {AMDRequireDependenciesBlock} AMDRequireDependenciesBlock + */ + newRequireDependenciesBlock(loc, request) { + return new AMDRequireDependenciesBlock(loc, request); + } + + /** + * @param {Range} outerRange outer range + * @param {Range} arrayRange array range + * @param {Range | null} functionRange function range + * @param {Range | null} errorCallbackRange error callback range + * @returns {AMDRequireDependency} dependency + */ + newRequireDependency( + outerRange, + arrayRange, + functionRange, + errorCallbackRange + ) { + return new AMDRequireDependency( + outerRange, + arrayRange, + functionRange, + errorCallbackRange + ); + } + + /** + * @param {string} request request + * @param {Range=} range range + * @returns {AMDRequireItemDependency} AMDRequireItemDependency + */ + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } + + /** + * @param {(string | LocalModuleDependency | AMDRequireItemDependency)[]} depsArray deps array + * @param {Range} range range + * @returns {AMDRequireArrayDependency} AMDRequireArrayDependency + */ + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } +} + +module.exports = AMDRequireDependenciesBlockParserPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..930348fc948969f5f4ac7f5f4c098a838387fd71 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireDependency.js @@ -0,0 +1,189 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class AMDRequireDependency extends NullDependency { + /** + * @param {Range} outerRange outer range + * @param {Range} arrayRange array range + * @param {Range | null} functionRange function range + * @param {Range | null} errorCallbackRange error callback range + */ + constructor(outerRange, arrayRange, functionRange, errorCallbackRange) { + super(); + + this.outerRange = outerRange; + this.arrayRange = arrayRange; + this.functionRange = functionRange; + this.errorCallbackRange = errorCallbackRange; + this.functionBindThis = false; + this.errorCallbackBindThis = false; + } + + get category() { + return "amd"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.outerRange); + write(this.arrayRange); + write(this.functionRange); + write(this.errorCallbackRange); + write(this.functionBindThis); + write(this.errorCallbackBindThis); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.outerRange = read(); + this.arrayRange = read(); + this.functionRange = read(); + this.errorCallbackRange = read(); + this.functionBindThis = read(); + this.errorCallbackBindThis = read(); + + super.deserialize(context); + } +} + +makeSerializable( + AMDRequireDependency, + "webpack/lib/dependencies/AMDRequireDependency" +); + +AMDRequireDependency.Template = class AMDRequireDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {AMDRequireDependency} */ (dependency); + const depBlock = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dep) + ); + const promise = runtimeTemplate.blockPromise({ + chunkGraph, + block: depBlock, + message: "AMD require", + runtimeRequirements + }); + + // has array range but no function range + if (dep.arrayRange && !dep.functionRange) { + const startBlock = `${promise}.then(function() {`; + const endBlock = `;})['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; + runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); + + source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); + + source.replace(dep.arrayRange[1], dep.outerRange[1] - 1, endBlock); + + return; + } + + // has function range but no array range + if (dep.functionRange && !dep.arrayRange) { + const startBlock = `${promise}.then((`; + const endBlock = `).bind(exports, ${RuntimeGlobals.require}, exports, module))['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; + runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); + + source.replace(dep.outerRange[0], dep.functionRange[0] - 1, startBlock); + + source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); + + return; + } + + // has array range, function range, and errorCallbackRange + if (dep.arrayRange && dep.functionRange && dep.errorCallbackRange) { + const startBlock = `${promise}.then(function() { `; + const errorRangeBlock = `}${ + dep.functionBindThis ? ".bind(this)" : "" + })['catch'](`; + const endBlock = `${dep.errorCallbackBindThis ? ".bind(this)" : ""})`; + + source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); + + source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); + + source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); + + source.insert( + dep.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + + source.replace( + dep.functionRange[1], + dep.errorCallbackRange[0] - 1, + errorRangeBlock + ); + + source.replace( + dep.errorCallbackRange[1], + dep.outerRange[1] - 1, + endBlock + ); + + return; + } + + // has array range, function range, but no errorCallbackRange + if (dep.arrayRange && dep.functionRange) { + const startBlock = `${promise}.then(function() { `; + const endBlock = `}${ + dep.functionBindThis ? ".bind(this)" : "" + })['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; + runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); + + source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); + + source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); + + source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); + + source.insert( + dep.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + + source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); + } + } +}; + +module.exports = AMDRequireDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireItemDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireItemDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..614633ad3246f40bf6bffd89bde5acdeb423fb2e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRequireItemDependency.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +class AMDRequireItemDependency extends ModuleDependency { + /** + * @param {string} request the request string + * @param {Range=} range location in source code + */ + constructor(request, range) { + super(request); + + this.range = range; + } + + get type() { + return "amd require"; + } + + get category() { + return "amd"; + } +} + +makeSerializable( + AMDRequireItemDependency, + "webpack/lib/dependencies/AMDRequireItemDependency" +); + +AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = AMDRequireItemDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRuntimeModules.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRuntimeModules.js new file mode 100644 index 0000000000000000000000000000000000000000..9a685851f4aa887a7270adcafeaa758ef8619147 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/AMDRuntimeModules.js @@ -0,0 +1,50 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("./AMDPlugin").AmdOptions} AmdOptions */ + +class AMDDefineRuntimeModule extends RuntimeModule { + constructor() { + super("amd define"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.amdDefine} = function () {`, + Template.indent("throw new Error('define cannot be used indirect');"), + "};" + ]); + } +} + +class AMDOptionsRuntimeModule extends RuntimeModule { + /** + * @param {AmdOptions} options the AMD options + */ + constructor(options) { + super("amd options"); + this.options = options; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.amdOptions} = ${JSON.stringify(this.options)};` + ]); + } +} + +module.exports.AMDDefineRuntimeModule = AMDDefineRuntimeModule; +module.exports.AMDOptionsRuntimeModule = AMDOptionsRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CachedConstDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CachedConstDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..01c0371ed3691d957c1fa65f4a7371eae7569b53 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CachedConstDependency.js @@ -0,0 +1,124 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +const DependencyTemplate = require("../DependencyTemplate"); +const InitFragment = require("../InitFragment"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ + +class CachedConstDependency extends NullDependency { + /** + * @param {string} expression expression + * @param {Range} range range + * @param {string} identifier identifier + */ + constructor(expression, range, identifier) { + super(); + + this.expression = expression; + this.range = range; + this.identifier = identifier; + this._hashUpdate = undefined; + } + + /** + * @returns {string} hash update + */ + _createHashUpdate() { + return `${this.identifier}${this.range}${this.expression}`; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = this._createHashUpdate(); + } + hash.update(this._hashUpdate); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.expression); + write(this.range); + write(this.identifier); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.expression = read(); + this.range = read(); + this.identifier = read(); + + super.deserialize(context); + } +} + +makeSerializable( + CachedConstDependency, + "webpack/lib/dependencies/CachedConstDependency" +); + +CachedConstDependency.Template = class CachedConstDependencyTemplate extends ( + DependencyTemplate +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { initFragments }) { + const dep = /** @type {CachedConstDependency} */ (dependency); + + initFragments.push( + new InitFragment( + `var ${dep.identifier} = ${dep.expression};\n`, + InitFragment.STAGE_CONSTANTS, + 0, + `const ${dep.identifier}` + ) + ); + + if (typeof dep.range === "number") { + source.insert(dep.range, dep.identifier); + + return; + } + + source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); + } +}; + +module.exports = CachedConstDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsDependencyHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsDependencyHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..0cd457ee73a4ed5627d70340af43fb1236999855 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsDependencyHelpers.js @@ -0,0 +1,63 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); + +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ +/** @typedef {"exports" | "module.exports" | "this" | "Object.defineProperty(exports)" | "Object.defineProperty(module.exports)" | "Object.defineProperty(this)"} CommonJSDependencyBaseKeywords */ + +/** + * @param {CommonJSDependencyBaseKeywords} depBase commonjs dependency base + * @param {Module} module module + * @param {RuntimeRequirements} runtimeRequirements runtime requirements + * @returns {[string, string]} type and base + */ +module.exports.handleDependencyBase = ( + depBase, + module, + runtimeRequirements +) => { + let base; + let type; + switch (depBase) { + case "exports": + runtimeRequirements.add(RuntimeGlobals.exports); + base = module.exportsArgument; + type = "expression"; + break; + case "module.exports": + runtimeRequirements.add(RuntimeGlobals.module); + base = `${module.moduleArgument}.exports`; + type = "expression"; + break; + case "this": + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + base = "this"; + type = "expression"; + break; + case "Object.defineProperty(exports)": + runtimeRequirements.add(RuntimeGlobals.exports); + base = module.exportsArgument; + type = "Object.defineProperty"; + break; + case "Object.defineProperty(module.exports)": + runtimeRequirements.add(RuntimeGlobals.module); + base = `${module.moduleArgument}.exports`; + type = "Object.defineProperty"; + break; + case "Object.defineProperty(this)": + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + base = "this"; + type = "Object.defineProperty"; + break; + default: + throw new Error(`Unsupported base ${depBase}`); + } + + return [type, base]; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsExportRequireDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsExportRequireDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..fc16baab9e14e11b30e411266aa7bc8cddf2482d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsExportRequireDependency.js @@ -0,0 +1,405 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const { UsageState } = require("../ExportsInfo"); +const Template = require("../Template"); +const { equals } = require("../util/ArrayHelpers"); +const makeSerializable = require("../util/makeSerializable"); +const propertyAccess = require("../util/propertyAccess"); +const { handleDependencyBase } = require("./CommonJsDependencyHelpers"); +const ModuleDependency = require("./ModuleDependency"); +const processExportInfo = require("./processExportInfo"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */ + +const idsSymbol = Symbol("CommonJsExportRequireDependency.ids"); + +const EMPTY_OBJECT = {}; + +class CommonJsExportRequireDependency extends ModuleDependency { + /** + * @param {Range} range range + * @param {Range | null} valueRange value range + * @param {CommonJSDependencyBaseKeywords} base base + * @param {string[]} names names + * @param {string} request request + * @param {string[]} ids ids + * @param {boolean} resultUsed true, when the result is used + */ + constructor(range, valueRange, base, names, request, ids, resultUsed) { + super(request); + this.range = range; + this.valueRange = valueRange; + this.base = base; + this.names = names; + this.ids = ids; + this.resultUsed = resultUsed; + this.asiSafe = undefined; + } + + get type() { + return "cjs export require"; + } + + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return Dependency.TRANSITIVE; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string[]} the imported id + */ + getIds(moduleGraph) { + return moduleGraph.getMeta(this)[idsSymbol] || this.ids; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {string[]} ids the imported ids + * @returns {void} + */ + setIds(moduleGraph, ids) { + moduleGraph.getMeta(this)[idsSymbol] = ids; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + const ids = this.getIds(moduleGraph); + const getFullResult = () => { + if (ids.length === 0) { + return Dependency.EXPORTS_OBJECT_REFERENCED; + } + return [ + { + name: ids, + canMangle: false + } + ]; + }; + if (this.resultUsed) return getFullResult(); + /** @type {ExportsInfo | undefined} */ + let exportsInfo = moduleGraph.getExportsInfo( + /** @type {Module} */ (moduleGraph.getParentModule(this)) + ); + for (const name of this.names) { + const exportInfo = /** @type {ExportInfo} */ ( + exportsInfo.getReadOnlyExportInfo(name) + ); + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED; + if (used !== UsageState.OnlyPropertiesUsed) return getFullResult(); + exportsInfo = exportInfo.exportsInfo; + if (!exportsInfo) return getFullResult(); + } + if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + return getFullResult(); + } + /** @type {string[][]} */ + const referencedExports = []; + for (const exportInfo of exportsInfo.orderedExports) { + processExportInfo( + runtime, + referencedExports, + [...ids, exportInfo.name], + exportInfo, + false + ); + } + return referencedExports.map((name) => ({ + name, + canMangle: false + })); + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + if (this.names.length === 1) { + const ids = this.getIds(moduleGraph); + const name = this.names[0]; + const from = moduleGraph.getConnection(this); + if (!from) return; + return { + exports: [ + { + name, + from, + export: ids.length === 0 ? null : ids, + // we can't mangle names that are in an empty object + // because one could access the prototype property + // when export isn't set yet + canMangle: !(name in EMPTY_OBJECT) && false + } + ], + dependencies: [from.module] + }; + } else if (this.names.length > 0) { + const name = this.names[0]; + return { + exports: [ + { + name, + // we can't mangle names that are in an empty object + // because one could access the prototype property + // when export isn't set yet + canMangle: !(name in EMPTY_OBJECT) && false + } + ], + dependencies: undefined + }; + } + const from = moduleGraph.getConnection(this); + if (!from) return; + const reexportInfo = this.getStarReexports( + moduleGraph, + undefined, + from.module + ); + const ids = this.getIds(moduleGraph); + if (reexportInfo) { + return { + exports: Array.from( + /** @type {Set} */ + (reexportInfo.exports), + (name) => ({ + name, + from, + export: [...ids, name], + canMangle: !(name in EMPTY_OBJECT) && false + }) + ), + // TODO handle deep reexports + dependencies: [from.module] + }; + } + return { + exports: true, + from: ids.length === 0 ? from : undefined, + canMangle: false, + dependencies: [from.module] + }; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @param {Module} importedModule the imported module (optional) + * @returns {{exports?: Set, checked?: Set} | undefined} information + */ + getStarReexports( + moduleGraph, + runtime, + importedModule = /** @type {Module} */ (moduleGraph.getModule(this)) + ) { + /** @type {ExportsInfo | undefined} */ + let importedExportsInfo = moduleGraph.getExportsInfo(importedModule); + const ids = this.getIds(moduleGraph); + if (ids.length > 0) { + importedExportsInfo = importedExportsInfo.getNestedExportsInfo(ids); + } + /** @type {ExportsInfo | undefined} */ + let exportsInfo = moduleGraph.getExportsInfo( + /** @type {Module} */ (moduleGraph.getParentModule(this)) + ); + if (this.names.length > 0) { + exportsInfo = exportsInfo.getNestedExportsInfo(this.names); + } + + const noExtraExports = + importedExportsInfo && + importedExportsInfo.otherExportsInfo.provided === false; + const noExtraImports = + exportsInfo && + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; + + if (!noExtraExports && !noExtraImports) { + return; + } + + const isNamespaceImport = + importedModule.getExportsType(moduleGraph, false) === "namespace"; + + /** @type {Set} */ + const exports = new Set(); + /** @type {Set} */ + const checked = new Set(); + + if (noExtraImports) { + for (const exportInfo of /** @type {ExportsInfo} */ (exportsInfo) + .orderedExports) { + const name = exportInfo.name; + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + if (name === "__esModule" && isNamespaceImport) { + exports.add(name); + } else if (importedExportsInfo) { + const importedExportInfo = + importedExportsInfo.getReadOnlyExportInfo(name); + if (importedExportInfo.provided === false) continue; + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } else { + exports.add(name); + checked.add(name); + } + } + } else if (noExtraExports) { + for (const importedExportInfo of /** @type {ExportsInfo} */ ( + importedExportsInfo + ).orderedExports) { + const name = importedExportInfo.name; + if (importedExportInfo.provided === false) continue; + if (exportsInfo) { + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + } + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } + if (isNamespaceImport) { + exports.add("__esModule"); + checked.delete("__esModule"); + } + } + + return { exports, checked }; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.asiSafe); + write(this.range); + write(this.valueRange); + write(this.base); + write(this.names); + write(this.ids); + write(this.resultUsed); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.asiSafe = read(); + this.range = read(); + this.valueRange = read(); + this.base = read(); + this.names = read(); + this.ids = read(); + this.resultUsed = read(); + super.deserialize(context); + } +} + +makeSerializable( + CommonJsExportRequireDependency, + "webpack/lib/dependencies/CommonJsExportRequireDependency" +); + +CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { + module, + runtimeTemplate, + chunkGraph, + moduleGraph, + runtimeRequirements, + runtime + } + ) { + const dep = /** @type {CommonJsExportRequireDependency} */ (dependency); + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.names, runtime); + + const [type, base] = handleDependencyBase( + dep.base, + module, + runtimeRequirements + ); + + const importedModule = moduleGraph.getModule(dep); + let requireExpr = runtimeTemplate.moduleExports({ + module: importedModule, + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); + if (importedModule) { + const ids = dep.getIds(moduleGraph); + const usedImported = moduleGraph + .getExportsInfo(importedModule) + .getUsedName(ids, runtime); + if (usedImported) { + const comment = equals(usedImported, ids) + ? "" + : `${Template.toNormalComment(propertyAccess(ids))} `; + requireExpr += `${comment}${propertyAccess(usedImported)}`; + } + } + + switch (type) { + case "expression": + source.replace( + dep.range[0], + dep.range[1] - 1, + used + ? `${base}${propertyAccess(used)} = ${requireExpr}` + : `/* unused reexport */ ${requireExpr}` + ); + return; + case "Object.defineProperty": + throw new Error("TODO"); + default: + throw new Error("Unexpected type"); + } + } +}; + +module.exports = CommonJsExportRequireDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsExportsDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsExportsDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..93c831b5dfd27940a500384d58d2eac38cf43787 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsExportsDependency.js @@ -0,0 +1,183 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const InitFragment = require("../InitFragment"); +const makeSerializable = require("../util/makeSerializable"); +const propertyAccess = require("../util/propertyAccess"); +const { handleDependencyBase } = require("./CommonJsDependencyHelpers"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */ + +const EMPTY_OBJECT = {}; + +class CommonJsExportsDependency extends NullDependency { + /** + * @param {Range} range range + * @param {Range | null} valueRange value range + * @param {CommonJSDependencyBaseKeywords} base base + * @param {string[]} names names + */ + constructor(range, valueRange, base, names) { + super(); + this.range = range; + this.valueRange = valueRange; + this.base = base; + this.names = names; + } + + get type() { + return "cjs exports"; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const name = this.names[0]; + return { + exports: [ + { + name, + // we can't mangle names that are in an empty object + // because one could access the prototype property + // when export isn't set yet + canMangle: !(name in EMPTY_OBJECT) + } + ], + dependencies: undefined + }; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + write(this.valueRange); + write(this.base); + write(this.names); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.range = read(); + this.valueRange = read(); + this.base = read(); + this.names = read(); + super.deserialize(context); + } +} + +makeSerializable( + CommonJsExportsDependency, + "webpack/lib/dependencies/CommonJsExportsDependency" +); + +CommonJsExportsDependency.Template = class CommonJsExportsDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { module, moduleGraph, initFragments, runtimeRequirements, runtime } + ) { + const dep = /** @type {CommonJsExportsDependency} */ (dependency); + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.names, runtime); + + const [type, base] = handleDependencyBase( + dep.base, + module, + runtimeRequirements + ); + + switch (type) { + case "expression": + if (!used) { + initFragments.push( + new InitFragment( + "var __webpack_unused_export__;\n", + InitFragment.STAGE_CONSTANTS, + 0, + "__webpack_unused_export__" + ) + ); + source.replace( + dep.range[0], + dep.range[1] - 1, + "__webpack_unused_export__" + ); + return; + } + source.replace( + dep.range[0], + dep.range[1] - 1, + `${base}${propertyAccess(used)}` + ); + return; + case "Object.defineProperty": + if (!used) { + initFragments.push( + new InitFragment( + "var __webpack_unused_export__;\n", + InitFragment.STAGE_CONSTANTS, + 0, + "__webpack_unused_export__" + ) + ); + source.replace( + dep.range[0], + /** @type {Range} */ (dep.valueRange)[0] - 1, + "__webpack_unused_export__ = (" + ); + source.replace( + /** @type {Range} */ (dep.valueRange)[1], + dep.range[1] - 1, + ")" + ); + return; + } + source.replace( + dep.range[0], + /** @type {Range} */ (dep.valueRange)[0] - 1, + `Object.defineProperty(${base}${propertyAccess( + used.slice(0, -1) + )}, ${JSON.stringify(used[used.length - 1])}, (` + ); + source.replace( + /** @type {Range} */ (dep.valueRange)[1], + dep.range[1] - 1, + "))" + ); + } + } +}; + +module.exports = CommonJsExportsDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsExportsParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsExportsParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..2592aa9816b2a0f5ca0c9827cfff5b4ee42dd4dc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsExportsParserPlugin.js @@ -0,0 +1,410 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const formatLocation = require("../formatLocation"); +const { evaluateToString } = require("../javascript/JavascriptParserHelpers"); +const propertyAccess = require("../util/propertyAccess"); +const CommonJsExportRequireDependency = require("./CommonJsExportRequireDependency"); +const CommonJsExportsDependency = require("./CommonJsExportsDependency"); +const CommonJsSelfReferenceDependency = require("./CommonJsSelfReferenceDependency"); +const DynamicExports = require("./DynamicExports"); +const HarmonyExports = require("./HarmonyExports"); +const ModuleDecoratorDependency = require("./ModuleDecoratorDependency"); + +/** @typedef {import("estree").AssignmentExpression} AssignmentExpression */ +/** @typedef {import("estree").CallExpression} CallExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").Super} Super */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../javascript/JavascriptParser").StatementPath} StatementPath */ +/** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */ + +/** + * This function takes a generic expression and detects whether it is an ObjectExpression. + * This is used in the context of parsing CommonJS exports to get the value of the property descriptor + * when the `exports` object is assigned to `Object.defineProperty`. + * + * In CommonJS modules, the `exports` object can be assigned to `Object.defineProperty` and therefore + * webpack has to detect this case and get the value key of the property descriptor. See the following example + * for more information: https://astexplorer.net/#/gist/83ce51a4e96e59d777df315a6d111da6/8058ead48a1bb53c097738225db0967ef7f70e57 + * + * This would be an example of a CommonJS module that exports an object with a property descriptor: + * ```js + * Object.defineProperty(exports, "__esModule", { value: true }); + * exports.foo = void 0; + * exports.foo = "bar"; + * ``` + * @param {Expression} expr expression + * @returns {Expression | undefined} returns the value of property descriptor + */ +const getValueOfPropertyDescription = (expr) => { + if (expr.type !== "ObjectExpression") return; + for (const property of expr.properties) { + if (property.type === "SpreadElement" || property.computed) continue; + const key = property.key; + if (key.type !== "Identifier" || key.name !== "value") continue; + return /** @type {Expression} */ (property.value); + } +}; + +/** + * The purpose of this function is to check whether an expression is a truthy literal or not. This is + * useful when parsing CommonJS exports, because CommonJS modules can export any value, including falsy + * values like `null` and `false`. However, exports should only be created if the exported value is truthy. + * @param {Expression} expr expression being checked + * @returns {boolean} true, when the expression is a truthy literal + */ +const isTruthyLiteral = (expr) => { + switch (expr.type) { + case "Literal": + return Boolean(expr.value); + case "UnaryExpression": + if (expr.operator === "!") return isFalsyLiteral(expr.argument); + } + return false; +}; + +/** + * The purpose of this function is to check whether an expression is a falsy literal or not. This is + * useful when parsing CommonJS exports, because CommonJS modules can export any value, including falsy + * values like `null` and `false`. However, exports should only be created if the exported value is truthy. + * @param {Expression} expr expression being checked + * @returns {boolean} true, when the expression is a falsy literal + */ +const isFalsyLiteral = (expr) => { + switch (expr.type) { + case "Literal": + return !expr.value; + case "UnaryExpression": + if (expr.operator === "!") return isTruthyLiteral(expr.argument); + } + return false; +}; + +/** + * @param {JavascriptParser} parser the parser + * @param {Expression} expr expression + * @returns {{ argument: BasicEvaluatedExpression, ids: string[] } | undefined} parsed call + */ +const parseRequireCall = (parser, expr) => { + const ids = []; + while (expr.type === "MemberExpression") { + if (expr.object.type === "Super") return; + if (!expr.property) return; + const prop = expr.property; + if (expr.computed) { + if (prop.type !== "Literal") return; + ids.push(`${prop.value}`); + } else { + if (prop.type !== "Identifier") return; + ids.push(prop.name); + } + expr = expr.object; + } + if (expr.type !== "CallExpression" || expr.arguments.length !== 1) return; + const callee = expr.callee; + if ( + callee.type !== "Identifier" || + parser.getVariableInfo(callee.name) !== "require" + ) { + return; + } + const arg = expr.arguments[0]; + if (arg.type === "SpreadElement") return; + const argValue = parser.evaluateExpression(arg); + return { argument: argValue, ids: ids.reverse() }; +}; + +const PLUGIN_NAME = "CommonJsExportsParserPlugin"; + +class CommonJsExportsParserPlugin { + /** + * @param {ModuleGraph} moduleGraph module graph + */ + constructor(moduleGraph) { + this.moduleGraph = moduleGraph; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + const enableStructuredExports = () => { + DynamicExports.enable(parser.state); + }; + + /** + * @param {boolean} topLevel true, when the export is on top level + * @param {string[]} members members of the export + * @param {Expression | undefined} valueExpr expression for the value + * @returns {void} + */ + const checkNamespace = (topLevel, members, valueExpr) => { + if (!DynamicExports.isEnabled(parser.state)) return; + if (members.length > 0 && members[0] === "__esModule") { + if (valueExpr && isTruthyLiteral(valueExpr) && topLevel) { + DynamicExports.setFlagged(parser.state); + } else { + DynamicExports.setDynamic(parser.state); + } + } + }; + /** + * @param {string=} reason reason + */ + const bailout = (reason) => { + DynamicExports.bailout(parser.state); + if (reason) bailoutHint(reason); + }; + /** + * @param {string} reason reason + */ + const bailoutHint = (reason) => { + this.moduleGraph + .getOptimizationBailout(parser.state.module) + .push(`CommonJS bailout: ${reason}`); + }; + + // metadata // + parser.hooks.evaluateTypeof + .for("module") + .tap(PLUGIN_NAME, evaluateToString("object")); + parser.hooks.evaluateTypeof + .for("exports") + .tap(PLUGIN_NAME, evaluateToString("object")); + + // exporting // + + /** + * @param {AssignmentExpression} expr expression + * @param {CommonJSDependencyBaseKeywords} base commonjs base keywords + * @param {string[]} members members of the export + * @returns {boolean | undefined} true, when the expression was handled + */ + const handleAssignExport = (expr, base, members) => { + if (HarmonyExports.isEnabled(parser.state)) return; + // Handle reexporting + const requireCall = parseRequireCall(parser, expr.right); + if ( + requireCall && + requireCall.argument.isString() && + (members.length === 0 || members[0] !== "__esModule") + ) { + enableStructuredExports(); + // It's possible to reexport __esModule, so we must convert to a dynamic module + if (members.length === 0) DynamicExports.setDynamic(parser.state); + const dep = new CommonJsExportRequireDependency( + /** @type {Range} */ (expr.range), + null, + base, + members, + /** @type {string} */ (requireCall.argument.string), + requireCall.ids, + !parser.isStatementLevelExpression(expr) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.module.addDependency(dep); + return true; + } + if (members.length === 0) return; + enableStructuredExports(); + const remainingMembers = members; + checkNamespace( + /** @type {StatementPath} */ + (parser.statementPath).length === 1 && + parser.isStatementLevelExpression(expr), + remainingMembers, + expr.right + ); + const dep = new CommonJsExportsDependency( + /** @type {Range} */ (expr.left.range), + null, + base, + remainingMembers + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + parser.walkExpression(expr.right); + return true; + }; + parser.hooks.assignMemberChain + .for("exports") + .tap(PLUGIN_NAME, (expr, members) => + handleAssignExport(expr, "exports", members) + ); + parser.hooks.assignMemberChain + .for("this") + .tap(PLUGIN_NAME, (expr, members) => { + if (!parser.scope.topLevelScope) return; + return handleAssignExport(expr, "this", members); + }); + parser.hooks.assignMemberChain + .for("module") + .tap(PLUGIN_NAME, (expr, members) => { + if (members[0] !== "exports") return; + return handleAssignExport(expr, "module.exports", members.slice(1)); + }); + parser.hooks.call + .for("Object.defineProperty") + .tap(PLUGIN_NAME, (expression) => { + const expr = /** @type {CallExpression} */ (expression); + if (!parser.isStatementLevelExpression(expr)) return; + if (expr.arguments.length !== 3) return; + if (expr.arguments[0].type === "SpreadElement") return; + if (expr.arguments[1].type === "SpreadElement") return; + if (expr.arguments[2].type === "SpreadElement") return; + const exportsArg = parser.evaluateExpression(expr.arguments[0]); + if (!exportsArg.isIdentifier()) return; + if ( + exportsArg.identifier !== "exports" && + exportsArg.identifier !== "module.exports" && + (exportsArg.identifier !== "this" || !parser.scope.topLevelScope) + ) { + return; + } + const propertyArg = parser.evaluateExpression(expr.arguments[1]); + const property = propertyArg.asString(); + if (typeof property !== "string") return; + enableStructuredExports(); + const descArg = expr.arguments[2]; + checkNamespace( + /** @type {StatementPath} */ + (parser.statementPath).length === 1, + [property], + getValueOfPropertyDescription(descArg) + ); + const dep = new CommonJsExportsDependency( + /** @type {Range} */ (expr.range), + /** @type {Range} */ (expr.arguments[2].range), + `Object.defineProperty(${exportsArg.identifier})`, + [property] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + + parser.walkExpression(expr.arguments[2]); + return true; + }); + + // Self reference // + + /** + * @param {Expression | Super} expr expression + * @param {CommonJSDependencyBaseKeywords} base commonjs base keywords + * @param {string[]} members members of the export + * @param {CallExpression=} call call expression + * @returns {boolean | void} true, when the expression was handled + */ + const handleAccessExport = (expr, base, members, call) => { + if (HarmonyExports.isEnabled(parser.state)) return; + if (members.length === 0) { + bailout( + `${base} is used directly at ${formatLocation( + /** @type {DependencyLocation} */ (expr.loc) + )}` + ); + } + if (call && members.length === 1) { + bailoutHint( + `${base}${propertyAccess( + members + )}(...) prevents optimization as ${base} is passed as call context at ${formatLocation( + /** @type {DependencyLocation} */ (expr.loc) + )}` + ); + } + const dep = new CommonJsSelfReferenceDependency( + /** @type {Range} */ (expr.range), + base, + members, + Boolean(call) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + if (call) { + parser.walkExpressions(call.arguments); + } + return true; + }; + parser.hooks.callMemberChain + .for("exports") + .tap(PLUGIN_NAME, (expr, members) => + handleAccessExport(expr.callee, "exports", members, expr) + ); + parser.hooks.expressionMemberChain + .for("exports") + .tap(PLUGIN_NAME, (expr, members) => + handleAccessExport(expr, "exports", members) + ); + parser.hooks.expression + .for("exports") + .tap(PLUGIN_NAME, (expr) => handleAccessExport(expr, "exports", [])); + parser.hooks.callMemberChain + .for("module") + .tap(PLUGIN_NAME, (expr, members) => { + if (members[0] !== "exports") return; + return handleAccessExport( + expr.callee, + "module.exports", + members.slice(1), + expr + ); + }); + parser.hooks.expressionMemberChain + .for("module") + .tap(PLUGIN_NAME, (expr, members) => { + if (members[0] !== "exports") return; + return handleAccessExport(expr, "module.exports", members.slice(1)); + }); + parser.hooks.expression + .for("module.exports") + .tap(PLUGIN_NAME, (expr) => + handleAccessExport(expr, "module.exports", []) + ); + parser.hooks.callMemberChain + .for("this") + .tap(PLUGIN_NAME, (expr, members) => { + if (!parser.scope.topLevelScope) return; + return handleAccessExport(expr.callee, "this", members, expr); + }); + parser.hooks.expressionMemberChain + .for("this") + .tap(PLUGIN_NAME, (expr, members) => { + if (!parser.scope.topLevelScope) return; + return handleAccessExport(expr, "this", members); + }); + parser.hooks.expression.for("this").tap(PLUGIN_NAME, (expr) => { + if (!parser.scope.topLevelScope) return; + return handleAccessExport(expr, "this", []); + }); + + // Bailouts // + parser.hooks.expression.for("module").tap(PLUGIN_NAME, (expr) => { + bailout(); + const isHarmony = HarmonyExports.isEnabled(parser.state); + const dep = new ModuleDecoratorDependency( + isHarmony + ? RuntimeGlobals.harmonyModuleDecorator + : RuntimeGlobals.nodeModuleDecorator, + !isHarmony + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + return true; + }); + } +} + +module.exports = CommonJsExportsParserPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsFullRequireDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsFullRequireDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..98b3b4cb1fa25120ec86ab89dd7c89ca55dee6d6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsFullRequireDependency.js @@ -0,0 +1,158 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Template = require("../Template"); +const { equals } = require("../util/ArrayHelpers"); +const { getTrimmedIdsAndRange } = require("../util/chainedImports"); +const makeSerializable = require("../util/makeSerializable"); +const propertyAccess = require("../util/propertyAccess"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class CommonJsFullRequireDependency extends ModuleDependency { + /** + * @param {string} request the request string + * @param {Range} range location in source code + * @param {string[]} names accessed properties on module + * @param {Range[]=} idRanges ranges for members of ids; the two arrays are right-aligned + */ + constructor( + request, + range, + names, + idRanges /* TODO webpack 6 make this non-optional. It must always be set to properly trim ids. */ + ) { + super(request); + this.range = range; + this.names = names; + this.idRanges = idRanges; + this.call = false; + this.asiSafe = undefined; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + if (this.call) { + const importedModule = moduleGraph.getModule(this); + if ( + !importedModule || + importedModule.getExportsType(moduleGraph, false) !== "namespace" + ) { + return [this.names.slice(0, -1)]; + } + } + return [this.names]; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.names); + write(this.idRanges); + write(this.call); + write(this.asiSafe); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.names = read(); + this.idRanges = read(); + this.call = read(); + this.asiSafe = read(); + super.deserialize(context); + } + + get type() { + return "cjs full require"; + } + + get category() { + return "commonjs"; + } +} + +CommonJsFullRequireDependency.Template = class CommonJsFullRequireDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements, runtime } + ) { + const dep = /** @type {CommonJsFullRequireDependency} */ (dependency); + if (!dep.range) return; + const importedModule = moduleGraph.getModule(dep); + let requireExpr = runtimeTemplate.moduleExports({ + module: importedModule, + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); + + const { + trimmedRange: [trimmedRangeStart, trimmedRangeEnd], + trimmedIds + } = getTrimmedIdsAndRange( + dep.names, + dep.range, + dep.idRanges, + moduleGraph, + dep + ); + + if (importedModule) { + const usedImported = moduleGraph + .getExportsInfo(importedModule) + .getUsedName(trimmedIds, runtime); + if (usedImported) { + const comment = equals(usedImported, trimmedIds) + ? "" + : `${Template.toNormalComment(propertyAccess(trimmedIds))} `; + const access = `${comment}${propertyAccess(usedImported)}`; + requireExpr = + dep.asiSafe === true + ? `(${requireExpr}${access})` + : `${requireExpr}${access}`; + } + } + source.replace(trimmedRangeStart, trimmedRangeEnd - 1, requireExpr); + } +}; + +makeSerializable( + CommonJsFullRequireDependency, + "webpack/lib/dependencies/CommonJsFullRequireDependency" +); + +module.exports = CommonJsFullRequireDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsImportsParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsImportsParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9bb81115c81d485b20b17a9890415b61f7ebcdda --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsImportsParserPlugin.js @@ -0,0 +1,802 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { fileURLToPath } = require("url"); +const CommentCompilationWarning = require("../CommentCompilationWarning"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); +const WebpackError = require("../WebpackError"); +const BasicEvaluatedExpression = require("../javascript/BasicEvaluatedExpression"); +const { VariableInfo } = require("../javascript/JavascriptParser"); +const { + evaluateToIdentifier, + evaluateToString, + expressionIsUnsupported, + toConstantDependency +} = require("../javascript/JavascriptParserHelpers"); +const CommonJsFullRequireDependency = require("./CommonJsFullRequireDependency"); +const CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency"); +const CommonJsRequireDependency = require("./CommonJsRequireDependency"); +const ConstDependency = require("./ConstDependency"); +const ContextDependencyHelpers = require("./ContextDependencyHelpers"); +const LocalModuleDependency = require("./LocalModuleDependency"); +const { getLocalModule } = require("./LocalModulesHelpers"); +const RequireHeaderDependency = require("./RequireHeaderDependency"); +const RequireResolveContextDependency = require("./RequireResolveContextDependency"); +const RequireResolveDependency = require("./RequireResolveDependency"); +const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency"); + +/** @typedef {import("estree").CallExpression} CallExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").NewExpression} NewExpression */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").ImportSource} ImportSource */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const createRequireSpecifierTag = Symbol("createRequire"); +const createdRequireIdentifierTag = Symbol("createRequire()"); + +const PLUGIN_NAME = "CommonJsImportsParserPlugin"; + +class CommonJsImportsParserPlugin { + /** + * @param {JavascriptParserOptions} options parser options + */ + constructor(options) { + this.options = options; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + const options = this.options; + + const getContext = () => { + if (parser.currentTagData) { + const { context } = parser.currentTagData; + return context; + } + }; + + // #region metadata + /** + * @param {string} expression expression + * @param {() => string[]} getMembers get members + */ + const tapRequireExpression = (expression, getMembers) => { + parser.hooks.typeof + .for(expression) + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for(expression) + .tap(PLUGIN_NAME, evaluateToString("function")); + parser.hooks.evaluateIdentifier + .for(expression) + .tap( + PLUGIN_NAME, + evaluateToIdentifier(expression, "require", getMembers, true) + ); + }; + /** + * @param {string | symbol} tag tag + */ + const tapRequireExpressionTag = (tag) => { + parser.hooks.typeof + .for(tag) + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for(tag) + .tap(PLUGIN_NAME, evaluateToString("function")); + }; + tapRequireExpression("require", () => []); + tapRequireExpression("require.resolve", () => ["resolve"]); + tapRequireExpression("require.resolveWeak", () => ["resolveWeak"]); + // #endregion + + // Weird stuff // + parser.hooks.assign.for("require").tap(PLUGIN_NAME, (expr) => { + // to not leak to global "require", we need to define a local require here. + const dep = new ConstDependency("var require;", 0); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + // #region Unsupported + parser.hooks.expression + .for("require.main") + .tap( + PLUGIN_NAME, + expressionIsUnsupported( + parser, + "require.main is not supported by webpack." + ) + ); + parser.hooks.call + .for("require.main.require") + .tap( + PLUGIN_NAME, + expressionIsUnsupported( + parser, + "require.main.require is not supported by webpack." + ) + ); + parser.hooks.expression + .for("module.parent.require") + .tap( + PLUGIN_NAME, + expressionIsUnsupported( + parser, + "module.parent.require is not supported by webpack." + ) + ); + parser.hooks.call + .for("module.parent.require") + .tap( + PLUGIN_NAME, + expressionIsUnsupported( + parser, + "module.parent.require is not supported by webpack." + ) + ); + // #endregion + + // #region Renaming + /** + * @param {Expression} expr expression + * @returns {boolean} true when set undefined + */ + const defineUndefined = (expr) => { + // To avoid "not defined" error, replace the value with undefined + const dep = new ConstDependency( + "undefined", + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return false; + }; + parser.hooks.canRename.for("require").tap(PLUGIN_NAME, () => true); + parser.hooks.rename.for("require").tap(PLUGIN_NAME, defineUndefined); + // #endregion + + // #region Inspection + const requireCache = toConstantDependency( + parser, + RuntimeGlobals.moduleCache, + [ + RuntimeGlobals.moduleCache, + RuntimeGlobals.moduleId, + RuntimeGlobals.moduleLoaded + ] + ); + + parser.hooks.expression.for("require.cache").tap(PLUGIN_NAME, requireCache); + // #endregion + + // #region Require as expression + /** + * @param {Expression} expr expression + * @returns {boolean} true when handled + */ + const requireAsExpressionHandler = (expr) => { + const dep = new CommonJsRequireContextDependency( + { + request: /** @type {string} */ (options.unknownContextRequest), + recursive: /** @type {boolean} */ (options.unknownContextRecursive), + regExp: /** @type {RegExp} */ (options.unknownContextRegExp), + mode: "sync" + }, + /** @type {Range} */ (expr.range), + undefined, + parser.scope.inShorthand, + getContext() + ); + dep.critical = + options.unknownContextCritical && + "require function is used in a way in which dependencies cannot be statically extracted"; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + }; + parser.hooks.expression + .for("require") + .tap(PLUGIN_NAME, requireAsExpressionHandler); + // #endregion + + // #region Require + /** + * @param {CallExpression | NewExpression} expr expression + * @param {BasicEvaluatedExpression} param param + * @returns {boolean | void} true when handled + */ + const processRequireItem = (expr, param) => { + if (param.isString()) { + const dep = new CommonJsRequireDependency( + /** @type {string} */ (param.string), + /** @type {Range} */ (param.range), + getContext() + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + } + }; + /** + * @param {CallExpression | NewExpression} expr expression + * @param {BasicEvaluatedExpression} param param + * @returns {boolean | void} true when handled + */ + const processRequireContext = (expr, param) => { + const dep = ContextDependencyHelpers.create( + CommonJsRequireContextDependency, + /** @type {Range} */ (expr.range), + param, + expr, + options, + { + category: "commonjs" + }, + parser, + undefined, + getContext() + ); + if (!dep) return; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + }; + /** + * @param {boolean} callNew true, when require is called with new + * @returns {(expr: CallExpression | NewExpression) => (boolean | void)} handler + */ + const createRequireHandler = (callNew) => (expr) => { + if (options.commonjsMagicComments) { + const { options: requireOptions, errors: commentErrors } = + parser.parseCommentOptions(/** @type {Range} */ (expr.range)); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + /** @type {DependencyLocation} */ (comment.loc) + ) + ); + } + } + if (requireOptions && requireOptions.webpackIgnore !== undefined) { + if (typeof requireOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${requireOptions.webpackIgnore}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else if (requireOptions.webpackIgnore) { + // Do not instrument `require()` if `webpackIgnore` is `true` + return true; + } + } + } + + if (expr.arguments.length !== 1) return; + let localModule; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + let isExpression = false; + for (const p of /** @type {BasicEvaluatedExpression[]} */ ( + param.options + )) { + const result = processRequireItem(expr, p); + if (result === undefined) { + isExpression = true; + } + } + if (!isExpression) { + const dep = new RequireHeaderDependency( + /** @type {Range} */ (expr.callee.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + if ( + param.isString() && + (localModule = getLocalModule( + parser.state, + /** @type {string} */ (param.string) + )) + ) { + localModule.flagUsed(); + const dep = new LocalModuleDependency( + localModule, + /** @type {Range} */ (expr.range), + callNew + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + } else { + const result = processRequireItem(expr, param); + if (result === undefined) { + processRequireContext(expr, param); + } else { + const dep = new RequireHeaderDependency( + /** @type {Range} */ (expr.callee.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + } + } + return true; + }; + parser.hooks.call + .for("require") + .tap(PLUGIN_NAME, createRequireHandler(false)); + parser.hooks.new + .for("require") + .tap(PLUGIN_NAME, createRequireHandler(true)); + parser.hooks.call + .for("module.require") + .tap(PLUGIN_NAME, createRequireHandler(false)); + parser.hooks.new + .for("module.require") + .tap(PLUGIN_NAME, createRequireHandler(true)); + // #endregion + + // #region Require with property access + /** + * @param {Expression} expr expression + * @param {string[]} calleeMembers callee members + * @param {CallExpression} callExpr call expression + * @param {string[]} members members + * @param {Range[]} memberRanges member ranges + * @returns {boolean | void} true when handled + */ + const chainHandler = ( + expr, + calleeMembers, + callExpr, + members, + memberRanges + ) => { + if (callExpr.arguments.length !== 1) return; + const param = parser.evaluateExpression(callExpr.arguments[0]); + if ( + param.isString() && + !getLocalModule(parser.state, /** @type {string} */ (param.string)) + ) { + const dep = new CommonJsFullRequireDependency( + /** @type {string} */ (param.string), + /** @type {Range} */ (expr.range), + members, + /** @type {Range[]} */ memberRanges + ); + dep.asiSafe = !parser.isAsiPosition( + /** @type {Range} */ (expr.range)[0] + ); + dep.optional = Boolean(parser.scope.inTry); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.current.addDependency(dep); + return true; + } + }; + /** + * @param {CallExpression} expr expression + * @param {string[]} calleeMembers callee members + * @param {CallExpression} callExpr call expression + * @param {string[]} members members + * @param {Range[]} memberRanges member ranges + * @returns {boolean | void} true when handled + */ + const callChainHandler = ( + expr, + calleeMembers, + callExpr, + members, + memberRanges + ) => { + if (callExpr.arguments.length !== 1) return; + const param = parser.evaluateExpression(callExpr.arguments[0]); + if ( + param.isString() && + !getLocalModule(parser.state, /** @type {string} */ (param.string)) + ) { + const dep = new CommonJsFullRequireDependency( + /** @type {string} */ (param.string), + /** @type {Range} */ (expr.callee.range), + members, + /** @type {Range[]} */ memberRanges + ); + dep.call = true; + dep.asiSafe = !parser.isAsiPosition( + /** @type {Range} */ (expr.range)[0] + ); + dep.optional = Boolean(parser.scope.inTry); + dep.loc = /** @type {DependencyLocation} */ (expr.callee.loc); + parser.state.current.addDependency(dep); + parser.walkExpressions(expr.arguments); + return true; + } + }; + parser.hooks.memberChainOfCallMemberChain + .for("require") + .tap(PLUGIN_NAME, chainHandler); + parser.hooks.memberChainOfCallMemberChain + .for("module.require") + .tap(PLUGIN_NAME, chainHandler); + parser.hooks.callMemberChainOfCallMemberChain + .for("require") + .tap(PLUGIN_NAME, callChainHandler); + parser.hooks.callMemberChainOfCallMemberChain + .for("module.require") + .tap(PLUGIN_NAME, callChainHandler); + // #endregion + + // #region Require.resolve + /** + * @param {CallExpression} expr call expression + * @param {boolean} weak weak + * @returns {boolean | void} true when handled + */ + const processResolve = (expr, weak) => { + if (!weak && options.commonjsMagicComments) { + const { options: requireOptions, errors: commentErrors } = + parser.parseCommentOptions(/** @type {Range} */ (expr.range)); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + /** @type {DependencyLocation} */ (comment.loc) + ) + ); + } + } + if (requireOptions && requireOptions.webpackIgnore !== undefined) { + if (typeof requireOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${requireOptions.webpackIgnore}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else if (requireOptions.webpackIgnore) { + // Do not instrument `require()` if `webpackIgnore` is `true` + return true; + } + } + } + + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + for (const option of /** @type {BasicEvaluatedExpression[]} */ ( + param.options + )) { + const result = processResolveItem(expr, option, weak); + if (result === undefined) { + processResolveContext(expr, option, weak); + } + } + const dep = new RequireResolveHeaderDependency( + /** @type {Range} */ (expr.callee.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + } + const result = processResolveItem(expr, param, weak); + if (result === undefined) { + processResolveContext(expr, param, weak); + } + const dep = new RequireResolveHeaderDependency( + /** @type {Range} */ (expr.callee.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }; + /** + * @param {CallExpression} expr call expression + * @param {BasicEvaluatedExpression} param param + * @param {boolean} weak weak + * @returns {boolean | void} true when handled + */ + const processResolveItem = (expr, param, weak) => { + if (param.isString()) { + const dep = new RequireResolveDependency( + /** @type {string} */ (param.string), + /** @type {Range} */ (param.range), + getContext() + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + dep.weak = weak; + parser.state.current.addDependency(dep); + return true; + } + }; + /** + * @param {CallExpression} expr call expression + * @param {BasicEvaluatedExpression} param param + * @param {boolean} weak weak + * @returns {boolean | void} true when handled + */ + const processResolveContext = (expr, param, weak) => { + const dep = ContextDependencyHelpers.create( + RequireResolveContextDependency, + /** @type {Range} */ (param.range), + param, + expr, + options, + { + category: "commonjs", + mode: weak ? "weak" : "sync" + }, + parser, + getContext() + ); + if (!dep) return; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + }; + + parser.hooks.call + .for("require.resolve") + .tap(PLUGIN_NAME, (expr) => processResolve(expr, false)); + parser.hooks.call + .for("require.resolveWeak") + .tap(PLUGIN_NAME, (expr) => processResolve(expr, true)); + // #endregion + + // #region Create require + + if (!options.createRequire) return; + + /** @type {ImportSource[]} */ + let moduleName = []; + /** @type {string | undefined} */ + let specifierName; + + if (options.createRequire === true) { + moduleName = ["module", "node:module"]; + specifierName = "createRequire"; + } else { + let moduleName; + const match = /^(.*) from (.*)$/.exec(options.createRequire); + if (match) { + [, specifierName, moduleName] = match; + } + if (!specifierName || !moduleName) { + const err = new WebpackError( + `Parsing javascript parser option "createRequire" failed, got ${JSON.stringify( + options.createRequire + )}` + ); + err.details = + 'Expected string in format "createRequire from module", where "createRequire" is specifier name and "module" name of the module'; + throw err; + } + } + + tapRequireExpressionTag(createdRequireIdentifierTag); + tapRequireExpressionTag(createRequireSpecifierTag); + parser.hooks.evaluateCallExpression + .for(createRequireSpecifierTag) + .tap(PLUGIN_NAME, (expr) => { + const context = parseCreateRequireArguments(expr); + if (context === undefined) return; + const ident = parser.evaluatedVariable({ + tag: createdRequireIdentifierTag, + data: { context }, + next: undefined + }); + + return new BasicEvaluatedExpression() + .setIdentifier(ident, ident, () => []) + .setSideEffects(false) + .setRange(/** @type {Range} */ (expr.range)); + }); + parser.hooks.unhandledExpressionMemberChain + .for(createdRequireIdentifierTag) + .tap(PLUGIN_NAME, (expr, members) => + expressionIsUnsupported( + parser, + `createRequire().${members.join(".")} is not supported by webpack.` + )(expr) + ); + parser.hooks.canRename + .for(createdRequireIdentifierTag) + .tap(PLUGIN_NAME, () => true); + parser.hooks.canRename + .for(createRequireSpecifierTag) + .tap(PLUGIN_NAME, () => true); + parser.hooks.rename + .for(createRequireSpecifierTag) + .tap(PLUGIN_NAME, defineUndefined); + parser.hooks.expression + .for(createdRequireIdentifierTag) + .tap(PLUGIN_NAME, requireAsExpressionHandler); + parser.hooks.call + .for(createdRequireIdentifierTag) + .tap(PLUGIN_NAME, createRequireHandler(false)); + /** + * @param {CallExpression} expr call expression + * @returns {string | void} context + */ + const parseCreateRequireArguments = (expr) => { + const args = expr.arguments; + if (args.length !== 1) { + const err = new WebpackError( + "module.createRequire supports only one argument." + ); + err.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addWarning(err); + return; + } + const arg = args[0]; + const evaluated = parser.evaluateExpression(arg); + if (!evaluated.isString()) { + const err = new WebpackError( + "module.createRequire failed parsing argument." + ); + err.loc = /** @type {DependencyLocation} */ (arg.loc); + parser.state.module.addWarning(err); + return; + } + const ctx = /** @type {string} */ (evaluated.string).startsWith("file://") + ? fileURLToPath(/** @type {string} */ (evaluated.string)) + : /** @type {string} */ (evaluated.string); + // argument always should be a filename + return ctx.slice(0, ctx.lastIndexOf(ctx.startsWith("/") ? "/" : "\\")); + }; + + parser.hooks.import.tap( + { + name: PLUGIN_NAME, + stage: -10 + }, + (statement, source) => { + if ( + !moduleName.includes(source) || + statement.specifiers.length !== 1 || + statement.specifiers[0].type !== "ImportSpecifier" || + statement.specifiers[0].imported.type !== "Identifier" || + statement.specifiers[0].imported.name !== specifierName + ) { + return; + } + // clear for 'import { createRequire as x } from "module"' + // if any other specifier was used import module + const clearDep = new ConstDependency( + parser.isAsiPosition(/** @type {Range} */ (statement.range)[0]) + ? ";" + : "", + /** @type {Range} */ (statement.range) + ); + clearDep.loc = /** @type {DependencyLocation} */ (statement.loc); + parser.state.module.addPresentationalDependency(clearDep); + parser.unsetAsiPosition(/** @type {Range} */ (statement.range)[1]); + return true; + } + ); + parser.hooks.importSpecifier.tap( + { + name: PLUGIN_NAME, + stage: -10 + }, + (statement, source, id, name) => { + if (!moduleName.includes(source) || id !== specifierName) return; + parser.tagVariable(name, createRequireSpecifierTag); + return true; + } + ); + parser.hooks.preDeclarator.tap(PLUGIN_NAME, (declarator) => { + if ( + declarator.id.type !== "Identifier" || + !declarator.init || + declarator.init.type !== "CallExpression" || + declarator.init.callee.type !== "Identifier" + ) { + return; + } + const variableInfo = parser.getVariableInfo(declarator.init.callee.name); + if ( + variableInfo instanceof VariableInfo && + variableInfo.tagInfo && + variableInfo.tagInfo.tag === createRequireSpecifierTag + ) { + const context = parseCreateRequireArguments(declarator.init); + if (context === undefined) return; + parser.tagVariable(declarator.id.name, createdRequireIdentifierTag, { + name: declarator.id.name, + context + }); + return true; + } + }); + + parser.hooks.memberChainOfCallMemberChain + .for(createRequireSpecifierTag) + .tap(PLUGIN_NAME, (expr, calleeMembers, callExpr, members) => { + if ( + calleeMembers.length !== 0 || + members.length !== 1 || + members[0] !== "cache" + ) { + return; + } + // createRequire().cache + const context = parseCreateRequireArguments(callExpr); + if (context === undefined) return; + return requireCache(expr); + }); + parser.hooks.callMemberChainOfCallMemberChain + .for(createRequireSpecifierTag) + .tap(PLUGIN_NAME, (expr, calleeMembers, innerCallExpression, members) => { + if ( + calleeMembers.length !== 0 || + members.length !== 1 || + members[0] !== "resolve" + ) { + return; + } + // createRequire().resolve() + return processResolve(expr, false); + }); + parser.hooks.expressionMemberChain + .for(createdRequireIdentifierTag) + .tap(PLUGIN_NAME, (expr, members) => { + // require.cache + if (members.length === 1 && members[0] === "cache") { + return requireCache(expr); + } + }); + parser.hooks.callMemberChain + .for(createdRequireIdentifierTag) + .tap(PLUGIN_NAME, (expr, members) => { + // require.resolve() + if (members.length === 1 && members[0] === "resolve") { + return processResolve(expr, false); + } + }); + parser.hooks.call + .for(createRequireSpecifierTag) + .tap(PLUGIN_NAME, (expr) => { + const clearDep = new ConstDependency( + "/* createRequire() */ undefined", + /** @type {Range} */ (expr.range) + ); + clearDep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(clearDep); + return true; + }); + // #endregion + } +} + +module.exports = CommonJsImportsParserPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..194a16c77e52bb1f1a235143ab55e69420bba8a5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsPlugin.js @@ -0,0 +1,304 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC +} = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const SelfModuleFactory = require("../SelfModuleFactory"); +const Template = require("../Template"); +const { + evaluateToIdentifier, + toConstantDependency +} = require("../javascript/JavascriptParserHelpers"); +const CommonJsExportRequireDependency = require("./CommonJsExportRequireDependency"); +const CommonJsExportsDependency = require("./CommonJsExportsDependency"); +const CommonJsExportsParserPlugin = require("./CommonJsExportsParserPlugin"); +const CommonJsFullRequireDependency = require("./CommonJsFullRequireDependency"); +const CommonJsImportsParserPlugin = require("./CommonJsImportsParserPlugin"); +const CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency"); +const CommonJsRequireDependency = require("./CommonJsRequireDependency"); +const CommonJsSelfReferenceDependency = require("./CommonJsSelfReferenceDependency"); +const ModuleDecoratorDependency = require("./ModuleDecoratorDependency"); +const RequireHeaderDependency = require("./RequireHeaderDependency"); +const RequireResolveContextDependency = require("./RequireResolveContextDependency"); +const RequireResolveDependency = require("./RequireResolveDependency"); +const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency"); +const RuntimeRequirementsDependency = require("./RuntimeRequirementsDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ + +const PLUGIN_NAME = "CommonJsPlugin"; + +class CommonJsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + CommonJsRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireDependency, + new CommonJsRequireDependency.Template() + ); + + compilation.dependencyFactories.set( + CommonJsFullRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsFullRequireDependency, + new CommonJsFullRequireDependency.Template() + ); + + compilation.dependencyFactories.set( + CommonJsRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireContextDependency, + new CommonJsRequireContextDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireResolveDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveDependency, + new RequireResolveDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireResolveContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveContextDependency, + new RequireResolveContextDependency.Template() + ); + + compilation.dependencyTemplates.set( + RequireResolveHeaderDependency, + new RequireResolveHeaderDependency.Template() + ); + + compilation.dependencyTemplates.set( + RequireHeaderDependency, + new RequireHeaderDependency.Template() + ); + + compilation.dependencyTemplates.set( + CommonJsExportsDependency, + new CommonJsExportsDependency.Template() + ); + + compilation.dependencyFactories.set( + CommonJsExportRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsExportRequireDependency, + new CommonJsExportRequireDependency.Template() + ); + + const selfFactory = new SelfModuleFactory(compilation.moduleGraph); + + compilation.dependencyFactories.set( + CommonJsSelfReferenceDependency, + selfFactory + ); + compilation.dependencyTemplates.set( + CommonJsSelfReferenceDependency, + new CommonJsSelfReferenceDependency.Template() + ); + + compilation.dependencyFactories.set( + ModuleDecoratorDependency, + selfFactory + ); + compilation.dependencyTemplates.set( + ModuleDecoratorDependency, + new ModuleDecoratorDependency.Template() + ); + + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.harmonyModuleDecorator) + .tap(PLUGIN_NAME, (module, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.requireScope); + }); + + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.nodeModuleDecorator) + .tap(PLUGIN_NAME, (module, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.requireScope); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.harmonyModuleDecorator) + .tap(PLUGIN_NAME, (chunk, _set) => { + compilation.addRuntimeModule( + chunk, + new HarmonyModuleDecoratorRuntimeModule() + ); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.nodeModuleDecorator) + .tap(PLUGIN_NAME, (chunk, _set) => { + compilation.addRuntimeModule( + chunk, + new NodeModuleDecoratorRuntimeModule() + ); + }); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) { + return; + } + parser.hooks.typeof + .for("module") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("object")) + ); + + parser.hooks.expression + .for("require.main") + .tap( + PLUGIN_NAME, + toConstantDependency( + parser, + `${RuntimeGlobals.moduleCache}[${RuntimeGlobals.entryModuleId}]`, + [RuntimeGlobals.moduleCache, RuntimeGlobals.entryModuleId] + ) + ); + parser.hooks.expression + .for(RuntimeGlobals.moduleLoaded) + .tap(PLUGIN_NAME, (expr) => { + /** @type {BuildInfo} */ + (parser.state.module.buildInfo).moduleConcatenationBailout = + RuntimeGlobals.moduleLoaded; + const dep = new RuntimeRequirementsDependency([ + RuntimeGlobals.moduleLoaded + ]); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + parser.hooks.expression + .for(RuntimeGlobals.moduleId) + .tap(PLUGIN_NAME, (expr) => { + /** @type {BuildInfo} */ + (parser.state.module.buildInfo).moduleConcatenationBailout = + RuntimeGlobals.moduleId; + const dep = new RuntimeRequirementsDependency([ + RuntimeGlobals.moduleId + ]); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + parser.hooks.evaluateIdentifier.for("module.hot").tap( + PLUGIN_NAME, + evaluateToIdentifier("module.hot", "module", () => ["hot"], null) + ); + + new CommonJsImportsParserPlugin(parserOptions).apply(parser); + new CommonJsExportsParserPlugin(compilation.moduleGraph).apply( + parser + ); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +class HarmonyModuleDecoratorRuntimeModule extends RuntimeModule { + constructor() { + super("harmony module decorator"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { runtimeTemplate } = /** @type {Compilation} */ (this.compilation); + return Template.asString([ + `${ + RuntimeGlobals.harmonyModuleDecorator + } = ${runtimeTemplate.basicFunction("module", [ + "module = Object.create(module);", + "if (!module.children) module.children = [];", + "Object.defineProperty(module, 'exports', {", + Template.indent([ + "enumerable: true,", + `set: ${runtimeTemplate.basicFunction("", [ + "throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);" + ])}` + ]), + "});", + "return module;" + ])};` + ]); + } +} + +class NodeModuleDecoratorRuntimeModule extends RuntimeModule { + constructor() { + super("node module decorator"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { runtimeTemplate } = /** @type {Compilation} */ (this.compilation); + return Template.asString([ + `${RuntimeGlobals.nodeModuleDecorator} = ${runtimeTemplate.basicFunction( + "module", + [ + "module.paths = [];", + "if (!module.children) module.children = [];", + "return module;" + ] + )};` + ]); + } +} + +module.exports = CommonJsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsRequireContextDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsRequireContextDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..68f9e66407f7e84c1323b314da04ac1d2a2b3199 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsRequireContextDependency.js @@ -0,0 +1,73 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ContextDependency = require("./ContextDependency"); +const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ + +class CommonJsRequireContextDependency extends ContextDependency { + /** + * @param {ContextDependencyOptions} options options for the context module + * @param {Range} range location in source code + * @param {Range | undefined} valueRange location of the require call + * @param {boolean | string } inShorthand true or name + * @param {string} context context + */ + constructor(options, range, valueRange, inShorthand, context) { + super(options, context); + + this.range = range; + this.valueRange = valueRange; + // inShorthand must be serialized by subclasses that use it + this.inShorthand = inShorthand; + } + + get type() { + return "cjs require context"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.range); + write(this.valueRange); + write(this.inShorthand); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.range = read(); + this.valueRange = read(); + this.inShorthand = read(); + + super.deserialize(context); + } +} + +makeSerializable( + CommonJsRequireContextDependency, + "webpack/lib/dependencies/CommonJsRequireContextDependency" +); + +CommonJsRequireContextDependency.Template = + ContextDependencyTemplateAsRequireCall; + +module.exports = CommonJsRequireContextDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsRequireDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsRequireDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..09545a86e5ee77937c1cb268534629fbc6047097 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsRequireDependency.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +class CommonJsRequireDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {Range=} range location in source code + * @param {string=} context request context + */ + constructor(request, range, context) { + super(request); + this.range = range; + this._context = context; + } + + get type() { + return "cjs require"; + } + + get category() { + return "commonjs"; + } +} + +CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; + +makeSerializable( + CommonJsRequireDependency, + "webpack/lib/dependencies/CommonJsRequireDependency" +); + +module.exports = CommonJsRequireDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsSelfReferenceDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsSelfReferenceDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..b1b368ead67fd005a0be0fa58dc7de66c456302a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CommonJsSelfReferenceDependency.js @@ -0,0 +1,155 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const { equals } = require("../util/ArrayHelpers"); +const makeSerializable = require("../util/makeSerializable"); +const propertyAccess = require("../util/propertyAccess"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */ + +class CommonJsSelfReferenceDependency extends NullDependency { + /** + * @param {Range} range range + * @param {CommonJSDependencyBaseKeywords} base base + * @param {string[]} names names + * @param {boolean} call is a call + */ + constructor(range, base, names, call) { + super(); + this.range = range; + this.base = base; + this.names = names; + this.call = call; + } + + get type() { + return "cjs self exports reference"; + } + + get category() { + return "self"; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return "self"; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + return [this.call ? this.names.slice(0, -1) : this.names]; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + write(this.base); + write(this.names); + write(this.call); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.range = read(); + this.base = read(); + this.names = read(); + this.call = read(); + super.deserialize(context); + } +} + +makeSerializable( + CommonJsSelfReferenceDependency, + "webpack/lib/dependencies/CommonJsSelfReferenceDependency" +); + +CommonJsSelfReferenceDependency.Template = class CommonJsSelfReferenceDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { module, moduleGraph, runtime, runtimeRequirements } + ) { + const dep = /** @type {CommonJsSelfReferenceDependency} */ (dependency); + const used = + dep.names.length === 0 + ? dep.names + : moduleGraph.getExportsInfo(module).getUsedName(dep.names, runtime); + if (!used) { + throw new Error( + "Self-reference dependency has unused export name: This should not happen" + ); + } + + let base; + switch (dep.base) { + case "exports": + runtimeRequirements.add(RuntimeGlobals.exports); + base = module.exportsArgument; + break; + case "module.exports": + runtimeRequirements.add(RuntimeGlobals.module); + base = `${module.moduleArgument}.exports`; + break; + case "this": + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + base = "this"; + break; + default: + throw new Error(`Unsupported base ${dep.base}`); + } + + if (base === dep.base && equals(used, dep.names)) { + // Nothing has to be changed + // We don't use a replacement for compat reasons + // for plugins that update `module._source` which they + // shouldn't do! + return; + } + + source.replace( + dep.range[0], + dep.range[1] - 1, + `${base}${propertyAccess(used)}` + ); + } +}; + +module.exports = CommonJsSelfReferenceDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ConstDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ConstDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..e41acef3accd716ecea4a92592b7ecd025de0f86 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ConstDependency.js @@ -0,0 +1,117 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ + +class ConstDependency extends NullDependency { + /** + * @param {string} expression the expression + * @param {number | Range} range the source range + * @param {(string[] | null)=} runtimeRequirements runtime requirements + */ + constructor(expression, range, runtimeRequirements) { + super(); + this.expression = expression; + this.range = range; + this.runtimeRequirements = runtimeRequirements + ? new Set(runtimeRequirements) + : null; + this._hashUpdate = undefined; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + let hashUpdate = `${this.range}|${this.expression}`; + if (this.runtimeRequirements) { + for (const item of this.runtimeRequirements) { + hashUpdate += "|"; + hashUpdate += item; + } + } + this._hashUpdate = hashUpdate; + } + hash.update(this._hashUpdate); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.expression); + write(this.range); + write(this.runtimeRequirements); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.expression = read(); + this.range = read(); + this.runtimeRequirements = read(); + super.deserialize(context); + } +} + +makeSerializable(ConstDependency, "webpack/lib/dependencies/ConstDependency"); + +ConstDependency.Template = class ConstDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {ConstDependency} */ (dependency); + if (dep.runtimeRequirements) { + for (const req of dep.runtimeRequirements) { + templateContext.runtimeRequirements.add(req); + } + } + if (typeof dep.range === "number") { + source.insert(dep.range, dep.expression); + return; + } + + source.replace(dep.range[0], dep.range[1] - 1, dep.expression); + } +}; + +module.exports = ConstDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..bcec13d18d5399b17e5f706c1db99ef0db2efcfe --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependency.js @@ -0,0 +1,178 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const DependencyTemplate = require("../DependencyTemplate"); +const makeSerializable = require("../util/makeSerializable"); +const memoize = require("../util/memoize"); + +/** @typedef {import("../ContextModule").ContextOptions} ContextOptions */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +const getCriticalDependencyWarning = memoize(() => + require("./CriticalDependencyWarning") +); + +/** @typedef {ContextOptions & { request: string }} ContextDependencyOptions */ + +/** + * @param {RegExp | null | undefined} r regexp + * @returns {string} stringified regexp + */ +const regExpToString = (r) => (r ? String(r) : ""); + +class ContextDependency extends Dependency { + /** + * @param {ContextDependencyOptions} options options for the context module + * @param {string=} context request context + */ + constructor(options, context) { + super(); + + this.options = options; + this.userRequest = this.options && this.options.request; + /** @type {false | undefined | string} */ + this.critical = false; + this.hadGlobalOrStickyRegExp = false; + + if ( + this.options && + (this.options.regExp.global || this.options.regExp.sticky) + ) { + this.options = { ...this.options, regExp: null }; + this.hadGlobalOrStickyRegExp = true; + } + + this.request = undefined; + this.range = undefined; + this.valueRange = undefined; + /** @type {boolean | string | undefined} */ + this.inShorthand = undefined; + // TODO refactor this + this.replaces = undefined; + this._requestContext = context; + } + + /** + * @returns {string | undefined} a request context + */ + getContext() { + return this._requestContext; + } + + get category() { + return "commonjs"; + } + + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return true; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return ( + `context${this._requestContext || ""}|ctx request${ + this.options.request + } ${this.options.recursive} ` + + `${regExpToString(this.options.regExp)} ${regExpToString( + this.options.include + )} ${regExpToString(this.options.exclude)} ` + + `${this.options.mode} ${this.options.chunkName} ` + + `${JSON.stringify(this.options.groupOptions)}` + + `${ + this.options.referencedExports + ? ` ${JSON.stringify(this.options.referencedExports)}` + : "" + }` + ); + } + + /** + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | null | undefined} warnings + */ + getWarnings(moduleGraph) { + let warnings = super.getWarnings(moduleGraph); + + if (this.critical) { + if (!warnings) warnings = []; + const CriticalDependencyWarning = getCriticalDependencyWarning(); + warnings.push(new CriticalDependencyWarning(this.critical)); + } + + if (this.hadGlobalOrStickyRegExp) { + if (!warnings) warnings = []; + const CriticalDependencyWarning = getCriticalDependencyWarning(); + warnings.push( + new CriticalDependencyWarning( + "Contexts can't use RegExps with the 'g' or 'y' flags." + ) + ); + } + + return warnings; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.options); + write(this.userRequest); + write(this.critical); + write(this.hadGlobalOrStickyRegExp); + write(this.request); + write(this._requestContext); + write(this.range); + write(this.valueRange); + write(this.prepend); + write(this.replaces); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.options = read(); + this.userRequest = read(); + this.critical = read(); + this.hadGlobalOrStickyRegExp = read(); + this.request = read(); + this._requestContext = read(); + this.range = read(); + this.valueRange = read(); + this.prepend = read(); + this.replaces = read(); + + super.deserialize(context); + } +} + +makeSerializable( + ContextDependency, + "webpack/lib/dependencies/ContextDependency" +); + +ContextDependency.Template = DependencyTemplate; + +module.exports = ContextDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependencyHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependencyHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..a0e713bff3e5d6461ec32bb64cdeac1b4283775b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependencyHelpers.js @@ -0,0 +1,270 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { parseResource } = require("../util/identifier"); + +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("./ContextDependency")} ContextDependency */ +/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ + +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quoteMeta = (str) => str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); + +/** + * @param {string} prefix prefix + * @returns {{prefix: string, context: string}} result + */ +const splitContextFromPrefix = (prefix) => { + const idx = prefix.lastIndexOf("/"); + let context = "."; + if (idx >= 0) { + context = prefix.slice(0, idx); + prefix = `.${prefix.slice(idx)}`; + } + return { + context, + prefix + }; +}; + +/** @typedef {Partial>} PartialContextDependencyOptions */ +/** @typedef {{ new(options: ContextDependencyOptions, range: Range, valueRange: Range, ...args: any[]): ContextDependency }} ContextDependencyConstructor */ + +/** + * @param {ContextDependencyConstructor} Dep the Dependency class + * @param {Range} range source range + * @param {BasicEvaluatedExpression} param context param + * @param {Expression} expr expr + * @param {Pick} options options for context creation + * @param {PartialContextDependencyOptions} contextOptions options for the ContextModule + * @param {JavascriptParser} parser the parser + * @param {...EXPECTED_ANY} depArgs depArgs + * @returns {ContextDependency} the created Dependency + */ +module.exports.create = ( + Dep, + range, + param, + expr, + options, + contextOptions, + parser, + ...depArgs +) => { + if (param.isTemplateString()) { + const quasis = /** @type {BasicEvaluatedExpression[]} */ (param.quasis); + const prefixRaw = /** @type {string} */ (quasis[0].string); + const postfixRaw = + /** @type {string} */ + (quasis.length > 1 ? quasis[quasis.length - 1].string : ""); + + const valueRange = /** @type {Range} */ (param.range); + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { + path: postfix, + query, + fragment + } = parseResource(postfixRaw, parser); + + // When there are more than two quasis, the generated RegExp can be more precise + // We join the quasis with the expression regexp + const innerQuasis = quasis.slice(1, -1); + const innerRegExp = + /** @type {RegExp} */ (options.wrappedContextRegExp).source + + innerQuasis + .map( + (q) => + quoteMeta(/** @type {string} */ (q.string)) + + /** @type {RegExp} */ (options.wrappedContextRegExp).source + ) + .join(""); + + // Example: `./context/pre${e}inner${e}inner2${e}post?query#frag` + // context: "./context" + // prefix: "./pre" + // innerQuasis: [BEE("inner"), BEE("inner2")] + // (BEE = BasicEvaluatedExpression) + // postfix: "post" + // query: "?query" + // fragment: "#frag" + // regExp: /^\.\/pre.*inner.*inner2.*post$/ + const regExp = new RegExp( + `^${quoteMeta(prefix)}${innerRegExp}${quoteMeta(postfix)}$` + ); + const dep = new Dep( + { + request: context + query + fragment, + recursive: /** @type {boolean} */ (options.wrappedContextRecursive), + regExp, + mode: "sync", + ...contextOptions + }, + range, + valueRange, + ...depArgs + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + + /** @type {{ value: string, range: Range }[]} */ + const replaces = []; + const parts = /** @type {BasicEvaluatedExpression[]} */ (param.parts); + + for (const [i, part] of parts.entries()) { + if (i % 2 === 0) { + // Quasis or merged quasi + let range = /** @type {Range} */ (part.range); + let value = /** @type {string} */ (part.string); + if (param.templateStringKind === "cooked") { + value = JSON.stringify(value); + value = value.slice(1, -1); + } + if (i === 0) { + // prefix + value = prefix; + range = [ + /** @type {Range} */ (param.range)[0], + /** @type {Range} */ (part.range)[1] + ]; + value = + (param.templateStringKind === "cooked" ? "`" : "String.raw`") + + value; + } else if (i === parts.length - 1) { + // postfix + value = postfix; + range = [ + /** @type {Range} */ (part.range)[0], + /** @type {Range} */ (param.range)[1] + ]; + value = `${value}\``; + } else if ( + part.expression && + part.expression.type === "TemplateElement" && + part.expression.value.raw === value + ) { + // Shortcut when it's a single quasi and doesn't need to be replaced + continue; + } + replaces.push({ + range, + value + }); + } else { + // Expression + parser.walkExpression( + /** @type {Expression} */ + (part.expression) + ); + } + } + + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; + return dep; + } else if ( + param.isWrapped() && + ((param.prefix && param.prefix.isString()) || + (param.postfix && param.postfix.isString())) + ) { + const prefixRaw = + /** @type {string} */ + (param.prefix && param.prefix.isString() ? param.prefix.string : ""); + const postfixRaw = + /** @type {string} */ + (param.postfix && param.postfix.isString() ? param.postfix.string : ""); + const prefixRange = + param.prefix && param.prefix.isString() ? param.prefix.range : null; + const postfixRange = + param.postfix && param.postfix.isString() ? param.postfix.range : null; + const valueRange = /** @type {Range} */ (param.range); + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { + path: postfix, + query, + fragment + } = parseResource(postfixRaw, parser); + const regExp = new RegExp( + `^${quoteMeta(prefix)}${ + /** @type {RegExp} */ (options.wrappedContextRegExp).source + }${quoteMeta(postfix)}$` + ); + const dep = new Dep( + { + request: context + query + fragment, + recursive: /** @type {boolean} */ (options.wrappedContextRecursive), + regExp, + mode: "sync", + ...contextOptions + }, + range, + valueRange, + ...depArgs + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + const replaces = []; + if (prefixRange) { + replaces.push({ + range: prefixRange, + value: JSON.stringify(prefix) + }); + } + if (postfixRange) { + replaces.push({ + range: postfixRange, + value: JSON.stringify(postfix) + }); + } + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; + + if (parser && param.wrappedInnerExpressions) { + for (const part of param.wrappedInnerExpressions) { + if (part.expression) { + parser.walkExpression( + /** @type {Expression} */ + (part.expression) + ); + } + } + } + + return dep; + } + const dep = new Dep( + { + request: /** @type {string} */ (options.exprContextRequest), + recursive: /** @type {boolean} */ (options.exprContextRecursive), + regExp: /** @type {RegExp} */ (options.exprContextRegExp), + mode: "sync", + ...contextOptions + }, + range, + /** @type {Range} */ (param.range), + ...depArgs + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.critical = + options.exprContextCritical && + "the request of a dependency is an expression"; + + parser.walkExpression(/** @type {Expression} */ (param.expression)); + + return dep; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsId.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsId.js new file mode 100644 index 0000000000000000000000000000000000000000..da119adb09f64da659fc1ed4010894db244e82a6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsId.js @@ -0,0 +1,63 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ContextDependency = require("./ContextDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class ContextDependencyTemplateAsId extends ContextDependency.Template { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ContextDependency} */ (dependency); + const module = moduleGraph.getModule(dep); + const moduleExports = runtimeTemplate.moduleExports({ + module, + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); + + if (module) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); + } + } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}.resolve(` + ); + } else { + source.replace( + dep.range[0], + dep.range[1] - 1, + `${moduleExports}.resolve` + ); + } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } +} + +module.exports = ContextDependencyTemplateAsId; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall.js new file mode 100644 index 0000000000000000000000000000000000000000..ef02cce675f43005357b23c2da748b0a7ef6e420 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall.js @@ -0,0 +1,60 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ContextDependency = require("./ContextDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class ContextDependencyTemplateAsRequireCall extends ContextDependency.Template { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ContextDependency} */ (dependency); + let moduleExports = runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + runtimeRequirements + }); + + if (dep.inShorthand) { + moduleExports = `${dep.inShorthand}: ${moduleExports}`; + } + if (moduleGraph.getModule(dep)) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); + } + } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}(` + ); + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } +} + +module.exports = ContextDependencyTemplateAsRequireCall; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextElementDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextElementDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..abe3d73b796682319ce4dab7a1742815d81ef1c6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ContextElementDependency.js @@ -0,0 +1,135 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("../ContextModule")} ContextModule */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class ContextElementDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {string | undefined} userRequest user request + * @param {string | undefined} typePrefix type prefix + * @param {string} category category + * @param {(string[][] | null)=} referencedExports referenced exports + * @param {string=} context context + * @param {ImportAttributes=} attributes import assertions + */ + constructor( + request, + userRequest, + typePrefix, + category, + referencedExports, + context, + attributes + ) { + super(request); + this.referencedExports = referencedExports; + this._typePrefix = typePrefix; + this._category = category; + this._context = context || undefined; + + if (userRequest) { + this.userRequest = userRequest; + } + + this.assertions = attributes; + } + + get type() { + if (this._typePrefix) { + return `${this._typePrefix} context element`; + } + + return "context element"; + } + + get category() { + return this._category; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED; + const refs = []; + for (const referencedExport of this.referencedExports) { + if ( + this._typePrefix === "import()" && + referencedExport[0] === "default" + ) { + const selfModule = + /** @type {ContextModule} */ + (moduleGraph.getParentModule(this)); + const importedModule = + /** @type {Module} */ + (moduleGraph.getModule(this)); + const exportsType = importedModule.getExportsType( + moduleGraph, + selfModule.options.namespaceObject === "strict" + ); + if ( + exportsType === "default-only" || + exportsType === "default-with-named" + ) { + return Dependency.EXPORTS_OBJECT_REFERENCED; + } + } + refs.push({ + name: referencedExport, + canMangle: false + }); + } + return refs; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this._typePrefix); + write(this._category); + write(this.referencedExports); + write(this.assertions); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this._typePrefix = read(); + this._category = read(); + this.referencedExports = read(); + this.assertions = read(); + super.deserialize(context); + } +} + +makeSerializable( + ContextElementDependency, + "webpack/lib/dependencies/ContextElementDependency" +); + +module.exports = ContextElementDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CreateScriptUrlDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CreateScriptUrlDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..9abb5c50cf43ebaa9eb005119c9f9e05df3aa58d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CreateScriptUrlDependency.js @@ -0,0 +1,75 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class CreateScriptUrlDependency extends NullDependency { + /** + * @param {Range} range range + */ + constructor(range) { + super(); + this.range = range; + } + + get type() { + return "create script url"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.range = read(); + super.deserialize(context); + } +} + +CreateScriptUrlDependency.Template = class CreateScriptUrlDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { runtimeRequirements }) { + const dep = /** @type {CreateScriptUrlDependency} */ (dependency); + + runtimeRequirements.add(RuntimeGlobals.createScriptUrl); + + source.insert(dep.range[0], `${RuntimeGlobals.createScriptUrl}(`); + source.insert(dep.range[1], ")"); + } +}; + +makeSerializable( + CreateScriptUrlDependency, + "webpack/lib/dependencies/CreateScriptUrlDependency" +); + +module.exports = CreateScriptUrlDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CriticalDependencyWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CriticalDependencyWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..3299150bd97ae1390915dd82abe31e8f6ecc6f1f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CriticalDependencyWarning.js @@ -0,0 +1,28 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("../WebpackError"); +const makeSerializable = require("../util/makeSerializable"); + +class CriticalDependencyWarning extends WebpackError { + /** + * @param {string} message message + */ + constructor(message) { + super(); + + this.name = "CriticalDependencyWarning"; + this.message = `Critical dependency: ${message}`; + } +} + +makeSerializable( + CriticalDependencyWarning, + "webpack/lib/dependencies/CriticalDependencyWarning" +); + +module.exports = CriticalDependencyWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssIcssExportDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssIcssExportDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..a4bb379c91b99b5125c4aacb29e35f66a760dabf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssIcssExportDependency.js @@ -0,0 +1,159 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const { cssExportConvention } = require("../util/conventions"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorExportsConvention} CssGeneratorExportsConvention */ +/** @typedef {import("../CssModule")} CssModule */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../css/CssGenerator")} CssGenerator */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ + +class CssIcssExportDependency extends NullDependency { + /** + * @param {string} name name + * @param {string} value value + */ + constructor(name, value) { + super(); + this.name = name; + this.value = value; + this._hashUpdate = undefined; + } + + get type() { + return "css :export"; + } + + /** + * @param {string} name export name + * @param {CssGeneratorExportsConvention} convention convention of the export name + * @returns {string[]} convention results + */ + getExportsConventionNames(name, convention) { + if (this._conventionNames) { + return this._conventionNames; + } + this._conventionNames = cssExportConvention(name, convention); + return this._conventionNames; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const module = /** @type {CssModule} */ (moduleGraph.getParentModule(this)); + const generator = /** @type {CssGenerator} */ (module.generator); + const names = this.getExportsConventionNames( + this.name, + /** @type {CssGeneratorExportsConvention} */ + (generator.convention) + ); + return { + exports: names.map((name) => ({ + name, + canMangle: true + })), + dependencies: undefined + }; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, { chunkGraph }) { + if (this._hashUpdate === undefined) { + const module = + /** @type {CssModule} */ + (chunkGraph.moduleGraph.getParentModule(this)); + const generator = /** @type {CssGenerator} */ (module.generator); + const names = this.getExportsConventionNames( + this.name, + /** @type {CssGeneratorExportsConvention} */ + (generator.convention) + ); + this._hashUpdate = JSON.stringify(names); + } + hash.update("exportsConvention"); + hash.update(this._hashUpdate); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.name); + write(this.value); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.name = read(); + this.value = read(); + super.deserialize(context); + } +} + +CssIcssExportDependency.Template = class CssIcssExportDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { cssData, module: m, runtime, moduleGraph }) { + const dep = /** @type {CssIcssExportDependency} */ (dependency); + const module = /** @type {CssModule} */ (m); + const generator = /** @type {CssGenerator} */ (module.generator); + const names = dep.getExportsConventionNames( + dep.name, + /** @type {CssGeneratorExportsConvention} */ + (generator.convention) + ); + const usedNames = + /** @type {string[]} */ + ( + names + .map((name) => + moduleGraph.getExportInfo(module, name).getUsedName(name, runtime) + ) + .filter(Boolean) + ); + + for (const used of [...usedNames, ...names]) { + cssData.exports.set(used, dep.value); + } + } +}; + +makeSerializable( + CssIcssExportDependency, + "webpack/lib/dependencies/CssIcssExportDependency" +); + +module.exports = CssIcssExportDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssIcssImportDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssIcssImportDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..3bfe6676798189c4694d0b6f002abbe303dc6141 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssIcssImportDependency.js @@ -0,0 +1,122 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const CssIcssExportDependency = require("./CssIcssExportDependency"); +const CssLocalIdentifierDependency = require("./CssLocalIdentifierDependency"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class CssIcssImportDependency extends ModuleDependency { + /** + * Example of dependency: + * + *:import('./style.css') { IMPORTED_NAME: v-primary } + * @param {string} request request request path which needs resolving + * @param {string} exportName export name + * @param {Range} range the range of dependency + */ + constructor(request, exportName, range) { + super(request); + this.exportName = exportName; + this.range = range; + } + + get type() { + return "css :import"; + } + + get category() { + return "css-import"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + write(this.exportName); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.range = read(); + this.exportName = read(); + super.deserialize(context); + } +} + +CssIcssImportDependency.Template = class CssIcssImportDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {CssIcssImportDependency} */ (dependency); + const { range } = dep; + const module = + /** @type {Module} */ + (templateContext.moduleGraph.getModule(dep)); + let value; + + for (const item of module.dependencies) { + if ( + item instanceof CssLocalIdentifierDependency && + dep.exportName === item.name + ) { + value = CssLocalIdentifierDependency.Template.getIdentifier( + item, + dep.exportName, + { + ...templateContext, + module + } + ); + break; + } else if ( + item instanceof CssIcssExportDependency && + dep.exportName === item.name + ) { + value = item.value; + break; + } + } + + if (!value) { + throw new Error( + `Imported '${dep.exportName}' name from '${dep.request}' not found` + ); + } + + source.replace(range[0], range[1], value); + } +}; + +makeSerializable( + CssIcssImportDependency, + "webpack/lib/dependencies/CssIcssImportDependency" +); + +module.exports = CssIcssImportDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssIcssSymbolDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssIcssSymbolDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..298e5d1cdc5f16b084b0e4b00cfe5bc09e527846 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssIcssSymbolDependency.js @@ -0,0 +1,132 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Alexander Akait @alexander-akait +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../css/CssParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class CssIcssSymbolDependency extends NullDependency { + /** + * @param {string} name name + * @param {string} value value + * @param {Range} range range + */ + constructor(name, value, range) { + super(); + this.name = name; + this.value = value; + this.range = range; + this._hashUpdate = undefined; + } + + get type() { + return "css @value identifier"; + } + + get category() { + return "self"; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = `${this.range}${this.name}${this.value}`; + } + hash.update(this._hashUpdate); + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: [ + { + name: this.name, + canMangle: true + } + ], + dependencies: undefined + }; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + return [[this.name]]; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.name); + write(this.value); + write(this.range); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.name = read(); + this.value = read(); + this.range = read(); + super.deserialize(context); + } +} + +CssIcssSymbolDependency.Template = class CssValueAtRuleDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { cssData }) { + const dep = /** @type {CssIcssSymbolDependency} */ (dependency); + + source.replace(dep.range[0], dep.range[1] - 1, dep.value); + + cssData.exports.set(dep.name, dep.value); + } +}; + +makeSerializable( + CssIcssSymbolDependency, + "webpack/lib/dependencies/CssIcssSymbolDependency" +); + +module.exports = CssIcssSymbolDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssImportDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssImportDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..b6a0772d2ba606805dbdc0f1df4ac7e1248e9bf5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssImportDependency.js @@ -0,0 +1,117 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../css/CssParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class CssImportDependency extends ModuleDependency { + /** + * Example of dependency: + * \@import url("landscape.css") layer(forms) screen and (orientation: landscape) screen and (orientation: landscape); + * @param {string} request request + * @param {Range} range range of the argument + * @param {string | undefined} layer layer + * @param {string | undefined} supports list of supports conditions + * @param {string | undefined} media list of media conditions + */ + constructor(request, range, layer, supports, media) { + super(request); + this.range = range; + this.layer = layer; + this.supports = supports; + this.media = media; + } + + get type() { + return "css @import"; + } + + get category() { + return "css-import"; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + let str = `context${this._context || ""}|module${this.request}`; + + if (this.layer) { + str += `|layer${this.layer}`; + } + + if (this.supports) { + str += `|supports${this.supports}`; + } + + if (this.media) { + str += `|media${this.media}`; + } + + return str; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.layer); + write(this.supports); + write(this.media); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.layer = read(); + this.supports = read(); + this.media = read(); + super.deserialize(context); + } +} + +CssImportDependency.Template = class CssImportDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {CssImportDependency} */ (dependency); + + source.replace(dep.range[0], dep.range[1] - 1, ""); + } +}; + +makeSerializable( + CssImportDependency, + "webpack/lib/dependencies/CssImportDependency" +); + +module.exports = CssImportDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssLocalIdentifierDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssLocalIdentifierDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..3be3ef0388f5c843789267290527373505b6187b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssLocalIdentifierDependency.js @@ -0,0 +1,253 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const { cssExportConvention } = require("../util/conventions"); +const createHash = require("../util/createHash"); +const { makePathsRelative } = require("../util/identifier"); +const makeSerializable = require("../util/makeSerializable"); +const memoize = require("../util/memoize"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorExportsConvention} CssGeneratorExportsConvention */ +/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorLocalIdentName} CssGeneratorLocalIdentName */ +/** @typedef {import("../../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CssModule")} CssModule */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../NormalModuleFactory").ResourceDataWithData} ResourceDataWithData */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../css/CssGenerator")} CssGenerator */ +/** @typedef {import("../css/CssParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ + +const getCssParser = memoize(() => require("../css/CssParser")); + +/** + * @param {string} local css local + * @param {CssModule} module module + * @param {ChunkGraph} chunkGraph chunk graph + * @param {RuntimeTemplate} runtimeTemplate runtime template + * @returns {string} local ident + */ +const getLocalIdent = (local, module, chunkGraph, runtimeTemplate) => { + const generator = /** @type {CssGenerator} */ (module.generator); + const localIdentName = + /** @type {CssGeneratorLocalIdentName} */ + (generator.localIdentName); + const relativeResourcePath = makePathsRelative( + /** @type {string} */ + (module.context), + module.matchResource || module.resource, + runtimeTemplate.compilation.compiler.root + ); + const { hashFunction, hashDigest, hashDigestLength, hashSalt, uniqueName } = + runtimeTemplate.outputOptions; + const hash = createHash(/** @type {HashFunction} */ (hashFunction)); + + if (hashSalt) { + hash.update(hashSalt); + } + + hash.update(relativeResourcePath); + + if (!/\[local\]/.test(localIdentName)) { + hash.update(local); + } + + const localIdentHash = + /** @type {string} */ + (hash.digest(hashDigest)).slice(0, hashDigestLength); + + return runtimeTemplate.compilation + .getPath(localIdentName, { + filename: relativeResourcePath, + hash: localIdentHash, + contentHash: localIdentHash, + chunkGraph, + module + }) + .replace(/\[local\]/g, local) + .replace(/\[uniqueName\]/g, /** @type {string} */ (uniqueName)) + .replace(/^((-?[0-9])|--)/, "_$1"); +}; + +class CssLocalIdentifierDependency extends NullDependency { + /** + * @param {string} name name + * @param {Range} range range + * @param {string=} prefix prefix + */ + constructor(name, range, prefix = "") { + super(); + this.name = name; + this.range = range; + this.prefix = prefix; + this._conventionNames = undefined; + this._hashUpdate = undefined; + } + + get type() { + return "css local identifier"; + } + + /** + * @param {string} name export name + * @param {CssGeneratorExportsConvention} convention convention of the export name + * @returns {string[]} convention results + */ + getExportsConventionNames(name, convention) { + if (this._conventionNames) { + return this._conventionNames; + } + this._conventionNames = cssExportConvention(this.name, convention); + return this._conventionNames; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const module = /** @type {CssModule} */ (moduleGraph.getParentModule(this)); + const generator = /** @type {CssGenerator} */ (module.generator); + const names = this.getExportsConventionNames( + this.name, + /** @type {CssGeneratorExportsConvention} */ (generator.convention) + ); + return { + exports: names.map((name) => ({ + name, + canMangle: true + })), + dependencies: undefined + }; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, { chunkGraph }) { + if (this._hashUpdate === undefined) { + const module = + /** @type {CssModule} */ + (chunkGraph.moduleGraph.getParentModule(this)); + const generator = /** @type {CssGenerator} */ (module.generator); + const names = this.getExportsConventionNames( + this.name, + /** @type {CssGeneratorExportsConvention} */ + (generator.convention) + ); + this._hashUpdate = `exportsConvention|${JSON.stringify(names)}|localIdentName|${JSON.stringify(generator.localIdentName)}`; + } + hash.update(this._hashUpdate); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.name); + write(this.range); + write(this.prefix); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.name = read(); + this.range = read(); + this.prefix = read(); + super.deserialize(context); + } +} + +CssLocalIdentifierDependency.Template = class CssLocalIdentifierDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {string} local local name + * @param {DependencyTemplateContext} templateContext the context object + * @returns {string} identifier + */ + static getIdentifier( + dependency, + local, + { module: m, chunkGraph, runtimeTemplate } + ) { + const dep = /** @type {CssLocalIdentifierDependency} */ (dependency); + const module = /** @type {CssModule} */ (m); + + return ( + dep.prefix + + getCssParser().escapeIdentifier( + getLocalIdent(local, module, chunkGraph, runtimeTemplate) + ) + ); + } + + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const { module: m, moduleGraph, runtime, cssData } = templateContext; + const dep = /** @type {CssLocalIdentifierDependency} */ (dependency); + const module = /** @type {CssModule} */ (m); + const generator = /** @type {CssGenerator} */ (module.generator); + const names = dep.getExportsConventionNames( + dep.name, + /** @type {CssGeneratorExportsConvention} */ + (generator.convention) + ); + const usedNames = + /** @type {string[]} */ + ( + names + .map((name) => + moduleGraph.getExportInfo(module, name).getUsedName(name, runtime) + ) + .filter(Boolean) + ); + const local = usedNames.length === 0 ? names[0] : usedNames[0]; + const identifier = CssLocalIdentifierDependencyTemplate.getIdentifier( + dep, + local, + templateContext + ); + + source.replace(dep.range[0], dep.range[1] - 1, identifier); + + for (const used of [...usedNames, ...names]) { + cssData.exports.set(used, getCssParser().unescapeIdentifier(identifier)); + } + } +}; + +makeSerializable( + CssLocalIdentifierDependency, + "webpack/lib/dependencies/CssLocalIdentifierDependency" +); + +module.exports = CssLocalIdentifierDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssSelfLocalIdentifierDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssSelfLocalIdentifierDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..6d4ac1ed180a6575e5c0cbd22353e0e941ad5cc4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssSelfLocalIdentifierDependency.js @@ -0,0 +1,112 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const makeSerializable = require("../util/makeSerializable"); +const CssLocalIdentifierDependency = require("./CssLocalIdentifierDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../css/CssParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class CssSelfLocalIdentifierDependency extends CssLocalIdentifierDependency { + /** + * @param {string} name name + * @param {Range} range range + * @param {string=} prefix prefix + * @param {Set=} declaredSet set of declared names (will only be active when in declared set) + */ + constructor(name, range, prefix = "", declaredSet = undefined) { + super(name, range, prefix); + this.declaredSet = declaredSet; + } + + get type() { + return "css self local identifier"; + } + + get category() { + return "self"; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return "self"; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + if (this.declaredSet && !this.declaredSet.has(this.name)) return; + return super.getExports(moduleGraph); + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + if (this.declaredSet && !this.declaredSet.has(this.name)) { + return Dependency.NO_EXPORTS_REFERENCED; + } + return [[this.name]]; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.declaredSet); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.declaredSet = read(); + super.deserialize(context); + } +} + +CssSelfLocalIdentifierDependency.Template = class CssSelfLocalIdentifierDependencyTemplate extends ( + CssLocalIdentifierDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {CssSelfLocalIdentifierDependency} */ (dependency); + if (dep.declaredSet && !dep.declaredSet.has(dep.name)) return; + super.apply(dependency, source, templateContext); + } +}; + +makeSerializable( + CssSelfLocalIdentifierDependency, + "webpack/lib/dependencies/CssSelfLocalIdentifierDependency" +); + +module.exports = CssSelfLocalIdentifierDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssUrlDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssUrlDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..a7cb4349cd4755b9f61f1b00427af81e32a80c71 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/CssUrlDependency.js @@ -0,0 +1,195 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const RawDataUrlModule = require("../asset/RawDataUrlModule"); +const makeSerializable = require("../util/makeSerializable"); +const memoize = require("../util/memoize"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +const getIgnoredRawDataUrlModule = memoize( + () => new RawDataUrlModule("data:,", "ignored-asset", "(ignored asset)") +); + +class CssUrlDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {Range} range range of the argument + * @param {"string" | "url" | "src"} urlType dependency type e.g. url() or string + */ + constructor(request, range, urlType) { + super(request); + this.range = range; + this.urlType = urlType; + } + + get type() { + return "css url()"; + } + + get category() { + return "url"; + } + + /** + * @param {string} context context directory + * @returns {Module} ignored module + */ + createIgnoredModule(context) { + return getIgnoredRawDataUrlModule(); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.urlType); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.urlType = read(); + super.deserialize(context); + } +} + +/** + * @param {string} str string + * @returns {string} string in quotes if needed + */ +const cssEscapeString = (str) => { + let countWhiteOrBracket = 0; + let countQuotation = 0; + let countApostrophe = 0; + for (let i = 0; i < str.length; i++) { + const cc = str.charCodeAt(i); + switch (cc) { + case 9: // tab + case 10: // nl + case 32: // space + case 40: // ( + case 41: // ) + countWhiteOrBracket++; + break; + case 34: + countQuotation++; + break; + case 39: + countApostrophe++; + break; + } + } + if (countWhiteOrBracket < 2) { + return str.replace(/[\n\t ()'"\\]/g, (m) => `\\${m}`); + } else if (countQuotation <= countApostrophe) { + return `"${str.replace(/[\n"\\]/g, (m) => `\\${m}`)}"`; + } + return `'${str.replace(/[\n'\\]/g, (m) => `\\${m}`)}'`; +}; + +CssUrlDependency.Template = class CssUrlDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { moduleGraph, runtimeTemplate, codeGenerationResults } + ) { + const dep = /** @type {CssUrlDependency} */ (dependency); + const module = /** @type {Module} */ (moduleGraph.getModule(dep)); + + /** @type {string | undefined} */ + let newValue; + + switch (dep.urlType) { + case "string": + newValue = cssEscapeString( + this.assetUrl({ + module, + codeGenerationResults + }) + ); + break; + case "url": + newValue = `url(${cssEscapeString( + this.assetUrl({ + module, + codeGenerationResults + }) + )})`; + break; + case "src": + newValue = `src(${cssEscapeString( + this.assetUrl({ + module, + codeGenerationResults + }) + )})`; + break; + } + + source.replace( + dep.range[0], + dep.range[1] - 1, + /** @type {string} */ (newValue) + ); + } + + /** + * @param {object} options options object + * @param {Module} options.module the module + * @param {RuntimeSpec=} options.runtime runtime + * @param {CodeGenerationResults} options.codeGenerationResults the code generation results + * @returns {string} the url of the asset + */ + assetUrl({ runtime, module, codeGenerationResults }) { + if (!module) { + return "data:,"; + } + const codeGen = codeGenerationResults.get(module, runtime); + const data = + /** @type {NonNullable} */ + (codeGen.data); + if (!data) return "data:,"; + const url = data.get("url"); + if (!url || !url["css-url"]) return "data:,"; + return url["css-url"]; + } +}; + +makeSerializable(CssUrlDependency, "webpack/lib/dependencies/CssUrlDependency"); + +CssUrlDependency.PUBLIC_PATH_AUTO = "__WEBPACK_CSS_PUBLIC_PATH_AUTO__"; + +module.exports = CssUrlDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/DelegatedSourceDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/DelegatedSourceDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..737f60e7727e75f174a23245b3ca5db76586eb7f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/DelegatedSourceDependency.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +class DelegatedSourceDependency extends ModuleDependency { + /** + * @param {string} request the request string + */ + constructor(request) { + super(request); + } + + get type() { + return "delegated source"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + DelegatedSourceDependency, + "webpack/lib/dependencies/DelegatedSourceDependency" +); + +module.exports = DelegatedSourceDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/DllEntryDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/DllEntryDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..74697042150b387b2cb219980a41d3cfe92512a6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/DllEntryDependency.js @@ -0,0 +1,61 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./EntryDependency")} EntryDependency */ + +class DllEntryDependency extends Dependency { + /** + * @param {EntryDependency[]} dependencies dependencies + * @param {string} name name + */ + constructor(dependencies, name) { + super(); + + this.dependencies = dependencies; + this.name = name; + } + + get type() { + return "dll entry"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.dependencies); + write(this.name); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.dependencies = read(); + this.name = read(); + + super.deserialize(context); + } +} + +makeSerializable( + DllEntryDependency, + "webpack/lib/dependencies/DllEntryDependency" +); + +module.exports = DllEntryDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/DynamicExports.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/DynamicExports.js new file mode 100644 index 0000000000000000000000000000000000000000..1d97fa5a90c1fd1e2c4ba294990ef374b1940a16 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/DynamicExports.js @@ -0,0 +1,73 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Parser").ParserState} ParserState */ + +/** @type {WeakMap} */ +const parserStateExportsState = new WeakMap(); + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +module.exports.bailout = (parserState) => { + const value = parserStateExportsState.get(parserState); + parserStateExportsState.set(parserState, false); + if (value === true) { + const buildMeta = /** @type {BuildMeta} */ (parserState.module.buildMeta); + buildMeta.exportsType = undefined; + buildMeta.defaultObject = false; + } +}; + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +module.exports.enable = (parserState) => { + const value = parserStateExportsState.get(parserState); + if (value === false) return; + parserStateExportsState.set(parserState, true); + if (value !== true) { + const buildMeta = /** @type {BuildMeta} */ (parserState.module.buildMeta); + buildMeta.exportsType = "default"; + buildMeta.defaultObject = "redirect"; + } +}; + +/** + * @param {ParserState} parserState parser state + * @returns {boolean} true, when enabled + */ +module.exports.isEnabled = (parserState) => { + const value = parserStateExportsState.get(parserState); + return value === true; +}; + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +module.exports.setDynamic = (parserState) => { + const value = parserStateExportsState.get(parserState); + if (value !== true) return; + /** @type {BuildMeta} */ + (parserState.module.buildMeta).exportsType = "dynamic"; +}; + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +module.exports.setFlagged = (parserState) => { + const value = parserStateExportsState.get(parserState); + if (value !== true) return; + const buildMeta = /** @type {BuildMeta} */ (parserState.module.buildMeta); + if (buildMeta.exportsType === "dynamic") return; + buildMeta.exportsType = "flagged"; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/EntryDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/EntryDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..f46444945b7ff8bdc5a726fb813a1d4e67066161 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/EntryDependency.js @@ -0,0 +1,30 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +class EntryDependency extends ModuleDependency { + /** + * @param {string} request request path for entry + */ + constructor(request) { + super(request); + } + + get type() { + return "entry"; + } + + get category() { + return "esm"; + } +} + +makeSerializable(EntryDependency, "webpack/lib/dependencies/EntryDependency"); + +module.exports = EntryDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ExportsInfoDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ExportsInfoDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..dd78aa160511b6b6bd21f8a5786490a896542817 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ExportsInfoDependency.js @@ -0,0 +1,163 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { UsageState } = require("../ExportsInfo"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @template T + * @typedef {import("../util/SortableSet")} SortableSet + */ + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} module the module + * @param {string[] | null} _exportName name of the export if any + * @param {string | null} property name of the requested property + * @param {RuntimeSpec} runtime for which runtime + * @returns {undefined | null | number | boolean | string[] | SortableSet} value of the property + */ +const getProperty = (moduleGraph, module, _exportName, property, runtime) => { + if (!_exportName) { + switch (property) { + case "usedExports": { + const usedExports = moduleGraph + .getExportsInfo(module) + .getUsedExports(runtime); + if ( + typeof usedExports === "boolean" || + usedExports === undefined || + usedExports === null + ) { + return usedExports; + } + return [...usedExports].sort(); + } + } + } + const exportName = /** @type {string[]} */ (_exportName); + switch (property) { + case "canMangle": { + const exportsInfo = moduleGraph.getExportsInfo(module); + const exportInfo = exportsInfo.getReadOnlyExportInfoRecursive(exportName); + if (exportInfo) return exportInfo.canMangle; + return exportsInfo.otherExportsInfo.canMangle; + } + case "used": + return ( + moduleGraph.getExportsInfo(module).getUsed(exportName, runtime) !== + UsageState.Unused + ); + case "useInfo": { + const state = moduleGraph + .getExportsInfo(module) + .getUsed(exportName, runtime); + switch (state) { + case UsageState.Used: + case UsageState.OnlyPropertiesUsed: + return true; + case UsageState.Unused: + return false; + case UsageState.NoInfo: + return; + case UsageState.Unknown: + return null; + default: + throw new Error(`Unexpected UsageState ${state}`); + } + } + case "provideInfo": + return moduleGraph.getExportsInfo(module).isExportProvided(exportName); + } +}; + +class ExportsInfoDependency extends NullDependency { + /** + * @param {Range} range range + * @param {string[] | null} exportName export name + * @param {string | null} property property + */ + constructor(range, exportName, property) { + super(); + this.range = range; + this.exportName = exportName; + this.property = property; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + write(this.exportName); + write(this.property); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {ExportsInfoDependency} ExportsInfoDependency + */ + static deserialize(context) { + const obj = new ExportsInfoDependency( + context.read(), + context.read(), + context.read() + ); + obj.deserialize(context); + return obj; + } +} + +makeSerializable( + ExportsInfoDependency, + "webpack/lib/dependencies/ExportsInfoDependency" +); + +ExportsInfoDependency.Template = class ExportsInfoDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { module, moduleGraph, runtime }) { + const dep = /** @type {ExportsInfoDependency} */ (dependency); + + const value = getProperty( + moduleGraph, + module, + dep.exportName, + dep.property, + runtime + ); + source.replace( + dep.range[0], + dep.range[1] - 1, + value === undefined ? "undefined" : JSON.stringify(value) + ); + } +}; + +module.exports = ExportsInfoDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ExternalModuleDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ExternalModuleDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..ce3e37858466a790eac4d5f9b0573fb8c1a35a02 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ExternalModuleDependency.js @@ -0,0 +1,109 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const CachedConstDependency = require("./CachedConstDependency"); +const ExternalModuleInitFragment = require("./ExternalModuleInitFragment"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ + +class ExternalModuleDependency extends CachedConstDependency { + /** + * @param {string} module module + * @param {{ name: string, value: string }[]} importSpecifiers import specifiers + * @param {string | undefined} defaultImport default import + * @param {string} expression expression + * @param {Range} range range + * @param {string} identifier identifier + */ + constructor( + module, + importSpecifiers, + defaultImport, + expression, + range, + identifier + ) { + super(expression, range, identifier); + + this.importedModule = module; + this.specifiers = importSpecifiers; + this.default = defaultImport; + } + + /** + * @returns {string} hash update + */ + _createHashUpdate() { + return `${this.importedModule}${JSON.stringify(this.specifiers)}${ + this.default || "null" + }${super._createHashUpdate()}`; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + super.serialize(context); + const { write } = context; + write(this.importedModule); + write(this.specifiers); + write(this.default); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + super.deserialize(context); + const { read } = context; + this.importedModule = read(); + this.specifiers = read(); + this.default = read(); + } +} + +makeSerializable( + ExternalModuleDependency, + "webpack/lib/dependencies/ExternalModuleDependency" +); + +ExternalModuleDependency.Template = class ExternalModuleDependencyTemplate extends ( + CachedConstDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + super.apply(dependency, source, templateContext); + const dep = /** @type {ExternalModuleDependency} */ (dependency); + const { chunkInitFragments, runtimeTemplate } = templateContext; + + chunkInitFragments.push( + new ExternalModuleInitFragment( + `${runtimeTemplate.supportNodePrefixForCoreModules() ? "node:" : ""}${ + dep.importedModule + }`, + dep.specifiers, + dep.default + ) + ); + } +}; + +module.exports = ExternalModuleDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ExternalModuleInitFragment.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ExternalModuleInitFragment.js new file mode 100644 index 0000000000000000000000000000000000000000..41bbe538e147da9f7e329838df7179149f8c4ae0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ExternalModuleInitFragment.js @@ -0,0 +1,133 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const InitFragment = require("../InitFragment"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {Map>} ImportSpecifiers */ + +/** + * @extends {InitFragment} + */ +class ExternalModuleInitFragment extends InitFragment { + /** + * @param {string} importedModule imported module + * @param {Array<{ name: string, value?: string }> | ImportSpecifiers} specifiers import specifiers + * @param {string=} defaultImport default import + */ + constructor(importedModule, specifiers, defaultImport) { + super( + undefined, + InitFragment.STAGE_CONSTANTS, + 0, + `external module imports|${importedModule}|${defaultImport || "null"}` + ); + this.importedModule = importedModule; + if (Array.isArray(specifiers)) { + /** @type {ImportSpecifiers} */ + this.specifiers = new Map(); + for (const { name, value } of specifiers) { + let specifiers = this.specifiers.get(name); + if (!specifiers) { + specifiers = new Set(); + this.specifiers.set(name, specifiers); + } + specifiers.add(value || name); + } + } else { + this.specifiers = specifiers; + } + this.defaultImport = defaultImport; + } + + /** + * @param {ExternalModuleInitFragment} other other + * @returns {ExternalModuleInitFragment} ExternalModuleInitFragment + */ + merge(other) { + const newSpecifiersMap = new Map(this.specifiers); + for (const [name, specifiers] of other.specifiers) { + if (newSpecifiersMap.has(name)) { + const currentSpecifiers = + /** @type {Set} */ + (newSpecifiersMap.get(name)); + for (const spec of specifiers) currentSpecifiers.add(spec); + } else { + newSpecifiersMap.set(name, specifiers); + } + } + return new ExternalModuleInitFragment( + this.importedModule, + newSpecifiersMap, + this.defaultImport + ); + } + + /** + * @param {GenerateContext} context context + * @returns {string | Source | undefined} the source code that will be included as initialization code + */ + getContent({ runtimeRequirements }) { + const namedImports = []; + + for (const [name, specifiers] of this.specifiers) { + for (const spec of specifiers) { + if (spec === name) { + namedImports.push(name); + } else { + namedImports.push(`${name} as ${spec}`); + } + } + } + + let importsString = + namedImports.length > 0 ? `{${namedImports.join(",")}}` : ""; + + if (this.defaultImport) { + importsString = `${this.defaultImport}${ + importsString ? `, ${importsString}` : "" + }`; + } + + return `import ${importsString} from ${JSON.stringify( + this.importedModule + )};`; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + super.serialize(context); + const { write } = context; + write(this.importedModule); + write(this.specifiers); + write(this.defaultImport); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + super.deserialize(context); + const { read } = context; + this.importedModule = read(); + this.specifiers = read(); + this.defaultImport = read(); + } +} + +makeSerializable( + ExternalModuleInitFragment, + "webpack/lib/dependencies/ExternalModuleInitFragment" +); + +module.exports = ExternalModuleInitFragment; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyAcceptDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyAcceptDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..27383d2ad2b6caee944d6269b38eb2ccf147b467 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyAcceptDependency.js @@ -0,0 +1,229 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Template = require("../Template"); +const AwaitDependenciesInitFragment = require("../async-modules/AwaitDependenciesInitFragment"); +const makeSerializable = require("../util/makeSerializable"); +const HarmonyImportDependency = require("./HarmonyImportDependency"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./HarmonyAcceptImportDependency")} HarmonyAcceptImportDependency */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").ModuleId} ModuleId */ + +class HarmonyAcceptDependency extends NullDependency { + /** + * @param {Range} range expression range + * @param {HarmonyAcceptImportDependency[]} dependencies import dependencies + * @param {boolean} hasCallback true, if the range wraps an existing callback + */ + constructor(range, dependencies, hasCallback) { + super(); + this.range = range; + this.dependencies = dependencies; + this.hasCallback = hasCallback; + } + + get type() { + return "accepted harmony modules"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + write(this.dependencies); + write(this.hasCallback); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.range = read(); + this.dependencies = read(); + this.hasCallback = read(); + super.deserialize(context); + } +} + +makeSerializable( + HarmonyAcceptDependency, + "webpack/lib/dependencies/HarmonyAcceptDependency" +); + +HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {HarmonyAcceptDependency} */ (dependency); + const { + module, + runtime, + runtimeRequirements, + runtimeTemplate, + moduleGraph, + chunkGraph + } = templateContext; + + /** + * @param {Dependency} dependency the dependency to get module id for + * @returns {ModuleId | null} the module id or null if not found + */ + const getDependencyModuleId = (dependency) => + chunkGraph.getModuleId( + /** @type {Module} */ (moduleGraph.getModule(dependency)) + ); + + /** + * @param {Dependency} a the first dependency + * @param {Dependency} b the second dependency + * @returns {boolean} true if the dependencies are related + */ + const isRelatedHarmonyImportDependency = (a, b) => + a !== b && + b instanceof HarmonyImportDependency && + getDependencyModuleId(a) === getDependencyModuleId(b); + + /** + * HarmonyAcceptImportDependency lacks a lot of information, such as the defer property. + * One HarmonyAcceptImportDependency may need to generate multiple ImportStatements. + * Therefore, we find its original HarmonyImportDependency for code generation. + * @param {HarmonyAcceptImportDependency} dependency the dependency to get harmony import dependencies for + * @returns {HarmonyImportDependency[]} array of related harmony import dependencies + */ + const getHarmonyImportDependencies = (dependency) => { + const result = []; + let deferDependency = null; + let noDeferredDependency = null; + + for (const d of module.dependencies) { + if (deferDependency && noDeferredDependency) break; + if (isRelatedHarmonyImportDependency(dependency, d)) { + if (d.defer) { + deferDependency = /** @type {HarmonyImportDependency} */ (d); + } else { + noDeferredDependency = /** @type {HarmonyImportDependency} */ (d); + } + } + } + if (deferDependency) result.push(deferDependency); + if (noDeferredDependency) result.push(noDeferredDependency); + if (result.length === 0) { + // fallback to the original dependency + result.push(dependency); + } + return result; + }; + + /** @type {HarmonyImportDependency[]} */ + const syncDeps = []; + + /** @type {HarmonyAcceptImportDependency[]} */ + const asyncDeps = []; + + for (const dependency of dep.dependencies) { + const connection = moduleGraph.getConnection(dependency); + + if (connection && moduleGraph.isAsync(connection.module)) { + asyncDeps.push(dependency); + } else { + syncDeps.push(...getHarmonyImportDependencies(dependency)); + } + } + + let content = syncDeps + .map((dependency) => { + const referencedModule = moduleGraph.getModule(dependency); + return { + dependency, + runtimeCondition: referencedModule + ? HarmonyImportDependency.Template.getImportEmittedRuntime( + module, + referencedModule + ) + : false + }; + }) + .filter(({ runtimeCondition }) => runtimeCondition !== false) + .map(({ dependency, runtimeCondition }) => { + const condition = runtimeTemplate.runtimeConditionExpression({ + chunkGraph, + runtime, + runtimeCondition, + runtimeRequirements + }); + const s = dependency.getImportStatement(true, templateContext); + const code = s[0] + s[1]; + if (condition !== "true") { + return `if (${condition}) {\n${Template.indent(code)}\n}\n`; + } + return code; + }) + .join(""); + + const promises = new Map( + asyncDeps.map((dependency) => [ + dependency.getImportVar(moduleGraph), + dependency.getModuleExports(templateContext) + ]) + ); + + let optAsync = ""; + if (promises.size !== 0) { + optAsync = "async "; + content += new AwaitDependenciesInitFragment(promises).getContent({ + ...templateContext, + type: "javascript" + }); + } + + if (dep.hasCallback) { + if (runtimeTemplate.supportsArrowFunction()) { + source.insert( + dep.range[0], + `${optAsync}__WEBPACK_OUTDATED_DEPENDENCIES__ => { ${content} return (` + ); + source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }"); + } else { + source.insert( + dep.range[0], + `${optAsync}function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content} return (` + ); + source.insert( + dep.range[1], + ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" + ); + } + return; + } + + const arrow = runtimeTemplate.supportsArrowFunction(); + source.insert( + dep.range[1] - 0.5, + `, ${arrow ? `${optAsync}() =>` : `${optAsync}function()`} { ${content} }` + ); + } +}; + +module.exports = HarmonyAcceptDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyAcceptImportDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyAcceptImportDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..03cb0002ddc4661b3f235c1161dc4dac154d8755 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyAcceptImportDependency.js @@ -0,0 +1,40 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const HarmonyImportDependency = require("./HarmonyImportDependency"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class HarmonyAcceptImportDependency extends HarmonyImportDependency { + /** + * @param {string} request the request string + */ + constructor(request) { + super(request, Number.NaN); + this.weak = true; + } + + get type() { + return "harmony accept"; + } +} + +makeSerializable( + HarmonyAcceptImportDependency, + "webpack/lib/dependencies/HarmonyAcceptImportDependency" +); + +HarmonyAcceptImportDependency.Template = + /** @type {typeof HarmonyImportDependency.Template} */ ( + NullDependency.Template + ); + +module.exports = HarmonyAcceptImportDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyCompatibilityDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyCompatibilityDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..5464f91b1f03fa09e23ad0e9c99250dd7a110e79 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyCompatibilityDependency.js @@ -0,0 +1,92 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { UsageState } = require("../ExportsInfo"); +const InitFragment = require("../InitFragment"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ + +class HarmonyCompatibilityDependency extends NullDependency { + get type() { + return "harmony export header"; + } +} + +makeSerializable( + HarmonyCompatibilityDependency, + "webpack/lib/dependencies/HarmonyCompatibilityDependency" +); + +HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { + module, + runtimeTemplate, + moduleGraph, + initFragments, + runtimeRequirements, + runtime, + concatenationScope + } + ) { + if (concatenationScope) return; + const exportsInfo = moduleGraph.getExportsInfo(module); + if ( + exportsInfo.getReadOnlyExportInfo("__esModule").getUsed(runtime) !== + UsageState.Unused + ) { + const content = runtimeTemplate.defineEsModuleFlagStatement({ + exportsArgument: module.exportsArgument, + runtimeRequirements + }); + initFragments.push( + new InitFragment( + content, + InitFragment.STAGE_HARMONY_EXPORTS, + 0, + "harmony compatibility" + ) + ); + } + if (moduleGraph.isAsync(module)) { + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.asyncModule); + initFragments.push( + new InitFragment( + runtimeTemplate.supportsArrowFunction() + ? `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n` + : `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async function (__webpack_handle_async_dependencies__, __webpack_async_result__) { try {\n`, + InitFragment.STAGE_ASYNC_BOUNDARY, + 0, + undefined, + `\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } }${ + /** @type {BuildMeta} */ (module.buildMeta).async ? ", 1" : "" + });` + ) + ); + } + } +}; + +module.exports = HarmonyCompatibilityDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyDetectionParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyDetectionParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7edd8dd5d594dc16584a8e8723ad389f65f60f9c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyDetectionParserPlugin.js @@ -0,0 +1,117 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const EnvironmentNotSupportAsyncWarning = require("../EnvironmentNotSupportAsyncWarning"); +const { JAVASCRIPT_MODULE_TYPE_ESM } = require("../ModuleTypeConstants"); +const DynamicExports = require("./DynamicExports"); +const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency"); +const HarmonyExports = require("./HarmonyExports"); + +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./HarmonyModulesPlugin").HarmonyModulesPluginOptions} HarmonyModulesPluginOptions */ + +const PLUGIN_NAME = "HarmonyDetectionParserPlugin"; + +module.exports = class HarmonyDetectionParserPlugin { + /** + * @param {HarmonyModulesPluginOptions} options options + */ + constructor(options) { + const { topLevelAwait = false } = options || {}; + this.topLevelAwait = topLevelAwait; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + parser.hooks.program.tap(PLUGIN_NAME, (ast) => { + const isStrictHarmony = + parser.state.module.type === JAVASCRIPT_MODULE_TYPE_ESM; + const isHarmony = + isStrictHarmony || + ast.body.some( + (statement) => + statement.type === "ImportDeclaration" || + statement.type === "ExportDefaultDeclaration" || + statement.type === "ExportNamedDeclaration" || + statement.type === "ExportAllDeclaration" + ); + if (isHarmony) { + const module = parser.state.module; + const compatDep = new HarmonyCompatibilityDependency(); + compatDep.loc = { + start: { + line: -1, + column: 0 + }, + end: { + line: -1, + column: 0 + }, + index: -3 + }; + module.addPresentationalDependency(compatDep); + DynamicExports.bailout(parser.state); + HarmonyExports.enable(parser.state, isStrictHarmony); + parser.scope.isStrict = true; + } + }); + + parser.hooks.topLevelAwait.tap(PLUGIN_NAME, () => { + const module = parser.state.module; + if (!this.topLevelAwait) { + throw new Error( + "The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enable it)" + ); + } + if (!HarmonyExports.isEnabled(parser.state)) { + throw new Error( + "Top-level-await is only supported in EcmaScript Modules" + ); + } + /** @type {BuildMeta} */ + (module.buildMeta).async = true; + EnvironmentNotSupportAsyncWarning.check( + module, + parser.state.compilation.runtimeTemplate, + "topLevelAwait" + ); + }); + + /** + * @returns {boolean | undefined} true if in harmony + */ + const skipInHarmony = () => { + if (HarmonyExports.isEnabled(parser.state)) { + return true; + } + }; + + /** + * @returns {null | undefined} null if in harmony + */ + const nullInHarmony = () => { + if (HarmonyExports.isEnabled(parser.state)) { + return null; + } + }; + + const nonHarmonyIdentifiers = ["define", "exports"]; + for (const identifier of nonHarmonyIdentifiers) { + parser.hooks.evaluateTypeof + .for(identifier) + .tap(PLUGIN_NAME, nullInHarmony); + parser.hooks.typeof.for(identifier).tap(PLUGIN_NAME, skipInHarmony); + parser.hooks.evaluate.for(identifier).tap(PLUGIN_NAME, nullInHarmony); + parser.hooks.expression.for(identifier).tap(PLUGIN_NAME, skipInHarmony); + parser.hooks.call.for(identifier).tap(PLUGIN_NAME, skipInHarmony); + } + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..58c1bef530dcb2467657c890eea62f97d212b000 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js @@ -0,0 +1,152 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** + * Dependency for static evaluating import specifier. e.g. + * @example + * import a from "a"; + * "x" in a; + * a.x !== undefined; // if x value statically analyzable + */ +class HarmonyEvaluatedImportSpecifierDependency extends HarmonyImportSpecifierDependency { + /** + * @param {string} request the request string + * @param {number} sourceOrder source order + * @param {string[]} ids ids + * @param {string} name name + * @param {Range} range location in source code + * @param {ImportAttributes} attributes import assertions + * @param {string} operator operator + */ + constructor(request, sourceOrder, ids, name, range, attributes, operator) { + super(request, sourceOrder, ids, name, range, false, attributes, []); + this.operator = operator; + } + + get type() { + return `evaluated X ${this.operator} harmony import specifier`; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + super.serialize(context); + const { write } = context; + write(this.operator); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + super.deserialize(context); + const { read } = context; + this.operator = read(); + } +} + +makeSerializable( + HarmonyEvaluatedImportSpecifierDependency, + "webpack/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency" +); + +HarmonyEvaluatedImportSpecifierDependency.Template = class HarmonyEvaluatedImportSpecifierDependencyTemplate extends ( + HarmonyImportSpecifierDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = + /** @type {HarmonyEvaluatedImportSpecifierDependency} */ + (dependency); + const { module, moduleGraph, runtime } = templateContext; + const connection = moduleGraph.getConnection(dep); + // Skip rendering depending when dependency is conditional + if (connection && !connection.isTargetActive(runtime)) return; + + const exportsInfo = moduleGraph.getExportsInfo( + /** @type {ModuleGraphConnection} */ (connection).module + ); + const ids = dep.getIds(moduleGraph); + + let value; + + const exportsType = + /** @type {ModuleGraphConnection} */ + (connection).module.getExportsType( + moduleGraph, + /** @type {BuildMeta} */ + (module.buildMeta).strictHarmonyModule + ); + switch (exportsType) { + case "default-with-named": { + if (ids[0] === "default") { + value = + ids.length === 1 || exportsInfo.isExportProvided(ids.slice(1)); + } else { + value = exportsInfo.isExportProvided(ids); + } + break; + } + case "namespace": { + value = + ids[0] === "__esModule" + ? ids.length === 1 || undefined + : exportsInfo.isExportProvided(ids); + break; + } + case "dynamic": { + if (ids[0] !== "default") { + value = exportsInfo.isExportProvided(ids); + } + break; + } + // default-only could lead to runtime error, when default value is primitive + } + + if (typeof value === "boolean") { + source.replace(dep.range[0], dep.range[1] - 1, ` ${value}`); + } else { + const usedName = exportsInfo.getUsedName(ids, runtime); + + const code = this._getCodeForIds( + dep, + source, + templateContext, + ids.slice(0, -1) + ); + source.replace( + dep.range[0], + dep.range[1] - 1, + `${ + usedName ? JSON.stringify(usedName[usedName.length - 1]) : '""' + } in ${code}` + ); + } + } +}; + +module.exports = HarmonyEvaluatedImportSpecifierDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportDependencyParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportDependencyParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..be2056fee9f1e9a7e11a9a03eb4a2aba9f5336af --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportDependencyParserPlugin.js @@ -0,0 +1,243 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("../WebpackError"); +const { getImportAttributes } = require("../javascript/JavascriptParser"); +const InnerGraph = require("../optimize/InnerGraph"); +const ConstDependency = require("./ConstDependency"); +const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency"); +const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency"); +const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency"); +const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency"); +const { ExportPresenceModes } = require("./HarmonyImportDependency"); +const { + getImportMode, + harmonySpecifierTag +} = require("./HarmonyImportDependencyParserPlugin"); +const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency"); + +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").ClassDeclaration} ClassDeclaration */ +/** @typedef {import("../javascript/JavascriptParser").FunctionDeclaration} FunctionDeclaration */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const { HarmonyStarExportsList } = HarmonyExportImportedSpecifierDependency; + +const PLUGIN_NAME = "HarmonyExportDependencyParserPlugin"; + +module.exports = class HarmonyExportDependencyParserPlugin { + /** + * @param {import("../../declarations/WebpackOptions").JavascriptParserOptions} options options + */ + constructor(options) { + this.exportPresenceMode = + options.reexportExportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.reexportExportsPresence) + : options.exportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.exportsPresence) + : options.strictExportPresence + ? ExportPresenceModes.ERROR + : ExportPresenceModes.AUTO; + this.deferImport = options.deferImport; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + const { exportPresenceMode } = this; + parser.hooks.export.tap(PLUGIN_NAME, (statement) => { + const dep = new HarmonyExportHeaderDependency( + /** @type {Range | false} */ ( + statement.declaration && statement.declaration.range + ), + /** @type {Range} */ (statement.range) + ); + dep.loc = Object.create( + /** @type {DependencyLocation} */ (statement.loc) + ); + dep.loc.index = -1; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.exportImport.tap(PLUGIN_NAME, (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency( + "", + /** @type {Range} */ (statement.range) + ); + clearDep.loc = /** @type {DependencyLocation} */ (statement.loc); + clearDep.loc.index = -1; + parser.state.module.addPresentationalDependency(clearDep); + let defer = false; + if (this.deferImport) { + ({ defer } = getImportMode(parser, statement)); + if (defer) { + const error = new WebpackError( + "Deferred re-export (`export defer * as namespace from '...'`) is not a part of the Import Defer proposal.\nUse the following code instead:\n import defer * as namespace from '...';\n export { namespace };" + ); + error.loc = statement.loc || undefined; + parser.state.current.addError(error); + } + } + const sideEffectDep = new HarmonyImportSideEffectDependency( + /** @type {string} */ (source), + parser.state.lastHarmonyImportOrder, + getImportAttributes(statement), + defer + ); + sideEffectDep.loc = Object.create( + /** @type {DependencyLocation} */ (statement.loc) + ); + sideEffectDep.loc.index = -1; + parser.state.current.addDependency(sideEffectDep); + return true; + }); + parser.hooks.exportExpression.tap(PLUGIN_NAME, (statement, node) => { + const isFunctionDeclaration = node.type === "FunctionDeclaration"; + const exprRange = /** @type {Range} */ (node.range); + const statementRange = /** @type {Range} */ (statement.range); + const comments = parser.getComments([statementRange[0], exprRange[0]]); + const dep = new HarmonyExportExpressionDependency( + exprRange, + statementRange, + comments + .map((c) => { + switch (c.type) { + case "Block": + return `/*${c.value}*/`; + case "Line": + return `//${c.value}\n`; + } + return ""; + }) + .join(""), + node.type.endsWith("Declaration") && + /** @type {FunctionDeclaration | ClassDeclaration} */ (node).id + ? /** @type {FunctionDeclaration | ClassDeclaration} */ + (node).id.name + : isFunctionDeclaration + ? { + range: [ + exprRange[0], + node.params.length > 0 + ? /** @type {Range} */ (node.params[0].range)[0] + : /** @type {Range} */ (node.body.range)[0] + ], + prefix: `${node.async ? "async " : ""}function${ + node.generator ? "*" : "" + } `, + suffix: `(${node.params.length > 0 ? "" : ") "}` + } + : undefined + ); + dep.loc = Object.create( + /** @type {DependencyLocation} */ (statement.loc) + ); + dep.loc.index = -1; + parser.state.current.addDependency(dep); + InnerGraph.addVariableUsage( + parser, + node.type.endsWith("Declaration") && + /** @type {FunctionDeclaration | ClassDeclaration} */ (node).id + ? /** @type {FunctionDeclaration | ClassDeclaration} */ (node).id.name + : "*default*", + "default" + ); + return true; + }); + parser.hooks.exportSpecifier.tap( + PLUGIN_NAME, + (statement, id, name, idx) => { + const settings = parser.getTagData(id, harmonySpecifierTag); + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + harmonyNamedExports.add(name); + InnerGraph.addVariableUsage(parser, id, name); + const dep = settings + ? new HarmonyExportImportedSpecifierDependency( + settings.source, + settings.sourceOrder, + settings.ids, + name, + harmonyNamedExports, + null, + exportPresenceMode, + null, + settings.attributes, + settings.defer + ) + : new HarmonyExportSpecifierDependency(id, name); + dep.loc = Object.create( + /** @type {DependencyLocation} */ (statement.loc) + ); + dep.loc.index = idx; + const isAsiSafe = !parser.isAsiPosition( + /** @type {Range} */ + (statement.range)[0] + ); + if (!isAsiSafe) { + parser.setAsiPosition(/** @type {Range} */ (statement.range)[1]); + } + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportImportSpecifier.tap( + PLUGIN_NAME, + (statement, source, id, name, idx) => { + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + /** @type {InstanceType | null} */ + let harmonyStarExports = null; + if (name) { + harmonyNamedExports.add(name); + } else { + harmonyStarExports = parser.state.harmonyStarExports = + parser.state.harmonyStarExports || new HarmonyStarExportsList(); + } + const attributes = getImportAttributes(statement); + const defer = this.deferImport + ? getImportMode(parser, statement).defer + : false; + const dep = new HarmonyExportImportedSpecifierDependency( + /** @type {string} */ + (source), + parser.state.lastHarmonyImportOrder, + id ? [id] : [], + name, + harmonyNamedExports, + // eslint-disable-next-line unicorn/prefer-spread + harmonyStarExports && harmonyStarExports.slice(), + exportPresenceMode, + harmonyStarExports, + attributes, + defer + ); + if (harmonyStarExports) { + harmonyStarExports.push(dep); + } + dep.loc = Object.create( + /** @type {DependencyLocation} */ (statement.loc) + ); + dep.loc.index = idx; + const isAsiSafe = !parser.isAsiPosition( + /** @type {Range} */ + (statement.range)[0] + ); + if (!isAsiSafe) { + parser.setAsiPosition(/** @type {Range} */ (statement.range)[1]); + } + parser.state.current.addDependency(dep); + return true; + } + ); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportExpressionDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportExpressionDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..531b139126ff8a3d9987e24b25052609861c5ece --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportExpressionDependency.js @@ -0,0 +1,207 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ConcatenationScope = require("../ConcatenationScope"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const propertyAccess = require("../util/propertyAccess"); +const HarmonyExportInitFragment = require("./HarmonyExportInitFragment"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class HarmonyExportExpressionDependency extends NullDependency { + /** + * @param {Range} range range + * @param {Range} rangeStatement range statement + * @param {string} prefix prefix + * @param {string | { id?: string | undefined, range: Range, prefix: string, suffix: string }=} declarationId declaration id + */ + constructor(range, rangeStatement, prefix, declarationId) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; + this.prefix = prefix; + this.declarationId = declarationId; + } + + get type() { + return "harmony export expression"; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: ["default"], + priority: 1, + terminalBinding: true, + dependencies: undefined + }; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + // The expression/declaration is already covered by SideEffectsFlagPlugin + return false; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + write(this.rangeStatement); + write(this.prefix); + write(this.declarationId); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.range = read(); + this.rangeStatement = read(); + this.prefix = read(); + this.declarationId = read(); + super.deserialize(context); + } +} + +makeSerializable( + HarmonyExportExpressionDependency, + "webpack/lib/dependencies/HarmonyExportExpressionDependency" +); + +HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { + module, + moduleGraph, + runtimeTemplate, + runtimeRequirements, + initFragments, + runtime, + concatenationScope + } + ) { + const dep = /** @type {HarmonyExportExpressionDependency} */ (dependency); + const { declarationId } = dep; + const exportsName = module.exportsArgument; + if (declarationId) { + let name; + if (typeof declarationId === "string") { + name = declarationId; + } else { + name = ConcatenationScope.DEFAULT_EXPORT; + source.replace( + declarationId.range[0], + declarationId.range[1] - 1, + `${declarationId.prefix}${name}${declarationId.suffix}` + ); + } + + if (concatenationScope) { + concatenationScope.registerExport("default", name); + } else { + const used = moduleGraph + .getExportsInfo(module) + .getUsedName("default", runtime); + if (used) { + const map = new Map(); + map.set(used, `/* export default binding */ ${name}`); + initFragments.push(new HarmonyExportInitFragment(exportsName, map)); + } + } + + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + `/* harmony default export */ ${dep.prefix}` + ); + } else { + /** @type {string} */ + let content; + const name = ConcatenationScope.DEFAULT_EXPORT; + if (runtimeTemplate.supportsConst()) { + content = `/* harmony default export */ const ${name} = `; + if (concatenationScope) { + concatenationScope.registerExport("default", name); + } else { + const used = moduleGraph + .getExportsInfo(module) + .getUsedName("default", runtime); + if (used) { + runtimeRequirements.add(RuntimeGlobals.exports); + const map = new Map(); + map.set(used, name); + initFragments.push(new HarmonyExportInitFragment(exportsName, map)); + } else { + content = `/* unused harmony default export */ var ${name} = `; + } + } + } else if (concatenationScope) { + content = `/* harmony default export */ var ${name} = `; + concatenationScope.registerExport("default", name); + } else { + const used = moduleGraph + .getExportsInfo(module) + .getUsedName("default", runtime); + if (used) { + runtimeRequirements.add(RuntimeGlobals.exports); + // This is a little bit incorrect as TDZ is not correct, but we can't use const. + content = `/* harmony default export */ ${exportsName}${propertyAccess( + typeof used === "string" ? [used] : used + )} = `; + } else { + content = `/* unused harmony default export */ var ${name} = `; + } + } + + if (dep.range) { + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + `${content}(${dep.prefix}` + ); + source.replace(dep.range[1], dep.rangeStatement[1] - 0.5, ");"); + return; + } + + source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); + } + } +}; + +module.exports = HarmonyExportExpressionDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportHeaderDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportHeaderDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..ae6497966862daa1105f812d69bc63b6f8792205 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportHeaderDependency.js @@ -0,0 +1,78 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class HarmonyExportHeaderDependency extends NullDependency { + /** + * @param {Range | false} range range + * @param {Range} rangeStatement range statement + */ + constructor(range, rangeStatement) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; + } + + get type() { + return "harmony export header"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + write(this.rangeStatement); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.range = read(); + this.rangeStatement = read(); + super.deserialize(context); + } +} + +makeSerializable( + HarmonyExportHeaderDependency, + "webpack/lib/dependencies/HarmonyExportHeaderDependency" +); + +HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {HarmonyExportHeaderDependency} */ (dependency); + const content = ""; + const replaceUntil = dep.range + ? dep.range[0] - 1 + : dep.rangeStatement[1] - 1; + source.replace(dep.rangeStatement[0], replaceUntil, content); + } +}; + +module.exports = HarmonyExportHeaderDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..84eabafe3f432226b571dedb835954ae7f23afe3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js @@ -0,0 +1,1487 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ConditionalInitFragment = require("../ConditionalInitFragment"); +const Dependency = require("../Dependency"); +const { UsageState } = require("../ExportsInfo"); +const HarmonyLinkingError = require("../HarmonyLinkingError"); +const InitFragment = require("../InitFragment"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const { + getMakeDeferredNamespaceModeFromExportsType +} = require("../runtime/MakeDeferredNamespaceObjectRuntime"); +const { countIterable } = require("../util/IterableHelpers"); +const { combine, first } = require("../util/SetHelpers"); +const makeSerializable = require("../util/makeSerializable"); +const propertyAccess = require("../util/propertyAccess"); +const { propertyName } = require("../util/propertyName"); +const { + filterRuntime, + getRuntimeKey, + keyToRuntime +} = require("../util/runtime"); +const HarmonyExportInitFragment = require("./HarmonyExportInitFragment"); +const HarmonyImportDependency = require("./HarmonyImportDependency"); +const processExportInfo = require("./processExportInfo"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("../ExportsInfo").UsedName} UsedName */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./HarmonyImportDependency").ExportPresenceMode} ExportPresenceMode */ +/** @typedef {import("./processExportInfo").ReferencedExports} ReferencedExports */ + +/** @typedef {"missing"|"unused"|"empty-star"|"reexport-dynamic-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-fake-namespace-object"|"reexport-undefined"|"normal-reexport"|"dynamic-reexport"} ExportModeType */ + +const { ExportPresenceModes } = HarmonyImportDependency; + +const idsSymbol = Symbol("HarmonyExportImportedSpecifierDependency.ids"); + +class NormalReexportItem { + /** + * @param {string} name export name + * @param {string[]} ids reexported ids from other module + * @param {ExportInfo} exportInfo export info from other module + * @param {boolean} checked true, if it should be checked at runtime if this export exists + * @param {boolean} hidden true, if it is hidden behind another active export in the same module + */ + constructor(name, ids, exportInfo, checked, hidden) { + this.name = name; + this.ids = ids; + this.exportInfo = exportInfo; + this.checked = checked; + this.hidden = hidden; + } +} + +/** @typedef {Set} ExportModeIgnored */ +/** @typedef {Set} ExportModeHidden */ + +class ExportMode { + /** + * @param {ExportModeType} type type of the mode + */ + constructor(type) { + /** @type {ExportModeType} */ + this.type = type; + + // for "normal-reexport": + /** @type {NormalReexportItem[] | null} */ + this.items = null; + + // for "reexport-named-default" | "reexport-fake-namespace-object" | "reexport-namespace-object" + /** @type {string | null} */ + this.name = null; + /** @type {ExportInfo | null} */ + this.partialNamespaceExportInfo = null; + + // for "dynamic-reexport": + /** @type {ExportModeIgnored | null} */ + this.ignored = null; + + // for "dynamic-reexport" | "empty-star": + /** @type {ExportModeHidden | undefined | null} */ + this.hidden = null; + + // for "missing": + /** @type {string | null} */ + this.userRequest = null; + + // for "reexport-fake-namespace-object": + /** @type {number} */ + this.fakeType = 0; + } +} + +/** @typedef {string[]} Names */ +/** @typedef {number[]} DependencyIndices */ + +/** + * @param {ModuleGraph} moduleGraph module graph + * @param {ReadonlyArray} dependencies dependencies + * @param {TODO=} additionalDependency additional dependency + * @returns {{ names: Names, dependencyIndices: DependencyIndices }} result + */ +const determineExportAssignments = ( + moduleGraph, + dependencies, + additionalDependency +) => { + /** @type {Set} */ + const names = new Set(); + /** @type {number[]} */ + const dependencyIndices = []; + + if (additionalDependency) { + dependencies = [...dependencies, additionalDependency]; + } + + for (const dep of dependencies) { + const i = dependencyIndices.length; + dependencyIndices[i] = names.size; + const otherImportedModule = moduleGraph.getModule(dep); + if (otherImportedModule) { + const exportsInfo = moduleGraph.getExportsInfo(otherImportedModule); + for (const exportInfo of exportsInfo.exports) { + if ( + exportInfo.provided === true && + exportInfo.name !== "default" && + !names.has(exportInfo.name) + ) { + names.add(exportInfo.name); + dependencyIndices[i] = names.size; + } + } + } + } + dependencyIndices.push(names.size); + + return { names: [...names], dependencyIndices }; +}; + +/** + * @param {object} options options + * @param {Names} options.names names + * @param {DependencyIndices} options.dependencyIndices dependency indices + * @param {string} name name + * @param {ReadonlyArray} dependencies dependencies + * @returns {HarmonyExportImportedSpecifierDependency | undefined} found dependency or nothing + */ +const findDependencyForName = ( + { names, dependencyIndices }, + name, + dependencies +) => { + const dependenciesIt = dependencies[Symbol.iterator](); + const dependencyIndicesIt = dependencyIndices[Symbol.iterator](); + let dependenciesItResult = dependenciesIt.next(); + let dependencyIndicesItResult = dependencyIndicesIt.next(); + if (dependencyIndicesItResult.done) return; + for (let i = 0; i < names.length; i++) { + while (i >= dependencyIndicesItResult.value) { + dependenciesItResult = dependenciesIt.next(); + dependencyIndicesItResult = dependencyIndicesIt.next(); + if (dependencyIndicesItResult.done) return; + } + if (names[i] === name) return dependenciesItResult.value; + } + return undefined; +}; + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {HarmonyExportImportedSpecifierDependency} dep the dependency + * @param {string} runtimeKey the runtime key + * @returns {ExportMode} the export mode + */ +const getMode = (moduleGraph, dep, runtimeKey) => { + const importedModule = moduleGraph.getModule(dep); + + if (!importedModule) { + const mode = new ExportMode("missing"); + + mode.userRequest = dep.userRequest; + + return mode; + } + + const name = dep.name; + const runtime = keyToRuntime(runtimeKey); + const parentModule = /** @type {Module} */ (moduleGraph.getParentModule(dep)); + const exportsInfo = moduleGraph.getExportsInfo(parentModule); + + if ( + name + ? exportsInfo.getUsed(name, runtime) === UsageState.Unused + : exportsInfo.isUsed(runtime) === false + ) { + const mode = new ExportMode("unused"); + + mode.name = name || "*"; + + return mode; + } + + const importedExportsType = importedModule.getExportsType( + moduleGraph, + /** @type {BuildMeta} */ + (parentModule.buildMeta).strictHarmonyModule + ); + + const ids = dep.getIds(moduleGraph); + + // Special handling for reexporting the default export + // from non-namespace modules + if (name && ids.length > 0 && ids[0] === "default") { + switch (importedExportsType) { + case "dynamic": { + const mode = new ExportMode("reexport-dynamic-default"); + + mode.name = name; + + return mode; + } + case "default-only": + case "default-with-named": { + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + const mode = new ExportMode("reexport-named-default"); + + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + + return mode; + } + } + } + + // reexporting with a fixed name + if (name) { + let mode; + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + + if (ids.length > 0) { + // export { name as name } + switch (importedExportsType) { + case "default-only": + mode = new ExportMode("reexport-undefined"); + mode.name = name; + break; + default: + mode = new ExportMode("normal-reexport"); + mode.items = [ + new NormalReexportItem(name, ids, exportInfo, false, false) + ]; + break; + } + } else { + // export * as name + switch (importedExportsType) { + case "default-only": + mode = new ExportMode("reexport-fake-namespace-object"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + mode.fakeType = 0; + break; + case "default-with-named": + mode = new ExportMode("reexport-fake-namespace-object"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + mode.fakeType = 2; + break; + case "dynamic": + default: + mode = new ExportMode("reexport-namespace-object"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + } + } + + return mode; + } + + // Star reexporting + const { ignoredExports, exports, checked, hidden } = dep.getStarReexports( + moduleGraph, + runtime, + exportsInfo, + importedModule + ); + if (!exports) { + // We have too few info about the modules + // Delegate the logic to the runtime code + + const mode = new ExportMode("dynamic-reexport"); + mode.ignored = ignoredExports; + mode.hidden = hidden; + + return mode; + } + + if (exports.size === 0) { + const mode = new ExportMode("empty-star"); + mode.hidden = hidden; + + return mode; + } + + const mode = new ExportMode("normal-reexport"); + + mode.items = Array.from( + exports, + (exportName) => + new NormalReexportItem( + exportName, + [exportName], + exportsInfo.getReadOnlyExportInfo(exportName), + /** @type {Set} */ + (checked).has(exportName), + false + ) + ); + if (hidden !== undefined) { + for (const exportName of hidden) { + mode.items.push( + new NormalReexportItem( + exportName, + [exportName], + exportsInfo.getReadOnlyExportInfo(exportName), + false, + true + ) + ); + } + } + + return mode; +}; + +/** @typedef {string[]} Ids */ +/** @typedef {Set} Exports */ +/** @typedef {Set} Checked */ +/** @typedef {Set} Hidden */ +/** @typedef {Set} IgnoredExports */ + +class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { + /** + * @param {string} request the request string + * @param {number} sourceOrder the order in the original source file + * @param {Ids} ids the requested export name of the imported module + * @param {string | null} name the export name of for this module + * @param {Set} activeExports other named exports in the module + * @param {ReadonlyArray | null} otherStarExports other star exports in the module before this import + * @param {ExportPresenceMode} exportPresenceMode mode of checking export names + * @param {HarmonyStarExportsList | null} allStarExports all star exports in the module + * @param {ImportAttributes=} attributes import attributes + * @param {boolean=} defer is defer phase + */ + constructor( + request, + sourceOrder, + ids, + name, + activeExports, + otherStarExports, + exportPresenceMode, + allStarExports, + attributes, + defer + ) { + super(request, sourceOrder, attributes, defer); + + this.ids = ids; + this.name = name; + this.activeExports = activeExports; + this.otherStarExports = otherStarExports; + this.exportPresenceMode = exportPresenceMode; + this.allStarExports = allStarExports; + } + + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return Dependency.TRANSITIVE; + } + + // TODO webpack 6 remove + get id() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + + // TODO webpack 6 remove + getId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + + // TODO webpack 6 remove + setId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + + get type() { + return "harmony export imported specifier"; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {Ids} the imported id + */ + getIds(moduleGraph) { + return moduleGraph.getMeta(this)[idsSymbol] || this.ids; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Ids} ids the imported ids + * @returns {void} + */ + setIds(moduleGraph, ids) { + moduleGraph.getMeta(this)[idsSymbol] = ids; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @returns {ExportMode} the export mode + */ + getMode(moduleGraph, runtime) { + return moduleGraph.dependencyCacheProvide( + this, + getRuntimeKey(runtime), + getMode + ); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @param {ExportsInfo} exportsInfo exports info about the current module (optional) + * @param {Module} importedModule the imported module (optional) + * @returns {{exports?: Exports, checked?: Checked, ignoredExports: IgnoredExports, hidden?: Hidden}} information + */ + getStarReexports( + moduleGraph, + runtime, + exportsInfo = moduleGraph.getExportsInfo( + /** @type {Module} */ (moduleGraph.getParentModule(this)) + ), + importedModule = /** @type {Module} */ (moduleGraph.getModule(this)) + ) { + const importedExportsInfo = moduleGraph.getExportsInfo(importedModule); + const noExtraExports = + importedExportsInfo.otherExportsInfo.provided === false; + const noExtraImports = + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; + + const ignoredExports = new Set(["default", ...this.activeExports]); + + let hiddenExports; + const otherStarExports = + this._discoverActiveExportsFromOtherStarExports(moduleGraph); + if (otherStarExports !== undefined) { + hiddenExports = new Set(); + for (let i = 0; i < otherStarExports.namesSlice; i++) { + hiddenExports.add(otherStarExports.names[i]); + } + for (const e of ignoredExports) hiddenExports.delete(e); + } + + if (!noExtraExports && !noExtraImports) { + return { + ignoredExports, + hidden: hiddenExports + }; + } + + /** @type {Exports} */ + const exports = new Set(); + /** @type {Checked} */ + const checked = new Set(); + /** @type {Hidden | undefined} */ + const hidden = hiddenExports !== undefined ? new Set() : undefined; + + if (noExtraImports) { + for (const exportInfo of exportsInfo.orderedExports) { + const name = exportInfo.name; + if (ignoredExports.has(name)) continue; + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + const importedExportInfo = + importedExportsInfo.getReadOnlyExportInfo(name); + if (importedExportInfo.provided === false) continue; + if (hiddenExports !== undefined && hiddenExports.has(name)) { + /** @type {Set} */ + (hidden).add(name); + continue; + } + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } + } else if (noExtraExports) { + for (const importedExportInfo of importedExportsInfo.orderedExports) { + const name = importedExportInfo.name; + if (ignoredExports.has(name)) continue; + if (importedExportInfo.provided === false) continue; + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + if (hiddenExports !== undefined && hiddenExports.has(name)) { + /** @type {ExportModeHidden} */ + (hidden).add(name); + continue; + } + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } + } + + return { ignoredExports, exports, checked, hidden }; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | GetConditionFn} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return (connection, runtime) => { + const mode = this.getMode(moduleGraph, runtime); + return mode.type !== "unused" && mode.type !== "empty-star"; + }; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + const mode = this.getMode(moduleGraph, runtime); + + switch (mode.type) { + case "missing": + case "unused": + case "empty-star": + case "reexport-undefined": + return Dependency.NO_EXPORTS_REFERENCED; + + case "reexport-dynamic-default": + return Dependency.EXPORTS_OBJECT_REFERENCED; + + case "reexport-named-default": { + if (!mode.partialNamespaceExportInfo) { + return Dependency.EXPORTS_OBJECT_REFERENCED; + } + /** @type {ReferencedExports} */ + const referencedExports = []; + processExportInfo( + runtime, + referencedExports, + [], + /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo) + ); + return referencedExports; + } + + case "reexport-namespace-object": + case "reexport-fake-namespace-object": { + if (!mode.partialNamespaceExportInfo) { + return Dependency.EXPORTS_OBJECT_REFERENCED; + } + /** @type {ReferencedExports} */ + const referencedExports = []; + processExportInfo( + runtime, + referencedExports, + [], + /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo), + mode.type === "reexport-fake-namespace-object" + ); + return referencedExports; + } + + case "dynamic-reexport": + return Dependency.EXPORTS_OBJECT_REFERENCED; + + case "normal-reexport": { + /** @type {ReferencedExports} */ + const referencedExports = []; + for (const { + ids, + exportInfo, + hidden + } of /** @type {NormalReexportItem[]} */ (mode.items)) { + if (hidden) continue; + processExportInfo(runtime, referencedExports, ids, exportInfo, false); + } + return referencedExports; + } + + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {{ names: Names, namesSlice: number, dependencyIndices: DependencyIndices, dependencyIndex: number } | undefined} exported names and their origin dependency + */ + _discoverActiveExportsFromOtherStarExports(moduleGraph) { + if (!this.otherStarExports) return; + + const i = + "length" in this.otherStarExports + ? this.otherStarExports.length + : countIterable(this.otherStarExports); + if (i === 0) return; + + if (this.allStarExports) { + const { names, dependencyIndices } = moduleGraph.cached( + determineExportAssignments, + this.allStarExports.dependencies + ); + + return { + names, + namesSlice: dependencyIndices[i - 1], + dependencyIndices, + dependencyIndex: i + }; + } + + const { names, dependencyIndices } = moduleGraph.cached( + determineExportAssignments, + /** @type {HarmonyExportImportedSpecifierDependency[]} */ + (this.otherStarExports), + this + ); + + return { + names, + namesSlice: dependencyIndices[i - 1], + dependencyIndices, + dependencyIndex: i + }; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const mode = this.getMode(moduleGraph, undefined); + + switch (mode.type) { + case "missing": + return; + case "dynamic-reexport": { + const from = + /** @type {ModuleGraphConnection} */ + (moduleGraph.getConnection(this)); + return { + exports: true, + from, + canMangle: false, + excludeExports: mode.hidden + ? combine( + /** @type {ExportModeIgnored} */ (mode.ignored), + mode.hidden + ) + : /** @type {ExportModeIgnored} */ (mode.ignored), + hideExports: mode.hidden, + dependencies: [from.module] + }; + } + case "empty-star": + return { + exports: [], + hideExports: mode.hidden, + dependencies: [/** @type {Module} */ (moduleGraph.getModule(this))] + }; + // falls through + case "normal-reexport": { + const from = + /** @type {ModuleGraphConnection} */ + (moduleGraph.getConnection(this)); + return { + exports: Array.from( + /** @type {NormalReexportItem[]} */ (mode.items), + (item) => ({ + name: item.name, + from, + export: item.ids, + hidden: item.hidden + }) + ), + priority: 1, + dependencies: [from.module] + }; + } + case "reexport-dynamic-default": { + const from = + /** @type {ModuleGraphConnection} */ + (moduleGraph.getConnection(this)); + return { + exports: [ + { + name: /** @type {string} */ (mode.name), + from, + export: ["default"] + } + ], + priority: 1, + dependencies: [from.module] + }; + } + case "reexport-undefined": + return { + exports: [/** @type {string} */ (mode.name)], + dependencies: [/** @type {Module} */ (moduleGraph.getModule(this))] + }; + case "reexport-fake-namespace-object": { + const from = + /** @type {ModuleGraphConnection} */ + (moduleGraph.getConnection(this)); + return { + exports: [ + { + name: /** @type {string} */ (mode.name), + from, + export: null, + exports: [ + { + name: "default", + canMangle: false, + from, + export: null + } + ] + } + ], + priority: 1, + dependencies: [from.module] + }; + } + case "reexport-namespace-object": { + const from = + /** @type {ModuleGraphConnection} */ + (moduleGraph.getConnection(this)); + return { + exports: [ + { + name: /** @type {string} */ (mode.name), + from, + export: null + } + ], + priority: 1, + dependencies: [from.module] + }; + } + case "reexport-named-default": { + const from = + /** @type {ModuleGraphConnection} */ + (moduleGraph.getConnection(this)); + return { + exports: [ + { + name: /** @type {string} */ (mode.name), + from, + export: ["default"] + } + ], + priority: 1, + dependencies: [from.module] + }; + } + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportPresenceMode} effective mode + */ + _getEffectiveExportPresenceLevel(moduleGraph) { + if (this.exportPresenceMode !== ExportPresenceModes.AUTO) { + return this.exportPresenceMode; + } + const module = /** @type {Module} */ (moduleGraph.getParentModule(this)); + return /** @type {BuildMeta} */ (module.buildMeta).strictHarmonyModule + ? ExportPresenceModes.ERROR + : ExportPresenceModes.WARN; + } + + /** + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | null | undefined} warnings + */ + getWarnings(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.WARN) { + return this._getErrors(moduleGraph); + } + return null; + } + + /** + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | null | undefined} errors + */ + getErrors(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.ERROR) { + return this._getErrors(moduleGraph); + } + return null; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | undefined} errors + */ + _getErrors(moduleGraph) { + const ids = this.getIds(moduleGraph); + let errors = this.getLinkingErrors( + moduleGraph, + ids, + `(reexported as '${this.name}')` + ); + if (ids.length === 0 && this.name === null) { + const potentialConflicts = + this._discoverActiveExportsFromOtherStarExports(moduleGraph); + if (potentialConflicts && potentialConflicts.namesSlice > 0) { + const ownNames = new Set( + potentialConflicts.names.slice( + potentialConflicts.namesSlice, + potentialConflicts.dependencyIndices[ + potentialConflicts.dependencyIndex + ] + ) + ); + const importedModule = moduleGraph.getModule(this); + if (importedModule) { + const exportsInfo = moduleGraph.getExportsInfo(importedModule); + /** @type {Map} */ + const conflicts = new Map(); + for (const exportInfo of exportsInfo.orderedExports) { + if (exportInfo.provided !== true) continue; + if (exportInfo.name === "default") continue; + if (this.activeExports.has(exportInfo.name)) continue; + if (ownNames.has(exportInfo.name)) continue; + const conflictingDependency = findDependencyForName( + potentialConflicts, + exportInfo.name, + this.allStarExports + ? this.allStarExports.dependencies + : [ + .../** @type {ReadonlyArray} */ + (this.otherStarExports), + this + ] + ); + if (!conflictingDependency) continue; + const target = exportInfo.getTerminalBinding(moduleGraph); + if (!target) continue; + const conflictingModule = + /** @type {Module} */ + (moduleGraph.getModule(conflictingDependency)); + if (conflictingModule === importedModule) continue; + const conflictingExportInfo = moduleGraph.getExportInfo( + conflictingModule, + exportInfo.name + ); + const conflictingTarget = + conflictingExportInfo.getTerminalBinding(moduleGraph); + if (!conflictingTarget) continue; + if (target === conflictingTarget) continue; + const list = conflicts.get(conflictingDependency.request); + if (list === undefined) { + conflicts.set(conflictingDependency.request, [exportInfo.name]); + } else { + list.push(exportInfo.name); + } + } + for (const [request, exports] of conflicts) { + if (!errors) errors = []; + errors.push( + new HarmonyLinkingError( + `The requested module '${ + this.request + }' contains conflicting star exports for the ${ + exports.length > 1 ? "names" : "name" + } ${exports + .map((e) => `'${e}'`) + .join(", ")} with the previous requested module '${request}'` + ) + ); + } + } + } + } + return errors; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write, setCircularReference } = context; + + setCircularReference(this); + write(this.ids); + write(this.name); + write(this.activeExports); + write(this.otherStarExports); + write(this.exportPresenceMode); + write(this.allStarExports); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read, setCircularReference } = context; + + setCircularReference(this); + this.ids = read(); + this.name = read(); + this.activeExports = read(); + this.otherStarExports = read(); + this.exportPresenceMode = read(); + this.allStarExports = read(); + + super.deserialize(context); + } +} + +makeSerializable( + HarmonyExportImportedSpecifierDependency, + "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency" +); + +module.exports = HarmonyExportImportedSpecifierDependency; + +HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends ( + HarmonyImportDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const { moduleGraph, runtime, concatenationScope } = templateContext; + + const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ ( + dependency + ); + + const mode = dep.getMode(moduleGraph, runtime); + + if (concatenationScope) { + switch (mode.type) { + case "reexport-undefined": + concatenationScope.registerRawExport( + /** @type {NonNullable} */ (mode.name), + "/* reexport non-default export from non-harmony */ undefined" + ); + } + return; + } + + if (mode.type !== "unused" && mode.type !== "empty-star") { + super.apply(dependency, source, templateContext); + + this._addExportFragments( + templateContext.initFragments, + dep, + mode, + templateContext.module, + moduleGraph, + templateContext.chunkGraph, + runtime, + templateContext.runtimeTemplate, + templateContext.runtimeRequirements + ); + } + } + + /** + * @param {InitFragment[]} initFragments target array for init fragments + * @param {HarmonyExportImportedSpecifierDependency} dep dependency + * @param {ExportMode} mode the export mode + * @param {Module} module the current module + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {RuntimeSpec} runtime the runtime + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {RuntimeRequirements} runtimeRequirements runtime requirements + * @returns {void} + */ + _addExportFragments( + initFragments, + dep, + mode, + module, + moduleGraph, + chunkGraph, + runtime, + runtimeTemplate, + runtimeRequirements + ) { + const importedModule = /** @type {Module} */ (moduleGraph.getModule(dep)); + const importVar = dep.getImportVar(moduleGraph); + + if ( + (mode.type === "reexport-namespace-object" || + mode.type === "reexport-fake-namespace-object") && + dep.defer && + !moduleGraph.isAsync(importedModule) + ) { + initFragments.push( + ...this.getReexportDeferredNamespaceObjectFragments( + importedModule, + chunkGraph, + moduleGraph + .getExportsInfo(module) + .getUsedName(mode.name ? mode.name : [], runtime), + importVar, + importedModule.getExportsType( + moduleGraph, + module.buildMeta && module.buildMeta.strictHarmonyModule + ), + runtimeRequirements + ) + ); + return; + } + switch (mode.type) { + case "missing": + case "empty-star": + initFragments.push( + new InitFragment( + "/* empty/unused harmony star reexport */\n", + InitFragment.STAGE_HARMONY_EXPORTS, + 1 + ) + ); + break; + + case "unused": + initFragments.push( + new InitFragment( + `${Template.toNormalComment( + `unused harmony reexport ${mode.name}` + )}\n`, + InitFragment.STAGE_HARMONY_EXPORTS, + 1 + ) + ); + break; + + case "reexport-dynamic-default": + initFragments.push( + this.getReexportFragment( + module, + "reexport default from dynamic", + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), + importVar, + null, + runtimeRequirements + ) + ); + break; + + case "reexport-fake-namespace-object": + initFragments.push( + ...this.getReexportFakeNamespaceObjectFragments( + module, + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), + importVar, + mode.fakeType, + runtimeRequirements + ) + ); + break; + + case "reexport-undefined": + initFragments.push( + this.getReexportFragment( + module, + "reexport non-default export from non-harmony", + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), + "undefined", + "", + runtimeRequirements + ) + ); + break; + + case "reexport-named-default": + initFragments.push( + this.getReexportFragment( + module, + "reexport default export from named module", + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), + importVar, + "", + runtimeRequirements + ) + ); + break; + + case "reexport-namespace-object": + initFragments.push( + this.getReexportFragment( + module, + "reexport module object", + moduleGraph + .getExportsInfo(module) + .getUsedName(/** @type {string} */ (mode.name), runtime), + importVar, + "", + runtimeRequirements + ) + ); + break; + + case "normal-reexport": + for (const { + name, + ids, + checked, + hidden + } of /** @type {NormalReexportItem[]} */ (mode.items)) { + if (hidden) continue; + if (checked) { + const connection = moduleGraph.getConnection(dep); + const key = `harmony reexport (checked) ${importVar} ${name}`; + const runtimeCondition = dep.weak + ? false + : connection + ? filterRuntime(runtime, (r) => connection.isTargetActive(r)) + : true; + initFragments.push( + new ConditionalInitFragment( + `/* harmony reexport (checked) */ ${this.getConditionalReexportStatement( + module, + name, + importVar, + ids, + runtimeRequirements + )}`, + moduleGraph.isAsync(importedModule) + ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS + : InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder, + key, + runtimeCondition + ) + ); + } else { + initFragments.push( + this.getReexportFragment( + module, + "reexport safe", + moduleGraph.getExportsInfo(module).getUsedName(name, runtime), + importVar, + moduleGraph + .getExportsInfo(importedModule) + .getUsedName(ids, runtime), + runtimeRequirements + ) + ); + } + } + break; + + case "dynamic-reexport": { + const ignored = mode.hidden + ? combine( + /** @type {ExportModeIgnored} */ + (mode.ignored), + mode.hidden + ) + : /** @type {ExportModeIgnored} */ (mode.ignored); + const modern = + runtimeTemplate.supportsConst() && + runtimeTemplate.supportsArrowFunction(); + let content = + "/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {};\n" + + `/* harmony reexport (unknown) */ for(${ + modern ? "const" : "var" + } __WEBPACK_IMPORT_KEY__ in ${importVar}) `; + + // Filter out exports which are defined by other exports + // and filter out default export because it cannot be reexported with * + if (ignored.size > 1) { + content += `if(${JSON.stringify([ + ...ignored + ])}.indexOf(__WEBPACK_IMPORT_KEY__) < 0) `; + } else if (ignored.size === 1) { + content += `if(__WEBPACK_IMPORT_KEY__ !== ${JSON.stringify( + first(ignored) + )}) `; + } + + content += "__WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = "; + content += modern + ? `() => ${importVar}[__WEBPACK_IMPORT_KEY__]` + : `function(key) { return ${importVar}[key]; }.bind(0, __WEBPACK_IMPORT_KEY__)`; + + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + + const exportsName = module.exportsArgument; + initFragments.push( + new InitFragment( + `${content}\n/* harmony reexport (unknown) */ ${RuntimeGlobals.definePropertyGetters}(${exportsName}, __WEBPACK_REEXPORT_OBJECT__);\n`, + moduleGraph.isAsync(importedModule) + ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS + : InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder + ) + ); + break; + } + + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } + + /** + * @param {Module} module the current module + * @param {string} comment comment + * @param {UsedName} key key + * @param {string} name name + * @param {string | string[] | null | false} valueKey value key + * @param {RuntimeRequirements} runtimeRequirements runtime requirements + * @returns {HarmonyExportInitFragment} harmony export init fragment + */ + getReexportFragment( + module, + comment, + key, + name, + valueKey, + runtimeRequirements + ) { + const returnValue = this.getReturnValue(name, valueKey); + + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + + const map = new Map(); + map.set(key, `/* ${comment} */ ${returnValue}`); + + return new HarmonyExportInitFragment(module.exportsArgument, map); + } + + /** + * @param {Module} module module + * @param {string | string[] | false} key key + * @param {string} name name + * @param {number} fakeType fake type + * @param {RuntimeRequirements} runtimeRequirements runtime requirements + * @returns {[InitFragment, HarmonyExportInitFragment]} init fragments + */ + getReexportFakeNamespaceObjectFragments( + module, + key, + name, + fakeType, + runtimeRequirements + ) { + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + + const map = new Map(); + map.set( + key, + `/* reexport fake namespace object from non-harmony */ ${name}_namespace_cache || (${name}_namespace_cache = ${ + RuntimeGlobals.createFakeNamespaceObject + }(${name}${fakeType ? `, ${fakeType}` : ""}))` + ); + + return [ + new InitFragment( + `var ${name}_namespace_cache;\n`, + InitFragment.STAGE_CONSTANTS, + -1, + `${name}_namespace_cache` + ), + new HarmonyExportInitFragment(module.exportsArgument, map) + ]; + } + + /** + * @param {Module} module module + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {string | false | string[]} key key + * @param {string} name name + * @param {import("../Module").ExportsType} exportsType exportsType + * @param {Set} runtimeRequirements runtimeRequirements + * @returns {InitFragment[]} fragments + */ + getReexportDeferredNamespaceObjectFragments( + module, + chunkGraph, + key, + name, + exportsType, + runtimeRequirements + ) { + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject); + + const map = new Map(); + const moduleId = JSON.stringify(chunkGraph.getModuleId(module)); + const mode = getMakeDeferredNamespaceModeFromExportsType(exportsType); + map.set( + key, + `/* reexport deferred namespace object */ ${name}_deferred_namespace_cache || (${name}_deferred_namespace_cache = ${RuntimeGlobals.makeDeferredNamespaceObject}(${moduleId}, ${mode}))` + ); + + return [ + new InitFragment( + `var ${name}_deferred_namespace_cache;\n`, + InitFragment.STAGE_CONSTANTS, + -1, + `${name}_deferred_namespace_cache` + ), + new HarmonyExportInitFragment(module.exportsArgument, map) + ]; + } + + /** + * @param {Module} module module + * @param {string} key key + * @param {string} name name + * @param {string | string[] | false} valueKey value key + * @param {RuntimeRequirements} runtimeRequirements runtime requirements + * @returns {string} result + */ + getConditionalReexportStatement( + module, + key, + name, + valueKey, + runtimeRequirements + ) { + if (valueKey === false) { + return "/* unused export */\n"; + } + + const exportsName = module.exportsArgument; + const returnValue = this.getReturnValue(name, valueKey); + + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + runtimeRequirements.add(RuntimeGlobals.hasOwnProperty); + + return `if(${RuntimeGlobals.hasOwnProperty}(${name}, ${JSON.stringify( + valueKey[0] + )})) ${ + RuntimeGlobals.definePropertyGetters + }(${exportsName}, { ${propertyName( + key + )}: function() { return ${returnValue}; } });\n`; + } + + /** + * @param {string} name name + * @param {null | false | string | string[]} valueKey value key + * @returns {string | undefined} value + */ + getReturnValue(name, valueKey) { + if (valueKey === null) { + return `${name}_default.a`; + } + + if (valueKey === "") { + return name; + } + + if (valueKey === false) { + return "/* unused export */ undefined"; + } + + return `${name}${propertyAccess(valueKey)}`; + } +}; + +class HarmonyStarExportsList { + constructor() { + /** @type {HarmonyExportImportedSpecifierDependency[]} */ + this.dependencies = []; + } + + /** + * @param {HarmonyExportImportedSpecifierDependency} dep dependency + * @returns {void} + */ + push(dep) { + this.dependencies.push(dep); + } + + slice() { + return [...this.dependencies]; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize({ write, setCircularReference }) { + setCircularReference(this); + write(this.dependencies); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize({ read, setCircularReference }) { + setCircularReference(this); + this.dependencies = read(); + } +} + +makeSerializable( + HarmonyStarExportsList, + "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency", + "HarmonyStarExportsList" +); + +module.exports.HarmonyStarExportsList = HarmonyStarExportsList; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportInitFragment.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportInitFragment.js new file mode 100644 index 0000000000000000000000000000000000000000..d81cbad9227fea48b1312e197082aeeffe98f4c1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportInitFragment.js @@ -0,0 +1,177 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const InitFragment = require("../InitFragment"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const { first } = require("../util/SetHelpers"); +const { propertyName } = require("../util/propertyName"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ + +/** + * @param {Iterable} iterable iterable strings + * @returns {string} result + */ +const joinIterableWithComma = (iterable) => { + // This is more performant than Array.from().join(", ") + // as it doesn't create an array + let str = ""; + let first = true; + for (const item of iterable) { + if (first) { + first = false; + } else { + str += ", "; + } + str += item; + } + return str; +}; + +const EMPTY_MAP = new Map(); +const EMPTY_SET = new Set(); + +/** + * @extends {InitFragment} Context + */ +class HarmonyExportInitFragment extends InitFragment { + /** + * @param {string} exportsArgument the exports identifier + * @param {Map} exportMap mapping from used name to exposed variable name + * @param {Set} unusedExports list of unused export names + */ + constructor( + exportsArgument, + exportMap = EMPTY_MAP, + unusedExports = EMPTY_SET + ) { + super(undefined, InitFragment.STAGE_HARMONY_EXPORTS, 1, "harmony-exports"); + this.exportsArgument = exportsArgument; + this.exportMap = exportMap; + this.unusedExports = unusedExports; + } + + /** + * @param {HarmonyExportInitFragment[]} fragments all fragments to merge + * @returns {HarmonyExportInitFragment} merged fragment + */ + mergeAll(fragments) { + let exportMap; + let exportMapOwned = false; + let unusedExports; + let unusedExportsOwned = false; + + for (const fragment of fragments) { + if (fragment.exportMap.size !== 0) { + if (exportMap === undefined) { + exportMap = fragment.exportMap; + exportMapOwned = false; + } else { + if (!exportMapOwned) { + exportMap = new Map(exportMap); + exportMapOwned = true; + } + for (const [key, value] of fragment.exportMap) { + if (!exportMap.has(key)) exportMap.set(key, value); + } + } + } + if (fragment.unusedExports.size !== 0) { + if (unusedExports === undefined) { + unusedExports = fragment.unusedExports; + unusedExportsOwned = false; + } else { + if (!unusedExportsOwned) { + unusedExports = new Set(unusedExports); + unusedExportsOwned = true; + } + for (const value of fragment.unusedExports) { + unusedExports.add(value); + } + } + } + } + return new HarmonyExportInitFragment( + this.exportsArgument, + exportMap, + unusedExports + ); + } + + /** + * @param {HarmonyExportInitFragment} other other + * @returns {HarmonyExportInitFragment} merged result + */ + merge(other) { + let exportMap; + if (this.exportMap.size === 0) { + exportMap = other.exportMap; + } else if (other.exportMap.size === 0) { + exportMap = this.exportMap; + } else { + exportMap = new Map(other.exportMap); + for (const [key, value] of this.exportMap) { + if (!exportMap.has(key)) exportMap.set(key, value); + } + } + let unusedExports; + if (this.unusedExports.size === 0) { + unusedExports = other.unusedExports; + } else if (other.unusedExports.size === 0) { + unusedExports = this.unusedExports; + } else { + unusedExports = new Set(other.unusedExports); + for (const value of this.unusedExports) { + unusedExports.add(value); + } + } + return new HarmonyExportInitFragment( + this.exportsArgument, + exportMap, + unusedExports + ); + } + + /** + * @param {GenerateContext} context context + * @returns {string | Source | undefined} the source code that will be included as initialization code + */ + getContent({ runtimeTemplate, runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + + const unusedPart = + this.unusedExports.size > 1 + ? `/* unused harmony exports ${joinIterableWithComma( + this.unusedExports + )} */\n` + : this.unusedExports.size > 0 + ? `/* unused harmony export ${first(this.unusedExports)} */\n` + : ""; + const definitions = []; + const orderedExportMap = [...this.exportMap].sort(([a], [b]) => + a < b ? -1 : 1 + ); + for (const [key, value] of orderedExportMap) { + definitions.push( + `\n/* harmony export */ ${propertyName( + key + )}: ${runtimeTemplate.returningFunction(value)}` + ); + } + const definePart = + this.exportMap.size > 0 + ? `/* harmony export */ ${RuntimeGlobals.definePropertyGetters}(${ + this.exportsArgument + }, {${definitions.join(",")}\n/* harmony export */ });\n` + : ""; + return `${definePart}${unusedPart}`; + } +} + +module.exports = HarmonyExportInitFragment; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportSpecifierDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportSpecifierDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..b15d0846e3d1c36b8f855e0a530b299f661898a3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExportSpecifierDependency.js @@ -0,0 +1,123 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const HarmonyExportInitFragment = require("./HarmonyExportInitFragment"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class HarmonyExportSpecifierDependency extends NullDependency { + /** + * @param {string} id the id + * @param {string} name the name + */ + constructor(id, name) { + super(); + this.id = id; + this.name = name; + } + + get type() { + return "harmony export specifier"; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: [this.name], + priority: 1, + terminalBinding: true, + dependencies: undefined + }; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.id); + write(this.name); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.id = read(); + this.name = read(); + super.deserialize(context); + } +} + +makeSerializable( + HarmonyExportSpecifierDependency, + "webpack/lib/dependencies/HarmonyExportSpecifierDependency" +); + +HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { module, moduleGraph, initFragments, runtime, concatenationScope } + ) { + const dep = /** @type {HarmonyExportSpecifierDependency} */ (dependency); + if (concatenationScope) { + concatenationScope.registerExport(dep.name, dep.id); + return; + } + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.name, runtime); + if (!used) { + const set = new Set(); + set.add(dep.name || "namespace"); + initFragments.push( + new HarmonyExportInitFragment(module.exportsArgument, undefined, set) + ); + return; + } + + const map = new Map(); + map.set(used, `/* binding */ ${dep.id}`); + initFragments.push( + new HarmonyExportInitFragment(module.exportsArgument, map, undefined) + ); + } +}; + +module.exports = HarmonyExportSpecifierDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExports.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExports.js new file mode 100644 index 0000000000000000000000000000000000000000..fe1b28d4e360a61328a5e7583f3ee3fb097de085 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyExports.js @@ -0,0 +1,46 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); + +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Parser").ParserState} ParserState */ + +/** @type {WeakMap} */ +const parserStateExportsState = new WeakMap(); + +/** + * @param {ParserState} parserState parser state + * @param {boolean} isStrictHarmony strict harmony mode should be enabled + * @returns {void} + */ +module.exports.enable = (parserState, isStrictHarmony) => { + const value = parserStateExportsState.get(parserState); + if (value === false) return; + parserStateExportsState.set(parserState, true); + if (value !== true) { + const buildMeta = /** @type {BuildMeta} */ (parserState.module.buildMeta); + buildMeta.exportsType = "namespace"; + const buildInfo = /** @type {BuildInfo} */ (parserState.module.buildInfo); + buildInfo.strict = true; + buildInfo.exportsArgument = RuntimeGlobals.exports; + if (isStrictHarmony) { + buildMeta.strictHarmonyModule = true; + buildInfo.moduleArgument = "__webpack_module__"; + } + } +}; + +/** + * @param {ParserState} parserState parser state + * @returns {boolean} true, when enabled + */ +module.exports.isEnabled = (parserState) => { + const value = parserStateExportsState.get(parserState); + return value === true; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..71bc6973572347bd5e282e066062a48f681e4d92 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportDependency.js @@ -0,0 +1,409 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ConditionalInitFragment = require("../ConditionalInitFragment"); +const Dependency = require("../Dependency"); +const HarmonyLinkingError = require("../HarmonyLinkingError"); +const InitFragment = require("../InitFragment"); +const Template = require("../Template"); +const AwaitDependenciesInitFragment = require("../async-modules/AwaitDependenciesInitFragment"); +const { filterRuntime, mergeRuntime } = require("../util/runtime"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** @typedef {0 | 1 | 2 | 3 | false} ExportPresenceMode */ + +const ExportPresenceModes = { + NONE: /** @type {ExportPresenceMode} */ (0), + WARN: /** @type {ExportPresenceMode} */ (1), + AUTO: /** @type {ExportPresenceMode} */ (2), + ERROR: /** @type {ExportPresenceMode} */ (3), + /** + * @param {string | false} str param + * @returns {ExportPresenceMode} result + */ + fromUserOption(str) { + switch (str) { + case "error": + return ExportPresenceModes.ERROR; + case "warn": + return ExportPresenceModes.WARN; + case "auto": + return ExportPresenceModes.AUTO; + case false: + return ExportPresenceModes.NONE; + default: + throw new Error(`Invalid export presence value ${str}`); + } + } +}; + +class HarmonyImportDependency extends ModuleDependency { + /** + * @param {string} request request string + * @param {number} sourceOrder source order + * @param {ImportAttributes=} attributes import attributes + * @param {boolean=} defer import attributes + */ + constructor(request, sourceOrder, attributes, defer) { + super(request); + this.sourceOrder = sourceOrder; + this.assertions = attributes; + this.defer = defer; + } + + get category() { + return "esm"; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + return Dependency.NO_EXPORTS_REFERENCED; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string} name of the variable for the import + */ + getImportVar(moduleGraph) { + const module = /** @type {Module} */ (moduleGraph.getParentModule(this)); + const meta = moduleGraph.getMeta(module); + const defer = this.defer; + + const metaKey = defer ? "deferredImportVarMap" : "importVarMap"; + let importVarMap = meta[metaKey]; + if (!importVarMap) meta[metaKey] = importVarMap = new Map(); + + let importVar = importVarMap.get( + /** @type {Module} */ (moduleGraph.getModule(this)) + ); + if (importVar) return importVar; + importVar = `${Template.toIdentifier( + `${this.userRequest}` + )}__WEBPACK_${this.defer ? "DEFERRED_" : ""}IMPORTED_MODULE_${importVarMap.size}__`; + importVarMap.set( + /** @type {Module} */ (moduleGraph.getModule(this)), + importVar + ); + return importVar; + } + + /** + * @param {DependencyTemplateContext} context the template context + * @returns {string} the expression + */ + getModuleExports({ + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements + }) { + return runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(this), + chunkGraph, + request: this.request, + runtimeRequirements + }); + } + + /** + * @param {boolean} update create new variables or update existing one + * @param {DependencyTemplateContext} templateContext the template context + * @returns {[string, string]} the import statement and the compat statement + */ + getImportStatement( + update, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + return runtimeTemplate.importStatement({ + update, + module: /** @type {Module} */ (moduleGraph.getModule(this)), + moduleGraph, + chunkGraph, + importVar: this.getImportVar(moduleGraph), + request: this.request, + originModule: module, + runtimeRequirements, + defer: this.defer + }); + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @param {string[]} ids imported ids + * @param {string} additionalMessage extra info included in the error message + * @returns {WebpackError[] | undefined} errors + */ + getLinkingErrors(moduleGraph, ids, additionalMessage) { + const importedModule = moduleGraph.getModule(this); + // ignore errors for missing or failed modules + if (!importedModule || importedModule.getNumberOfErrors() > 0) { + return; + } + + const parentModule = + /** @type {Module} */ + (moduleGraph.getParentModule(this)); + const exportsType = importedModule.getExportsType( + moduleGraph, + /** @type {BuildMeta} */ (parentModule.buildMeta).strictHarmonyModule + ); + if (exportsType === "namespace" || exportsType === "default-with-named") { + if (ids.length === 0) { + return; + } + + if ( + (exportsType !== "default-with-named" || ids[0] !== "default") && + moduleGraph.isExportProvided(importedModule, ids) === false + ) { + // We are sure that it's not provided + + // Try to provide detailed info in the error message + let pos = 0; + let exportsInfo = moduleGraph.getExportsInfo(importedModule); + while (pos < ids.length && exportsInfo) { + const id = ids[pos++]; + const exportInfo = exportsInfo.getReadOnlyExportInfo(id); + if (exportInfo.provided === false) { + // We are sure that it's not provided + const providedExports = exportsInfo.getProvidedExports(); + const moreInfo = !Array.isArray(providedExports) + ? " (possible exports unknown)" + : providedExports.length === 0 + ? " (module has no exports)" + : ` (possible exports: ${providedExports.join(", ")})`; + return [ + new HarmonyLinkingError( + `export ${ids + .slice(0, pos) + .map((id) => `'${id}'`) + .join(".")} ${additionalMessage} was not found in '${ + this.userRequest + }'${moreInfo}` + ) + ]; + } + exportsInfo = + /** @type {ExportsInfo} */ + (exportInfo.getNestedExportsInfo()); + } + + // General error message + return [ + new HarmonyLinkingError( + `export ${ids + .map((id) => `'${id}'`) + .join(".")} ${additionalMessage} was not found in '${ + this.userRequest + }'` + ) + ]; + } + } + switch (exportsType) { + case "default-only": + // It's has only a default export + if (ids.length > 0 && ids[0] !== "default") { + // In strict harmony modules we only support the default export + return [ + new HarmonyLinkingError( + `Can't import the named export ${ids + .map((id) => `'${id}'`) + .join( + "." + )} ${additionalMessage} from default-exporting module (only default export is available)` + ) + ]; + } + break; + case "default-with-named": + // It has a default export and named properties redirect + // In some cases we still want to warn here + if ( + ids.length > 0 && + ids[0] !== "default" && + /** @type {BuildMeta} */ + (importedModule.buildMeta).defaultObject === "redirect-warn" + ) { + // For these modules only the default export is supported + return [ + new HarmonyLinkingError( + `Should not import the named export ${ids + .map((id) => `'${id}'`) + .join( + "." + )} ${additionalMessage} from default-exporting module (only default export is available soon)` + ) + ]; + } + break; + } + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.sourceOrder); + write(this.assertions); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.sourceOrder = read(); + this.assertions = read(); + super.deserialize(context); + } +} + +module.exports = HarmonyImportDependency; + +/** @type {WeakMap>} */ +const importEmittedMap = new WeakMap(); + +HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {HarmonyImportDependency} */ (dependency); + const { module, chunkGraph, moduleGraph, runtime } = templateContext; + + const connection = moduleGraph.getConnection(dep); + if (connection && !connection.isTargetActive(runtime)) return; + + const referencedModule = connection && connection.module; + + if ( + connection && + connection.weak && + referencedModule && + chunkGraph.getModuleId(referencedModule) === null + ) { + // in weak references, module might not be in any chunk + // but that's ok, we don't need that logic in this case + return; + } + + const moduleKey = referencedModule + ? referencedModule.identifier() + : dep.request; + const key = `${dep.defer ? "deferred " : ""}harmony import ${moduleKey}`; + + const runtimeCondition = dep.weak + ? false + : connection + ? filterRuntime(runtime, (r) => connection.isTargetActive(r)) + : true; + + if (module && referencedModule) { + let emittedModules = importEmittedMap.get(module); + if (emittedModules === undefined) { + emittedModules = new WeakMap(); + importEmittedMap.set(module, emittedModules); + } + let mergedRuntimeCondition = runtimeCondition; + const oldRuntimeCondition = emittedModules.get(referencedModule) || false; + if (oldRuntimeCondition !== false && mergedRuntimeCondition !== true) { + if (mergedRuntimeCondition === false || oldRuntimeCondition === true) { + mergedRuntimeCondition = oldRuntimeCondition; + } else { + mergedRuntimeCondition = mergeRuntime( + oldRuntimeCondition, + mergedRuntimeCondition + ); + } + } + emittedModules.set(referencedModule, mergedRuntimeCondition); + } + + const importStatement = dep.getImportStatement(false, templateContext); + if ( + referencedModule && + templateContext.moduleGraph.isAsync(referencedModule) + ) { + templateContext.initFragments.push( + new ConditionalInitFragment( + importStatement[0], + InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder, + key, + runtimeCondition + ) + ); + const importVar = dep.getImportVar(templateContext.moduleGraph); + templateContext.initFragments.push( + new AwaitDependenciesInitFragment(new Map([[importVar, importVar]])) + ); + templateContext.initFragments.push( + new ConditionalInitFragment( + importStatement[1], + InitFragment.STAGE_ASYNC_HARMONY_IMPORTS, + dep.sourceOrder, + `${key} compat`, + runtimeCondition + ) + ); + } else { + templateContext.initFragments.push( + new ConditionalInitFragment( + importStatement[0] + importStatement[1], + InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder, + key, + runtimeCondition + ) + ); + } + } + + /** + * @param {Module} module the module + * @param {Module} referencedModule the referenced module + * @returns {RuntimeSpec | boolean} runtimeCondition in which this import has been emitted + */ + static getImportEmittedRuntime(module, referencedModule) { + const emittedModules = importEmittedMap.get(module); + if (emittedModules === undefined) return false; + return emittedModules.get(referencedModule) || false; + } +}; + +module.exports.ExportPresenceModes = ExportPresenceModes; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportDependencyParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportDependencyParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7eaba5ed70e262d4fe844d229022b594430de512 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportDependencyParserPlugin.js @@ -0,0 +1,452 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const CommentCompilationWarning = require("../CommentCompilationWarning"); +const HotModuleReplacementPlugin = require("../HotModuleReplacementPlugin"); +const WebpackError = require("../WebpackError"); +const { + VariableInfo, + getImportAttributes +} = require("../javascript/JavascriptParser"); +const InnerGraph = require("../optimize/InnerGraph"); +const ConstDependency = require("./ConstDependency"); +const HarmonyAcceptDependency = require("./HarmonyAcceptDependency"); +const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency"); +const HarmonyEvaluatedImportSpecifierDependency = require("./HarmonyEvaluatedImportSpecifierDependency"); +const HarmonyExports = require("./HarmonyExports"); +const { ExportPresenceModes } = require("./HarmonyImportDependency"); +const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency"); +const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency"); + +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").Literal} Literal */ +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("estree").ObjectExpression} ObjectExpression */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */ +/** @typedef {import("../javascript/JavascriptParser").ExportAllDeclaration} ExportAllDeclaration */ +/** @typedef {import("../javascript/JavascriptParser").ExportNamedDeclaration} ExportNamedDeclaration */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../javascript/JavascriptParser").ImportDeclaration} ImportDeclaration */ +/** @typedef {import("../javascript/JavascriptParser").ImportExpression} ImportExpression */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../javascript/JavascriptParser").TagData} TagData */ +/** @typedef {import("../optimize/InnerGraph").InnerGraph} InnerGraph */ +/** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */ +/** @typedef {import("./HarmonyImportDependency")} HarmonyImportDependency */ + +const harmonySpecifierTag = Symbol("harmony import"); + +/** + * @typedef {object} HarmonySettings + * @property {string[]} ids + * @property {string} source + * @property {number} sourceOrder + * @property {string} name + * @property {boolean} await + * @property {ImportAttributes=} attributes + * @property {boolean | undefined} defer + */ + +const PLUGIN_NAME = "HarmonyImportDependencyParserPlugin"; + +module.exports = class HarmonyImportDependencyParserPlugin { + /** + * @param {JavascriptParserOptions} options options + */ + constructor(options) { + this.exportPresenceMode = + options.importExportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.importExportsPresence) + : options.exportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.exportsPresence) + : options.strictExportPresence + ? ExportPresenceModes.ERROR + : ExportPresenceModes.AUTO; + this.strictThisContextOnImports = options.strictThisContextOnImports; + this.deferImport = options.deferImport; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + const { exportPresenceMode } = this; + + /** + * @param {string[]} members members + * @param {boolean[]} membersOptionals members Optionals + * @returns {string[]} a non optional part + */ + function getNonOptionalPart(members, membersOptionals) { + let i = 0; + while (i < members.length && membersOptionals[i] === false) i++; + return i !== members.length ? members.slice(0, i) : members; + } + + /** + * @param {MemberExpression} node member expression + * @param {number} count count + * @returns {Expression} member expression + */ + function getNonOptionalMemberChain(node, count) { + while (count--) node = /** @type {MemberExpression} */ (node.object); + return node; + } + + parser.hooks.isPure.for("Identifier").tap(PLUGIN_NAME, (expression) => { + const expr = /** @type {Identifier} */ (expression); + if ( + parser.isVariableDefined(expr.name) || + parser.getTagData(expr.name, harmonySpecifierTag) + ) { + return true; + } + }); + parser.hooks.import.tap(PLUGIN_NAME, (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency( + parser.isAsiPosition(/** @type {Range} */ (statement.range)[0]) + ? ";" + : "", + /** @type {Range} */ (statement.range) + ); + clearDep.loc = /** @type {DependencyLocation} */ (statement.loc); + parser.state.module.addPresentationalDependency(clearDep); + parser.unsetAsiPosition(/** @type {Range} */ (statement.range)[1]); + const attributes = getImportAttributes(statement); + let defer = false; + if (this.deferImport) { + ({ defer } = getImportMode(parser, statement)); + if ( + defer && + (statement.specifiers.length !== 1 || + statement.specifiers[0].type !== "ImportNamespaceSpecifier") + ) { + const error = new WebpackError( + "Deferred import can only be used with `import * as namespace from '...'` syntax." + ); + error.loc = statement.loc || undefined; + parser.state.current.addError(error); + } + } + const sideEffectDep = new HarmonyImportSideEffectDependency( + /** @type {string} */ (source), + parser.state.lastHarmonyImportOrder, + attributes, + defer + ); + sideEffectDep.loc = /** @type {DependencyLocation} */ (statement.loc); + parser.state.module.addDependency(sideEffectDep); + return true; + }); + parser.hooks.importSpecifier.tap( + PLUGIN_NAME, + (statement, source, id, name) => { + const ids = id === null ? [] : [id]; + const defer = this.deferImport + ? getImportMode(parser, statement).defer + : false; + parser.tagVariable(name, harmonySpecifierTag, { + name, + source, + ids, + sourceOrder: parser.state.lastHarmonyImportOrder, + attributes: getImportAttributes(statement), + defer + }); + return true; + } + ); + parser.hooks.binaryExpression.tap(PLUGIN_NAME, (expression) => { + if (expression.operator !== "in") return; + + const leftPartEvaluated = parser.evaluateExpression(expression.left); + if (leftPartEvaluated.couldHaveSideEffects()) return; + /** @type {string | undefined} */ + const leftPart = leftPartEvaluated.asString(); + if (!leftPart) return; + + const rightPart = parser.evaluateExpression(expression.right); + if (!rightPart.isIdentifier()) return; + + const rootInfo = rightPart.rootInfo; + if ( + typeof rootInfo === "string" || + !rootInfo || + !rootInfo.tagInfo || + rootInfo.tagInfo.tag !== harmonySpecifierTag + ) { + return; + } + const settings = + /** @type {TagData} */ + (rootInfo.tagInfo.data); + const members = + /** @type {(() => string[])} */ + (rightPart.getMembers)(); + const dep = new HarmonyEvaluatedImportSpecifierDependency( + settings.source, + settings.sourceOrder, + [...settings.ids, ...members, leftPart], + settings.name, + /** @type {Range} */ (expression.range), + settings.attributes, + "in" + ); + dep.directImport = members.length === 0; + dep.asiSafe = !parser.isAsiPosition( + /** @type {Range} */ (expression.range)[0] + ); + dep.loc = /** @type {DependencyLocation} */ (expression.loc); + parser.state.module.addDependency(dep); + InnerGraph.onUsage(parser.state, (e) => (dep.usedByExports = e)); + return true; + }); + parser.hooks.collectDestructuringAssignmentProperties.tap( + PLUGIN_NAME, + (expr) => { + const nameInfo = parser.getNameForExpression(expr); + if ( + nameInfo && + nameInfo.rootInfo instanceof VariableInfo && + nameInfo.rootInfo.name && + parser.getTagData(nameInfo.rootInfo.name, harmonySpecifierTag) + ) { + return true; + } + } + ); + parser.hooks.expression + .for(harmonySpecifierTag) + .tap(PLUGIN_NAME, (expr) => { + const settings = /** @type {HarmonySettings} */ (parser.currentTagData); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + settings.ids, + settings.name, + /** @type {Range} */ + (expr.range), + exportPresenceMode, + settings.attributes, + [], + settings.defer + ); + dep.referencedPropertiesInDestructuring = + parser.destructuringAssignmentPropertiesFor(expr); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = true; + dep.asiSafe = !parser.isAsiPosition( + /** @type {Range} */ (expr.range)[0] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.call = parser.scope.inTaggedTemplateTag; + parser.state.module.addDependency(dep); + InnerGraph.onUsage(parser.state, (e) => (dep.usedByExports = e)); + return true; + }); + parser.hooks.expressionMemberChain + .for(harmonySpecifierTag) + .tap( + PLUGIN_NAME, + (expression, members, membersOptionals, memberRanges) => { + const settings = + /** @type {HarmonySettings} */ + (parser.currentTagData); + const nonOptionalMembers = getNonOptionalPart( + members, + membersOptionals + ); + /** @type {Range[]} */ + const ranges = memberRanges.slice( + 0, + memberRanges.length - (members.length - nonOptionalMembers.length) + ); + const expr = + nonOptionalMembers !== members + ? getNonOptionalMemberChain( + expression, + members.length - nonOptionalMembers.length + ) + : expression; + const ids = [...settings.ids, ...nonOptionalMembers]; + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + ids, + settings.name, + /** @type {Range} */ + (expr.range), + exportPresenceMode, + settings.attributes, + ranges, + settings.defer + ); + dep.referencedPropertiesInDestructuring = + parser.destructuringAssignmentPropertiesFor(expr); + dep.asiSafe = !parser.isAsiPosition( + /** @type {Range} */ + (expr.range)[0] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + InnerGraph.onUsage(parser.state, (e) => (dep.usedByExports = e)); + return true; + } + ); + parser.hooks.callMemberChain + .for(harmonySpecifierTag) + .tap( + PLUGIN_NAME, + (expression, members, membersOptionals, memberRanges) => { + const { arguments: args } = expression; + const callee = /** @type {MemberExpression} */ (expression.callee); + const settings = /** @type {HarmonySettings} */ ( + parser.currentTagData + ); + const nonOptionalMembers = getNonOptionalPart( + members, + membersOptionals + ); + /** @type {Range[]} */ + const ranges = memberRanges.slice( + 0, + memberRanges.length - (members.length - nonOptionalMembers.length) + ); + const expr = + nonOptionalMembers !== members + ? getNonOptionalMemberChain( + callee, + members.length - nonOptionalMembers.length + ) + : callee; + const ids = [...settings.ids, ...nonOptionalMembers]; + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + ids, + settings.name, + /** @type {Range} */ (expr.range), + exportPresenceMode, + settings.attributes, + ranges, + settings.defer + ); + dep.directImport = members.length === 0; + dep.call = true; + dep.asiSafe = !parser.isAsiPosition( + /** @type {Range} */ (expr.range)[0] + ); + // only in case when we strictly follow the spec we need a special case here + dep.namespaceObjectAsContext = + members.length > 0 && + /** @type {boolean} */ (this.strictThisContextOnImports); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + if (args) parser.walkExpressions(args); + InnerGraph.onUsage(parser.state, (e) => (dep.usedByExports = e)); + return true; + } + ); + const { hotAcceptCallback, hotAcceptWithoutCallback } = + HotModuleReplacementPlugin.getParserHooks(parser); + hotAcceptCallback.tap(PLUGIN_NAME, (expr, requests) => { + if (!HarmonyExports.isEnabled(parser.state)) { + // This is not a harmony module, skip it + return; + } + const dependencies = requests.map((request) => { + const dep = new HarmonyAcceptImportDependency(request); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + /** @type {Range} */ + (expr.range), + dependencies, + true + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + } + }); + hotAcceptWithoutCallback.tap(PLUGIN_NAME, (expr, requests) => { + if (!HarmonyExports.isEnabled(parser.state)) { + // This is not a harmony module, skip it + return; + } + const dependencies = requests.map((request) => { + const dep = new HarmonyAcceptImportDependency(request); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + /** @type {Range} */ + (expr.range), + dependencies, + false + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + } + }); + } +}; + +/** + * @param {JavascriptParser} parser parser + * @param {ExportNamedDeclaration | ExportAllDeclaration | ImportDeclaration} node node + * @returns {{ defer: boolean }} import attributes + */ +function getImportMode(parser, node) { + const result = { defer: "phase" in node && node.phase === "defer" }; + if (!node.range) { + return result; + } + const { options, errors } = parser.parseCommentOptions(node.range); + if (errors) { + for (const e of errors) { + const { comment } = e; + if (!comment.loc) continue; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); + } + } + if (!options) return result; + if (options.webpackDefer) { + if (typeof options.webpackDefer === "boolean") { + result.defer = options.webpackDefer; + } else if (node.loc) { + parser.state.module.addWarning( + new CommentCompilationWarning( + "webpackDefer magic comment expected a boolean value.", + node.loc + ) + ); + } + } + return result; +} + +module.exports.getImportMode = getImportMode; +module.exports.harmonySpecifierTag = harmonySpecifierTag; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportSideEffectDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportSideEffectDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..9db49f07ddb5d5965c1e1a70f545a8c1345de0ff --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportSideEffectDependency.js @@ -0,0 +1,88 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const HarmonyImportDependency = require("./HarmonyImportDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class HarmonyImportSideEffectDependency extends HarmonyImportDependency { + /** + * @param {string} request the request string + * @param {number} sourceOrder source order + * @param {ImportAttributes=} attributes import attributes + * @param {boolean=} defer is defer phase + */ + constructor(request, sourceOrder, attributes, defer) { + super(request, sourceOrder, attributes, defer); + } + + get type() { + return "harmony side effect evaluation"; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | GetConditionFn} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return (connection) => { + const refModule = connection.resolvedModule; + if (!refModule) return true; + return refModule.getSideEffectsConnectionState(moduleGraph); + }; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + const refModule = moduleGraph.getModule(this); + if (!refModule) return true; + return refModule.getSideEffectsConnectionState(moduleGraph); + } +} + +makeSerializable( + HarmonyImportSideEffectDependency, + "webpack/lib/dependencies/HarmonyImportSideEffectDependency" +); + +HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends ( + HarmonyImportDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const { moduleGraph, concatenationScope } = templateContext; + if (concatenationScope) { + const module = /** @type {Module} */ (moduleGraph.getModule(dependency)); + if (concatenationScope.isModuleInScope(module)) { + return; + } + } + super.apply(dependency, source, templateContext); + } +}; + +module.exports = HarmonyImportSideEffectDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..bf3f7070d40887c1d602c53c82ce79ccf1dcfb77 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js @@ -0,0 +1,478 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const Template = require("../Template"); +const { + getDependencyUsedByExportsCondition +} = require("../optimize/InnerGraph"); +const { getTrimmedIdsAndRange } = require("../util/chainedImports"); +const makeSerializable = require("../util/makeSerializable"); +const propertyAccess = require("../util/propertyAccess"); +const HarmonyImportDependency = require("./HarmonyImportDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./HarmonyImportDependency").ExportPresenceMode} ExportPresenceMode */ + +const idsSymbol = Symbol("HarmonyImportSpecifierDependency.ids"); + +const { ExportPresenceModes } = HarmonyImportDependency; + +class HarmonyImportSpecifierDependency extends HarmonyImportDependency { + /** + * @param {string} request request + * @param {number} sourceOrder source order + * @param {string[]} ids ids + * @param {string} name name + * @param {Range} range range + * @param {ExportPresenceMode} exportPresenceMode export presence mode + * @param {ImportAttributes | undefined} attributes import attributes + * @param {Range[] | undefined} idRanges ranges for members of ids; the two arrays are right-aligned + * @param {boolean=} defer is defer phase + */ + constructor( + request, + sourceOrder, + ids, + name, + range, + exportPresenceMode, + attributes, + idRanges, // TODO webpack 6 make this non-optional. It must always be set to properly trim ids. + defer + ) { + super(request, sourceOrder, attributes, defer); + this.ids = ids; + this.name = name; + this.range = range; + this.idRanges = idRanges; + this.exportPresenceMode = exportPresenceMode; + this.namespaceObjectAsContext = false; + this.call = undefined; + this.directImport = undefined; + this.shorthand = undefined; + this.asiSafe = undefined; + /** @type {Set | boolean | undefined} */ + this.usedByExports = undefined; + /** @type {Set | undefined} */ + this.referencedPropertiesInDestructuring = undefined; + } + + // TODO webpack 6 remove + get id() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + + // TODO webpack 6 remove + getId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + + // TODO webpack 6 remove + setId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + + get type() { + return "harmony import specifier"; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string[]} the imported ids + */ + getIds(moduleGraph) { + const meta = moduleGraph.getMetaIfExisting(this); + if (meta === undefined) return this.ids; + const ids = meta[idsSymbol]; + return ids !== undefined ? ids : this.ids; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {string[]} ids the imported ids + * @returns {void} + */ + setIds(moduleGraph, ids) { + moduleGraph.getMeta(this)[idsSymbol] = ids; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | GetConditionFn} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return getDependencyUsedByExportsCondition( + this, + this.usedByExports, + moduleGraph + ); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + let ids = this.getIds(moduleGraph); + if (ids.length === 0) return this._getReferencedExportsInDestructuring(); + let namespaceObjectAsContext = this.namespaceObjectAsContext; + if (ids[0] === "default") { + const selfModule = + /** @type {Module} */ + (moduleGraph.getParentModule(this)); + const importedModule = + /** @type {Module} */ + (moduleGraph.getModule(this)); + switch ( + importedModule.getExportsType( + moduleGraph, + /** @type {BuildMeta} */ + (selfModule.buildMeta).strictHarmonyModule + ) + ) { + case "default-only": + case "default-with-named": + if (ids.length === 1) { + return this._getReferencedExportsInDestructuring(); + } + ids = ids.slice(1); + namespaceObjectAsContext = true; + break; + case "dynamic": + return Dependency.EXPORTS_OBJECT_REFERENCED; + } + } + + if ( + this.call && + !this.directImport && + (namespaceObjectAsContext || ids.length > 1) + ) { + if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED; + ids = ids.slice(0, -1); + } + + return this._getReferencedExportsInDestructuring(ids); + } + + /** + * @param {string[]=} ids ids + * @returns {string[][]} referenced exports + */ + _getReferencedExportsInDestructuring(ids) { + if (this.referencedPropertiesInDestructuring) { + /** @type {string[][]} */ + const refs = []; + for (const { id } of this.referencedPropertiesInDestructuring) { + refs.push(ids ? [...ids, id] : [id]); + } + return refs; + } + return ids ? [ids] : Dependency.EXPORTS_OBJECT_REFERENCED; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportPresenceMode} effective mode + */ + _getEffectiveExportPresenceLevel(moduleGraph) { + if (this.exportPresenceMode !== ExportPresenceModes.AUTO) { + return this.exportPresenceMode; + } + const buildMeta = + /** @type {BuildMeta} */ + ( + /** @type {Module} */ + (moduleGraph.getParentModule(this)).buildMeta + ); + return buildMeta.strictHarmonyModule + ? ExportPresenceModes.ERROR + : ExportPresenceModes.WARN; + } + + /** + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | null | undefined} warnings + */ + getWarnings(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.WARN) { + return this._getErrors(moduleGraph); + } + return null; + } + + /** + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | null | undefined} errors + */ + getErrors(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.ERROR) { + return this._getErrors(moduleGraph); + } + return null; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | undefined} errors + */ + _getErrors(moduleGraph) { + const ids = this.getIds(moduleGraph); + return this.getLinkingErrors( + moduleGraph, + ids, + `(imported as '${this.name}')` + ); + } + + /** + * implement this method to allow the occurrence order plugin to count correctly + * @returns {number} count how often the id is used in this dependency + */ + getNumberOfIdOccurrences() { + return 0; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.ids); + write(this.name); + write(this.range); + write(this.idRanges); + write(this.exportPresenceMode); + write(this.namespaceObjectAsContext); + write(this.call); + write(this.directImport); + write(this.shorthand); + write(this.asiSafe); + write(this.usedByExports); + write(this.referencedPropertiesInDestructuring); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.ids = read(); + this.name = read(); + this.range = read(); + this.idRanges = read(); + this.exportPresenceMode = read(); + this.namespaceObjectAsContext = read(); + this.call = read(); + this.directImport = read(); + this.shorthand = read(); + this.asiSafe = read(); + this.usedByExports = read(); + this.referencedPropertiesInDestructuring = read(); + super.deserialize(context); + } +} + +makeSerializable( + HarmonyImportSpecifierDependency, + "webpack/lib/dependencies/HarmonyImportSpecifierDependency" +); + +HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends ( + HarmonyImportDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency); + const { moduleGraph, runtime } = templateContext; + const connection = moduleGraph.getConnection(dep); + // Skip rendering depending when dependency is conditional + if (connection && !connection.isTargetActive(runtime)) return; + + const ids = dep.getIds(moduleGraph); + const { + trimmedRange: [trimmedRangeStart, trimmedRangeEnd], + trimmedIds + } = getTrimmedIdsAndRange(ids, dep.range, dep.idRanges, moduleGraph, dep); + + const exportExpr = this._getCodeForIds( + dep, + source, + templateContext, + trimmedIds + ); + if (dep.shorthand) { + source.insert(trimmedRangeEnd, `: ${exportExpr}`); + } else { + source.replace(trimmedRangeStart, trimmedRangeEnd - 1, exportExpr); + } + + if (dep.referencedPropertiesInDestructuring) { + let prefixedIds = ids; + + if (ids[0] === "default") { + const selfModule = + /** @type {Module} */ + (moduleGraph.getParentModule(dep)); + const importedModule = + /** @type {Module} */ + (moduleGraph.getModule(dep)); + const exportsType = importedModule.getExportsType( + moduleGraph, + /** @type {BuildMeta} */ + (selfModule.buildMeta).strictHarmonyModule + ); + if ( + (exportsType === "default-only" || + exportsType === "default-with-named") && + ids.length >= 1 + ) { + prefixedIds = ids.slice(1); + } + } + + for (const { + id, + shorthand, + range + } of dep.referencedPropertiesInDestructuring) { + /** @type {string[]} */ + const concatedIds = [...prefixedIds, id]; + const module = /** @type {Module} */ (moduleGraph.getModule(dep)); + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(concatedIds, runtime); + if (!used) return; + const newName = used[used.length - 1]; + const name = concatedIds[concatedIds.length - 1]; + if (newName === name) continue; + + const comment = `${Template.toNormalComment(name)} `; + const key = comment + JSON.stringify(newName); + source.replace( + /** @type {Range} */ + (range)[0], + /** @type {Range} */ + (range)[1] - 1, + shorthand ? `${key}: ${name}` : `${key}` + ); + } + } + } + + /** + * @param {HarmonyImportSpecifierDependency} dep dependency + * @param {ReplaceSource} source source + * @param {DependencyTemplateContext} templateContext context + * @param {string[]} ids ids + * @returns {string} generated code + */ + _getCodeForIds(dep, source, templateContext, ids) { + const { moduleGraph, module, runtime, concatenationScope } = + templateContext; + const connection = moduleGraph.getConnection(dep); + let exportExpr; + if ( + connection && + concatenationScope && + concatenationScope.isModuleInScope(connection.module) + ) { + if (ids.length === 0) { + exportExpr = concatenationScope.createModuleReference( + connection.module, + { + asiSafe: dep.asiSafe, + deferredImport: dep.defer + } + ); + } else if (dep.namespaceObjectAsContext && ids.length === 1) { + exportExpr = + concatenationScope.createModuleReference(connection.module, { + asiSafe: dep.asiSafe, + deferredImport: dep.defer + }) + propertyAccess(ids); + } else { + exportExpr = concatenationScope.createModuleReference( + connection.module, + { + ids, + call: dep.call, + directImport: dep.directImport, + asiSafe: dep.asiSafe, + deferredImport: dep.defer + } + ); + } + } else { + super.apply(dep, source, templateContext); + + const { runtimeTemplate, initFragments, runtimeRequirements } = + templateContext; + + exportExpr = runtimeTemplate.exportFromImport({ + moduleGraph, + module: /** @type {Module} */ (moduleGraph.getModule(dep)), + chunkGraph: templateContext.chunkGraph, + request: dep.request, + exportName: ids, + originModule: module, + asiSafe: dep.shorthand ? true : dep.asiSafe, + isCall: dep.call, + callContext: !dep.directImport, + defaultInterop: true, + importVar: dep.getImportVar(moduleGraph), + initFragments, + runtime, + runtimeRequirements, + defer: dep.defer + }); + } + return exportExpr; + } +}; + +module.exports = HarmonyImportSpecifierDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..3d2bf7230a0eaf391332511df42e9715e84507b4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyModulesPlugin.js @@ -0,0 +1,154 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("../ModuleTypeConstants"); +const HarmonyAcceptDependency = require("./HarmonyAcceptDependency"); +const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency"); +const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency"); +const HarmonyDetectionParserPlugin = require("./HarmonyDetectionParserPlugin"); +const HarmonyEvaluatedImportSpecifierDependency = require("./HarmonyEvaluatedImportSpecifierDependency"); +const HarmonyExportDependencyParserPlugin = require("./HarmonyExportDependencyParserPlugin"); +const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency"); +const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency"); +const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency"); +const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency"); +const HarmonyImportDependencyParserPlugin = require("./HarmonyImportDependencyParserPlugin"); +const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency"); +const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency"); + +const HarmonyTopLevelThisParserPlugin = require("./HarmonyTopLevelThisParserPlugin"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ +/** + * @typedef HarmonyModulesPluginOptions + * @property {boolean=} topLevelAwait + * @property {boolean=} deferImport + */ + +const PLUGIN_NAME = "HarmonyModulesPlugin"; + +class HarmonyModulesPlugin { + /** + * @param {HarmonyModulesPluginOptions} options options + */ + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + HarmonyCompatibilityDependency, + new HarmonyCompatibilityDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyImportSideEffectDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyImportSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyEvaluatedImportSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyEvaluatedImportSpecifierDependency, + new HarmonyEvaluatedImportSpecifierDependency.Template() + ); + + compilation.dependencyTemplates.set( + HarmonyExportHeaderDependency, + new HarmonyExportHeaderDependency.Template() + ); + + compilation.dependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependency.Template() + ); + + compilation.dependencyTemplates.set( + HarmonyExportSpecifierDependency, + new HarmonyExportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportImportedSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyExportImportedSpecifierDependency, + new HarmonyExportImportedSpecifierDependency.Template() + ); + + compilation.dependencyTemplates.set( + HarmonyAcceptDependency, + new HarmonyAcceptDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyAcceptImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyAcceptImportDependency, + new HarmonyAcceptImportDependency.Template() + ); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + // TODO webpack 6: rename harmony to esm or module + if (parserOptions.harmony !== undefined && !parserOptions.harmony) { + return; + } + + new HarmonyDetectionParserPlugin(this.options).apply(parser); + new HarmonyImportDependencyParserPlugin(parserOptions).apply(parser); + new HarmonyExportDependencyParserPlugin(parserOptions).apply(parser); + new HarmonyTopLevelThisParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = HarmonyModulesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyTopLevelThisParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyTopLevelThisParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..5039eb9da7f2051f272dc22201c208357de7da62 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/HarmonyTopLevelThisParserPlugin.js @@ -0,0 +1,39 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +const ConstDependency = require("./ConstDependency"); +const HarmonyExports = require("./HarmonyExports"); + +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "HarmonyTopLevelThisParserPlugin"; + +class HarmonyTopLevelThisParserPlugin { + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + parser.hooks.expression.for("this").tap(PLUGIN_NAME, (node) => { + if (!parser.scope.topLevelScope) return; + if (HarmonyExports.isEnabled(parser.state)) { + const dep = new ConstDependency( + "undefined", + /** @type {Range} */ (node.range), + null + ); + dep.loc = /** @type {DependencyLocation} */ (node.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + } + }); + } +} + +module.exports = HarmonyTopLevelThisParserPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportContextDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportContextDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..cdade589cbd21fdb6ecc31358198f5a001541f5a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportContextDependency.js @@ -0,0 +1,68 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ContextDependency = require("./ContextDependency"); +const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ + +class ImportContextDependency extends ContextDependency { + /** + * @param {ContextDependencyOptions} options options + * @param {Range} range range + * @param {Range} valueRange value range + */ + constructor(options, range, valueRange) { + super(options); + + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return `import() context ${this.options.mode}`; + } + + get category() { + return "esm"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.valueRange); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.valueRange = read(); + + super.deserialize(context); + } +} + +makeSerializable( + ImportContextDependency, + "webpack/lib/dependencies/ImportContextDependency" +); + +ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; + +module.exports = ImportContextDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..1368d405a10e0bf53b4d9d5034837e8deeb99af8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportDependency.js @@ -0,0 +1,139 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class ImportDependency extends ModuleDependency { + /** + * @param {string} request the request + * @param {Range} range expression range + * @param {(string[][] | null)=} referencedExports list of referenced exports + * @param {ImportAttributes=} attributes import attributes + */ + constructor(request, range, referencedExports, attributes) { + super(request); + this.range = range; + this.referencedExports = referencedExports; + this.assertions = attributes; + } + + get type() { + return "import()"; + } + + get category() { + return "esm"; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED; + const refs = []; + for (const referencedExport of this.referencedExports) { + if (referencedExport[0] === "default") { + const selfModule = + /** @type {Module} */ + (moduleGraph.getParentModule(this)); + const importedModule = + /** @type {Module} */ + (moduleGraph.getModule(this)); + const exportsType = importedModule.getExportsType( + moduleGraph, + /** @type {BuildMeta} */ + (selfModule.buildMeta).strictHarmonyModule + ); + if ( + exportsType === "default-only" || + exportsType === "default-with-named" + ) { + return Dependency.EXPORTS_OBJECT_REFERENCED; + } + } + refs.push({ + name: referencedExport, + canMangle: false + }); + } + return refs; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + context.write(this.range); + context.write(this.referencedExports); + context.write(this.assertions); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + this.range = context.read(); + this.referencedExports = context.read(); + this.assertions = context.read(); + super.deserialize(context); + } +} + +makeSerializable(ImportDependency, "webpack/lib/dependencies/ImportDependency"); + +ImportDependency.Template = class ImportDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ImportDependency} */ (dependency); + const block = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dep) + ); + const content = runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + block, + module: /** @type {Module} */ (moduleGraph.getModule(dep)), + request: dep.request, + strict: /** @type {BuildMeta} */ (module.buildMeta).strictHarmonyModule, + message: "import()", + runtimeRequirements + }); + + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; + +module.exports = ImportDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportEagerDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportEagerDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..dd607302029629824954c0b03b412ebc96542e0d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportEagerDependency.js @@ -0,0 +1,74 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ImportDependency = require("./ImportDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +class ImportEagerDependency extends ImportDependency { + /** + * @param {string} request the request + * @param {Range} range expression range + * @param {(string[][] | null)=} referencedExports list of referenced exports + * @param {ImportAttributes=} attributes import attributes + */ + constructor(request, range, referencedExports, attributes) { + super(request, range, referencedExports, attributes); + } + + get type() { + return "import() eager"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + ImportEagerDependency, + "webpack/lib/dependencies/ImportEagerDependency" +); + +ImportEagerDependency.Template = class ImportEagerDependencyTemplate extends ( + ImportDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ImportEagerDependency} */ (dependency); + const content = runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + module: /** @type {Module} */ (moduleGraph.getModule(dep)), + request: dep.request, + strict: /** @type {BuildMeta} */ (module.buildMeta).strictHarmonyModule, + message: "import() eager", + runtimeRequirements + }); + + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; + +module.exports = ImportEagerDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaContextDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaContextDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..ee27ee1573f9dd7d793383d43f5574ab3fb95c22 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaContextDependency.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ContextDependency = require("./ContextDependency"); +const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ + +class ImportMetaContextDependency extends ContextDependency { + /** + * @param {ContextDependencyOptions} options options + * @param {Range} range range + */ + constructor(options, range) { + super(options); + + this.range = range; + } + + get category() { + return "esm"; + } + + get type() { + return `import.meta.webpackContext ${this.options.mode}`; + } +} + +makeSerializable( + ImportMetaContextDependency, + "webpack/lib/dependencies/ImportMetaContextDependency" +); + +ImportMetaContextDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = ImportMetaContextDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaContextDependencyParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaContextDependencyParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d52c09d5ccf3fd5df028918bf73f91db6343134d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaContextDependencyParserPlugin.js @@ -0,0 +1,308 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const WebpackError = require("../WebpackError"); +const { + evaluateToIdentifier +} = require("../javascript/JavascriptParserHelpers"); +const ImportMetaContextDependency = require("./ImportMetaContextDependency"); + +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").ObjectExpression} ObjectExpression */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").SourceLocation} SourceLocation */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../ContextModule").ContextModuleOptions} ContextModuleOptions */ +/** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {Pick&{groupOptions: RawChunkGroupOptions, exports?: ContextModuleOptions["referencedExports"]}} ImportMetaContextOptions */ + +/** + * @param {Property} prop property + * @param {string} expect except message + * @returns {WebpackError} error + */ +function createPropertyParseError(prop, expect) { + return createError( + `Parsing import.meta.webpackContext options failed. Unknown value for property ${JSON.stringify( + /** @type {Identifier} */ + (prop.key).name + )}, expected type ${expect}.`, + /** @type {DependencyLocation} */ + (prop.value.loc) + ); +} + +/** + * @param {string} msg message + * @param {DependencyLocation} loc location + * @returns {WebpackError} error + */ +function createError(msg, loc) { + const error = new WebpackError(msg); + error.name = "ImportMetaContextError"; + error.loc = loc; + return error; +} + +const PLUGIN_NAME = "ImportMetaContextDependencyParserPlugin"; + +module.exports = class ImportMetaContextDependencyParserPlugin { + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + parser.hooks.evaluateIdentifier + .for("import.meta.webpackContext") + .tap(PLUGIN_NAME, (expr) => + evaluateToIdentifier( + "import.meta.webpackContext", + "import.meta", + () => ["webpackContext"], + true + )(expr) + ); + parser.hooks.call + .for("import.meta.webpackContext") + .tap(PLUGIN_NAME, (expr) => { + if (expr.arguments.length < 1 || expr.arguments.length > 2) return; + const [directoryNode, optionsNode] = expr.arguments; + if (optionsNode && optionsNode.type !== "ObjectExpression") return; + const requestExpr = parser.evaluateExpression( + /** @type {Expression} */ (directoryNode) + ); + if (!requestExpr.isString()) return; + const request = /** @type {string} */ (requestExpr.string); + const errors = []; + let regExp = /^\.\/.*$/; + let recursive = true; + /** @type {ContextModuleOptions["mode"]} */ + let mode = "sync"; + /** @type {ContextModuleOptions["include"]} */ + let include; + /** @type {ContextModuleOptions["exclude"]} */ + let exclude; + /** @type {RawChunkGroupOptions} */ + const groupOptions = {}; + /** @type {ContextModuleOptions["chunkName"]} */ + let chunkName; + /** @type {ContextModuleOptions["referencedExports"]} */ + let exports; + if (optionsNode) { + for (const prop of /** @type {ObjectExpression} */ (optionsNode) + .properties) { + if (prop.type !== "Property" || prop.key.type !== "Identifier") { + errors.push( + createError( + "Parsing import.meta.webpackContext options failed.", + /** @type {DependencyLocation} */ + (optionsNode.loc) + ) + ); + break; + } + switch (prop.key.name) { + case "regExp": { + const regExpExpr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (!regExpExpr.isRegExp()) { + errors.push(createPropertyParseError(prop, "RegExp")); + } else { + regExp = /** @type {RegExp} */ (regExpExpr.regExp); + } + break; + } + case "include": { + const regExpExpr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (!regExpExpr.isRegExp()) { + errors.push(createPropertyParseError(prop, "RegExp")); + } else { + include = regExpExpr.regExp; + } + break; + } + case "exclude": { + const regExpExpr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (!regExpExpr.isRegExp()) { + errors.push(createPropertyParseError(prop, "RegExp")); + } else { + exclude = regExpExpr.regExp; + } + break; + } + case "mode": { + const modeExpr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (!modeExpr.isString()) { + errors.push(createPropertyParseError(prop, "string")); + } else { + mode = /** @type {ContextModuleOptions["mode"]} */ ( + modeExpr.string + ); + } + break; + } + case "chunkName": { + const expr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (!expr.isString()) { + errors.push(createPropertyParseError(prop, "string")); + } else { + chunkName = expr.string; + } + break; + } + case "exports": { + const expr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (expr.isString()) { + exports = [[/** @type {string} */ (expr.string)]]; + } else if (expr.isArray()) { + const items = + /** @type {BasicEvaluatedExpression[]} */ + (expr.items); + if ( + items.every((i) => { + if (!i.isArray()) return false; + const innerItems = + /** @type {BasicEvaluatedExpression[]} */ (i.items); + return innerItems.every((i) => i.isString()); + }) + ) { + exports = []; + + for (const i1 of items) { + /** @type {string[]} */ + const export_ = []; + for (const i2 of /** @type {BasicEvaluatedExpression[]} */ ( + i1.items + )) { + export_.push(/** @type {string} */ (i2.string)); + } + exports.push(export_); + } + } else { + errors.push( + createPropertyParseError(prop, "string|string[][]") + ); + } + } else { + errors.push( + createPropertyParseError(prop, "string|string[][]") + ); + } + break; + } + case "prefetch": { + const expr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (expr.isBoolean()) { + groupOptions.prefetchOrder = 0; + } else if (expr.isNumber()) { + groupOptions.prefetchOrder = expr.number; + } else { + errors.push(createPropertyParseError(prop, "boolean|number")); + } + break; + } + case "preload": { + const expr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (expr.isBoolean()) { + groupOptions.preloadOrder = 0; + } else if (expr.isNumber()) { + groupOptions.preloadOrder = expr.number; + } else { + errors.push(createPropertyParseError(prop, "boolean|number")); + } + break; + } + case "fetchPriority": { + const expr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if ( + expr.isString() && + ["high", "low", "auto"].includes( + /** @type {string} */ (expr.string) + ) + ) { + groupOptions.fetchPriority = + /** @type {RawChunkGroupOptions["fetchPriority"]} */ ( + expr.string + ); + } else { + errors.push( + createPropertyParseError(prop, '"high"|"low"|"auto"') + ); + } + break; + } + case "recursive": { + const recursiveExpr = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (!recursiveExpr.isBoolean()) { + errors.push(createPropertyParseError(prop, "boolean")); + } else { + recursive = /** @type {boolean} */ (recursiveExpr.bool); + } + break; + } + default: + errors.push( + createError( + `Parsing import.meta.webpackContext options failed. Unknown property ${JSON.stringify( + prop.key.name + )}.`, + /** @type {DependencyLocation} */ (optionsNode.loc) + ) + ); + } + } + } + if (errors.length) { + for (const error of errors) parser.state.current.addError(error); + return; + } + + const dep = new ImportMetaContextDependency( + { + request, + include, + exclude, + recursive, + regExp, + groupOptions, + chunkName, + referencedExports: exports, + mode, + category: "esm" + }, + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + }); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaContextPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaContextPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d3b96203e8421f25a6707e771e3530be0429d1f5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaContextPlugin.js @@ -0,0 +1,73 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("../ModuleTypeConstants"); +const ContextElementDependency = require("./ContextElementDependency"); +const ImportMetaContextDependency = require("./ImportMetaContextDependency"); +const ImportMetaContextDependencyParserPlugin = require("./ImportMetaContextDependencyParserPlugin"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ + +const PLUGIN_NAME = "ImportMetaContextPlugin"; + +class ImportMetaContextPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + ImportMetaContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + ImportMetaContextDependency, + new ImportMetaContextDependency.Template() + ); + compilation.dependencyFactories.set( + ContextElementDependency, + normalModuleFactory + ); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if ( + parserOptions.importMetaContext !== undefined && + !parserOptions.importMetaContext + ) { + return; + } + + new ImportMetaContextDependencyParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = ImportMetaContextPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaHotAcceptDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaHotAcceptDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..70d8199338d05c708562ccf795fd04e2f0ba3c90 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaHotAcceptDependency.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +class ImportMetaHotAcceptDependency extends ModuleDependency { + /** + * @param {string} request the request string + * @param {Range} range location in source code + */ + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } + + get type() { + return "import.meta.webpackHot.accept"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + ImportMetaHotAcceptDependency, + "webpack/lib/dependencies/ImportMetaHotAcceptDependency" +); + +ImportMetaHotAcceptDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ImportMetaHotAcceptDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaHotDeclineDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaHotDeclineDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..c6c35a250ce17bdf080140f364dd8a9bba467194 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaHotDeclineDependency.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +class ImportMetaHotDeclineDependency extends ModuleDependency { + /** + * @param {string} request the request string + * @param {Range} range location in source code + */ + constructor(request, range) { + super(request); + + this.range = range; + this.weak = true; + } + + get type() { + return "import.meta.webpackHot.decline"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + ImportMetaHotDeclineDependency, + "webpack/lib/dependencies/ImportMetaHotDeclineDependency" +); + +ImportMetaHotDeclineDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ImportMetaHotDeclineDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..e904a526ce3dc6deae66c38be135bb225b08908a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportMetaPlugin.js @@ -0,0 +1,259 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const { pathToFileURL } = require("url"); +const ModuleDependencyWarning = require("../ModuleDependencyWarning"); +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("../ModuleTypeConstants"); +const Template = require("../Template"); +const BasicEvaluatedExpression = require("../javascript/BasicEvaluatedExpression"); +const { + evaluateToIdentifier, + evaluateToNumber, + evaluateToString, + toConstantDependency +} = require("../javascript/JavascriptParserHelpers"); +const memoize = require("../util/memoize"); +const propertyAccess = require("../util/propertyAccess"); +const ConstDependency = require("./ConstDependency"); + +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const getCriticalDependencyWarning = memoize(() => + require("./CriticalDependencyWarning") +); + +const PLUGIN_NAME = "ImportMetaPlugin"; + +class ImportMetaPlugin { + /** + * @param {Compiler} compiler compiler + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + /** + * @param {NormalModule} module module + * @returns {string} file url + */ + const getUrl = (module) => pathToFileURL(module.resource).toString(); + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const parserHandler = (parser, { importMeta }) => { + if (importMeta === false) { + const { importMetaName } = compilation.outputOptions; + if (importMetaName === "import.meta") return; + + parser.hooks.expression + .for("import.meta") + .tap(PLUGIN_NAME, (metaProperty) => { + const dep = new ConstDependency( + /** @type {string} */ (importMetaName), + /** @type {Range} */ (metaProperty.range) + ); + dep.loc = /** @type {DependencyLocation} */ (metaProperty.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + return; + } + + // import.meta direct + const webpackVersion = Number.parseInt( + require("../../package.json").version, + 10 + ); + const importMetaUrl = () => + JSON.stringify(getUrl(parser.state.module)); + const importMetaWebpackVersion = () => JSON.stringify(webpackVersion); + /** + * @param {string[]} members members + * @returns {string} error message + */ + const importMetaUnknownProperty = (members) => + `${Template.toNormalComment( + `unsupported import.meta.${members.join(".")}` + )} undefined${propertyAccess(members, 1)}`; + parser.hooks.typeof + .for("import.meta") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("object")) + ); + parser.hooks.collectDestructuringAssignmentProperties.tap( + PLUGIN_NAME, + (expr) => { + if (expr.type === "MetaProperty") return true; + } + ); + parser.hooks.expression + .for("import.meta") + .tap(PLUGIN_NAME, (metaProperty) => { + const referencedPropertiesInDestructuring = + parser.destructuringAssignmentPropertiesFor(metaProperty); + if (!referencedPropertiesInDestructuring) { + const CriticalDependencyWarning = + getCriticalDependencyWarning(); + parser.state.module.addWarning( + new ModuleDependencyWarning( + parser.state.module, + new CriticalDependencyWarning( + "Accessing import.meta directly is unsupported (only property access or destructuring is supported)" + ), + /** @type {DependencyLocation} */ (metaProperty.loc) + ) + ); + const dep = new ConstDependency( + `${ + parser.isAsiPosition( + /** @type {Range} */ (metaProperty.range)[0] + ) + ? ";" + : "" + }({})`, + /** @type {Range} */ (metaProperty.range) + ); + dep.loc = /** @type {DependencyLocation} */ (metaProperty.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + } + + let str = ""; + for (const { id: prop } of referencedPropertiesInDestructuring) { + switch (prop) { + case "url": + str += `url: ${importMetaUrl()},`; + break; + case "webpack": + str += `webpack: ${importMetaWebpackVersion()},`; + break; + default: + str += `[${JSON.stringify( + prop + )}]: ${importMetaUnknownProperty([prop])},`; + break; + } + } + const dep = new ConstDependency( + `({${str}})`, + /** @type {Range} */ (metaProperty.range) + ); + dep.loc = /** @type {DependencyLocation} */ (metaProperty.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("import.meta") + .tap(PLUGIN_NAME, evaluateToString("object")); + parser.hooks.evaluateIdentifier.for("import.meta").tap( + PLUGIN_NAME, + evaluateToIdentifier("import.meta", "import.meta", () => [], true) + ); + + // import.meta.url + parser.hooks.typeof + .for("import.meta.url") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("string")) + ); + parser.hooks.expression + .for("import.meta.url") + .tap(PLUGIN_NAME, (expr) => { + const dep = new ConstDependency( + importMetaUrl(), + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("import.meta.url") + .tap(PLUGIN_NAME, evaluateToString("string")); + parser.hooks.evaluateIdentifier + .for("import.meta.url") + .tap(PLUGIN_NAME, (expr) => + new BasicEvaluatedExpression() + .setString(getUrl(parser.state.module)) + .setRange(/** @type {Range} */ (expr.range)) + ); + + // import.meta.webpack + parser.hooks.typeof + .for("import.meta.webpack") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("number")) + ); + parser.hooks.expression + .for("import.meta.webpack") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, importMetaWebpackVersion()) + ); + parser.hooks.evaluateTypeof + .for("import.meta.webpack") + .tap(PLUGIN_NAME, evaluateToString("number")); + parser.hooks.evaluateIdentifier + .for("import.meta.webpack") + .tap(PLUGIN_NAME, evaluateToNumber(webpackVersion)); + + // Unknown properties + parser.hooks.unhandledExpressionMemberChain + .for("import.meta") + .tap(PLUGIN_NAME, (expr, members) => { + const dep = new ConstDependency( + importMetaUnknownProperty(members), + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluate + .for("MemberExpression") + .tap(PLUGIN_NAME, (expression) => { + const expr = /** @type {MemberExpression} */ (expression); + if ( + expr.object.type === "MetaProperty" && + expr.object.meta.name === "import" && + expr.object.property.name === "meta" && + expr.property.type === + (expr.computed ? "Literal" : "Identifier") + ) { + return new BasicEvaluatedExpression() + .setUndefined() + .setRange(/** @type {Range} */ (expr.range)); + } + }); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, parserHandler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, parserHandler); + } + ); + } +} + +module.exports = ImportMetaPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7b9904a4ef5aa821c1e6635d5c2584dabe987eda --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportParserPlugin.js @@ -0,0 +1,376 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const CommentCompilationWarning = require("../CommentCompilationWarning"); +const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); +const { getImportAttributes } = require("../javascript/JavascriptParser"); +const ContextDependencyHelpers = require("./ContextDependencyHelpers"); +const ImportContextDependency = require("./ImportContextDependency"); +const ImportDependency = require("./ImportDependency"); +const ImportEagerDependency = require("./ImportEagerDependency"); +const ImportWeakDependency = require("./ImportWeakDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ +/** @typedef {import("../ContextModule").ContextMode} ContextMode */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").ImportExpression} ImportExpression */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "ImportParserPlugin"; + +class ImportParserPlugin { + /** + * @param {JavascriptParserOptions} options options + */ + constructor(options) { + this.options = options; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + /** + * @template T + * @param {Iterable} enumerable enumerable + * @returns {T[][]} array of array + */ + const exportsFromEnumerable = (enumerable) => + Array.from(enumerable, (e) => [e]); + parser.hooks.collectDestructuringAssignmentProperties.tap( + PLUGIN_NAME, + (expr) => { + if (expr.type === "ImportExpression") return true; + } + ); + parser.hooks.importCall.tap(PLUGIN_NAME, (expr) => { + const param = parser.evaluateExpression(expr.source); + + let chunkName = null; + let mode = /** @type {ContextMode} */ (this.options.dynamicImportMode); + let include = null; + let exclude = null; + /** @type {string[][] | null} */ + let exports = null; + /** @type {RawChunkGroupOptions} */ + const groupOptions = {}; + + const { + dynamicImportPreload, + dynamicImportPrefetch, + dynamicImportFetchPriority + } = this.options; + if ( + dynamicImportPreload !== undefined && + dynamicImportPreload !== false + ) { + groupOptions.preloadOrder = + dynamicImportPreload === true ? 0 : dynamicImportPreload; + } + if ( + dynamicImportPrefetch !== undefined && + dynamicImportPrefetch !== false + ) { + groupOptions.prefetchOrder = + dynamicImportPrefetch === true ? 0 : dynamicImportPrefetch; + } + if ( + dynamicImportFetchPriority !== undefined && + dynamicImportFetchPriority !== false + ) { + groupOptions.fetchPriority = dynamicImportFetchPriority; + } + + const { options: importOptions, errors: commentErrors } = + parser.parseCommentOptions(/** @type {Range} */ (expr.range)); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + /** @type {DependencyLocation} */ (comment.loc) + ) + ); + } + } + + let phase = expr.phase; + if (!phase && importOptions && importOptions.webpackDefer !== undefined) { + if (typeof importOptions.webpackDefer !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackDefer\` expected a boolean, but received: ${importOptions.webpackDefer}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else if (importOptions.webpackDefer) { + phase = "defer"; + } + } + if (phase === "defer") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + "import.defer() is not implemented yet.", + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } + + if (importOptions) { + if (importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else if (importOptions.webpackIgnore) { + // Do not instrument `import()` if `webpackIgnore` is `true` + return false; + } + } + if (importOptions.webpackChunkName !== undefined) { + if (typeof importOptions.webpackChunkName !== "string") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else { + chunkName = importOptions.webpackChunkName; + } + } + if (importOptions.webpackMode !== undefined) { + if (typeof importOptions.webpackMode !== "string") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else { + mode = /** @type {ContextMode} */ (importOptions.webpackMode); + } + } + if (importOptions.webpackPrefetch !== undefined) { + if (importOptions.webpackPrefetch === true) { + groupOptions.prefetchOrder = 0; + } else if (typeof importOptions.webpackPrefetch === "number") { + groupOptions.prefetchOrder = importOptions.webpackPrefetch; + } else { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackPrefetch\` expected true or a number, but received: ${importOptions.webpackPrefetch}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } + } + if (importOptions.webpackPreload !== undefined) { + if (importOptions.webpackPreload === true) { + groupOptions.preloadOrder = 0; + } else if (typeof importOptions.webpackPreload === "number") { + groupOptions.preloadOrder = importOptions.webpackPreload; + } else { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackPreload\` expected true or a number, but received: ${importOptions.webpackPreload}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } + } + if (importOptions.webpackFetchPriority !== undefined) { + if ( + typeof importOptions.webpackFetchPriority === "string" && + ["high", "low", "auto"].includes(importOptions.webpackFetchPriority) + ) { + groupOptions.fetchPriority = + /** @type {"low" | "high" | "auto"} */ + (importOptions.webpackFetchPriority); + } else { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackFetchPriority\` expected true or "low", "high" or "auto", but received: ${importOptions.webpackFetchPriority}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } + } + if (importOptions.webpackInclude !== undefined) { + if ( + !importOptions.webpackInclude || + !(importOptions.webpackInclude instanceof RegExp) + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackInclude\` expected a regular expression, but received: ${importOptions.webpackInclude}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else { + include = importOptions.webpackInclude; + } + } + if (importOptions.webpackExclude !== undefined) { + if ( + !importOptions.webpackExclude || + !(importOptions.webpackExclude instanceof RegExp) + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackExclude\` expected a regular expression, but received: ${importOptions.webpackExclude}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else { + exclude = importOptions.webpackExclude; + } + } + if (importOptions.webpackExports !== undefined) { + if ( + !( + typeof importOptions.webpackExports === "string" || + (Array.isArray(importOptions.webpackExports) && + /** @type {string[]} */ (importOptions.webpackExports).every( + (item) => typeof item === "string" + )) + ) + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackExports\` expected a string or an array of strings, but received: ${importOptions.webpackExports}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else if (typeof importOptions.webpackExports === "string") { + exports = [[importOptions.webpackExports]]; + } else { + exports = exportsFromEnumerable(importOptions.webpackExports); + } + } + } + + if ( + mode !== "lazy" && + mode !== "lazy-once" && + mode !== "eager" && + mode !== "weak" + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + mode = "lazy"; + } + + const referencedPropertiesInDestructuring = + parser.destructuringAssignmentPropertiesFor(expr); + if (referencedPropertiesInDestructuring) { + if (exports) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + "`webpackExports` could not be used with destructuring assignment.", + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } + + exports = exportsFromEnumerable( + [...referencedPropertiesInDestructuring].map(({ id }) => id) + ); + } + + if (param.isString()) { + const attributes = getImportAttributes(expr); + + if (mode === "eager") { + const dep = new ImportEagerDependency( + /** @type {string} */ (param.string), + /** @type {Range} */ (expr.range), + exports, + attributes + ); + parser.state.current.addDependency(dep); + } else if (mode === "weak") { + const dep = new ImportWeakDependency( + /** @type {string} */ (param.string), + /** @type {Range} */ (expr.range), + exports, + attributes + ); + parser.state.current.addDependency(dep); + } else { + const depBlock = new AsyncDependenciesBlock( + { + ...groupOptions, + name: chunkName + }, + /** @type {DependencyLocation} */ (expr.loc), + param.string + ); + const dep = new ImportDependency( + /** @type {string} */ (param.string), + /** @type {Range} */ (expr.range), + exports, + attributes + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + depBlock.addDependency(dep); + parser.state.current.addBlock(depBlock); + } + return true; + } + if (mode === "weak") { + mode = "async-weak"; + } + const dep = ContextDependencyHelpers.create( + ImportContextDependency, + /** @type {Range} */ (expr.range), + param, + expr, + this.options, + { + chunkName, + groupOptions, + include, + exclude, + mode, + namespaceObject: + /** @type {BuildMeta} */ + (parser.state.module.buildMeta).strictHarmonyModule + ? "strict" + : true, + typePrefix: "import()", + category: "esm", + referencedExports: exports, + attributes: getImportAttributes(expr) + }, + parser + ); + if (!dep) return; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + }); + } +} + +module.exports = ImportParserPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..50537ad6ffcc0bc0f73fdf203b043ec21aa957b1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportPlugin.js @@ -0,0 +1,98 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("../ModuleTypeConstants"); +const ImportContextDependency = require("./ImportContextDependency"); +const ImportDependency = require("./ImportDependency"); +const ImportEagerDependency = require("./ImportEagerDependency"); +const ImportParserPlugin = require("./ImportParserPlugin"); +const ImportWeakDependency = require("./ImportWeakDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ + +const PLUGIN_NAME = "ImportPlugin"; + +class ImportPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + ImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportDependency, + new ImportDependency.Template() + ); + + compilation.dependencyFactories.set( + ImportEagerDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportEagerDependency, + new ImportEagerDependency.Template() + ); + + compilation.dependencyFactories.set( + ImportWeakDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportWeakDependency, + new ImportWeakDependency.Template() + ); + + compilation.dependencyFactories.set( + ImportContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + ImportContextDependency, + new ImportContextDependency.Template() + ); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if (parserOptions.import !== undefined && !parserOptions.import) { + return; + } + + new ImportParserPlugin(parserOptions).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = ImportPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportWeakDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportWeakDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..0ed3b053f96cd1501b99dea66bd819a8a48f13ae --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ImportWeakDependency.js @@ -0,0 +1,72 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ImportDependency = require("./ImportDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +class ImportWeakDependency extends ImportDependency { + /** + * @param {string} request the request + * @param {Range} range expression range + * @param {(string[][] | null)=} referencedExports list of referenced exports + * @param {ImportAttributes=} attributes import attributes + */ + constructor(request, range, referencedExports, attributes) { + super(request, range, referencedExports, attributes); + this.weak = true; + } + + get type() { + return "import() weak"; + } +} + +makeSerializable( + ImportWeakDependency, + "webpack/lib/dependencies/ImportWeakDependency" +); + +ImportWeakDependency.Template = class ImportDependencyTemplate extends ( + ImportDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ImportWeakDependency} */ (dependency); + const content = runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + module: /** @type {Module} */ (moduleGraph.getModule(dep)), + request: dep.request, + strict: /** @type {BuildMeta} */ (module.buildMeta).strictHarmonyModule, + message: "import() weak", + weak: true, + runtimeRequirements + }); + + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; + +module.exports = ImportWeakDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/JsonExportsDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/JsonExportsDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..600351a919259d63813dc296bc4f5e9799d223f3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/JsonExportsDependency.js @@ -0,0 +1,138 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../json/JsonData")} JsonData */ +/** @typedef {import("../json/JsonData").JsonValue} JsonValue */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ + +/** + * @callback GetExportsFromDataFn + * @param {JsonValue} data raw json data + * @param {number=} curDepth current depth + * @returns {ExportSpec[] | null} export spec or nothing + */ + +/** + * @param {number} exportsDepth exportsDepth + * @returns {GetExportsFromDataFn} value + */ +const getExportsWithDepth = (exportsDepth) => + /** @type {GetExportsFromDataFn} */ + function getExportsFromData(data, curDepth = 1) { + if (curDepth > exportsDepth) { + return null; + } + + if (data && typeof data === "object") { + if (Array.isArray(data)) { + return data.length < 100 + ? data.map((item, idx) => ({ + name: `${idx}`, + canMangle: true, + exports: getExportsFromData(item, curDepth + 1) || undefined + })) + : null; + } + + /** @type {ExportSpec[]} */ + const exports = []; + + for (const key of Object.keys(data)) { + exports.push({ + name: key, + canMangle: true, + exports: + getExportsFromData( + /** @type {JsonValue} */ + (data[key]), + curDepth + 1 + ) || undefined + }); + } + + return exports; + } + + return null; + }; + +class JsonExportsDependency extends NullDependency { + /** + * @param {JsonData} data json data + * @param {number} exportsDepth the depth of json exports to analyze + */ + constructor(data, exportsDepth) { + super(); + this.data = data; + this.exportsDepth = exportsDepth; + } + + get type() { + return "json exports"; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: getExportsWithDepth(this.exportsDepth)( + this.data && /** @type {JsonValue} */ (this.data.get()) + ), + dependencies: undefined + }; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + this.data.updateHash(hash); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.data); + write(this.exportsDepth); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.data = read(); + this.exportsDepth = read(); + super.deserialize(context); + } +} + +makeSerializable( + JsonExportsDependency, + "webpack/lib/dependencies/JsonExportsDependency" +); + +module.exports = JsonExportsDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LoaderDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LoaderDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..7ae66b3d2b00e6e454b463a04980b44d45396157 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LoaderDependency.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class LoaderDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { + super(request); + } + + get type() { + return "loader"; + } + + get category() { + return "loader"; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | GetConditionFn} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return false; + } +} + +module.exports = LoaderDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LoaderImportDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LoaderImportDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..94937922d60d0a1c78d22f9ded556680ea5f61a7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LoaderImportDependency.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class LoaderImportDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { + super(request); + this.weak = true; + } + + get type() { + return "loader import"; + } + + get category() { + return "loaderImport"; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | GetConditionFn} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return false; + } +} + +module.exports = LoaderImportDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LoaderPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LoaderPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..c57250eae5d1108145e7bb44e299c33fdb70263e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LoaderPlugin.js @@ -0,0 +1,285 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const NormalModule = require("../NormalModule"); +const LazySet = require("../util/LazySet"); +const LoaderDependency = require("./LoaderDependency"); +const LoaderImportDependency = require("./LoaderImportDependency"); + +/** @typedef {import("../../declarations/LoaderContext").LoaderPluginLoaderContext} LoaderPluginLoaderContext */ +/** @typedef {import("../Compilation").DepConstructor} DepConstructor */ +/** @typedef {import("../Compilation").ExecuteModuleExports} ExecuteModuleExports */ +/** @typedef {import("../Compilation").ExecuteModuleResult} ExecuteModuleResult */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ + +/** + * @callback ImportModuleCallback + * @param {(Error | null)=} err error object + * @param {ExecuteModuleExports=} exports exports of the evaluated module + */ + +/** + * @typedef {object} ImportModuleOptions + * @property {string=} layer the target layer + * @property {string=} publicPath the target public path + * @property {string=} baseUri target base uri + */ + +const PLUGIN_NAME = "LoaderPlugin"; + +class LoaderPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + LoaderDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + LoaderImportDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const moduleGraph = compilation.moduleGraph; + NormalModule.getCompilationHooks(compilation).loader.tap( + PLUGIN_NAME, + (loaderContext) => { + loaderContext.loadModule = (request, callback) => { + const dep = new LoaderDependency(request); + dep.loc = { + name: request + }; + const factory = compilation.dependencyFactories.get( + /** @type {DepConstructor} */ (dep.constructor) + ); + if (factory === undefined) { + return callback( + new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ) + ); + } + const oldFactorizeQueueContext = + compilation.factorizeQueue.getContext(); + compilation.factorizeQueue.setContext("load-module"); + const oldAddModuleQueueContext = + compilation.addModuleQueue.getContext(); + compilation.addModuleQueue.setContext("load-module"); + compilation.buildQueue.increaseParallelism(); + compilation.handleModuleCreation( + { + factory, + dependencies: [dep], + originModule: + /** @type {NormalModule} */ + (loaderContext._module), + context: loaderContext.context, + recursive: false + }, + (err) => { + compilation.factorizeQueue.setContext(oldFactorizeQueueContext); + compilation.addModuleQueue.setContext(oldAddModuleQueueContext); + compilation.buildQueue.decreaseParallelism(); + if (err) { + return callback(err); + } + const referencedModule = moduleGraph.getModule(dep); + if (!referencedModule) { + return callback(new Error("Cannot load the module")); + } + if (referencedModule.getNumberOfErrors() > 0) { + return callback( + new Error("The loaded module contains errors") + ); + } + const moduleSource = referencedModule.originalSource(); + if (!moduleSource) { + return callback( + new Error( + "The module created for a LoaderDependency must have an original source" + ) + ); + } + let map; + let source; + if (moduleSource.sourceAndMap) { + const sourceAndMap = moduleSource.sourceAndMap(); + map = sourceAndMap.map; + source = sourceAndMap.source; + } else { + map = moduleSource.map(); + source = moduleSource.source(); + } + const fileDependencies = new LazySet(); + const contextDependencies = new LazySet(); + const missingDependencies = new LazySet(); + const buildDependencies = new LazySet(); + referencedModule.addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ); + + for (const d of fileDependencies) { + loaderContext.addDependency(d); + } + for (const d of contextDependencies) { + loaderContext.addContextDependency(d); + } + for (const d of missingDependencies) { + loaderContext.addMissingDependency(d); + } + for (const d of buildDependencies) { + loaderContext.addBuildDependency(d); + } + return callback(null, source, map, referencedModule); + } + ); + }; + + /** + * @param {string} request the request string to load the module from + * @param {ImportModuleOptions} options options + * @param {ImportModuleCallback} callback callback returning the exports + * @returns {void} + */ + const importModule = (request, options, callback) => { + const dep = new LoaderImportDependency(request); + dep.loc = { + name: request + }; + const factory = compilation.dependencyFactories.get( + /** @type {DepConstructor} */ (dep.constructor) + ); + if (factory === undefined) { + return callback( + new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ) + ); + } + + const oldFactorizeQueueContext = + compilation.factorizeQueue.getContext(); + compilation.factorizeQueue.setContext("import-module"); + const oldAddModuleQueueContext = + compilation.addModuleQueue.getContext(); + compilation.addModuleQueue.setContext("import-module"); + compilation.buildQueue.increaseParallelism(); + compilation.handleModuleCreation( + { + factory, + dependencies: [dep], + originModule: + /** @type {NormalModule} */ + (loaderContext._module), + contextInfo: { + issuerLayer: options.layer + }, + context: loaderContext.context, + connectOrigin: false, + checkCycle: true + }, + (err) => { + compilation.factorizeQueue.setContext(oldFactorizeQueueContext); + compilation.addModuleQueue.setContext(oldAddModuleQueueContext); + compilation.buildQueue.decreaseParallelism(); + if (err) { + return callback(err); + } + const referencedModule = moduleGraph.getModule(dep); + if (!referencedModule) { + return callback(new Error("Cannot load the module")); + } + compilation.buildQueue.increaseParallelism(); + compilation.executeModule( + referencedModule, + { + entryOptions: { + baseUri: options.baseUri, + publicPath: options.publicPath + } + }, + (err, result) => { + compilation.buildQueue.decreaseParallelism(); + if (err) return callback(err); + const { + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies, + cacheable, + assets, + exports + } = /** @type {ExecuteModuleResult} */ (result); + for (const d of fileDependencies) { + loaderContext.addDependency(d); + } + for (const d of contextDependencies) { + loaderContext.addContextDependency(d); + } + for (const d of missingDependencies) { + loaderContext.addMissingDependency(d); + } + for (const d of buildDependencies) { + loaderContext.addBuildDependency(d); + } + if (cacheable === false) loaderContext.cacheable(false); + for (const [name, { source, info }] of assets) { + const buildInfo = + /** @type {BuildInfo} */ + ( + /** @type {NormalModule} */ (loaderContext._module) + .buildInfo + ); + if (!buildInfo.assets) { + buildInfo.assets = Object.create(null); + buildInfo.assetsInfo = new Map(); + } + /** @type {NonNullable} */ + (buildInfo.assets)[name] = source; + /** @type {NonNullable} */ + (buildInfo.assetsInfo).set(name, info); + } + callback(null, exports); + } + ); + } + ); + }; + + // @ts-expect-error overloading doesn't work + loaderContext.importModule = (request, options, callback) => { + if (!callback) { + return new Promise((resolve, reject) => { + importModule(request, options || {}, (err, result) => { + if (err) reject(err); + else resolve(result); + }); + }); + } + return importModule(request, options || {}, callback); + }; + } + ); + }); + } +} + +module.exports = LoaderPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LocalModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LocalModule.js new file mode 100644 index 0000000000000000000000000000000000000000..7748a06ba6a7cbbb934f4a14b867bb76be18390b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LocalModule.js @@ -0,0 +1,60 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class LocalModule { + /** + * @param {string} name name + * @param {number} idx index + */ + constructor(name, idx) { + this.name = name; + this.idx = idx; + this.used = false; + } + + flagUsed() { + this.used = true; + } + + /** + * @returns {string} variable name + */ + variableName() { + return `__WEBPACK_LOCAL_MODULE_${this.idx}__`; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.name); + write(this.idx); + write(this.used); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.name = read(); + this.idx = read(); + this.used = read(); + } +} + +makeSerializable(LocalModule, "webpack/lib/dependencies/LocalModule"); + +module.exports = LocalModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LocalModuleDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LocalModuleDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..2cde22fe145a4619ecf108cf77b325a7555a95f8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LocalModuleDependency.js @@ -0,0 +1,84 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./LocalModule")} LocalModule */ + +class LocalModuleDependency extends NullDependency { + /** + * @param {LocalModule} localModule local module + * @param {Range | undefined} range range + * @param {boolean} callNew true, when the local module should be called with new + */ + constructor(localModule, range, callNew) { + super(); + + this.localModule = localModule; + this.range = range; + this.callNew = callNew; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.localModule); + write(this.range); + write(this.callNew); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.localModule = read(); + this.range = read(); + this.callNew = read(); + + super.deserialize(context); + } +} + +makeSerializable( + LocalModuleDependency, + "webpack/lib/dependencies/LocalModuleDependency" +); + +LocalModuleDependency.Template = class LocalModuleDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {LocalModuleDependency} */ (dependency); + if (!dep.range) return; + const moduleInstance = dep.callNew + ? `new (function () { return ${dep.localModule.variableName()}; })()` + : dep.localModule.variableName(); + source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); + } +}; + +module.exports = LocalModuleDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LocalModulesHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LocalModulesHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..b94d149386f562a07d9f3333d397bea958a77ba9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/LocalModulesHelpers.js @@ -0,0 +1,68 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const LocalModule = require("./LocalModule"); + +/** @typedef {import("../javascript/JavascriptParser").ParserState} ParserState */ + +/** + * @param {string} parent parent module + * @param {string} mod module to resolve + * @returns {string} resolved module + */ +const lookup = (parent, mod) => { + if (mod.charAt(0) !== ".") return mod; + + const path = parent.split("/"); + const segments = mod.split("/"); + path.pop(); + + for (let i = 0; i < segments.length; i++) { + const seg = segments[i]; + if (seg === "..") { + path.pop(); + } else if (seg !== ".") { + path.push(seg); + } + } + + return path.join("/"); +}; + +/** + * @param {ParserState} state parser state + * @param {string} name name + * @returns {LocalModule} local module + */ +module.exports.addLocalModule = (state, name) => { + if (!state.localModules) { + state.localModules = []; + } + const m = new LocalModule(name, state.localModules.length); + state.localModules.push(m); + return m; +}; + +/** + * @param {ParserState} state parser state + * @param {string} name name + * @param {string=} namedModule named module + * @returns {LocalModule | null} local module or null + */ +module.exports.getLocalModule = (state, name, namedModule) => { + if (!state.localModules) return null; + if (namedModule) { + // resolve dependency name relative to the defining named module + name = lookup(namedModule, name); + } + for (let i = 0; i < state.localModules.length; i++) { + if (state.localModules[i].name === name) { + return state.localModules[i]; + } + } + return null; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDecoratorDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDecoratorDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..fd2b3fe5f730ad3973597b8d327fb88a62704cdd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDecoratorDependency.js @@ -0,0 +1,137 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const InitFragment = require("../InitFragment"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class ModuleDecoratorDependency extends NullDependency { + /** + * @param {string} decorator the decorator requirement + * @param {boolean} allowExportsAccess allow to access exports from module + */ + constructor(decorator, allowExportsAccess) { + super(); + this.decorator = decorator; + this.allowExportsAccess = allowExportsAccess; + this._hashUpdate = undefined; + } + + /** + * @returns {string} a display name for the type of dependency + */ + get type() { + return "module decorator"; + } + + get category() { + return "self"; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return "self"; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + return this.allowExportsAccess + ? Dependency.EXPORTS_OBJECT_REFERENCED + : Dependency.NO_EXPORTS_REFERENCED; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = `${this.decorator}${this.allowExportsAccess}`; + } + hash.update(this._hashUpdate); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.decorator); + write(this.allowExportsAccess); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.decorator = read(); + this.allowExportsAccess = read(); + super.deserialize(context); + } +} + +makeSerializable( + ModuleDecoratorDependency, + "webpack/lib/dependencies/ModuleDecoratorDependency" +); + +ModuleDecoratorDependency.Template = class ModuleDecoratorDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { module, chunkGraph, initFragments, runtimeRequirements } + ) { + const dep = /** @type {ModuleDecoratorDependency} */ (dependency); + runtimeRequirements.add(RuntimeGlobals.moduleLoaded); + runtimeRequirements.add(RuntimeGlobals.moduleId); + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(dep.decorator); + initFragments.push( + new InitFragment( + `/* module decorator */ ${module.moduleArgument} = ${dep.decorator}(${module.moduleArgument});\n`, + InitFragment.STAGE_PROVIDES, + 0, + `module decorator ${chunkGraph.getModuleId(module)}` + ) + ); + } +}; + +module.exports = ModuleDecoratorDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..82483dd727f5ce85a622158ff1d869a31c1f906e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDependency.js @@ -0,0 +1,101 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const DependencyTemplate = require("../DependencyTemplate"); + +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class ModuleDependency extends Dependency { + /** + * @param {string} request request path which needs resolving + */ + constructor(request) { + super(); + this.request = request; + this.userRequest = request; + this.range = undefined; + // TODO move it to subclasses and rename + // assertions must be serialized by subclasses that use it + /** @type {ImportAttributes | undefined} */ + this.assertions = undefined; + this._context = undefined; + } + + /** + * @returns {string | undefined} a request context + */ + getContext() { + return this._context; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + let str = `context${this._context || ""}|module${this.request}`; + if (this.assertions !== undefined) { + str += JSON.stringify(this.assertions); + } + return str; + } + + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return true; + } + + /** + * @param {string} context context directory + * @returns {Module} ignored module + */ + createIgnoredModule(context) { + const RawModule = require("../RawModule"); + + const module = new RawModule( + "/* (ignored) */", + `ignored|${context}|${this.request}`, + `${this.request} (ignored)` + ); + module.factoryMeta = { sideEffectFree: true }; + return module; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.request); + write(this.userRequest); + write(this._context); + write(this.range); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.request = read(); + this.userRequest = read(); + this._context = read(); + this.range = read(); + super.deserialize(context); + } +} + +ModuleDependency.Template = DependencyTemplate; + +module.exports = ModuleDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsId.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsId.js new file mode 100644 index 0000000000000000000000000000000000000000..8086fc79717efc69f351e82ae143b2dee49ac47b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsId.js @@ -0,0 +1,35 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ + +class ModuleDependencyTemplateAsId extends ModuleDependency.Template { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { runtimeTemplate, moduleGraph, chunkGraph }) { + const dep = /** @type {ModuleDependency} */ (dependency); + if (!dep.range) return; + const content = runtimeTemplate.moduleId({ + module: /** @type {Module} */ (moduleGraph.getModule(dep)), + chunkGraph, + request: dep.request, + weak: dep.weak + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} + +module.exports = ModuleDependencyTemplateAsId; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId.js new file mode 100644 index 0000000000000000000000000000000000000000..6b1641789799f11ab6e152ebab60142dd43fc28f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId.js @@ -0,0 +1,39 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class ModuleDependencyTemplateAsRequireId extends ModuleDependency.Template { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ModuleDependency} */ (dependency); + if (!dep.range) return; + const content = runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} + +module.exports = ModuleDependencyTemplateAsRequireId; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleHotAcceptDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleHotAcceptDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..1916a7e25638c03940fb591edc9b4ff6a937b3bf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleHotAcceptDependency.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +class ModuleHotAcceptDependency extends ModuleDependency { + /** + * @param {string} request the request string + * @param {Range} range location in source code + */ + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } + + get type() { + return "module.hot.accept"; + } + + get category() { + return "commonjs"; + } +} + +makeSerializable( + ModuleHotAcceptDependency, + "webpack/lib/dependencies/ModuleHotAcceptDependency" +); + +ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ModuleHotAcceptDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleHotDeclineDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleHotDeclineDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..70423774b4e535003b7920e87541148bae746c28 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ModuleHotDeclineDependency.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +class ModuleHotDeclineDependency extends ModuleDependency { + /** + * @param {string} request the request string + * @param {Range} range location in source code + */ + constructor(request, range) { + super(request); + + this.range = range; + this.weak = true; + } + + get type() { + return "module.hot.decline"; + } + + get category() { + return "commonjs"; + } +} + +makeSerializable( + ModuleHotDeclineDependency, + "webpack/lib/dependencies/ModuleHotDeclineDependency" +); + +ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ModuleHotDeclineDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/NullDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/NullDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..c22cafc7c7a8f9244bcdf56dc221bc50e307f4ba --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/NullDependency.js @@ -0,0 +1,40 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const DependencyTemplate = require("../DependencyTemplate"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class NullDependency extends Dependency { + get type() { + return "null"; + } + + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return false; + } +} + +NullDependency.Template = class NullDependencyTemplate extends ( + DependencyTemplate +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) {} +}; + +module.exports = NullDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/PrefetchDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/PrefetchDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..59e22c59a796f9d42209d9010e7a3af4a188c308 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/PrefetchDependency.js @@ -0,0 +1,27 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleDependency = require("./ModuleDependency"); + +class PrefetchDependency extends ModuleDependency { + /** + * @param {string} request the request string + */ + constructor(request) { + super(request); + } + + get type() { + return "prefetch"; + } + + get category() { + return "esm"; + } +} + +module.exports = PrefetchDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ProvidedDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ProvidedDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..422e1b63d65a156c958d10d48d5d0163e02eead3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/ProvidedDependency.js @@ -0,0 +1,157 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const InitFragment = require("../InitFragment"); +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @param {string[]|null} path the property path array + * @returns {string} the converted path + */ +const pathToString = (path) => + path !== null && path.length > 0 + ? path.map((part) => `[${JSON.stringify(part)}]`).join("") + : ""; + +class ProvidedDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {string} identifier identifier + * @param {string[]} ids ids + * @param {Range} range range + */ + constructor(request, identifier, ids, range) { + super(request); + this.identifier = identifier; + this.ids = ids; + this.range = range; + this._hashUpdate = undefined; + } + + get type() { + return "provided"; + } + + get category() { + return "esm"; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + const ids = this.ids; + if (ids.length === 0) return Dependency.EXPORTS_OBJECT_REFERENCED; + return [ids]; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = this.identifier + (this.ids ? this.ids.join(",") : ""); + } + hash.update(this._hashUpdate); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.identifier); + write(this.ids); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.identifier = read(); + this.ids = read(); + super.deserialize(context); + } +} + +makeSerializable( + ProvidedDependency, + "webpack/lib/dependencies/ProvidedDependency" +); + +class ProvidedDependencyTemplate extends ModuleDependency.Template { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { + runtime, + runtimeTemplate, + moduleGraph, + chunkGraph, + initFragments, + runtimeRequirements + } + ) { + const dep = /** @type {ProvidedDependency} */ (dependency); + const connection = + /** @type {ModuleGraphConnection} */ + (moduleGraph.getConnection(dep)); + const exportsInfo = moduleGraph.getExportsInfo(connection.module); + const usedName = exportsInfo.getUsedName(dep.ids, runtime); + initFragments.push( + new InitFragment( + `/* provided dependency */ var ${ + dep.identifier + } = ${runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + runtimeRequirements + })}${pathToString(/** @type {string[]} */ (usedName))};\n`, + InitFragment.STAGE_PROVIDES, + 1, + `provided ${dep.identifier}` + ) + ); + source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); + } +} + +ProvidedDependency.Template = ProvidedDependencyTemplate; + +module.exports = ProvidedDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/PureExpressionDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/PureExpressionDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..1df2517db1a047810f5afbaa5677453d08accd8d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/PureExpressionDependency.js @@ -0,0 +1,162 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { UsageState } = require("../ExportsInfo"); +const makeSerializable = require("../util/makeSerializable"); +const { filterRuntime, runtimeToString } = require("../util/runtime"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ + +class PureExpressionDependency extends NullDependency { + /** + * @param {Range} range the source range + */ + constructor(range) { + super(); + this.range = range; + /** @type {Set | false} */ + this.usedByExports = false; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime current runtimes + * @returns {boolean | RuntimeSpec} runtime condition + */ + _getRuntimeCondition(moduleGraph, runtime) { + const usedByExports = this.usedByExports; + if (usedByExports !== false) { + const selfModule = + /** @type {Module} */ + (moduleGraph.getParentModule(this)); + const exportsInfo = moduleGraph.getExportsInfo(selfModule); + const runtimeCondition = filterRuntime(runtime, (runtime) => { + for (const exportName of usedByExports) { + if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) { + return true; + } + } + return false; + }); + return runtimeCondition; + } + return false; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const runtimeCondition = this._getRuntimeCondition( + context.chunkGraph.moduleGraph, + context.runtime + ); + if (runtimeCondition === true) { + return; + } else if (runtimeCondition === false) { + hash.update("null"); + } else { + hash.update( + `${runtimeToString(runtimeCondition)}|${runtimeToString( + context.runtime + )}` + ); + } + hash.update(String(this.range)); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + write(this.usedByExports); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.range = read(); + this.usedByExports = read(); + super.deserialize(context); + } +} + +makeSerializable( + PureExpressionDependency, + "webpack/lib/dependencies/PureExpressionDependency" +); + +PureExpressionDependency.Template = class PureExpressionDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { chunkGraph, moduleGraph, runtime, runtimeTemplate, runtimeRequirements } + ) { + const dep = /** @type {PureExpressionDependency} */ (dependency); + const runtimeCondition = dep._getRuntimeCondition(moduleGraph, runtime); + if (runtimeCondition === true) { + // Do nothing + } else if (runtimeCondition === false) { + source.insert( + dep.range[0], + "(/* unused pure expression or super */ null && (" + ); + source.insert(dep.range[1], "))"); + } else { + const condition = runtimeTemplate.runtimeConditionExpression({ + chunkGraph, + runtime, + runtimeCondition, + runtimeRequirements + }); + source.insert( + dep.range[0], + `(/* runtime-dependent pure expression or super */ ${condition} ? (` + ); + source.insert(dep.range[1], ") : null)"); + } + } +}; + +module.exports = PureExpressionDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireContextDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireContextDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..87885a4987090913bbb2f0c3f3a98671e289759f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireContextDependency.js @@ -0,0 +1,38 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ContextDependency = require("./ContextDependency"); +const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ + +class RequireContextDependency extends ContextDependency { + /** + * @param {ContextDependencyOptions} options options + * @param {Range} range range + */ + constructor(options, range) { + super(options); + + this.range = range; + } + + get type() { + return "require.context"; + } +} + +makeSerializable( + RequireContextDependency, + "webpack/lib/dependencies/RequireContextDependency" +); + +RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = RequireContextDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireContextDependencyParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireContextDependencyParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..08ac21631d84c1fed0445944bb6ddfd529482571 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireContextDependencyParserPlugin.js @@ -0,0 +1,69 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RequireContextDependency = require("./RequireContextDependency"); + +/** @typedef {import("../ContextModule").ContextMode} ContextMode */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "RequireContextDependencyParserPlugin"; + +module.exports = class RequireContextDependencyParserPlugin { + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + parser.hooks.call.for("require.context").tap(PLUGIN_NAME, (expr) => { + let regExp = /^\.\/.*$/; + let recursive = true; + /** @type {ContextMode} */ + let mode = "sync"; + switch (expr.arguments.length) { + case 4: { + const modeExpr = parser.evaluateExpression(expr.arguments[3]); + if (!modeExpr.isString()) return; + mode = /** @type {ContextMode} */ (modeExpr.string); + } + // falls through + case 3: { + const regExpExpr = parser.evaluateExpression(expr.arguments[2]); + if (!regExpExpr.isRegExp()) return; + regExp = /** @type {RegExp} */ (regExpExpr.regExp); + } + // falls through + case 2: { + const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); + if (!recursiveExpr.isBoolean()) return; + recursive = /** @type {boolean} */ (recursiveExpr.bool); + } + // falls through + case 1: { + const requestExpr = parser.evaluateExpression(expr.arguments[0]); + if (!requestExpr.isString()) return; + const dep = new RequireContextDependency( + { + request: /** @type {string} */ (requestExpr.string), + recursive, + regExp, + mode, + category: "commonjs" + }, + /** @type {Range} */ + (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + } + } + }); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireContextPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireContextPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..5ac66f930e4b42bbc2a50e799257b718335a2dcc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireContextPlugin.js @@ -0,0 +1,166 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC +} = require("../ModuleTypeConstants"); +const { cachedSetProperty } = require("../util/cleverMerge"); +const ContextElementDependency = require("./ContextElementDependency"); +const RequireContextDependency = require("./RequireContextDependency"); +const RequireContextDependencyParserPlugin = require("./RequireContextDependencyParserPlugin"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ + +/** @type {ResolveOptions} */ +const EMPTY_RESOLVE_OPTIONS = {}; + +const PLUGIN_NAME = "RequireContextPlugin"; + +class RequireContextPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireContextDependency, + new RequireContextDependency.Template() + ); + + compilation.dependencyFactories.set( + ContextElementDependency, + normalModuleFactory + ); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireContext !== undefined && + !parserOptions.requireContext + ) { + return; + } + + new RequireContextDependencyParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + + contextModuleFactory.hooks.alternativeRequests.tap( + PLUGIN_NAME, + (items, options) => { + if (items.length === 0) return items; + + const finalResolveOptions = compiler.resolverFactory.get( + "normal", + cachedSetProperty( + options.resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + /** @type {string} */ + (options.category) + ) + ).options; + + let newItems; + if (!finalResolveOptions.fullySpecified) { + newItems = []; + for (const item of items) { + const { request, context } = item; + for (const ext of finalResolveOptions.extensions) { + if (request.endsWith(ext)) { + newItems.push({ + context, + request: request.slice(0, -ext.length) + }); + } + } + if (!finalResolveOptions.enforceExtension) { + newItems.push(item); + } + } + items = newItems; + + newItems = []; + for (const obj of items) { + const { request, context } = obj; + for (const mainFile of finalResolveOptions.mainFiles) { + if (request.endsWith(`/${mainFile}`)) { + newItems.push({ + context, + request: request.slice(0, -mainFile.length) + }); + newItems.push({ + context, + request: request.slice(0, -mainFile.length - 1) + }); + } + } + newItems.push(obj); + } + items = newItems; + } + + newItems = []; + for (const item of items) { + let hideOriginal = false; + for (const modulesItems of finalResolveOptions.modules) { + if (Array.isArray(modulesItems)) { + for (const dir of modulesItems) { + if (item.request.startsWith(`./${dir}/`)) { + newItems.push({ + context: item.context, + request: item.request.slice(dir.length + 3) + }); + hideOriginal = true; + } + } + } else { + const dir = modulesItems.replace(/\\/g, "/"); + const fullPath = + item.context.replace(/\\/g, "/") + item.request.slice(1); + if (fullPath.startsWith(dir)) { + newItems.push({ + context: item.context, + request: fullPath.slice(dir.length + 1) + }); + } + } + } + if (!hideOriginal) { + newItems.push(item); + } + } + return newItems; + } + ); + } + ); + } +} + +module.exports = RequireContextPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlock.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlock.js new file mode 100644 index 0000000000000000000000000000000000000000..da36d8546dde710c47a5fd5e6e6e894cb085d0b2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlock.js @@ -0,0 +1,30 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("../AsyncDependenciesBlock").GroupOptions} GroupOptions */ +/** @typedef {import("../ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ + +class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { + /** + * @param {GroupOptions | null} chunkName chunk name + * @param {(DependencyLocation | null)=} loc location info + */ + constructor(chunkName, loc) { + super(chunkName, loc, null); + } +} + +makeSerializable( + RequireEnsureDependenciesBlock, + "webpack/lib/dependencies/RequireEnsureDependenciesBlock" +); + +module.exports = RequireEnsureDependenciesBlock; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9c9a9c6869964516e49f6d6920a0299f9112a40a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js @@ -0,0 +1,141 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RequireEnsureDependenciesBlock = require("./RequireEnsureDependenciesBlock"); +const RequireEnsureDependency = require("./RequireEnsureDependency"); +const RequireEnsureItemDependency = require("./RequireEnsureItemDependency"); +const getFunctionExpression = require("./getFunctionExpression"); + +/** @typedef {import("../AsyncDependenciesBlock").GroupOptions} GroupOptions */ +/** @typedef {import("../ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "RequireEnsureDependenciesBlockParserPlugin"; + +module.exports = class RequireEnsureDependenciesBlockParserPlugin { + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + parser.hooks.call.for("require.ensure").tap(PLUGIN_NAME, (expr) => { + /** @type {string | GroupOptions | null} */ + let chunkName = null; + let errorExpressionArg = null; + let errorExpression = null; + switch (expr.arguments.length) { + case 4: { + const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); + if (!chunkNameExpr.isString()) return; + chunkName = + /** @type {string} */ + (chunkNameExpr.string); + } + // falls through + case 3: { + errorExpressionArg = expr.arguments[2]; + errorExpression = getFunctionExpression(errorExpressionArg); + + if (!errorExpression && !chunkName) { + const chunkNameExpr = parser.evaluateExpression(expr.arguments[2]); + if (!chunkNameExpr.isString()) return; + chunkName = + /** @type {string} */ + (chunkNameExpr.string); + } + } + // falls through + case 2: { + const dependenciesExpr = parser.evaluateExpression(expr.arguments[0]); + const dependenciesItems = /** @type {BasicEvaluatedExpression[]} */ ( + dependenciesExpr.isArray() + ? dependenciesExpr.items + : [dependenciesExpr] + ); + const successExpressionArg = expr.arguments[1]; + const successExpression = getFunctionExpression(successExpressionArg); + + if (successExpression) { + parser.walkExpressions(successExpression.expressions); + } + if (errorExpression) { + parser.walkExpressions(errorExpression.expressions); + } + + const depBlock = new RequireEnsureDependenciesBlock( + chunkName, + /** @type {DependencyLocation} */ + (expr.loc) + ); + const errorCallbackExists = + expr.arguments.length === 4 || + (!chunkName && expr.arguments.length === 3); + const dep = new RequireEnsureDependency( + /** @type {Range} */ (expr.range), + /** @type {Range} */ (expr.arguments[1].range), + errorCallbackExists && + /** @type {Range} */ (expr.arguments[2].range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + depBlock.addDependency(dep); + const old = parser.state.current; + parser.state.current = /** @type {TODO} */ (depBlock); + try { + let failed = false; + parser.inScope([], () => { + for (const ee of dependenciesItems) { + if (ee.isString()) { + const ensureDependency = new RequireEnsureItemDependency( + /** @type {string} */ (ee.string) + ); + ensureDependency.loc = + /** @type {DependencyLocation} */ + (expr.loc); + depBlock.addDependency(ensureDependency); + } else { + failed = true; + } + } + }); + if (failed) { + return; + } + if (successExpression) { + if (successExpression.fn.body.type === "BlockStatement") { + // Opt-out of Dead Control Flow detection for this block + const oldTerminated = parser.scope.terminated; + parser.walkStatement(successExpression.fn.body); + parser.scope.terminated = oldTerminated; + } else { + parser.walkExpression(successExpression.fn.body); + } + } + old.addBlock(depBlock); + } finally { + parser.state.current = old; + } + if (!successExpression) { + parser.walkExpression(successExpressionArg); + } + if (errorExpression) { + if (errorExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(errorExpression.fn.body); + } else { + parser.walkExpression(errorExpression.fn.body); + } + } else if (errorExpressionArg) { + parser.walkExpression(errorExpressionArg); + } + return true; + } + } + }); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..4fcec7731ceb1e7d16a1969a68e64ecf516a7374 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureDependency.js @@ -0,0 +1,115 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class RequireEnsureDependency extends NullDependency { + /** + * @param {Range} range range + * @param {Range} contentRange content range + * @param {Range | false} errorHandlerRange error handler range + */ + constructor(range, contentRange, errorHandlerRange) { + super(); + + this.range = range; + this.contentRange = contentRange; + this.errorHandlerRange = errorHandlerRange; + } + + get type() { + return "require.ensure"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.range); + write(this.contentRange); + write(this.errorHandlerRange); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.range = read(); + this.contentRange = read(); + this.errorHandlerRange = read(); + + super.deserialize(context); + } +} + +makeSerializable( + RequireEnsureDependency, + "webpack/lib/dependencies/RequireEnsureDependency" +); + +RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply( + dependency, + source, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {RequireEnsureDependency} */ (dependency); + const depBlock = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dep) + ); + const promise = runtimeTemplate.blockPromise({ + chunkGraph, + block: depBlock, + message: "require.ensure", + runtimeRequirements + }); + const range = dep.range; + const contentRange = dep.contentRange; + const errorHandlerRange = dep.errorHandlerRange; + source.replace(range[0], contentRange[0] - 1, `${promise}.then((`); + if (errorHandlerRange) { + source.replace( + contentRange[1], + errorHandlerRange[0] - 1, + `).bind(null, ${RuntimeGlobals.require}))['catch'](` + ); + source.replace(errorHandlerRange[1], range[1] - 1, ")"); + } else { + source.replace( + contentRange[1], + range[1] - 1, + `).bind(null, ${RuntimeGlobals.require}))['catch'](${RuntimeGlobals.uncaughtErrorHandler})` + ); + } + } +}; + +module.exports = RequireEnsureDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureItemDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureItemDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..f9a465a55c9fddb5a6822ca628314106a13e762a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsureItemDependency.js @@ -0,0 +1,36 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); +const NullDependency = require("./NullDependency"); + +class RequireEnsureItemDependency extends ModuleDependency { + /** + * @param {string} request the request string + */ + constructor(request) { + super(request); + } + + get type() { + return "require.ensure item"; + } + + get category() { + return "commonjs"; + } +} + +makeSerializable( + RequireEnsureItemDependency, + "webpack/lib/dependencies/RequireEnsureItemDependency" +); + +RequireEnsureItemDependency.Template = NullDependency.Template; + +module.exports = RequireEnsureItemDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsurePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsurePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..bcca946fa68e172930cab3fc36649c1c97a8f293 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireEnsurePlugin.js @@ -0,0 +1,86 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC +} = require("../ModuleTypeConstants"); +const { + evaluateToString, + toConstantDependency +} = require("../javascript/JavascriptParserHelpers"); +const RequireEnsureDependenciesBlockParserPlugin = require("./RequireEnsureDependenciesBlockParserPlugin"); +const RequireEnsureDependency = require("./RequireEnsureDependency"); +const RequireEnsureItemDependency = require("./RequireEnsureItemDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ + +const PLUGIN_NAME = "RequireEnsurePlugin"; + +class RequireEnsurePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireEnsureItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireEnsureItemDependency, + new RequireEnsureItemDependency.Template() + ); + + compilation.dependencyTemplates.set( + RequireEnsureDependency, + new RequireEnsureDependency.Template() + ); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireEnsure !== undefined && + !parserOptions.requireEnsure + ) { + return; + } + + new RequireEnsureDependenciesBlockParserPlugin().apply(parser); + parser.hooks.evaluateTypeof + .for("require.ensure") + .tap(PLUGIN_NAME, evaluateToString("function")); + parser.hooks.typeof + .for("require.ensure") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("function")) + ); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = RequireEnsurePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireHeaderDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireHeaderDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..7bf756035938b8227a8fb037597bc32fb9475aea --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireHeaderDependency.js @@ -0,0 +1,70 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class RequireHeaderDependency extends NullDependency { + /** + * @param {Range} range range + */ + constructor(range) { + super(); + if (!Array.isArray(range)) throw new Error("range must be valid"); + this.range = range; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.range); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {RequireHeaderDependency} RequireHeaderDependency + */ + static deserialize(context) { + const obj = new RequireHeaderDependency(context.read()); + obj.deserialize(context); + return obj; + } +} + +makeSerializable( + RequireHeaderDependency, + "webpack/lib/dependencies/RequireHeaderDependency" +); + +RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { runtimeRequirements }) { + const dep = /** @type {RequireHeaderDependency} */ (dependency); + runtimeRequirements.add(RuntimeGlobals.require); + source.replace(dep.range[0], dep.range[1] - 1, RuntimeGlobals.require); + } +}; + +module.exports = RequireHeaderDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireIncludeDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireIncludeDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..3a25e84a8ff66871cf18f60db81ff53b82f75cd2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireIncludeDependency.js @@ -0,0 +1,79 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const Template = require("../Template"); +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class RequireIncludeDependency extends ModuleDependency { + /** + * @param {string} request the request string + * @param {Range} range location in source code + */ + constructor(request, range) { + super(request); + + this.range = range; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + // This doesn't use any export + return Dependency.NO_EXPORTS_REFERENCED; + } + + get type() { + return "require.include"; + } + + get category() { + return "commonjs"; + } +} + +makeSerializable( + RequireIncludeDependency, + "webpack/lib/dependencies/RequireIncludeDependency" +); + +RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { runtimeTemplate }) { + const dep = /** @type {RequireIncludeDependency} */ (dependency); + const comment = runtimeTemplate.outputOptions.pathinfo + ? Template.toComment( + `require.include ${runtimeTemplate.requestShortener.shorten( + dep.request + )}` + ) + : ""; + + source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); + } +}; + +module.exports = RequireIncludeDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireIncludeDependencyParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireIncludeDependencyParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d6f59bf7222a4475c7f0cfe43455346e1b147461 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireIncludeDependencyParserPlugin.js @@ -0,0 +1,100 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("../WebpackError"); +const { + evaluateToString, + toConstantDependency +} = require("../javascript/JavascriptParserHelpers"); +const makeSerializable = require("../util/makeSerializable"); +const RequireIncludeDependency = require("./RequireIncludeDependency"); + +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "RequireIncludeDependencyParserPlugin"; + +module.exports = class RequireIncludeDependencyParserPlugin { + /** + * @param {boolean} warn true: warn about deprecation, false: don't warn + */ + constructor(warn) { + this.warn = warn; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + const { warn } = this; + parser.hooks.call.for("require.include").tap(PLUGIN_NAME, (expr) => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (!param.isString()) return; + + if (warn) { + parser.state.module.addWarning( + new RequireIncludeDeprecationWarning( + /** @type {DependencyLocation} */ + (expr.loc) + ) + ); + } + + const dep = new RequireIncludeDependency( + /** @type {string} */ (param.string), + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.current.addDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("require.include") + .tap(PLUGIN_NAME, (expr) => { + if (warn) { + parser.state.module.addWarning( + new RequireIncludeDeprecationWarning( + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } + return evaluateToString("function")(expr); + }); + parser.hooks.typeof.for("require.include").tap(PLUGIN_NAME, (expr) => { + if (warn) { + parser.state.module.addWarning( + new RequireIncludeDeprecationWarning( + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } + return toConstantDependency(parser, JSON.stringify("function"))(expr); + }); + } +}; + +class RequireIncludeDeprecationWarning extends WebpackError { + /** + * @param {DependencyLocation} loc location + */ + constructor(loc) { + super("require.include() is deprecated and will be removed soon."); + + this.name = "RequireIncludeDeprecationWarning"; + + this.loc = loc; + } +} + +makeSerializable( + RequireIncludeDeprecationWarning, + "webpack/lib/dependencies/RequireIncludeDependencyParserPlugin", + "RequireIncludeDeprecationWarning" +); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireIncludePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireIncludePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..850d69549e3c1d94266c4feef567879ada00463f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireIncludePlugin.js @@ -0,0 +1,63 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC +} = require("../ModuleTypeConstants"); +const RequireIncludeDependency = require("./RequireIncludeDependency"); +const RequireIncludeDependencyParserPlugin = require("./RequireIncludeDependencyParserPlugin"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ + +const PLUGIN_NAME = "RequireIncludePlugin"; + +class RequireIncludePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireIncludeDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireIncludeDependency, + new RequireIncludeDependency.Template() + ); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if (parserOptions.requireInclude === false) return; + const warn = parserOptions.requireInclude === undefined; + + new RequireIncludeDependencyParserPlugin(warn).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = RequireIncludePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireResolveContextDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireResolveContextDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..5745be890165caa4df125655286b468841290d30 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireResolveContextDependency.js @@ -0,0 +1,67 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ContextDependency = require("./ContextDependency"); +const ContextDependencyTemplateAsId = require("./ContextDependencyTemplateAsId"); + +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ + +class RequireResolveContextDependency extends ContextDependency { + /** + * @param {ContextDependencyOptions} options options + * @param {Range} range range + * @param {Range} valueRange value range + * @param {string=} context context + */ + constructor(options, range, valueRange, context) { + super(options, context); + + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "amd require context"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.range); + write(this.valueRange); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.range = read(); + this.valueRange = read(); + + super.deserialize(context); + } +} + +makeSerializable( + RequireResolveContextDependency, + "webpack/lib/dependencies/RequireResolveContextDependency" +); + +RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; + +module.exports = RequireResolveContextDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireResolveDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireResolveDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..3205925d2eb9575952fa2faa2c1d2b0abb1ea40c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireResolveDependency.js @@ -0,0 +1,58 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyAsId = require("./ModuleDependencyTemplateAsId"); + +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class RequireResolveDependency extends ModuleDependency { + /** + * @param {string} request the request string + * @param {Range} range location in source code + * @param {string=} context context + */ + constructor(request, range, context) { + super(request); + + this.range = range; + this._context = context; + } + + get type() { + return "require.resolve"; + } + + get category() { + return "commonjs"; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + // This doesn't use any export + return Dependency.NO_EXPORTS_REFERENCED; + } +} + +makeSerializable( + RequireResolveDependency, + "webpack/lib/dependencies/RequireResolveDependency" +); + +RequireResolveDependency.Template = ModuleDependencyAsId; + +module.exports = RequireResolveDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireResolveHeaderDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireResolveHeaderDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..2c9524c98ee1d3f16f0f714d4b9fa3177d55b0ef --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RequireResolveHeaderDependency.js @@ -0,0 +1,81 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class RequireResolveHeaderDependency extends NullDependency { + /** + * @param {Range} range range + */ + constructor(range) { + super(); + + if (!Array.isArray(range)) throw new Error("range must be valid"); + + this.range = range; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.range); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {RequireResolveHeaderDependency} RequireResolveHeaderDependency + */ + static deserialize(context) { + const obj = new RequireResolveHeaderDependency(context.read()); + obj.deserialize(context); + return obj; + } +} + +makeSerializable( + RequireResolveHeaderDependency, + "webpack/lib/dependencies/RequireResolveHeaderDependency" +); + +RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const dep = /** @type {RequireResolveHeaderDependency} */ (dependency); + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } + + /** + * @param {string} name name + * @param {RequireResolveHeaderDependency} dep dependency + * @param {ReplaceSource} source source + */ + applyAsTemplateArgument(name, dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } +}; + +module.exports = RequireResolveHeaderDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RuntimeRequirementsDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RuntimeRequirementsDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..0eee6e716ba73a4c9e42d8fe6adab3a741cc783b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/RuntimeRequirementsDependency.js @@ -0,0 +1,85 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ + +class RuntimeRequirementsDependency extends NullDependency { + /** + * @param {string[]} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super(); + this.runtimeRequirements = new Set(runtimeRequirements); + this._hashUpdate = undefined; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = `${[...this.runtimeRequirements].join()}`; + } + hash.update(this._hashUpdate); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.runtimeRequirements); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.runtimeRequirements = read(); + super.deserialize(context); + } +} + +makeSerializable( + RuntimeRequirementsDependency, + "webpack/lib/dependencies/RuntimeRequirementsDependency" +); + +RuntimeRequirementsDependency.Template = class RuntimeRequirementsDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { runtimeRequirements }) { + const dep = /** @type {RuntimeRequirementsDependency} */ (dependency); + for (const req of dep.runtimeRequirements) { + runtimeRequirements.add(req); + } + } +}; + +module.exports = RuntimeRequirementsDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/StaticExportsDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/StaticExportsDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..d91b5e43da5821362773cc5cfbae941fc6883e7c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/StaticExportsDependency.js @@ -0,0 +1,74 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ + +class StaticExportsDependency extends NullDependency { + /** + * @param {string[] | true} exports export names + * @param {boolean} canMangle true, if mangling exports names is allowed + */ + constructor(exports, canMangle) { + super(); + this.exports = exports; + this.canMangle = canMangle; + } + + get type() { + return "static exports"; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: this.exports, + canMangle: this.canMangle, + dependencies: undefined + }; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.exports); + write(this.canMangle); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.exports = read(); + this.canMangle = read(); + super.deserialize(context); + } +} + +makeSerializable( + StaticExportsDependency, + "webpack/lib/dependencies/StaticExportsDependency" +); + +module.exports = StaticExportsDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/SystemPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/SystemPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..bd0ca25585b0c3b1c428e706d6b4ab3d327a442b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/SystemPlugin.js @@ -0,0 +1,168 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC +} = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const WebpackError = require("../WebpackError"); +const { + evaluateToString, + expressionIsUnsupported, + toConstantDependency +} = require("../javascript/JavascriptParserHelpers"); +const makeSerializable = require("../util/makeSerializable"); +const ConstDependency = require("./ConstDependency"); +const SystemRuntimeModule = require("./SystemRuntimeModule"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "SystemPlugin"; + +class SystemPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.system) + .tap(PLUGIN_NAME, (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.system) + .tap(PLUGIN_NAME, (chunk, _set) => { + compilation.addRuntimeModule(chunk, new SystemRuntimeModule()); + }); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if (parserOptions.system === undefined || !parserOptions.system) { + return; + } + + /** + * @param {string} name name + */ + const setNotSupported = (name) => { + parser.hooks.evaluateTypeof + .for(name) + .tap(PLUGIN_NAME, evaluateToString("undefined")); + parser.hooks.expression + .for(name) + .tap( + PLUGIN_NAME, + expressionIsUnsupported( + parser, + `${name} is not supported by webpack.` + ) + ); + }; + + parser.hooks.typeof + .for("System.import") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for("System.import") + .tap(PLUGIN_NAME, evaluateToString("function")); + parser.hooks.typeof + .for("System") + .tap( + PLUGIN_NAME, + toConstantDependency(parser, JSON.stringify("object")) + ); + parser.hooks.evaluateTypeof + .for("System") + .tap(PLUGIN_NAME, evaluateToString("object")); + + setNotSupported("System.set"); + setNotSupported("System.get"); + setNotSupported("System.register"); + + parser.hooks.expression.for("System").tap(PLUGIN_NAME, (expr) => { + const dep = new ConstDependency( + RuntimeGlobals.system, + /** @type {Range} */ (expr.range), + [RuntimeGlobals.system] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + parser.hooks.call.for("System.import").tap(PLUGIN_NAME, (expr) => { + parser.state.module.addWarning( + new SystemImportDeprecationWarning( + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + + return parser.hooks.importCall.call({ + type: "ImportExpression", + source: + /** @type {import("estree").Literal} */ + (expr.arguments[0]), + loc: expr.loc, + range: expr.range, + options: null + }); + }); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +class SystemImportDeprecationWarning extends WebpackError { + /** + * @param {DependencyLocation} loc location + */ + constructor(loc) { + super( + "System.import() is deprecated and will be removed soon. Use import() instead.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); + + this.name = "SystemImportDeprecationWarning"; + + this.loc = loc; + } +} + +makeSerializable( + SystemImportDeprecationWarning, + "webpack/lib/dependencies/SystemPlugin", + "SystemImportDeprecationWarning" +); + +module.exports = SystemPlugin; +module.exports.SystemImportDeprecationWarning = SystemImportDeprecationWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/SystemRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/SystemRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..a7c3fba72f9171712f0feef82479532bec8c03b1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/SystemRuntimeModule.js @@ -0,0 +1,35 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +class SystemRuntimeModule extends RuntimeModule { + constructor() { + super("system"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.system} = {`, + Template.indent([ + "import: function () {", + Template.indent( + "throw new Error('System.import cannot be used indirectly');" + ), + "}" + ]), + "};" + ]); + } +} + +module.exports = SystemRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/URLContextDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/URLContextDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..cdf10312cb4e949896a63054503c238e7932b2b2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/URLContextDependency.js @@ -0,0 +1,65 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Haijie Xie @hai-x +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const ContextDependency = require("./ContextDependency"); +const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); + +/** @typedef {import("../ContextModule").ContextOptions} ContextOptions */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** @typedef {ContextOptions & { request: string }} ContextDependencyOptions */ + +class URLContextDependency extends ContextDependency { + /** + * @param {ContextDependencyOptions} options options + * @param {Range} range range + * @param {Range} valueRange value range + */ + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "new URL() context"; + } + + get category() { + return "url"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.valueRange); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.valueRange = read(); + super.deserialize(context); + } +} + +makeSerializable( + URLContextDependency, + "webpack/lib/dependencies/URLContextDependency" +); + +URLContextDependency.Template = ContextDependencyTemplateAsRequireCall; + +module.exports = URLContextDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/URLDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/URLDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..f105e0cf5921af37843b4787eb00e0e78146684b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/URLDependency.js @@ -0,0 +1,170 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RawDataUrlModule = require("../asset/RawDataUrlModule"); +const { + getDependencyUsedByExportsCondition +} = require("../optimize/InnerGraph"); +const makeSerializable = require("../util/makeSerializable"); +const memoize = require("../util/memoize"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +const getIgnoredRawDataUrlModule = memoize( + () => new RawDataUrlModule("data:,", "ignored-asset", "(ignored asset)") +); + +class URLDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {Range} range range of the arguments of new URL( |> ... <| ) + * @param {Range} outerRange range of the full |> new URL(...) <| + * @param {boolean=} relative use relative urls instead of absolute with base uri + */ + constructor(request, range, outerRange, relative) { + super(request); + this.range = range; + this.outerRange = outerRange; + this.relative = relative || false; + /** @type {Set | boolean | undefined} */ + this.usedByExports = undefined; + } + + get type() { + return "new URL()"; + } + + get category() { + return "url"; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | GetConditionFn} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return getDependencyUsedByExportsCondition( + this, + this.usedByExports, + moduleGraph + ); + } + + /** + * @param {string} context context directory + * @returns {Module} ignored module + */ + createIgnoredModule(context) { + return getIgnoredRawDataUrlModule(); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.outerRange); + write(this.relative); + write(this.usedByExports); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.outerRange = read(); + this.relative = read(); + this.usedByExports = read(); + super.deserialize(context); + } +} + +URLDependency.Template = class URLDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const { + chunkGraph, + moduleGraph, + runtimeRequirements, + runtimeTemplate, + runtime + } = templateContext; + const dep = /** @type {URLDependency} */ (dependency); + const connection = moduleGraph.getConnection(dep); + // Skip rendering depending when dependency is conditional + if (connection && !connection.isTargetActive(runtime)) { + source.replace( + dep.outerRange[0], + dep.outerRange[1] - 1, + "/* unused asset import */ undefined" + ); + return; + } + + runtimeRequirements.add(RuntimeGlobals.require); + + if (dep.relative) { + runtimeRequirements.add(RuntimeGlobals.relativeUrl); + source.replace( + dep.outerRange[0], + dep.outerRange[1] - 1, + `/* asset import */ new ${ + RuntimeGlobals.relativeUrl + }(${runtimeTemplate.moduleRaw({ + chunkGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + runtimeRequirements, + weak: false + })})` + ); + } else { + runtimeRequirements.add(RuntimeGlobals.baseURI); + + source.replace( + dep.range[0], + dep.range[1] - 1, + `/* asset import */ ${runtimeTemplate.moduleRaw({ + chunkGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + runtimeRequirements, + weak: false + })}, ${RuntimeGlobals.baseURI}` + ); + } + } +}; + +makeSerializable(URLDependency, "webpack/lib/dependencies/URLDependency"); + +module.exports = URLDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/URLPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/URLPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..709465887651663a017caaac073211cd120df3f0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/URLPlugin.js @@ -0,0 +1,68 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("../ModuleTypeConstants"); + +const URLContextDependency = require("../dependencies/URLContextDependency"); +const URLDependency = require("../dependencies/URLDependency"); +const URLParserPlugin = require("../url/URLParserPlugin"); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ + +const PLUGIN_NAME = "URLPlugin"; + +class URLPlugin { + /** + * @param {Compiler} compiler compiler + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory, contextModuleFactory }) => { + compilation.dependencyFactories.set(URLDependency, normalModuleFactory); + compilation.dependencyTemplates.set( + URLDependency, + new URLDependency.Template() + ); + compilation.dependencyFactories.set( + URLContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + URLContextDependency, + new URLContextDependency.Template() + ); + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const handler = (parser, parserOptions) => { + if (parserOptions.url === false) return; + new URLParserPlugin(parserOptions).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + } + ); + } +} + +module.exports = URLPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/UnsupportedDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/UnsupportedDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..6796634c9b49dbc5e515ade157d1b05d99992fb0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/UnsupportedDependency.js @@ -0,0 +1,82 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const NullDependency = require("./NullDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class UnsupportedDependency extends NullDependency { + /** + * @param {string} request the request string + * @param {Range} range location in source code + */ + constructor(request, range) { + super(); + + this.request = request; + this.range = range; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.request); + write(this.range); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.request = read(); + this.range = read(); + + super.deserialize(context); + } +} + +makeSerializable( + UnsupportedDependency, + "webpack/lib/dependencies/UnsupportedDependency" +); + +UnsupportedDependency.Template = class UnsupportedDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { runtimeTemplate }) { + const dep = /** @type {UnsupportedDependency} */ (dependency); + + source.replace( + dep.range[0], + dep.range[1], + runtimeTemplate.missingModule({ + request: dep.request + }) + ); + } +}; + +module.exports = UnsupportedDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WebAssemblyExportImportedDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WebAssemblyExportImportedDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..4ae5bd881aa7d77f8e3f46186901381008b4c931 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WebAssemblyExportImportedDependency.js @@ -0,0 +1,93 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class WebAssemblyExportImportedDependency extends ModuleDependency { + /** + * @param {string} exportName export name + * @param {string} request request + * @param {string} name name + * @param {string} valueType value type + */ + constructor(exportName, request, name, valueType) { + super(request); + /** @type {string} */ + this.exportName = exportName; + /** @type {string} */ + this.name = name; + /** @type {string} */ + this.valueType = valueType; + } + + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return Dependency.TRANSITIVE; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + return [[this.name]]; + } + + get type() { + return "wasm export import"; + } + + get category() { + return "wasm"; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.exportName); + write(this.name); + write(this.valueType); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.exportName = read(); + this.name = read(); + this.valueType = read(); + + super.deserialize(context); + } +} + +makeSerializable( + WebAssemblyExportImportedDependency, + "webpack/lib/dependencies/WebAssemblyExportImportedDependency" +); + +module.exports = WebAssemblyExportImportedDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WebAssemblyImportDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WebAssemblyImportDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..de23f76f19af01ab48c503069983bfd8838e4d3e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WebAssemblyImportDependency.js @@ -0,0 +1,108 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("../util/makeSerializable"); +const UnsupportedWebAssemblyFeatureError = require("../wasm-sync/UnsupportedWebAssemblyFeatureError"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class WebAssemblyImportDependency extends ModuleDependency { + /** + * @param {string} request the request + * @param {string} name the imported name + * @param {ModuleImportDescription} description the WASM ast node + * @param {false | string} onlyDirectImport if only direct imports are allowed + */ + constructor(request, name, description, onlyDirectImport) { + super(request); + /** @type {string} */ + this.name = name; + /** @type {ModuleImportDescription} */ + this.description = description; + /** @type {false | string} */ + this.onlyDirectImport = onlyDirectImport; + } + + get type() { + return "wasm import"; + } + + get category() { + return "wasm"; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + return [[this.name]]; + } + + /** + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | null | undefined} errors + */ + getErrors(moduleGraph) { + const module = moduleGraph.getModule(this); + + if ( + this.onlyDirectImport && + module && + !module.type.startsWith("webassembly") + ) { + return [ + new UnsupportedWebAssemblyFeatureError( + `Import "${this.name}" from "${this.request}" with ${this.onlyDirectImport} can only be used for direct wasm to wasm dependencies` + ) + ]; + } + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + + write(this.name); + write(this.description); + write(this.onlyDirectImport); + + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + + this.name = read(); + this.description = read(); + this.onlyDirectImport = read(); + + super.deserialize(context); + } +} + +makeSerializable( + WebAssemblyImportDependency, + "webpack/lib/dependencies/WebAssemblyImportDependency" +); + +module.exports = WebAssemblyImportDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WebpackIsIncludedDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WebpackIsIncludedDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..0b308734ee7a5f8ebe517840327d64b324161389 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WebpackIsIncludedDependency.js @@ -0,0 +1,85 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const Template = require("../Template"); +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class WebpackIsIncludedDependency extends ModuleDependency { + /** + * @param {string} request the request string + * @param {Range} range location in source code + */ + constructor(request, range) { + super(request); + + this.weak = true; + this.range = range; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + // This doesn't use any export + return Dependency.NO_EXPORTS_REFERENCED; + } + + get type() { + return "__webpack_is_included__"; + } +} + +makeSerializable( + WebpackIsIncludedDependency, + "webpack/lib/dependencies/WebpackIsIncludedDependency" +); + +WebpackIsIncludedDependency.Template = class WebpackIsIncludedDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, { runtimeTemplate, chunkGraph, moduleGraph }) { + const dep = /** @type {WebpackIsIncludedDependency} */ (dependency); + const connection = moduleGraph.getConnection(dep); + const included = connection + ? chunkGraph.getNumberOfModuleChunks(connection.module) > 0 + : false; + const comment = runtimeTemplate.outputOptions.pathinfo + ? Template.toComment( + `__webpack_is_included__ ${runtimeTemplate.requestShortener.shorten( + dep.request + )}` + ) + : ""; + + source.replace( + dep.range[0], + dep.range[1] - 1, + `${comment}${JSON.stringify(included)}` + ); + } +}; + +module.exports = WebpackIsIncludedDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WorkerDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WorkerDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..eafc653d95c248a3899de34c198c7231286d54e7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WorkerDependency.js @@ -0,0 +1,136 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const ModuleDependency = require("./ModuleDependency"); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class WorkerDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {Range} range range + * @param {object} workerDependencyOptions options + * @param {string=} workerDependencyOptions.publicPath public path for the worker + * @param {boolean=} workerDependencyOptions.needNewUrl need generate `new URL(...)` + */ + constructor(request, range, workerDependencyOptions) { + super(request); + this.range = range; + // If options are updated, don't forget to update the hash and serialization functions + this.options = workerDependencyOptions; + /** Cache the hash */ + this._hashUpdate = undefined; + } + + /** + * Returns list of exports referenced by this dependency + * @param {ModuleGraph} moduleGraph module graph + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getReferencedExports(moduleGraph, runtime) { + return Dependency.NO_EXPORTS_REFERENCED; + } + + get type() { + return "new Worker()"; + } + + get category() { + return "worker"; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = JSON.stringify(this.options); + } + hash.update(this._hashUpdate); + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.options); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.options = read(); + super.deserialize(context); + } +} + +WorkerDependency.Template = class WorkerDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @param {Dependency} dependency the dependency for which the template should be applied + * @param {ReplaceSource} source the current replace source which can be modified + * @param {DependencyTemplateContext} templateContext the context object + * @returns {void} + */ + apply(dependency, source, templateContext) { + const { chunkGraph, moduleGraph, runtimeRequirements } = templateContext; + const dep = /** @type {WorkerDependency} */ (dependency); + const block = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dependency) + ); + const entrypoint = /** @type {Entrypoint} */ ( + chunkGraph.getBlockChunkGroup(block) + ); + const chunk = entrypoint.getEntrypointChunk(); + // We use the workerPublicPath option if provided, else we fallback to the RuntimeGlobal publicPath + const workerImportBaseUrl = dep.options.publicPath + ? `"${dep.options.publicPath}"` + : RuntimeGlobals.publicPath; + + runtimeRequirements.add(RuntimeGlobals.publicPath); + runtimeRequirements.add(RuntimeGlobals.baseURI); + runtimeRequirements.add(RuntimeGlobals.getChunkScriptFilename); + + const workerImportStr = `/* worker import */ ${workerImportBaseUrl} + ${ + RuntimeGlobals.getChunkScriptFilename + }(${JSON.stringify(chunk.id)}), ${RuntimeGlobals.baseURI}`; + + source.replace( + dep.range[0], + dep.range[1] - 1, + dep.options.needNewUrl ? `new URL(${workerImportStr})` : workerImportStr + ); + } +}; + +makeSerializable(WorkerDependency, "webpack/lib/dependencies/WorkerDependency"); + +module.exports = WorkerDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WorkerPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WorkerPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..6d28cfbe0ba04333b7314bb6948823e9ec8e933f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/WorkerPlugin.js @@ -0,0 +1,572 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { pathToFileURL } = require("url"); +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const CommentCompilationWarning = require("../CommentCompilationWarning"); +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("../ModuleTypeConstants"); +const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); +const EnableChunkLoadingPlugin = require("../javascript/EnableChunkLoadingPlugin"); +const { equals } = require("../util/ArrayHelpers"); +const createHash = require("../util/createHash"); +const { contextify } = require("../util/identifier"); +const EnableWasmLoadingPlugin = require("../wasm/EnableWasmLoadingPlugin"); +const ConstDependency = require("./ConstDependency"); +const CreateScriptUrlDependency = require("./CreateScriptUrlDependency"); +const { + harmonySpecifierTag +} = require("./HarmonyImportDependencyParserPlugin"); +const WorkerDependency = require("./WorkerDependency"); + +/** @typedef {import("estree").CallExpression} CallExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("estree").ObjectExpression} ObjectExpression */ +/** @typedef {import("estree").Pattern} Pattern */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").SpreadElement} SpreadElement */ +/** @typedef {import("../../declarations/WebpackOptions").ChunkLoading} ChunkLoading */ +/** @typedef {import("../../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").OutputModule} OutputModule */ +/** @typedef {import("../../declarations/WebpackOptions").WasmLoading} WasmLoading */ +/** @typedef {import("../../declarations/WebpackOptions").WorkerPublicPath} WorkerPublicPath */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("./HarmonyImportDependencyParserPlugin").HarmonySettings} HarmonySettings */ + +/** + * @param {NormalModule} module module + * @returns {string} url + */ +const getUrl = (module) => pathToFileURL(module.resource).toString(); + +const WorkerSpecifierTag = Symbol("worker specifier tag"); + +const DEFAULT_SYNTAX = [ + "Worker", + "SharedWorker", + "navigator.serviceWorker.register()", + "Worker from worker_threads" +]; + +/** @type {WeakMap} */ +const workerIndexMap = new WeakMap(); + +const PLUGIN_NAME = "WorkerPlugin"; + +class WorkerPlugin { + /** + * @param {ChunkLoading=} chunkLoading chunk loading + * @param {WasmLoading=} wasmLoading wasm loading + * @param {OutputModule=} module output module + * @param {WorkerPublicPath=} workerPublicPath worker public path + */ + constructor(chunkLoading, wasmLoading, module, workerPublicPath) { + this._chunkLoading = chunkLoading; + this._wasmLoading = wasmLoading; + this._module = module; + this._workerPublicPath = workerPublicPath; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + if (this._chunkLoading) { + new EnableChunkLoadingPlugin(this._chunkLoading).apply(compiler); + } + if (this._wasmLoading) { + new EnableWasmLoadingPlugin(this._wasmLoading).apply(compiler); + } + const cachedContextify = contextify.bindContextCache( + compiler.context, + compiler.root + ); + compiler.hooks.thisCompilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WorkerDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + WorkerDependency, + new WorkerDependency.Template() + ); + compilation.dependencyTemplates.set( + CreateScriptUrlDependency, + new CreateScriptUrlDependency.Template() + ); + + /** + * @param {JavascriptParser} parser the parser + * @param {Expression} expr expression + * @returns {[string, Range] | void} parsed + */ + const parseModuleUrl = (parser, expr) => { + if (expr.type !== "NewExpression" || expr.callee.type === "Super") { + return; + } + if ( + expr.arguments.length === 1 && + expr.arguments[0].type === "MemberExpression" && + isMetaUrl(parser, expr.arguments[0]) + ) { + const arg1 = expr.arguments[0]; + return [ + getUrl(parser.state.module), + [ + /** @type {Range} */ (arg1.range)[0], + /** @type {Range} */ (arg1.range)[1] + ] + ]; + } else if (expr.arguments.length === 2) { + const [arg1, arg2] = expr.arguments; + if (arg1.type === "SpreadElement") return; + if (arg2.type === "SpreadElement") return; + const callee = parser.evaluateExpression(expr.callee); + if (!callee.isIdentifier() || callee.identifier !== "URL") return; + const arg2Value = parser.evaluateExpression(arg2); + if ( + !arg2Value.isString() || + !( + /** @type {string} */ (arg2Value.string).startsWith("file://") + ) || + arg2Value.string !== getUrl(parser.state.module) + ) { + return; + } + const arg1Value = parser.evaluateExpression(arg1); + if (!arg1Value.isString()) return; + return [ + /** @type {string} */ (arg1Value.string), + [ + /** @type {Range} */ (arg1.range)[0], + /** @type {Range} */ (arg2.range)[1] + ] + ]; + } + }; + + /** + * @param {JavascriptParser} parser the parser + * @param {MemberExpression} expr expression + * @returns {boolean} is `import.meta.url` + */ + const isMetaUrl = (parser, expr) => { + const chain = parser.extractMemberExpressionChain(expr); + + if ( + chain.members.length !== 1 || + chain.object.type !== "MetaProperty" || + chain.object.meta.name !== "import" || + chain.object.property.name !== "meta" || + chain.members[0] !== "url" + ) { + return false; + } + + return true; + }; + + /** @typedef {Record} Values */ + + /** + * @param {JavascriptParser} parser the parser + * @param {ObjectExpression} expr expression + * @returns {{ expressions: Record, otherElements: (Property | SpreadElement)[], values: Values, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object + */ + const parseObjectExpression = (parser, expr) => { + /** @type {Values} */ + const values = {}; + /** @type {Record} */ + const expressions = {}; + /** @type {(Property | SpreadElement)[]} */ + const otherElements = []; + let spread = false; + for (const prop of expr.properties) { + if (prop.type === "SpreadElement") { + spread = true; + } else if ( + prop.type === "Property" && + !prop.method && + !prop.computed && + prop.key.type === "Identifier" + ) { + expressions[prop.key.name] = prop.value; + if (!prop.shorthand && !prop.value.type.endsWith("Pattern")) { + const value = parser.evaluateExpression( + /** @type {Expression} */ + (prop.value) + ); + if (value.isCompileTimeValue()) { + values[prop.key.name] = value.asCompileTimeValue(); + } + } + } else { + otherElements.push(prop); + } + } + const insertType = expr.properties.length > 0 ? "comma" : "single"; + const insertLocation = /** @type {Range} */ ( + expr.properties[expr.properties.length - 1].range + )[1]; + return { + expressions, + otherElements, + values, + spread, + insertType, + insertLocation + }; + }; + + /** + * @param {Parser} parser parser parser + * @param {JavascriptParserOptions} parserOptions parserOptions + * @returns {void} + */ + const parserPlugin = (parser, parserOptions) => { + if (parserOptions.worker === false) return; + const options = !Array.isArray(parserOptions.worker) + ? ["..."] + : parserOptions.worker; + /** + * @param {CallExpression} expr expression + * @returns {boolean | void} true when handled + */ + const handleNewWorker = (expr) => { + if (expr.arguments.length === 0 || expr.arguments.length > 2) { + return; + } + const [arg1, arg2] = expr.arguments; + if (arg1.type === "SpreadElement") return; + if (arg2 && arg2.type === "SpreadElement") return; + + /** @type {string} */ + let url; + /** @type {Range} */ + let range; + /** @type {boolean} */ + let needNewUrl = false; + + if (arg1.type === "MemberExpression" && isMetaUrl(parser, arg1)) { + url = getUrl(parser.state.module); + range = [ + /** @type {Range} */ (arg1.range)[0], + /** @type {Range} */ (arg1.range)[1] + ]; + needNewUrl = true; + } else { + const parsedUrl = parseModuleUrl(parser, arg1); + if (!parsedUrl) return; + [url, range] = parsedUrl; + } + + const { + expressions, + otherElements, + values: options, + spread: hasSpreadInOptions, + insertType, + insertLocation + } = arg2 && arg2.type === "ObjectExpression" + ? parseObjectExpression(parser, arg2) + : { + /** @type {Record} */ + expressions: {}, + otherElements: [], + /** @type {Values} */ + values: {}, + spread: false, + insertType: arg2 ? "spread" : "argument", + insertLocation: arg2 + ? /** @type {Range} */ (arg2.range) + : /** @type {Range} */ (arg1.range)[1] + }; + const { options: importOptions, errors: commentErrors } = + parser.parseCommentOptions(/** @type {Range} */ (expr.range)); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + /** @type {DependencyLocation} */ (comment.loc) + ) + ); + } + } + + /** @type {EntryOptions} */ + const entryOptions = {}; + + if (importOptions) { + if (importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else if (importOptions.webpackIgnore) { + return false; + } + } + if (importOptions.webpackEntryOptions !== undefined) { + if ( + typeof importOptions.webpackEntryOptions !== "object" || + importOptions.webpackEntryOptions === null + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackEntryOptions\` expected a object, but received: ${importOptions.webpackEntryOptions}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else { + Object.assign( + entryOptions, + importOptions.webpackEntryOptions + ); + } + } + if (importOptions.webpackChunkName !== undefined) { + if (typeof importOptions.webpackChunkName !== "string") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else { + entryOptions.name = importOptions.webpackChunkName; + } + } + } + + if ( + !Object.prototype.hasOwnProperty.call(entryOptions, "name") && + options && + typeof options.name === "string" + ) { + entryOptions.name = options.name; + } + + if (entryOptions.runtime === undefined) { + const i = workerIndexMap.get(parser.state) || 0; + workerIndexMap.set(parser.state, i + 1); + const name = `${cachedContextify( + parser.state.module.identifier() + )}|${i}`; + const hash = createHash( + /** @type {HashFunction} */ + (compilation.outputOptions.hashFunction) + ); + hash.update(name); + const digest = + /** @type {string} */ + (hash.digest(compilation.outputOptions.hashDigest)); + entryOptions.runtime = digest.slice( + 0, + compilation.outputOptions.hashDigestLength + ); + } + + const block = new AsyncDependenciesBlock({ + name: entryOptions.name, + entryOptions: { + chunkLoading: this._chunkLoading, + wasmLoading: this._wasmLoading, + ...entryOptions + } + }); + block.loc = expr.loc; + const dep = new WorkerDependency(url, range, { + publicPath: this._workerPublicPath, + needNewUrl + }); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + block.addDependency(dep); + parser.state.module.addBlock(block); + + if (compilation.outputOptions.trustedTypes) { + const dep = new CreateScriptUrlDependency( + /** @type {Range} */ (expr.arguments[0].range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addDependency(dep); + } + + if (expressions.type) { + const expr = expressions.type; + if (options.type !== false) { + const dep = new ConstDependency( + this._module ? '"module"' : "undefined", + /** @type {Range} */ (expr.range) + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + /** @type {EXPECTED_ANY} */ + (expressions).type = undefined; + } + } else if (insertType === "comma") { + if (this._module || hasSpreadInOptions) { + const dep = new ConstDependency( + `, type: ${this._module ? '"module"' : "undefined"}`, + insertLocation + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + } + } else if (insertType === "spread") { + const dep1 = new ConstDependency( + "Object.assign({}, ", + /** @type {Range} */ (insertLocation)[0] + ); + const dep2 = new ConstDependency( + `, { type: ${this._module ? '"module"' : "undefined"} })`, + /** @type {Range} */ (insertLocation)[1] + ); + dep1.loc = /** @type {DependencyLocation} */ (expr.loc); + dep2.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep1); + parser.state.module.addPresentationalDependency(dep2); + } else if (insertType === "argument" && this._module) { + const dep = new ConstDependency( + ', { type: "module" }', + insertLocation + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + } + + parser.walkExpression(expr.callee); + for (const key of Object.keys(expressions)) { + if (expressions[key]) { + if (expressions[key].type.endsWith("Pattern")) continue; + parser.walkExpression( + /** @type {Expression} */ + (expressions[key]) + ); + } + } + for (const prop of otherElements) { + parser.walkProperty(prop); + } + if (insertType === "spread") { + parser.walkExpression(arg2); + } + + return true; + }; + /** + * @param {string} item item + */ + const processItem = (item) => { + if ( + item.startsWith("*") && + item.includes(".") && + item.endsWith("()") + ) { + const firstDot = item.indexOf("."); + const pattern = item.slice(1, firstDot); + const itemMembers = item.slice(firstDot + 1, -2); + + parser.hooks.preDeclarator.tap( + PLUGIN_NAME, + (decl, _statement) => { + if ( + decl.id.type === "Identifier" && + decl.id.name === pattern + ) { + parser.tagVariable(decl.id.name, WorkerSpecifierTag); + return true; + } + } + ); + parser.hooks.pattern.for(pattern).tap(PLUGIN_NAME, (pattern) => { + parser.tagVariable(pattern.name, WorkerSpecifierTag); + return true; + }); + parser.hooks.callMemberChain + .for(WorkerSpecifierTag) + .tap(PLUGIN_NAME, (expression, members) => { + if (itemMembers !== members.join(".")) { + return; + } + + return handleNewWorker(expression); + }); + } else if (item.endsWith("()")) { + parser.hooks.call + .for(item.slice(0, -2)) + .tap(PLUGIN_NAME, handleNewWorker); + } else { + const match = /^(.+?)(\(\))?\s+from\s+(.+)$/.exec(item); + if (match) { + const ids = match[1].split("."); + const call = match[2]; + const source = match[3]; + (call ? parser.hooks.call : parser.hooks.new) + .for(harmonySpecifierTag) + .tap(PLUGIN_NAME, (expr) => { + const settings = /** @type {HarmonySettings} */ ( + parser.currentTagData + ); + if ( + !settings || + settings.source !== source || + !equals(settings.ids, ids) + ) { + return; + } + return handleNewWorker(expr); + }); + } else { + parser.hooks.new.for(item).tap(PLUGIN_NAME, handleNewWorker); + } + } + }; + for (const item of options) { + if (item === "...") { + for (const itemFromDefault of DEFAULT_SYNTAX) { + processItem(itemFromDefault); + } + } else { + processItem(item); + } + } + }; + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, parserPlugin); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, parserPlugin); + } + ); + } +} + +module.exports = WorkerPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/getFunctionExpression.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/getFunctionExpression.js new file mode 100644 index 0000000000000000000000000000000000000000..e213fa6cedd046110714f53d0c9a68cfd5c367ff --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/getFunctionExpression.js @@ -0,0 +1,64 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("estree").ArrowFunctionExpression} ArrowFunctionExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").FunctionExpression} FunctionExpression */ +/** @typedef {import("estree").SpreadElement} SpreadElement */ + +/** + * @param {Expression | SpreadElement} expr expressions + * @returns {{fn: FunctionExpression | ArrowFunctionExpression, expressions: (Expression | SpreadElement)[], needThis: boolean | undefined } | undefined} function expression with additional information + */ +module.exports = (expr) => { + // + if ( + expr.type === "FunctionExpression" || + expr.type === "ArrowFunctionExpression" + ) { + return { + fn: expr, + expressions: [], + needThis: false + }; + } + + // .bind() + if ( + expr.type === "CallExpression" && + expr.callee.type === "MemberExpression" && + expr.callee.object.type === "FunctionExpression" && + expr.callee.property.type === "Identifier" && + expr.callee.property.name === "bind" && + expr.arguments.length === 1 + ) { + return { + fn: expr.callee.object, + expressions: [expr.arguments[0]], + needThis: undefined + }; + } + // (function(_this) {return })(this) (Coffeescript) + if ( + expr.type === "CallExpression" && + expr.callee.type === "FunctionExpression" && + expr.callee.body.type === "BlockStatement" && + expr.arguments.length === 1 && + expr.arguments[0].type === "ThisExpression" && + expr.callee.body.body && + expr.callee.body.body.length === 1 && + expr.callee.body.body[0].type === "ReturnStatement" && + expr.callee.body.body[0].argument && + expr.callee.body.body[0].argument.type === "FunctionExpression" + ) { + return { + fn: expr.callee.body.body[0].argument, + expressions: [], + needThis: true + }; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/processExportInfo.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/processExportInfo.js new file mode 100644 index 0000000000000000000000000000000000000000..ff43885570f6f51b545768e2c74b09ad68da79e5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/dependencies/processExportInfo.js @@ -0,0 +1,68 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { UsageState } = require("../ExportsInfo"); + +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** @typedef {string[][]} ReferencedExports */ + +/** + * @param {RuntimeSpec} runtime the runtime + * @param {ReferencedExports} referencedExports list of referenced exports, will be added to + * @param {string[]} prefix export prefix + * @param {ExportInfo=} exportInfo the export info + * @param {boolean} defaultPointsToSelf when true, using default will reference itself + * @param {Set} alreadyVisited already visited export info (to handle circular reexports) + */ +const processExportInfo = ( + runtime, + referencedExports, + prefix, + exportInfo, + defaultPointsToSelf = false, + alreadyVisited = new Set() +) => { + if (!exportInfo) { + referencedExports.push(prefix); + return; + } + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) return; + if (alreadyVisited.has(exportInfo)) { + referencedExports.push(prefix); + return; + } + alreadyVisited.add(exportInfo); + if ( + used !== UsageState.OnlyPropertiesUsed || + !exportInfo.exportsInfo || + exportInfo.exportsInfo.otherExportsInfo.getUsed(runtime) !== + UsageState.Unused + ) { + alreadyVisited.delete(exportInfo); + referencedExports.push(prefix); + return; + } + const exportsInfo = exportInfo.exportsInfo; + for (const exportInfo of exportsInfo.orderedExports) { + processExportInfo( + runtime, + referencedExports, + defaultPointsToSelf && exportInfo.name === "default" + ? prefix + : [...prefix, exportInfo.name], + exportInfo, + false, + alreadyVisited + ); + } + alreadyVisited.delete(exportInfo); +}; + +module.exports = processExportInfo; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/electron/ElectronTargetPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/electron/ElectronTargetPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..e8c4e844a8715be8dd19b36bf4493583a33b7b36 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/electron/ElectronTargetPlugin.js @@ -0,0 +1,69 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ExternalsPlugin = require("../ExternalsPlugin"); + +/** @typedef {import("../Compiler")} Compiler */ + +class ElectronTargetPlugin { + /** + * @param {"main" | "preload" | "renderer"=} context in main, preload or renderer context? + */ + constructor(context) { + this._context = context; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + new ExternalsPlugin("node-commonjs", [ + "clipboard", + "crash-reporter", + "electron", + "ipc", + "native-image", + "original-fs", + "screen", + "shell" + ]).apply(compiler); + switch (this._context) { + case "main": + new ExternalsPlugin("node-commonjs", [ + "app", + "auto-updater", + "browser-window", + "content-tracing", + "dialog", + "global-shortcut", + "ipc-main", + "menu", + "menu-item", + "power-monitor", + "power-save-blocker", + "protocol", + "session", + "tray", + "web-contents" + ]).apply(compiler); + break; + case "preload": + case "renderer": + new ExternalsPlugin("node-commonjs", [ + "desktop-capturer", + "ipc-renderer", + "remote", + "web-frame" + ]).apply(compiler); + break; + } + } +} + +module.exports = ElectronTargetPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/errors/BuildCycleError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/errors/BuildCycleError.js new file mode 100644 index 0000000000000000000000000000000000000000..a235fcebbe4411b2dd21b2bf27df7badecfa6833 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/errors/BuildCycleError.js @@ -0,0 +1,27 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const WebpackError = require("../WebpackError"); + +/** @typedef {import("../Module")} Module */ + +class BuildCycleError extends WebpackError { + /** + * Creates an instance of ModuleDependencyError. + * @param {Module} module the module starting the cycle + */ + constructor(module) { + super( + "There is a circular build dependency, which makes it impossible to create this module" + ); + + this.name = "BuildCycleError"; + this.module = module; + } +} + +module.exports = BuildCycleError; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ExportWebpackRequireRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ExportWebpackRequireRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..0f1a4c70c31896cdcccb338ae951681c0d87414b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ExportWebpackRequireRuntimeModule.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +// CompatibilityPlugin renames `__webpack_require__` but doesn’t account for `export { __webpack_require__ }`, so we create a temporary variable to handle it. +const EXPORT_TEMP_NAME = "__webpack_require_temp__"; + +class ExportWebpackRequireRuntimeModule extends RuntimeModule { + constructor() { + super("export webpack runtime", RuntimeModule.STAGE_ATTACH); + } + + /** + * @returns {boolean} true, if the runtime module should get it's own scope + */ + shouldIsolate() { + return false; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + return Template.asString([ + `var ${EXPORT_TEMP_NAME} = ${RuntimeGlobals.require};`, + `export { ${EXPORT_TEMP_NAME} as ${RuntimeGlobals.require} };` + ]); + } +} + +module.exports = ExportWebpackRequireRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ModuleChunkFormatPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ModuleChunkFormatPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..dc28f9562d5705d1ff5536b88bc7b51a99946e9c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ModuleChunkFormatPlugin.js @@ -0,0 +1,273 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const { HotUpdateChunk, RuntimeGlobals } = require(".."); +const Template = require("../Template"); +const { + createChunkHashHandler, + getChunkInfo +} = require("../javascript/ChunkFormatHelpers"); +const { getAllChunks } = require("../javascript/ChunkHelpers"); +const { + chunkHasJs, + getChunkFilenameTemplate, + getCompilationHooks +} = require("../javascript/JavascriptModulesPlugin"); +const { getUndoPath } = require("../util/identifier"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ + +/** + * @param {Compilation} compilation the compilation instance + * @param {Chunk} chunk the chunk + * @param {Chunk} runtimeChunk the runtime chunk + * @returns {string} the relative path + */ +const getRelativePath = (compilation, chunk, runtimeChunk) => { + const currentOutputName = compilation + .getPath( + getChunkFilenameTemplate(runtimeChunk, compilation.outputOptions), + { + chunk: runtimeChunk, + contentHashType: "javascript" + } + ) + .replace(/^\/+/g, "") + .split("/"); + const baseOutputName = [...currentOutputName]; + const chunkOutputName = compilation + .getPath(getChunkFilenameTemplate(chunk, compilation.outputOptions), { + chunk, + contentHashType: "javascript" + }) + .replace(/^\/+/g, "") + .split("/"); + + // remove common parts except filename + while ( + baseOutputName.length > 1 && + chunkOutputName.length > 1 && + baseOutputName[0] === chunkOutputName[0] + ) { + baseOutputName.shift(); + chunkOutputName.shift(); + } + const last = chunkOutputName.join("/"); + // create final path + return getUndoPath(baseOutputName.join("/"), last, true) + last; +}; + +/** + * @param {Compilation} compilation the compilation instance + * @param {Chunk} chunk the chunk to render the import for + * @param {string=} namedImport the named import to use for the import + * @param {Chunk=} runtimeChunk the runtime chunk + * @returns {string} the import source + */ +function renderChunkImport(compilation, chunk, namedImport, runtimeChunk) { + return `import ${namedImport ? `* as ${namedImport}` : `{ ${RuntimeGlobals.require} }`} from ${JSON.stringify( + getRelativePath(compilation, chunk, runtimeChunk || chunk) + )};\n`; +} + +/** + * @param {number} index the index of the chunk + * @returns {string} the named import to use for the import + */ +function getChunkNamedImport(index) { + return `__webpack_chunk_${index}__`; +} + +const PLUGIN_NAME = "ModuleChunkFormatPlugin"; + +class ModuleChunkFormatPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set) => { + if (chunk.hasRuntime()) return; + if (compilation.chunkGraph.getNumberOfEntryModules(chunk) > 0) { + set.add(RuntimeGlobals.require); + set.add(RuntimeGlobals.externalInstallChunk); + } + } + ); + const hooks = getCompilationHooks(compilation); + /** + * @param {Set} chunks the chunks to render + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk=} runtimeChunk the runtime chunk + * @returns {Source|undefined} the source + */ + const withDependentChunks = (chunks, chunkGraph, runtimeChunk) => { + if (/** @type {Set} */ (chunks).size > 0) { + const source = new ConcatSource(); + let index = 0; + + for (const chunk of chunks) { + index++; + + if (!chunkHasJs(chunk, chunkGraph)) { + continue; + } + const namedImport = getChunkNamedImport(index); + source.add( + renderChunkImport( + compilation, + chunk, + namedImport, + runtimeChunk || chunk + ) + ); + source.add( + `${RuntimeGlobals.externalInstallChunk}(${namedImport});\n` + ); + } + return source; + } + }; + hooks.renderStartup.tap( + PLUGIN_NAME, + (modules, _lastModule, renderContext) => { + const { chunk, chunkGraph } = renderContext; + if ( + chunkGraph.getNumberOfEntryModules(chunk) > 0 && + chunk.hasRuntime() + ) { + const entryDependentChunks = + chunkGraph.getChunkEntryDependentChunksIterable(chunk); + const sourceWithDependentChunks = withDependentChunks( + /** @type {Set} */ (entryDependentChunks), + chunkGraph, + chunk + ); + if (!sourceWithDependentChunks) { + return modules; + } + if (modules.size() === 0) { + return sourceWithDependentChunks; + } + const source = new ConcatSource(); + source.add(sourceWithDependentChunks); + source.add("\n"); + source.add(modules); + return source; + } + return modules; + } + ); + hooks.renderChunk.tap(PLUGIN_NAME, (modules, renderContext) => { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + const hotUpdateChunk = chunk instanceof HotUpdateChunk ? chunk : null; + const source = new ConcatSource(); + source.add( + `export const ${RuntimeGlobals.esmId} = ${JSON.stringify(chunk.id)};\n` + ); + source.add( + `export const ${RuntimeGlobals.esmIds} = ${JSON.stringify(chunk.ids)};\n` + ); + source.add(`export const ${RuntimeGlobals.esmModules} = `); + source.add(modules); + source.add(";\n"); + const runtimeModules = chunkGraph.getChunkRuntimeModulesInOrder(chunk); + if (runtimeModules.length > 0) { + source.add(`export const ${RuntimeGlobals.esmRuntime} =\n`); + source.add( + Template.renderChunkRuntimeModules(runtimeModules, renderContext) + ); + } + if (hotUpdateChunk) { + return source; + } + const { entries, runtimeChunk } = getChunkInfo(chunk, chunkGraph); + if (runtimeChunk) { + const entrySource = new ConcatSource(); + entrySource.add(source); + entrySource.add(";\n\n// load runtime\n"); + entrySource.add( + renderChunkImport(compilation, runtimeChunk, "", chunk) + ); + const startupSource = new ConcatSource(); + startupSource.add( + `var __webpack_exec__ = ${runtimeTemplate.returningFunction( + `${RuntimeGlobals.require}(${RuntimeGlobals.entryModuleId} = moduleId)`, + "moduleId" + )}\n` + ); + + const loadedChunks = new Set(); + for (let i = 0; i < entries.length; i++) { + const [module, entrypoint] = entries[i]; + if (!chunkGraph.getModuleSourceTypes(module).has("javascript")) { + continue; + } + const final = i + 1 === entries.length; + const moduleId = chunkGraph.getModuleId(module); + const chunks = getAllChunks( + /** @type {Entrypoint} */ (entrypoint), + /** @type {Chunk} */ (runtimeChunk), + undefined + ); + const processChunks = new Set(); + for (const _chunk of chunks) { + if (loadedChunks.has(_chunk)) { + continue; + } + loadedChunks.add(_chunk); + processChunks.add(_chunk); + } + const sourceWithDependentChunks = withDependentChunks( + processChunks, + chunkGraph, + chunk + ); + if (sourceWithDependentChunks) { + startupSource.add("\n"); + startupSource.add(sourceWithDependentChunks); + } + startupSource.add( + `${ + final ? `var ${RuntimeGlobals.exports} = ` : "" + }__webpack_exec__(${JSON.stringify(moduleId)});\n` + ); + } + + entrySource.add( + hooks.renderStartup.call( + startupSource, + entries[entries.length - 1][0], + { + ...renderContext, + inlined: false + } + ) + ); + return entrySource; + } + return source; + }); + hooks.chunkHash.tap(PLUGIN_NAME, createChunkHashHandler(PLUGIN_NAME)); + }); + } +} + +module.exports = ModuleChunkFormatPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ModuleChunkLoadingPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ModuleChunkLoadingPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..eb3d384bc77098f181d96c13324ac5a4f845cc51 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ModuleChunkLoadingPlugin.js @@ -0,0 +1,141 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const ExportWebpackRequireRuntimeModule = require("./ExportWebpackRequireRuntimeModule"); +const ModuleChunkLoadingRuntimeModule = require("./ModuleChunkLoadingRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "ModuleChunkLoadingPlugin"; + +class ModuleChunkLoadingPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + /** + * @param {Chunk} chunk chunk to check + * @returns {boolean} true, when the plugin is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === "import"; + }; + const onceForChunkSet = new WeakSet(); + /** + * @param {Chunk} chunk chunk to check + * @param {Set} set runtime requirements + */ + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ModuleChunkLoadingRuntimeModule(set) + ); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.externalInstallChunk) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.externalInstallChunk) + .tap(PLUGIN_NAME, (chunk) => { + if (!isEnabledForChunk(chunk)) return; + compilation.addRuntimeModule( + chunk, + new ExportWebpackRequireRuntimeModule() + ); + }); + + // We need public path only when we prefetch/preload chunk or public path is not `auto` + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.prefetchChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.preloadChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + + if (compilation.outputOptions.publicPath !== "auto") { + set.add(RuntimeGlobals.publicPath); + } + + set.add(RuntimeGlobals.getChunkScriptFilename); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.loadScript); + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getUpdateManifestFilename); + }); + + compilation.hooks.additionalTreeRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set, { chunkGraph }) => { + if (chunkGraph.hasChunkEntryDependentChunks(chunk)) { + set.add(RuntimeGlobals.externalInstallChunk); + } + } + ); + }); + } +} + +module.exports = ModuleChunkLoadingPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ModuleChunkLoadingRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ModuleChunkLoadingRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..3df1e1e3a95cc87923a6633f6144c579019de5ac --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/esm/ModuleChunkLoadingRuntimeModule.js @@ -0,0 +1,425 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const { SyncWaterfallHook } = require("tapable"); +const Compilation = require("../Compilation"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const { + generateJavascriptHMR +} = require("../hmr/JavascriptHotModuleReplacementHelper"); +const { + chunkHasJs, + getChunkFilenameTemplate +} = require("../javascript/JavascriptModulesPlugin"); +const { getInitialChunkIds } = require("../javascript/StartupHelpers"); +const compileBooleanMatcher = require("../util/compileBooleanMatcher"); +const { getUndoPath } = require("../util/identifier"); + +/** @typedef {import("../../declarations/WebpackOptions").Environment} Environment */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ + +/** + * @typedef {object} JsonpCompilationPluginHooks + * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload + * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class ModuleChunkLoadingRuntimeModule extends RuntimeModule { + /** + * @param {Compilation} compilation the compilation + * @returns {JsonpCompilationPluginHooks} hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + linkPreload: new SyncWaterfallHook(["source", "chunk"]), + linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** + * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super("import chunk loading", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; + } + + /** + * @private + * @param {Chunk} chunk chunk + * @param {string} rootOutputDir root output directory + * @returns {string} generated code + */ + _generateBaseUri(chunk, rootOutputDir) { + const options = chunk.getEntryOptions(); + if (options && options.baseUri) { + return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`; + } + const compilation = /** @type {Compilation} */ (this.compilation); + const { + outputOptions: { importMetaName } + } = compilation; + return `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify( + rootOutputDir + )}, ${importMetaName}.url);`; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const environment = + /** @type {Environment} */ + (compilation.outputOptions.environment); + const { + runtimeTemplate, + outputOptions: { importFunctionName, crossOriginLoading, charset } + } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); + const withExternalInstallChunk = this._runtimeRequirements.has( + RuntimeGlobals.externalInstallChunk + ); + const withLoading = this._runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withOnChunkLoad = this._runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withHmr = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const { linkPreload, linkPrefetch } = + ModuleChunkLoadingRuntimeModule.getCompilationHooks(compilation); + const isNeutralPlatform = runtimeTemplate.isNeutralPlatform(); + const withPrefetch = + (environment.document || isNeutralPlatform) && + this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) && + chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasJs); + const withPreload = + (environment.document || isNeutralPlatform) && + this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) && + chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasJs); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const outputName = compilation.getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + /** @type {string} */ (compilation.outputOptions.path), + true + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module` + : undefined; + + return Template.asString([ + withBaseURI + ? this._generateBaseUri(chunk, rootOutputDir) + : "// no baseURI", + "", + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// [resolve, Promise] = chunk loading, 0 = chunk loaded", + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), + "};", + "", + withLoading || withExternalInstallChunk + ? `var installChunk = ${runtimeTemplate.basicFunction("data", [ + runtimeTemplate.destructureObject( + [ + RuntimeGlobals.esmIds, + RuntimeGlobals.esmModules, + RuntimeGlobals.esmRuntime + ], + "data" + ), + '// add "modules" to the modules object,', + '// then flag all "ids" as loaded and fire callback', + "var moduleId, chunkId, i = 0;", + `for(moduleId in ${RuntimeGlobals.esmModules}) {`, + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(${RuntimeGlobals.esmModules}, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = ${RuntimeGlobals.esmModules}[moduleId];` + ), + "}" + ]), + "}", + `if(${RuntimeGlobals.esmRuntime}) ${RuntimeGlobals.esmRuntime}(${RuntimeGlobals.require});`, + `for(;i < ${RuntimeGlobals.esmIds}.length; i++) {`, + Template.indent([ + `chunkId = ${RuntimeGlobals.esmIds}[i];`, + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, + Template.indent("installedChunks[chunkId][0]();"), + "}", + `installedChunks[${RuntimeGlobals.esmIds}[i]] = 0;` + ]), + "}", + withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" + ])}` + : "// no install chunk", + "", + withLoading + ? Template.asString([ + `${fn}.j = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? Template.indent([ + "// import() chunk loading for javascript", + `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent([ + "promises.push(installedChunkData[1]);" + ]), + "} else {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + "// setup Promise in chunk cache", + `var promise = ${importFunctionName}(${ + compilation.outputOptions.publicPath === "auto" + ? JSON.stringify(rootOutputDir) + : RuntimeGlobals.publicPath + } + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction( + "e", + [ + "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;", + "throw e;" + ] + )});`, + `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction( + "installedChunkData = installedChunks[chunkId] = [resolve]", + "resolve" + )})])`, + "promises.push(installedChunkData[1] = promise);" + ]), + hasJsMatcher === true + ? "}" + : "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ]) + : Template.indent(["installedChunks[chunkId] = 0;"]) + )};` + ]) + : "// no chunk on demand loading", + "", + withPrefetch && hasJsMatcher !== false + ? `${ + RuntimeGlobals.prefetchChunkHandlers + }.j = ${runtimeTemplate.basicFunction("chunkId", [ + isNeutralPlatform + ? "if (typeof document === 'undefined') return;" + : "", + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + linkPrefetch.call( + Template.asString([ + "var link = document.createElement('link');", + charset ? "link.charset = 'utf-8';" : "", + crossOriginLoading + ? `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + : "", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + 'link.rel = "prefetch";', + 'link.as = "script";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);` + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no prefetching", + "", + withPreload && hasJsMatcher !== false + ? `${ + RuntimeGlobals.preloadChunkHandlers + }.j = ${runtimeTemplate.basicFunction("chunkId", [ + isNeutralPlatform + ? "if (typeof document === 'undefined') return;" + : "", + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + linkPreload.call( + Template.asString([ + "var link = document.createElement('link');", + charset ? "link.charset = 'utf-8';" : "", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + 'link.rel = "modulepreload";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, + crossOriginLoading + ? crossOriginLoading === "use-credentials" + ? 'link.crossOrigin = "use-credentials";' + : Template.asString([ + "if (link.href.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + ), + "}" + ]) + : "" + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no preloaded", + "", + withExternalInstallChunk + ? Template.asString([ + `${RuntimeGlobals.externalInstallChunk} = installChunk;` + ]) + : "// no external install chunk", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.j = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId] === 0", + "chunkId" + )};` + : "// no on chunks loaded", + withHmr + ? Template.asString([ + generateJavascriptHMR("module"), + "", + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + `return new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + "// start update chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, + `var onResolve = ${runtimeTemplate.basicFunction("obj", [ + `var updatedModules = obj.${RuntimeGlobals.esmModules};`, + `var updatedRuntime = obj.${RuntimeGlobals.esmRuntime};`, + "if(updatedRuntime) currentUpdateRuntime.push(updatedRuntime);", + "for(var moduleId in updatedModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, + Template.indent([ + "currentUpdate[moduleId] = updatedModules[moduleId];", + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "resolve(obj);" + ])};`, + `var onReject = ${runtimeTemplate.basicFunction("error", [ + "var errorMsg = error.message || 'unknown reason';", + "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorMsg + ')';", + "error.name = 'ChunkLoadError';", + "reject(error);" + ])}`, + `var loadScript = ${runtimeTemplate.basicFunction( + "url, onResolve, onReject", + [ + `return ${importFunctionName}(/* webpackIgnore: true */ url).then(onResolve).catch(onReject)` + ] + )} + loadScript(url, onResolve, onReject);` + ] + )});` + ]), + "}", + "" + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${ + RuntimeGlobals.hmrDownloadManifest + } = ${runtimeTemplate.basicFunction("", [ + `return ${importFunctionName}(/* webpackIgnore: true */ ${RuntimeGlobals.publicPath} + ${ + RuntimeGlobals.getUpdateManifestFilename + }()).then(${runtimeTemplate.basicFunction("obj", [ + "return obj.default;" + ])});` + ])};` + ]) + : "// no HMR manifest" + ]); + } +} + +module.exports = ModuleChunkLoadingRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/formatLocation.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/formatLocation.js new file mode 100644 index 0000000000000000000000000000000000000000..f75bc73ede15c8edc7353c59ab26234b5377a92c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/formatLocation.js @@ -0,0 +1,67 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ + +/** + * @param {SourcePosition} pos position + * @returns {string} formatted position + */ +const formatPosition = (pos) => { + if (pos && typeof pos === "object") { + if ("line" in pos && "column" in pos) { + return `${pos.line}:${pos.column}`; + } else if ("line" in pos) { + return `${pos.line}:?`; + } + } + return ""; +}; + +/** + * @param {DependencyLocation} loc location + * @returns {string} formatted location + */ +const formatLocation = (loc) => { + if (loc && typeof loc === "object") { + if ("start" in loc && loc.start && "end" in loc && loc.end) { + if ( + typeof loc.start === "object" && + typeof loc.start.line === "number" && + typeof loc.end === "object" && + typeof loc.end.line === "number" && + typeof loc.end.column === "number" && + loc.start.line === loc.end.line + ) { + return `${formatPosition(loc.start)}-${loc.end.column}`; + } else if ( + typeof loc.start === "object" && + typeof loc.start.line === "number" && + typeof loc.start.column !== "number" && + typeof loc.end === "object" && + typeof loc.end.line === "number" && + typeof loc.end.column !== "number" + ) { + return `${loc.start.line}-${loc.end.line}`; + } + return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; + } + if ("start" in loc && loc.start) { + return formatPosition(loc.start); + } + if ("name" in loc && "index" in loc) { + return `${loc.name}[${loc.index}]`; + } + if ("name" in loc) { + return loc.name; + } + } + return ""; +}; + +module.exports = formatLocation; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/HotModuleReplacement.runtime.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/HotModuleReplacement.runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..5f297710e139755cfef0a9431c586a52ea20c8df --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/HotModuleReplacement.runtime.js @@ -0,0 +1,418 @@ +// @ts-nocheck +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +var $interceptModuleExecution$ = undefined; +var $moduleCache$ = undefined; +var $hmrModuleData$ = undefined; +/** @type {() => Promise} */ +var $hmrDownloadManifest$ = undefined; +var $hmrDownloadUpdateHandlers$ = undefined; +var $hmrInvalidateModuleHandlers$ = undefined; +var __webpack_require__ = undefined; + +module.exports = function () { + var currentModuleData = {}; + var installedModules = $moduleCache$; + + // module and require creation + var currentChildModule; + var currentParents = []; + + // status + var registeredStatusHandlers = []; + var currentStatus = "idle"; + + // while downloading + var blockingPromises = 0; + var blockingPromisesWaiting = []; + + // The update info + var currentUpdateApplyHandlers; + var queuedInvalidatedModules; + + $hmrModuleData$ = currentModuleData; + + $interceptModuleExecution$.push(function (options) { + var module = options.module; + var require = createRequire(options.require, options.id); + module.hot = createModuleHotObject(options.id, module); + module.parents = currentParents; + module.children = []; + currentParents = []; + options.require = require; + }); + + $hmrDownloadUpdateHandlers$ = {}; + $hmrInvalidateModuleHandlers$ = {}; + + function createRequire(require, moduleId) { + var me = installedModules[moduleId]; + if (!me) return require; + var fn = function (request) { + if (me.hot.active) { + if (installedModules[request]) { + var parents = installedModules[request].parents; + if (parents.indexOf(moduleId) === -1) { + parents.push(moduleId); + } + } else { + currentParents = [moduleId]; + currentChildModule = request; + } + if (me.children.indexOf(request) === -1) { + me.children.push(request); + } + } else { + console.warn( + "[HMR] unexpected require(" + + request + + ") from disposed module " + + moduleId + ); + currentParents = []; + } + return require(request); + }; + var createPropertyDescriptor = function (name) { + return { + configurable: true, + enumerable: true, + get: function () { + return require[name]; + }, + set: function (value) { + require[name] = value; + } + }; + }; + for (var name in require) { + if (Object.prototype.hasOwnProperty.call(require, name) && name !== "e") { + Object.defineProperty(fn, name, createPropertyDescriptor(name)); + } + } + fn.e = function (chunkId, fetchPriority) { + return trackBlockingPromise(require.e(chunkId, fetchPriority)); + }; + return fn; + } + + function createModuleHotObject(moduleId, me) { + var _main = currentChildModule !== moduleId; + var hot = { + // private stuff + _acceptedDependencies: {}, + _acceptedErrorHandlers: {}, + _declinedDependencies: {}, + _selfAccepted: false, + _selfDeclined: false, + _selfInvalidated: false, + _disposeHandlers: [], + _main: _main, + _requireSelf: function () { + currentParents = me.parents.slice(); + currentChildModule = _main ? undefined : moduleId; + __webpack_require__(moduleId); + }, + + // Module API + active: true, + accept: function (dep, callback, errorHandler) { + if (dep === undefined) hot._selfAccepted = true; + else if (typeof dep === "function") hot._selfAccepted = dep; + else if (typeof dep === "object" && dep !== null) { + for (var i = 0; i < dep.length; i++) { + hot._acceptedDependencies[dep[i]] = callback || function () {}; + hot._acceptedErrorHandlers[dep[i]] = errorHandler; + } + } else { + hot._acceptedDependencies[dep] = callback || function () {}; + hot._acceptedErrorHandlers[dep] = errorHandler; + } + }, + decline: function (dep) { + if (dep === undefined) hot._selfDeclined = true; + else if (typeof dep === "object" && dep !== null) + for (var i = 0; i < dep.length; i++) + hot._declinedDependencies[dep[i]] = true; + else hot._declinedDependencies[dep] = true; + }, + dispose: function (callback) { + hot._disposeHandlers.push(callback); + }, + addDisposeHandler: function (callback) { + hot._disposeHandlers.push(callback); + }, + removeDisposeHandler: function (callback) { + var idx = hot._disposeHandlers.indexOf(callback); + if (idx >= 0) hot._disposeHandlers.splice(idx, 1); + }, + invalidate: function () { + this._selfInvalidated = true; + switch (currentStatus) { + case "idle": + currentUpdateApplyHandlers = []; + Object.keys($hmrInvalidateModuleHandlers$).forEach(function (key) { + $hmrInvalidateModuleHandlers$[key]( + moduleId, + currentUpdateApplyHandlers + ); + }); + setStatus("ready"); + break; + case "ready": + Object.keys($hmrInvalidateModuleHandlers$).forEach(function (key) { + $hmrInvalidateModuleHandlers$[key]( + moduleId, + currentUpdateApplyHandlers + ); + }); + break; + case "prepare": + case "check": + case "dispose": + case "apply": + (queuedInvalidatedModules = queuedInvalidatedModules || []).push( + moduleId + ); + break; + default: + // ignore requests in error states + break; + } + }, + + // Management API + check: hotCheck, + apply: hotApply, + status: function (l) { + if (!l) return currentStatus; + registeredStatusHandlers.push(l); + }, + addStatusHandler: function (l) { + registeredStatusHandlers.push(l); + }, + removeStatusHandler: function (l) { + var idx = registeredStatusHandlers.indexOf(l); + if (idx >= 0) registeredStatusHandlers.splice(idx, 1); + }, + + // inherit from previous dispose call + data: currentModuleData[moduleId] + }; + currentChildModule = undefined; + return hot; + } + + function setStatus(newStatus) { + currentStatus = newStatus; + var results = []; + + for (var i = 0; i < registeredStatusHandlers.length; i++) + results[i] = registeredStatusHandlers[i].call(null, newStatus); + + return Promise.all(results).then(function () {}); + } + + function unblock() { + if (--blockingPromises === 0) { + setStatus("ready").then(function () { + if (blockingPromises === 0) { + var list = blockingPromisesWaiting; + blockingPromisesWaiting = []; + for (var i = 0; i < list.length; i++) { + list[i](); + } + } + }); + } + } + + function trackBlockingPromise(promise) { + switch (currentStatus) { + case "ready": + setStatus("prepare"); + /* fallthrough */ + case "prepare": + blockingPromises++; + promise.then(unblock, unblock); + return promise; + default: + return promise; + } + } + + function waitForBlockingPromises(fn) { + if (blockingPromises === 0) return fn(); + return new Promise(function (resolve) { + blockingPromisesWaiting.push(function () { + resolve(fn()); + }); + }); + } + + function hotCheck(applyOnUpdate) { + if (currentStatus !== "idle") { + throw new Error("check() is only allowed in idle status"); + } + return setStatus("check") + .then($hmrDownloadManifest$) + .then(function (update) { + if (!update) { + return setStatus(applyInvalidatedModules() ? "ready" : "idle").then( + function () { + return null; + } + ); + } + + return setStatus("prepare").then(function () { + var updatedModules = []; + currentUpdateApplyHandlers = []; + + return Promise.all( + Object.keys($hmrDownloadUpdateHandlers$).reduce(function ( + promises, + key + ) { + $hmrDownloadUpdateHandlers$[key]( + update.c, + update.r, + update.m, + promises, + currentUpdateApplyHandlers, + updatedModules + ); + return promises; + }, []) + ).then(function () { + return waitForBlockingPromises(function () { + if (applyOnUpdate) { + return internalApply(applyOnUpdate); + } + return setStatus("ready").then(function () { + return updatedModules; + }); + }); + }); + }); + }); + } + + function hotApply(options) { + if (currentStatus !== "ready") { + return Promise.resolve().then(function () { + throw new Error( + "apply() is only allowed in ready status (state: " + + currentStatus + + ")" + ); + }); + } + return internalApply(options); + } + + function internalApply(options) { + options = options || {}; + + applyInvalidatedModules(); + + var results = currentUpdateApplyHandlers.map(function (handler) { + return handler(options); + }); + currentUpdateApplyHandlers = undefined; + + var errors = results + .map(function (r) { + return r.error; + }) + .filter(Boolean); + + if (errors.length > 0) { + return setStatus("abort").then(function () { + throw errors[0]; + }); + } + + // Now in "dispose" phase + var disposePromise = setStatus("dispose"); + + results.forEach(function (result) { + if (result.dispose) result.dispose(); + }); + + // Now in "apply" phase + var applyPromise = setStatus("apply"); + + var error; + var reportError = function (err) { + if (!error) error = err; + }; + + var outdatedModules = []; + + var onAccepted = function () { + return Promise.all([disposePromise, applyPromise]).then(function () { + // handle errors in accept handlers and self accepted module load + if (error) { + return setStatus("fail").then(function () { + throw error; + }); + } + + if (queuedInvalidatedModules) { + return internalApply(options).then(function (list) { + outdatedModules.forEach(function (moduleId) { + if (list.indexOf(moduleId) < 0) list.push(moduleId); + }); + return list; + }); + } + + return setStatus("idle").then(function () { + return outdatedModules; + }); + }); + }; + + return Promise.all( + results + .filter(function (result) { + return result.apply; + }) + .map(function (result) { + return result.apply(reportError); + }) + ) + .then(function (applyResults) { + applyResults.forEach(function (modules) { + if (modules) { + for (var i = 0; i < modules.length; i++) { + outdatedModules.push(modules[i]); + } + } + }); + }) + .then(onAccepted); + } + + function applyInvalidatedModules() { + if (queuedInvalidatedModules) { + if (!currentUpdateApplyHandlers) currentUpdateApplyHandlers = []; + Object.keys($hmrInvalidateModuleHandlers$).forEach(function (key) { + queuedInvalidatedModules.forEach(function (moduleId) { + $hmrInvalidateModuleHandlers$[key]( + moduleId, + currentUpdateApplyHandlers + ); + }); + }); + queuedInvalidatedModules = undefined; + return true; + } + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/HotModuleReplacementRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/HotModuleReplacementRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..67b1a983ae598f990f8dab68216ec249f037157b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/HotModuleReplacementRuntimeModule.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +class HotModuleReplacementRuntimeModule extends RuntimeModule { + constructor() { + super("hot module replacement", RuntimeModule.STAGE_BASIC); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + return Template.getFunctionContent( + require("./HotModuleReplacement.runtime") + ) + .replace( + /\$interceptModuleExecution\$/g, + RuntimeGlobals.interceptModuleExecution + ) + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace(/\$hmrDownloadManifest\$/g, RuntimeGlobals.hmrDownloadManifest) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + } +} + +module.exports = HotModuleReplacementRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/JavascriptHotModuleReplacement.runtime.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/JavascriptHotModuleReplacement.runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..fecf52e5c0c927f692c237ccbd2c818904ef5be5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/JavascriptHotModuleReplacement.runtime.js @@ -0,0 +1,471 @@ +// @ts-nocheck +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +var $installedChunks$ = undefined; +var $loadUpdateChunk$ = undefined; +var $moduleCache$ = undefined; +var $moduleFactories$ = undefined; +var $ensureChunkHandlers$ = undefined; +var $hasOwnProperty$ = undefined; +var $hmrModuleData$ = undefined; +var $hmrDownloadUpdateHandlers$ = undefined; +var $hmrInvalidateModuleHandlers$ = undefined; +var __webpack_require__ = undefined; + +module.exports = function () { + var currentUpdateChunks; + var currentUpdate; + var currentUpdateRemovedChunks; + var currentUpdateRuntime; + function applyHandler(options) { + if ($ensureChunkHandlers$) delete $ensureChunkHandlers$.$key$Hmr; + currentUpdateChunks = undefined; + function getAffectedModuleEffects(updateModuleId) { + var outdatedModules = [updateModuleId]; + var outdatedDependencies = {}; + + var queue = outdatedModules.map(function (id) { + return { + chain: [id], + id: id + }; + }); + while (queue.length > 0) { + var queueItem = queue.pop(); + var moduleId = queueItem.id; + var chain = queueItem.chain; + var module = $moduleCache$[moduleId]; + if ( + !module || + (module.hot._selfAccepted && !module.hot._selfInvalidated) + ) + continue; + if (module.hot._selfDeclined) { + return { + type: "self-declined", + chain: chain, + moduleId: moduleId + }; + } + if (module.hot._main) { + return { + type: "unaccepted", + chain: chain, + moduleId: moduleId + }; + } + for (var i = 0; i < module.parents.length; i++) { + var parentId = module.parents[i]; + var parent = $moduleCache$[parentId]; + if (!parent) continue; + if (parent.hot._declinedDependencies[moduleId]) { + return { + type: "declined", + chain: chain.concat([parentId]), + moduleId: moduleId, + parentId: parentId + }; + } + if (outdatedModules.indexOf(parentId) !== -1) continue; + if (parent.hot._acceptedDependencies[moduleId]) { + if (!outdatedDependencies[parentId]) + outdatedDependencies[parentId] = []; + addAllToSet(outdatedDependencies[parentId], [moduleId]); + continue; + } + delete outdatedDependencies[parentId]; + outdatedModules.push(parentId); + queue.push({ + chain: chain.concat([parentId]), + id: parentId + }); + } + } + + return { + type: "accepted", + moduleId: updateModuleId, + outdatedModules: outdatedModules, + outdatedDependencies: outdatedDependencies + }; + } + + function addAllToSet(a, b) { + for (var i = 0; i < b.length; i++) { + var item = b[i]; + if (a.indexOf(item) === -1) a.push(item); + } + } + + // at begin all updates modules are outdated + // the "outdated" status can propagate to parents if they don't accept the children + var outdatedDependencies = {}; + var outdatedModules = []; + var appliedUpdate = {}; + + var warnUnexpectedRequire = function warnUnexpectedRequire(module) { + console.warn( + "[HMR] unexpected require(" + module.id + ") to disposed module" + ); + }; + + for (var moduleId in currentUpdate) { + if ($hasOwnProperty$(currentUpdate, moduleId)) { + var newModuleFactory = currentUpdate[moduleId]; + var result = newModuleFactory + ? getAffectedModuleEffects(moduleId) + : { + type: "disposed", + moduleId: moduleId + }; + /** @type {Error|false} */ + var abortError = false; + var doApply = false; + var doDispose = false; + var chainInfo = ""; + if (result.chain) { + chainInfo = "\nUpdate propagation: " + result.chain.join(" -> "); + } + switch (result.type) { + case "self-declined": + if (options.onDeclined) options.onDeclined(result); + if (!options.ignoreDeclined) + abortError = new Error( + "Aborted because of self decline: " + + result.moduleId + + chainInfo + ); + break; + case "declined": + if (options.onDeclined) options.onDeclined(result); + if (!options.ignoreDeclined) + abortError = new Error( + "Aborted because of declined dependency: " + + result.moduleId + + " in " + + result.parentId + + chainInfo + ); + break; + case "unaccepted": + if (options.onUnaccepted) options.onUnaccepted(result); + if (!options.ignoreUnaccepted) + abortError = new Error( + "Aborted because " + moduleId + " is not accepted" + chainInfo + ); + break; + case "accepted": + if (options.onAccepted) options.onAccepted(result); + doApply = true; + break; + case "disposed": + if (options.onDisposed) options.onDisposed(result); + doDispose = true; + break; + default: + throw new Error("Unexception type " + result.type); + } + if (abortError) { + return { + error: abortError + }; + } + if (doApply) { + appliedUpdate[moduleId] = newModuleFactory; + addAllToSet(outdatedModules, result.outdatedModules); + for (moduleId in result.outdatedDependencies) { + if ($hasOwnProperty$(result.outdatedDependencies, moduleId)) { + if (!outdatedDependencies[moduleId]) + outdatedDependencies[moduleId] = []; + addAllToSet( + outdatedDependencies[moduleId], + result.outdatedDependencies[moduleId] + ); + } + } + } + if (doDispose) { + addAllToSet(outdatedModules, [result.moduleId]); + appliedUpdate[moduleId] = warnUnexpectedRequire; + } + } + } + currentUpdate = undefined; + + // Store self accepted outdated modules to require them later by the module system + var outdatedSelfAcceptedModules = []; + for (var j = 0; j < outdatedModules.length; j++) { + var outdatedModuleId = outdatedModules[j]; + var module = $moduleCache$[outdatedModuleId]; + if ( + module && + (module.hot._selfAccepted || module.hot._main) && + // removed self-accepted modules should not be required + appliedUpdate[outdatedModuleId] !== warnUnexpectedRequire && + // when called invalidate self-accepting is not possible + !module.hot._selfInvalidated + ) { + outdatedSelfAcceptedModules.push({ + module: outdatedModuleId, + require: module.hot._requireSelf, + errorHandler: module.hot._selfAccepted + }); + } + } + + var moduleOutdatedDependencies; + + return { + dispose: function () { + currentUpdateRemovedChunks.forEach(function (chunkId) { + delete $installedChunks$[chunkId]; + }); + currentUpdateRemovedChunks = undefined; + + var idx; + var queue = outdatedModules.slice(); + while (queue.length > 0) { + var moduleId = queue.pop(); + var module = $moduleCache$[moduleId]; + if (!module) continue; + + var data = {}; + + // Call dispose handlers + var disposeHandlers = module.hot._disposeHandlers; + for (j = 0; j < disposeHandlers.length; j++) { + disposeHandlers[j].call(null, data); + } + $hmrModuleData$[moduleId] = data; + + // disable module (this disables requires from this module) + module.hot.active = false; + + // remove module from cache + delete $moduleCache$[moduleId]; + + // when disposing there is no need to call dispose handler + delete outdatedDependencies[moduleId]; + + // remove "parents" references from all children + for (j = 0; j < module.children.length; j++) { + var child = $moduleCache$[module.children[j]]; + if (!child) continue; + idx = child.parents.indexOf(moduleId); + if (idx >= 0) { + child.parents.splice(idx, 1); + } + } + } + + // remove outdated dependency from module children + var dependency; + for (var outdatedModuleId in outdatedDependencies) { + if ($hasOwnProperty$(outdatedDependencies, outdatedModuleId)) { + module = $moduleCache$[outdatedModuleId]; + if (module) { + moduleOutdatedDependencies = + outdatedDependencies[outdatedModuleId]; + for (j = 0; j < moduleOutdatedDependencies.length; j++) { + dependency = moduleOutdatedDependencies[j]; + idx = module.children.indexOf(dependency); + if (idx >= 0) module.children.splice(idx, 1); + } + } + } + } + }, + apply: function (reportError) { + var acceptPromises = []; + // insert new code + for (var updateModuleId in appliedUpdate) { + if ($hasOwnProperty$(appliedUpdate, updateModuleId)) { + $moduleFactories$[updateModuleId] = appliedUpdate[updateModuleId]; + } + } + + // run new runtime modules + for (var i = 0; i < currentUpdateRuntime.length; i++) { + currentUpdateRuntime[i](__webpack_require__); + } + + // call accept handlers + for (var outdatedModuleId in outdatedDependencies) { + if ($hasOwnProperty$(outdatedDependencies, outdatedModuleId)) { + var module = $moduleCache$[outdatedModuleId]; + if (module) { + moduleOutdatedDependencies = + outdatedDependencies[outdatedModuleId]; + var callbacks = []; + var errorHandlers = []; + var dependenciesForCallbacks = []; + for (var j = 0; j < moduleOutdatedDependencies.length; j++) { + var dependency = moduleOutdatedDependencies[j]; + var acceptCallback = + module.hot._acceptedDependencies[dependency]; + var errorHandler = + module.hot._acceptedErrorHandlers[dependency]; + if (acceptCallback) { + if (callbacks.indexOf(acceptCallback) !== -1) continue; + callbacks.push(acceptCallback); + errorHandlers.push(errorHandler); + dependenciesForCallbacks.push(dependency); + } + } + for (var k = 0; k < callbacks.length; k++) { + var result; + try { + result = callbacks[k].call(null, moduleOutdatedDependencies); + } catch (err) { + if (typeof errorHandlers[k] === "function") { + try { + errorHandlers[k](err, { + moduleId: outdatedModuleId, + dependencyId: dependenciesForCallbacks[k] + }); + } catch (err2) { + if (options.onErrored) { + options.onErrored({ + type: "accept-error-handler-errored", + moduleId: outdatedModuleId, + dependencyId: dependenciesForCallbacks[k], + error: err2, + originalError: err + }); + } + if (!options.ignoreErrored) { + reportError(err2); + reportError(err); + } + } + } else { + if (options.onErrored) { + options.onErrored({ + type: "accept-errored", + moduleId: outdatedModuleId, + dependencyId: dependenciesForCallbacks[k], + error: err + }); + } + if (!options.ignoreErrored) { + reportError(err); + } + } + } + if (result && typeof result.then === "function") { + acceptPromises.push(result); + } + } + } + } + } + + var onAccepted = function () { + // Load self accepted modules + for (var o = 0; o < outdatedSelfAcceptedModules.length; o++) { + var item = outdatedSelfAcceptedModules[o]; + var moduleId = item.module; + try { + item.require(moduleId); + } catch (err) { + if (typeof item.errorHandler === "function") { + try { + item.errorHandler(err, { + moduleId: moduleId, + module: $moduleCache$[moduleId] + }); + } catch (err1) { + if (options.onErrored) { + options.onErrored({ + type: "self-accept-error-handler-errored", + moduleId: moduleId, + error: err1, + originalError: err + }); + } + if (!options.ignoreErrored) { + reportError(err1); + reportError(err); + } + } + } else { + if (options.onErrored) { + options.onErrored({ + type: "self-accept-errored", + moduleId: moduleId, + error: err + }); + } + if (!options.ignoreErrored) { + reportError(err); + } + } + } + } + }; + + return Promise.all(acceptPromises) + .then(onAccepted) + .then(function () { + return outdatedModules; + }); + } + }; + } + $hmrInvalidateModuleHandlers$.$key$ = function (moduleId, applyHandlers) { + if (!currentUpdate) { + currentUpdate = {}; + currentUpdateRuntime = []; + currentUpdateRemovedChunks = []; + applyHandlers.push(applyHandler); + } + if (!$hasOwnProperty$(currentUpdate, moduleId)) { + currentUpdate[moduleId] = $moduleFactories$[moduleId]; + } + }; + $hmrDownloadUpdateHandlers$.$key$ = function ( + chunkIds, + removedChunks, + removedModules, + promises, + applyHandlers, + updatedModulesList + ) { + applyHandlers.push(applyHandler); + currentUpdateChunks = {}; + currentUpdateRemovedChunks = removedChunks; + currentUpdate = removedModules.reduce(function (obj, key) { + obj[key] = false; + return obj; + }, {}); + currentUpdateRuntime = []; + chunkIds.forEach(function (chunkId) { + if ( + $hasOwnProperty$($installedChunks$, chunkId) && + $installedChunks$[chunkId] !== undefined + ) { + promises.push($loadUpdateChunk$(chunkId, updatedModulesList)); + currentUpdateChunks[chunkId] = true; + } else { + currentUpdateChunks[chunkId] = false; + } + }); + if ($ensureChunkHandlers$) { + $ensureChunkHandlers$.$key$Hmr = function (chunkId, promises) { + if ( + currentUpdateChunks && + $hasOwnProperty$(currentUpdateChunks, chunkId) && + !currentUpdateChunks[chunkId] + ) { + promises.push($loadUpdateChunk$(chunkId)); + currentUpdateChunks[chunkId] = true; + } + }; + } + }; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/JavascriptHotModuleReplacementHelper.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/JavascriptHotModuleReplacementHelper.js new file mode 100644 index 0000000000000000000000000000000000000000..935fce0cc7e0d33fbddaeb34ee98b604e9968c07 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/JavascriptHotModuleReplacementHelper.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Haijie Xie @hai-x +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); + +const Template = require("../Template"); + +/** + * @param {string} type unique identifier used for HMR runtime properties + * @returns {string} HMR runtime code + */ +const generateJavascriptHMR = (type) => + Template.getFunctionContent( + require("../hmr/JavascriptHotModuleReplacement.runtime") + ) + .replace(/\$key\$/g, type) + .replace(/\$installedChunks\$/g, "installedChunks") + .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) + .replace(/\$ensureChunkHandlers\$/g, RuntimeGlobals.ensureChunkHandlers) + .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ); + +module.exports.generateJavascriptHMR = generateJavascriptHMR; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/LazyCompilationPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/LazyCompilationPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b37ff4b597405175f7d21a1a0dffd1a9c161866e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/LazyCompilationPlugin.js @@ -0,0 +1,464 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const Dependency = require("../Dependency"); +const Module = require("../Module"); +const ModuleFactory = require("../ModuleFactory"); +const { JS_TYPES } = require("../ModuleSourceTypesConstants"); +const { + WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY +} = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const CommonJsRequireDependency = require("../dependencies/CommonJsRequireDependency"); +const { registerNotSerializable } = require("../util/serialization"); + +/** @typedef {import("../../declarations/WebpackOptions")} WebpackOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").BuildCallback} BuildCallback */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../dependencies/HarmonyImportDependency")} HarmonyImportDependency */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + +/** @typedef {{ client: string, data: string, active: boolean }} ModuleResult */ + +/** + * @typedef {object} BackendApi + * @property {(callback: (err?: (Error | null)) => void) => void} dispose + * @property {(module: Module) => ModuleResult} module + */ + +const HMR_DEPENDENCY_TYPES = new Set([ + "import.meta.webpackHot.accept", + "import.meta.webpackHot.decline", + "module.hot.accept", + "module.hot.decline" +]); + +/** + * @param {Options["test"]} test test option + * @param {Module} module the module + * @returns {boolean | null | string} true, if the module should be selected + */ +const checkTest = (test, module) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module); + } + if (typeof test === "string") { + const name = module.nameForCondition(); + return name && name.startsWith(test); + } + if (test instanceof RegExp) { + const name = module.nameForCondition(); + return name && test.test(name); + } + return false; +}; + +class LazyCompilationDependency extends Dependency { + /** + * @param {LazyCompilationProxyModule} proxyModule proxy module + */ + constructor(proxyModule) { + super(); + this.proxyModule = proxyModule; + } + + get category() { + return "esm"; + } + + get type() { + return "lazy import()"; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return this.proxyModule.originalModule.identifier(); + } +} + +registerNotSerializable(LazyCompilationDependency); + +class LazyCompilationProxyModule extends Module { + /** + * @param {string} context context + * @param {Module} originalModule an original module + * @param {string} request request + * @param {ModuleResult["client"]} client client + * @param {ModuleResult["data"]} data data + * @param {ModuleResult["active"]} active true when active, otherwise false + */ + constructor(context, originalModule, request, client, data, active) { + super( + WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY, + context, + originalModule.layer + ); + this.originalModule = originalModule; + this.request = request; + this.client = client; + this.data = data; + this.active = active; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `${WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY}|${this.originalModule.identifier()}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `${WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY} ${this.originalModule.readableIdentifier( + requestShortener + )}`; + } + + /** + * Assuming this module is in the cache. Update the (cached) module with + * the fresh module from the factory. Usually updates internal references + * and properties. + * @param {Module} module fresh module + * @returns {void} + */ + updateCacheModule(module) { + super.updateCacheModule(module); + const m = /** @type {LazyCompilationProxyModule} */ (module); + this.originalModule = m.originalModule; + this.request = m.request; + this.client = m.client; + this.data = m.data; + this.active = m.active; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.originalModule.libIdent( + options + )}!${WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY}`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo || this.buildInfo.active !== this.active); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildInfo = { + active: this.active + }; + /** @type {BuildMeta} */ + this.buildMeta = {}; + this.clearDependenciesAndBlocks(); + const dep = new CommonJsRequireDependency(this.client); + this.addDependency(dep); + if (this.active) { + const dep = new LazyCompilationDependency(this); + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); + } + callback(); + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return JS_TYPES; + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return 200; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ runtimeTemplate, chunkGraph, moduleGraph }) { + const sources = new Map(); + const runtimeRequirements = new Set(); + runtimeRequirements.add(RuntimeGlobals.module); + const clientDep = /** @type {CommonJsRequireDependency} */ ( + this.dependencies[0] + ); + const clientModule = moduleGraph.getModule(clientDep); + const block = this.blocks[0]; + const client = Template.asString([ + `var client = ${runtimeTemplate.moduleExports({ + module: clientModule, + chunkGraph, + request: clientDep.userRequest, + runtimeRequirements + })}`, + `var data = ${JSON.stringify(this.data)};` + ]); + const keepActive = Template.asString([ + `var dispose = client.keepAlive({ data: data, active: ${JSON.stringify( + Boolean(block) + )}, module: module, onError: onError });` + ]); + let source; + if (block) { + const dep = block.dependencies[0]; + const module = /** @type {Module} */ (moduleGraph.getModule(dep)); + source = Template.asString([ + client, + `module.exports = ${runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + block, + module, + request: this.request, + strict: false, // TODO this should be inherited from the original module + message: "import()", + runtimeRequirements + })};`, + "if (module.hot) {", + Template.indent([ + "module.hot.accept();", + `module.hot.accept(${JSON.stringify( + chunkGraph.getModuleId(module) + )}, function() { module.hot.invalidate(); });`, + "module.hot.dispose(function(data) { delete data.resolveSelf; dispose(data); });", + "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);" + ]), + "}", + "function onError() { /* ignore */ }", + keepActive + ]); + } else { + source = Template.asString([ + client, + "var resolveSelf, onError;", + "module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });", + "if (module.hot) {", + Template.indent([ + "module.hot.accept();", + "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);", + "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });" + ]), + "}", + keepActive + ]); + } + sources.set("javascript", new RawSource(source)); + return { + sources, + runtimeRequirements + }; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + super.updateHash(hash, context); + hash.update(this.active ? "active" : ""); + hash.update(JSON.stringify(this.data)); + } +} + +registerNotSerializable(LazyCompilationProxyModule); + +class LazyCompilationDependencyFactory extends ModuleFactory { + constructor() { + super(); + } + + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create(data, callback) { + const dependency = + /** @type {LazyCompilationDependency} */ + (data.dependencies[0]); + callback(null, { + module: dependency.proxyModule.originalModule + }); + } +} + +/** + * @callback BackendHandler + * @param {Compiler} compiler compiler + * @param {(err: Error | null, backendApi?: BackendApi) => void} callback callback + * @returns {void} + */ + +/** + * @callback PromiseBackendHandler + * @param {Compiler} compiler compiler + * @returns {Promise} backend + */ + +/** @typedef {BackendHandler | PromiseBackendHandler} BackEnd */ + +/** + * @typedef {object} Options options + * @property {BackEnd} backend the backend + * @property {boolean=} entries + * @property {boolean=} imports + * @property {(RegExp | string | ((module: Module) => boolean))=} test additional filter for lazy compiled entrypoint modules + */ + +const PLUGIN_NAME = "LazyCompilationPlugin"; + +class LazyCompilationPlugin { + /** + * @param {Options} options options + */ + constructor({ backend, entries, imports, test }) { + this.backend = backend; + this.entries = entries; + this.imports = imports; + this.test = test; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + /** @type {BackendApi} */ + let backend; + compiler.hooks.beforeCompile.tapAsync(PLUGIN_NAME, (params, callback) => { + if (backend !== undefined) return callback(); + const promise = this.backend(compiler, (err, result) => { + if (err) return callback(err); + backend = /** @type {BackendApi} */ (result); + callback(); + }); + if (promise && promise.then) { + promise.then((b) => { + backend = b; + callback(); + }, callback); + } + }); + compiler.hooks.thisCompilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.module.tap( + PLUGIN_NAME, + (module, createData, resolveData) => { + if ( + resolveData.dependencies.every((dep) => + HMR_DEPENDENCY_TYPES.has(dep.type) + ) + ) { + // for HMR only resolving, try to determine if the HMR accept/decline refers to + // an import() or not + const hmrDep = resolveData.dependencies[0]; + const originModule = + /** @type {Module} */ + (compilation.moduleGraph.getParentModule(hmrDep)); + const isReferringToDynamicImport = originModule.blocks.some( + (block) => + block.dependencies.some( + (dep) => + dep.type === "import()" && + /** @type {HarmonyImportDependency} */ (dep).request === + hmrDep.request + ) + ); + if (!isReferringToDynamicImport) return module; + } else if ( + !resolveData.dependencies.every( + (dep) => + HMR_DEPENDENCY_TYPES.has(dep.type) || + (this.imports && + (dep.type === "import()" || + dep.type === "import() context element")) || + (this.entries && dep.type === "entry") + ) + ) { + return module; + } + if ( + /webpack[/\\]hot[/\\]|webpack-dev-server[/\\]client|webpack-hot-middleware[/\\]client/.test( + resolveData.request + ) || + !checkTest(this.test, module) + ) { + return module; + } + const moduleInfo = backend.module(module); + if (!moduleInfo) return module; + const { client, data, active } = moduleInfo; + + return new LazyCompilationProxyModule( + compiler.context, + module, + resolveData.request, + client, + data, + active + ); + } + ); + compilation.dependencyFactories.set( + LazyCompilationDependency, + new LazyCompilationDependencyFactory() + ); + } + ); + compiler.hooks.shutdown.tapAsync(PLUGIN_NAME, (callback) => { + backend.dispose(callback); + }); + } +} + +module.exports = LazyCompilationPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/lazyCompilationBackend.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/lazyCompilationBackend.js new file mode 100644 index 0000000000000000000000000000000000000000..c5fbbbf72ad69131db873b050b96a47c7356ac53 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/hmr/lazyCompilationBackend.js @@ -0,0 +1,163 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("http").IncomingMessage} IncomingMessage */ +/** @typedef {import("http").RequestListener} RequestListener */ +/** @typedef {import("http").ServerOptions} HttpServerOptions */ +/** @typedef {import("http").ServerResponse} ServerResponse */ +/** @typedef {import("https").ServerOptions} HttpsServerOptions */ +/** @typedef {import("net").AddressInfo} AddressInfo */ +/** @typedef {import("net").Server} Server */ +/** @typedef {import("../../declarations/WebpackOptions").LazyCompilationDefaultBackendOptions} LazyCompilationDefaultBackendOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("./LazyCompilationPlugin").BackendApi} BackendApi */ +/** @typedef {import("./LazyCompilationPlugin").BackendHandler} BackendHandler */ + +/** + * @param {Omit & { client: NonNullable}} options additional options for the backend + * @returns {BackendHandler} backend + */ +module.exports = (options) => (compiler, callback) => { + const logger = compiler.getInfrastructureLogger("LazyCompilationBackend"); + const activeModules = new Map(); + const prefix = "/lazy-compilation-using-"; + + const isHttps = + options.protocol === "https" || + (typeof options.server === "object" && + ("key" in options.server || "pfx" in options.server)); + + const createServer = + typeof options.server === "function" + ? options.server + : (() => { + const http = isHttps ? require("https") : require("http"); + return http.createServer.bind( + http, + /** @type {HttpServerOptions | HttpsServerOptions} */ + (options.server) + ); + })(); + /** @type {(server: Server) => void} */ + const listen = + typeof options.listen === "function" + ? options.listen + : (server) => { + let listen = options.listen; + if (typeof listen === "object" && !("port" in listen)) { + listen = { ...listen, port: undefined }; + } + server.listen(listen); + }; + + const protocol = options.protocol || (isHttps ? "https" : "http"); + + /** @type {RequestListener} */ + const requestListener = (req, res) => { + if (req.url === undefined) return; + const keys = req.url.slice(prefix.length).split("@"); + req.socket.on("close", () => { + setTimeout(() => { + for (const key of keys) { + const oldValue = activeModules.get(key) || 0; + activeModules.set(key, oldValue - 1); + if (oldValue === 1) { + logger.log( + `${key} is no longer in use. Next compilation will skip this module.` + ); + } + } + }, 120000); + }); + req.socket.setNoDelay(true); + res.writeHead(200, { + "content-type": "text/event-stream", + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "*", + "Access-Control-Allow-Headers": "*" + }); + res.write("\n"); + let moduleActivated = false; + for (const key of keys) { + const oldValue = activeModules.get(key) || 0; + activeModules.set(key, oldValue + 1); + if (oldValue === 0) { + logger.log(`${key} is now in use and will be compiled.`); + moduleActivated = true; + } + } + if (moduleActivated && compiler.watching) compiler.watching.invalidate(); + }; + + const server = /** @type {Server} */ (createServer()); + server.on("request", requestListener); + + let isClosing = false; + /** @type {Set} */ + const sockets = new Set(); + server.on("connection", (socket) => { + sockets.add(socket); + socket.on("close", () => { + sockets.delete(socket); + }); + if (isClosing) socket.destroy(); + }); + server.on("clientError", (e) => { + if (e.message !== "Server is disposing") logger.warn(e); + }); + + server.on( + "listening", + /** + * @param {Error} err error + * @returns {void} + */ + (err) => { + if (err) return callback(err); + const _addr = server.address(); + if (typeof _addr === "string") { + throw new Error("addr must not be a string"); + } + const addr = /** @type {AddressInfo} */ (_addr); + const urlBase = + addr.address === "::" || addr.address === "0.0.0.0" + ? `${protocol}://localhost:${addr.port}` + : addr.family === "IPv6" + ? `${protocol}://[${addr.address}]:${addr.port}` + : `${protocol}://${addr.address}:${addr.port}`; + logger.log( + `Server-Sent-Events server for lazy compilation open at ${urlBase}.` + ); + callback(null, { + dispose(callback) { + isClosing = true; + // Removing the listener is a workaround for a memory leak in node.js + server.off("request", requestListener); + server.close((err) => { + callback(err); + }); + for (const socket of sockets) { + socket.destroy(new Error("Server is disposing")); + } + }, + module(originalModule) { + const key = `${encodeURIComponent( + originalModule.identifier().replace(/\\/g, "/").replace(/@/g, "_") + ).replace(/%(2F|3A|24|26|2B|2C|3B|3D)/g, decodeURIComponent)}`; + const active = activeModules.get(key) > 0; + return { + client: `${options.client}?${encodeURIComponent(urlBase + prefix)}`, + data: key, + active + }; + } + }); + } + ); + listen(server); +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/ChunkModuleIdRangePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/ChunkModuleIdRangePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..a3233bb969c7be7837efb9319243d0b076ccf8ff --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/ChunkModuleIdRangePlugin.js @@ -0,0 +1,92 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { find } = require("../util/SetHelpers"); +const { + compareModulesByPostOrderIndexOrIdentifier, + compareModulesByPreOrderIndexOrIdentifier +} = require("../util/comparators"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +/** + * @typedef {object} ChunkModuleIdRangePluginOptions + * @property {string} name the chunk name + * @property {("index" | "index2" | "preOrderIndex" | "postOrderIndex")=} order order + * @property {number=} start start id + * @property {number=} end end id + */ + +const PLUGIN_NAME = "ChunkModuleIdRangePlugin"; + +class ChunkModuleIdRangePlugin { + /** + * @param {ChunkModuleIdRangePluginOptions} options options object + */ + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.moduleIds.tap(PLUGIN_NAME, (modules) => { + const chunkGraph = compilation.chunkGraph; + const chunk = find( + compilation.chunks, + (chunk) => chunk.name === options.name + ); + if (!chunk) { + throw new Error( + `${PLUGIN_NAME}: Chunk with name '${options.name}"' was not found` + ); + } + + /** @type {Module[]} */ + let chunkModules; + if (options.order) { + let cmpFn; + switch (options.order) { + case "index": + case "preOrderIndex": + cmpFn = compareModulesByPreOrderIndexOrIdentifier(moduleGraph); + break; + case "index2": + case "postOrderIndex": + cmpFn = compareModulesByPostOrderIndexOrIdentifier(moduleGraph); + break; + default: + throw new Error(`${PLUGIN_NAME}: unexpected value of order`); + } + chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn); + } else { + chunkModules = [...modules] + .filter((m) => chunkGraph.isModuleInChunk(m, chunk)) + .sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph)); + } + + let currentId = options.start || 0; + for (let i = 0; i < chunkModules.length; i++) { + const m = chunkModules[i]; + if (m.needId && chunkGraph.getModuleId(m) === null) { + chunkGraph.setModuleId(m, currentId++); + } + if (options.end && currentId > options.end) break; + } + }); + }); + } +} + +module.exports = ChunkModuleIdRangePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/DeterministicChunkIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/DeterministicChunkIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d06b7b3a7ec398fbd01dae66711d26556a083633 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/DeterministicChunkIdsPlugin.js @@ -0,0 +1,73 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +const { compareChunksNatural } = require("../util/comparators"); +const { + assignDeterministicIds, + getFullChunkName, + getUsedChunkIds +} = require("./IdHelpers"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +/** + * @typedef {object} DeterministicChunkIdsPluginOptions + * @property {string=} context context for ids + * @property {number=} maxLength maximum length of ids + */ + +const PLUGIN_NAME = "DeterministicChunkIdsPlugin"; + +class DeterministicChunkIdsPlugin { + /** + * @param {DeterministicChunkIdsPluginOptions=} options options + */ + constructor(options = {}) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.chunkIds.tap(PLUGIN_NAME, (chunks) => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + const maxLength = this.options.maxLength || 3; + + const compareNatural = compareChunksNatural(chunkGraph); + + const usedIds = getUsedChunkIds(compilation); + assignDeterministicIds( + [...chunks].filter((chunk) => chunk.id === null), + (chunk) => + getFullChunkName(chunk, chunkGraph, context, compiler.root), + compareNatural, + (chunk, id) => { + const size = usedIds.size; + usedIds.add(`${id}`); + if (size === usedIds.size) return false; + chunk.id = id; + chunk.ids = [id]; + return true; + }, + [10 ** maxLength], + 10, + usedIds.size + ); + }); + }); + } +} + +module.exports = DeterministicChunkIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/DeterministicModuleIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/DeterministicModuleIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7ed80a67ef51e116b98dde61567971e97dc81294 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/DeterministicModuleIdsPlugin.js @@ -0,0 +1,97 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +const { + compareModulesByPreOrderIndexOrIdentifier +} = require("../util/comparators"); +const { + assignDeterministicIds, + getFullModuleName, + getUsedModuleIdsAndModules +} = require("./IdHelpers"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +/** + * @typedef {object} DeterministicModuleIdsPluginOptions + * @property {string=} context context relative to which module identifiers are computed + * @property {((module: Module) => boolean)=} test selector function for modules + * @property {number=} maxLength maximum id length in digits (used as starting point) + * @property {number=} salt hash salt for ids + * @property {boolean=} fixedLength do not increase the maxLength to find an optimal id space size + * @property {boolean=} failOnConflict throw an error when id conflicts occur (instead of rehashing) + */ + +const PLUGIN_NAME = "DeterministicModuleIdsPlugin"; + +class DeterministicModuleIdsPlugin { + /** + * @param {DeterministicModuleIdsPluginOptions=} options options + */ + constructor(options = {}) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.moduleIds.tap(PLUGIN_NAME, () => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + const maxLength = this.options.maxLength || 3; + const failOnConflict = this.options.failOnConflict || false; + const fixedLength = this.options.fixedLength || false; + const salt = this.options.salt || 0; + let conflicts = 0; + + const [usedIds, modules] = getUsedModuleIdsAndModules( + compilation, + this.options.test + ); + assignDeterministicIds( + modules, + (module) => getFullModuleName(module, context, compiler.root), + failOnConflict + ? () => 0 + : compareModulesByPreOrderIndexOrIdentifier( + compilation.moduleGraph + ), + (module, id) => { + const size = usedIds.size; + usedIds.add(`${id}`); + if (size === usedIds.size) { + conflicts++; + return false; + } + chunkGraph.setModuleId(module, id); + return true; + }, + [10 ** maxLength], + fixedLength ? 0 : 10, + usedIds.size, + salt + ); + if (failOnConflict && conflicts) { + throw new Error( + `Assigning deterministic module ids has lead to ${conflicts} conflict${ + conflicts > 1 ? "s" : "" + }.\nIncrease the 'maxLength' to increase the id space and make conflicts less likely (recommended when there are many conflicts or application is expected to grow), or add an 'salt' number to try another hash starting value in the same id space (recommended when there is only a single conflict).` + ); + } + }); + }); + } +} + +module.exports = DeterministicModuleIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/HashedModuleIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/HashedModuleIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..3944f8d2747145ac5a65d891c07275c15ebcf06f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/HashedModuleIdsPlugin.js @@ -0,0 +1,92 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { DEFAULTS } = require("../config/defaults"); +const { + compareModulesByPreOrderIndexOrIdentifier +} = require("../util/comparators"); +const createSchemaValidation = require("../util/create-schema-validation"); +const createHash = require("../util/createHash"); +const { + getFullModuleName, + getUsedModuleIdsAndModules +} = require("./IdHelpers"); + +/** @typedef {import("../../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/HashedModuleIdsPlugin.check"), + () => require("../../schemas/plugins/HashedModuleIdsPlugin.json"), + { + name: "Hashed Module Ids Plugin", + baseDataPath: "options" + } +); + +const PLUGIN_NAME = "HashedModuleIdsPlugin"; + +class HashedModuleIdsPlugin { + /** + * @param {HashedModuleIdsPluginOptions=} options options object + */ + constructor(options = {}) { + validate(options); + + /** @type {HashedModuleIdsPluginOptions} */ + this.options = { + context: undefined, + hashFunction: DEFAULTS.HASH_FUNCTION, + hashDigest: "base64", + hashDigestLength: 4, + ...options + }; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.moduleIds.tap(PLUGIN_NAME, () => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + + const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); + const modulesInNaturalOrder = modules.sort( + compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) + ); + for (const module of modulesInNaturalOrder) { + const ident = getFullModuleName(module, context, compiler.root); + const hash = createHash( + /** @type {NonNullable} */ ( + options.hashFunction + ) + ); + hash.update(ident || ""); + const hashId = /** @type {string} */ ( + hash.digest(options.hashDigest) + ); + let len = options.hashDigestLength; + while (usedIds.has(hashId.slice(0, len))) { + /** @type {number} */ (len)++; + } + const moduleId = hashId.slice(0, len); + chunkGraph.setModuleId(module, moduleId); + usedIds.add(moduleId); + } + }); + }); + } +} + +module.exports = HashedModuleIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/IdHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/IdHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..142af991bfdc13ac3241f14561721a7c44ddaabf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/IdHelpers.js @@ -0,0 +1,478 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const createHash = require("../util/createHash"); +const { makePathsRelative } = require("../util/identifier"); +const numberHash = require("../util/numberHash"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ + +/** + * @param {string} str string to hash + * @param {number} len max length of the hash + * @param {string | Hash} hashFunction hash function to use + * @returns {string} hash + */ +const getHash = (str, len, hashFunction) => { + const hash = createHash(hashFunction); + hash.update(str); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.slice(0, len); +}; + +/** + * @param {string} str the string + * @returns {string} string prefixed by an underscore if it is a number + */ +const avoidNumber = (str) => { + // max length of a number is 21 chars, bigger numbers a written as "...e+xx" + if (str.length > 21) return str; + const firstChar = str.charCodeAt(0); + // skip everything that doesn't look like a number + // charCodes: "-": 45, "1": 49, "9": 57 + if (firstChar < 49) { + if (firstChar !== 45) return str; + } else if (firstChar > 57) { + return str; + } + if (str === String(Number(str))) { + return `_${str}`; + } + return str; +}; + +/** + * @param {string} request the request + * @returns {string} id representation + */ +const requestToId = (request) => + request.replace(/^(\.\.?\/)+/, "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); + +/** + * @param {string} string the string + * @param {string} delimiter separator for string and hash + * @param {string | Hash} hashFunction hash function to use + * @returns {string} string with limited max length to 100 chars + */ +const shortenLongString = (string, delimiter, hashFunction) => { + if (string.length < 100) return string; + return ( + string.slice(0, 100 - 6 - delimiter.length) + + delimiter + + getHash(string, 6, hashFunction) + ); +}; + +/** + * @param {Module} module the module + * @param {string} context context directory + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} short module name + */ +const getShortModuleName = (module, context, associatedObjectForCache) => { + const libIdent = module.libIdent({ context, associatedObjectForCache }); + if (libIdent) return avoidNumber(libIdent); + const nameForCondition = module.nameForCondition(); + if (nameForCondition) { + return avoidNumber( + makePathsRelative(context, nameForCondition, associatedObjectForCache) + ); + } + return ""; +}; + +/** + * @param {string} shortName the short name + * @param {Module} module the module + * @param {string} context context directory + * @param {string | Hash} hashFunction hash function to use + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} long module name + */ +const getLongModuleName = ( + shortName, + module, + context, + hashFunction, + associatedObjectForCache +) => { + const fullName = getFullModuleName(module, context, associatedObjectForCache); + return `${shortName}?${getHash(fullName, 4, hashFunction)}`; +}; + +/** + * @param {Module} module the module + * @param {string} context context directory + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} full module name + */ +const getFullModuleName = (module, context, associatedObjectForCache) => + makePathsRelative(context, module.identifier(), associatedObjectForCache); + +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} context context directory + * @param {string} delimiter delimiter for names + * @param {string | Hash} hashFunction hash function to use + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} short chunk name + */ +const getShortChunkName = ( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + associatedObjectForCache +) => { + const modules = chunkGraph.getChunkRootModules(chunk); + const shortModuleNames = modules.map((m) => + requestToId(getShortModuleName(m, context, associatedObjectForCache)) + ); + chunk.idNameHints.sort(); + const chunkName = [...chunk.idNameHints, ...shortModuleNames] + .filter(Boolean) + .join(delimiter); + return shortenLongString(chunkName, delimiter, hashFunction); +}; + +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} context context directory + * @param {string} delimiter delimiter for names + * @param {string | Hash} hashFunction hash function to use + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} short chunk name + */ +const getLongChunkName = ( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + associatedObjectForCache +) => { + const modules = chunkGraph.getChunkRootModules(chunk); + const shortModuleNames = modules.map((m) => + requestToId(getShortModuleName(m, context, associatedObjectForCache)) + ); + const longModuleNames = modules.map((m) => + requestToId( + getLongModuleName("", m, context, hashFunction, associatedObjectForCache) + ) + ); + chunk.idNameHints.sort(); + const chunkName = [ + ...chunk.idNameHints, + ...shortModuleNames, + ...longModuleNames + ] + .filter(Boolean) + .join(delimiter); + return shortenLongString(chunkName, delimiter, hashFunction); +}; + +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} context context directory + * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} full chunk name + */ +const getFullChunkName = ( + chunk, + chunkGraph, + context, + associatedObjectForCache +) => { + if (chunk.name) return chunk.name; + const modules = chunkGraph.getChunkRootModules(chunk); + const fullModuleNames = modules.map((m) => + makePathsRelative(context, m.identifier(), associatedObjectForCache) + ); + return fullModuleNames.join(); +}; + +/** + * @template K + * @template V + * @param {Map} map a map from key to values + * @param {K} key key + * @param {V} value value + * @returns {void} + */ +const addToMapOfItems = (map, key, value) => { + let array = map.get(key); + if (array === undefined) { + array = []; + map.set(key, array); + } + array.push(value); +}; + +/** + * @param {Compilation} compilation the compilation + * @param {((module: Module) => boolean)=} filter filter modules + * @returns {[Set, Module[]]} used module ids as strings and modules without id matching the filter + */ +const getUsedModuleIdsAndModules = (compilation, filter) => { + const chunkGraph = compilation.chunkGraph; + + const modules = []; + + /** @type {Set} */ + const usedIds = new Set(); + if (compilation.usedModuleIds) { + for (const id of compilation.usedModuleIds) { + usedIds.add(String(id)); + } + } + + for (const module of compilation.modules) { + if (!module.needId) continue; + const moduleId = chunkGraph.getModuleId(module); + if (moduleId !== null) { + usedIds.add(String(moduleId)); + } else if ( + (!filter || filter(module)) && + chunkGraph.getNumberOfModuleChunks(module) !== 0 + ) { + modules.push(module); + } + } + + return [usedIds, modules]; +}; + +/** + * @param {Compilation} compilation the compilation + * @returns {Set} used chunk ids as strings + */ +const getUsedChunkIds = (compilation) => { + /** @type {Set} */ + const usedIds = new Set(); + if (compilation.usedChunkIds) { + for (const id of compilation.usedChunkIds) { + usedIds.add(String(id)); + } + } + + for (const chunk of compilation.chunks) { + const chunkId = chunk.id; + if (chunkId !== null) { + usedIds.add(String(chunkId)); + } + } + + return usedIds; +}; + +/** + * @template T + * @param {Iterable} items list of items to be named + * @param {(item: T) => string} getShortName get a short name for an item + * @param {(item: T, name: string) => string} getLongName get a long name for an item + * @param {(a: T, b: T) => -1 | 0 | 1} comparator order of items + * @param {Set} usedIds already used ids, will not be assigned + * @param {(item: T, name: string) => void} assignName assign a name to an item + * @returns {T[]} list of items without a name + */ +const assignNames = ( + items, + getShortName, + getLongName, + comparator, + usedIds, + assignName +) => { + /** @type {Map} */ + const nameToItems = new Map(); + + for (const item of items) { + const name = getShortName(item); + addToMapOfItems(nameToItems, name, item); + } + + /** @type {Map} */ + const nameToItems2 = new Map(); + + for (const [name, items] of nameToItems) { + if (items.length > 1 || !name) { + for (const item of items) { + const longName = getLongName(item, name); + addToMapOfItems(nameToItems2, longName, item); + } + } else { + addToMapOfItems(nameToItems2, name, items[0]); + } + } + + /** @type {T[]} */ + const unnamedItems = []; + + for (const [name, items] of nameToItems2) { + if (!name) { + for (const item of items) { + unnamedItems.push(item); + } + } else if (items.length === 1 && !usedIds.has(name)) { + assignName(items[0], name); + usedIds.add(name); + } else { + items.sort(comparator); + let i = 0; + for (const item of items) { + while (nameToItems2.has(name + i) && usedIds.has(name + i)) i++; + assignName(item, name + i); + usedIds.add(name + i); + i++; + } + } + } + + unnamedItems.sort(comparator); + return unnamedItems; +}; + +/** + * @template T + * @param {T[]} items list of items to be named + * @param {(item: T) => string} getName get a name for an item + * @param {(a: T, n: T) => -1 | 0 | 1} comparator order of items + * @param {(item: T, id: number) => boolean} assignId assign an id to an item + * @param {number[]} ranges usable ranges for ids + * @param {number} expandFactor factor to create more ranges + * @param {number} extraSpace extra space to allocate, i. e. when some ids are already used + * @param {number} salt salting number to initialize hashing + * @returns {void} + */ +const assignDeterministicIds = ( + items, + getName, + comparator, + assignId, + ranges = [10], + expandFactor = 10, + extraSpace = 0, + salt = 0 +) => { + items.sort(comparator); + + // max 5% fill rate + const optimalRange = Math.min( + items.length * 20 + extraSpace, + Number.MAX_SAFE_INTEGER + ); + + let i = 0; + let range = ranges[i]; + while (range < optimalRange) { + i++; + if (i < ranges.length) { + range = Math.min(ranges[i], Number.MAX_SAFE_INTEGER); + } else if (expandFactor) { + range = Math.min(range * expandFactor, Number.MAX_SAFE_INTEGER); + } else { + break; + } + } + + for (const item of items) { + const ident = getName(item); + let id; + let i = salt; + do { + id = numberHash(ident + i++, range); + } while (!assignId(item, id)); + } +}; + +/** + * @param {Set} usedIds used ids + * @param {Iterable} modules the modules + * @param {Compilation} compilation the compilation + * @returns {void} + */ +const assignAscendingModuleIds = (usedIds, modules, compilation) => { + const chunkGraph = compilation.chunkGraph; + + let nextId = 0; + let assignId; + if (usedIds.size > 0) { + /** + * @param {Module} module the module + */ + assignId = (module) => { + if (chunkGraph.getModuleId(module) === null) { + while (usedIds.has(String(nextId))) nextId++; + chunkGraph.setModuleId(module, nextId++); + } + }; + } else { + /** + * @param {Module} module the module + */ + assignId = (module) => { + if (chunkGraph.getModuleId(module) === null) { + chunkGraph.setModuleId(module, nextId++); + } + }; + } + for (const module of modules) { + assignId(module); + } +}; + +/** + * @param {Iterable} chunks the chunks + * @param {Compilation} compilation the compilation + * @returns {void} + */ +const assignAscendingChunkIds = (chunks, compilation) => { + const usedIds = getUsedChunkIds(compilation); + + let nextId = 0; + if (usedIds.size > 0) { + for (const chunk of chunks) { + if (chunk.id === null) { + while (usedIds.has(String(nextId))) nextId++; + chunk.id = nextId; + chunk.ids = [nextId]; + nextId++; + } + } + } else { + for (const chunk of chunks) { + if (chunk.id === null) { + chunk.id = nextId; + chunk.ids = [nextId]; + nextId++; + } + } + } +}; + +module.exports.assignAscendingChunkIds = assignAscendingChunkIds; +module.exports.assignAscendingModuleIds = assignAscendingModuleIds; +module.exports.assignDeterministicIds = assignDeterministicIds; +module.exports.assignNames = assignNames; +module.exports.getFullChunkName = getFullChunkName; +module.exports.getFullModuleName = getFullModuleName; +module.exports.getLongChunkName = getLongChunkName; +module.exports.getLongModuleName = getLongModuleName; +module.exports.getShortChunkName = getShortChunkName; +module.exports.getShortModuleName = getShortModuleName; +module.exports.getUsedChunkIds = getUsedChunkIds; +module.exports.getUsedModuleIdsAndModules = getUsedModuleIdsAndModules; +module.exports.requestToId = requestToId; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NamedChunkIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NamedChunkIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..139d4793377c10fb60ca71cec80a17ce8c848416 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NamedChunkIdsPlugin.js @@ -0,0 +1,95 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { compareChunksNatural } = require("../util/comparators"); +const { + assignAscendingChunkIds, + assignNames, + getLongChunkName, + getShortChunkName, + getUsedChunkIds +} = require("./IdHelpers"); + +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +/** + * @typedef {object} NamedChunkIdsPluginOptions + * @property {string=} context context + * @property {string=} delimiter delimiter + */ + +const PLUGIN_NAME = "NamedChunkIdsPlugin"; + +class NamedChunkIdsPlugin { + /** + * @param {NamedChunkIdsPluginOptions=} options options + */ + constructor(options) { + this.delimiter = (options && options.delimiter) || "-"; + this.context = options && options.context; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const hashFunction = + /** @type {NonNullable} */ + (compilation.outputOptions.hashFunction); + compilation.hooks.chunkIds.tap(PLUGIN_NAME, (chunks) => { + const chunkGraph = compilation.chunkGraph; + const context = this.context ? this.context : compiler.context; + const delimiter = this.delimiter; + + const unnamedChunks = assignNames( + [...chunks].filter((chunk) => { + if (chunk.name) { + chunk.id = chunk.name; + chunk.ids = [chunk.name]; + } + return chunk.id === null; + }), + (chunk) => + getShortChunkName( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + compiler.root + ), + (chunk) => + getLongChunkName( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + compiler.root + ), + compareChunksNatural(chunkGraph), + getUsedChunkIds(compilation), + (chunk, name) => { + chunk.id = name; + chunk.ids = [name]; + } + ); + if (unnamedChunks.length > 0) { + assignAscendingChunkIds(unnamedChunks, compilation); + } + }); + }); + } +} + +module.exports = NamedChunkIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NamedModuleIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NamedModuleIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..8ac07eea8df7d7df3b80556cae0bfc92c7011ab5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NamedModuleIdsPlugin.js @@ -0,0 +1,71 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { compareModulesByIdentifier } = require("../util/comparators"); +const { + assignAscendingModuleIds, + assignNames, + getLongModuleName, + getShortModuleName, + getUsedModuleIdsAndModules +} = require("./IdHelpers"); + +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +/** + * @typedef {object} NamedModuleIdsPluginOptions + * @property {string=} context context + */ + +const PLUGIN_NAME = "NamedModuleIdsPlugin"; + +class NamedModuleIdsPlugin { + /** + * @param {NamedModuleIdsPluginOptions=} options options + */ + constructor(options = {}) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { root } = compiler; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const hashFunction = + /** @type {NonNullable} */ + (compilation.outputOptions.hashFunction); + compilation.hooks.moduleIds.tap(PLUGIN_NAME, () => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + + const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); + const unnamedModules = assignNames( + modules, + (m) => getShortModuleName(m, context, root), + (m, shortName) => + getLongModuleName(shortName, m, context, hashFunction, root), + compareModulesByIdentifier, + usedIds, + (m, name) => chunkGraph.setModuleId(m, name) + ); + if (unnamedModules.length > 0) { + assignAscendingModuleIds(usedIds, unnamedModules, compilation); + } + }); + }); + } +} + +module.exports = NamedModuleIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NaturalChunkIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NaturalChunkIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b6f2fd7fdcba91dd4091dec5d65984804fd9a51d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NaturalChunkIdsPlugin.js @@ -0,0 +1,36 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { compareChunksNatural } = require("../util/comparators"); +const { assignAscendingChunkIds } = require("./IdHelpers"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +const PLUGIN_NAME = "NaturalChunkIdsPlugin"; + +class NaturalChunkIdsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.chunkIds.tap(PLUGIN_NAME, (chunks) => { + const chunkGraph = compilation.chunkGraph; + const compareNatural = compareChunksNatural(chunkGraph); + /** @type {Chunk[]} */ + const chunksInNaturalOrder = [...chunks].sort(compareNatural); + assignAscendingChunkIds(chunksInNaturalOrder, compilation); + }); + }); + } +} + +module.exports = NaturalChunkIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NaturalModuleIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NaturalModuleIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..8915b3f28108d6ae04db90fe098e2ccb365808f1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/NaturalModuleIdsPlugin.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + +"use strict"; + +const { + compareModulesByPreOrderIndexOrIdentifier +} = require("../util/comparators"); +const { + assignAscendingModuleIds, + getUsedModuleIdsAndModules +} = require("./IdHelpers"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +const PLUGIN_NAME = "NaturalModuleIdsPlugin"; + +class NaturalModuleIdsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.moduleIds.tap(PLUGIN_NAME, () => { + const [usedIds, modulesInNaturalOrder] = + getUsedModuleIdsAndModules(compilation); + modulesInNaturalOrder.sort( + compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) + ); + assignAscendingModuleIds(usedIds, modulesInNaturalOrder, compilation); + }); + }); + } +} + +module.exports = NaturalModuleIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/OccurrenceChunkIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/OccurrenceChunkIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..2cb6c9b61f83d7d058773207756bfce52c6ddf5a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/OccurrenceChunkIdsPlugin.js @@ -0,0 +1,87 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { compareChunksNatural } = require("../util/comparators"); +const createSchemaValidation = require("../util/create-schema-validation"); +const { assignAscendingChunkIds } = require("./IdHelpers"); + +/** @typedef {import("../../declarations/plugins/ids/OccurrenceChunkIdsPlugin").OccurrenceChunkIdsPluginOptions} OccurrenceChunkIdsPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/ids/OccurrenceChunkIdsPlugin.check"), + () => require("../../schemas/plugins/ids/OccurrenceChunkIdsPlugin.json"), + { + name: "Occurrence Order Chunk Ids Plugin", + baseDataPath: "options" + } +); + +const PLUGIN_NAME = "OccurrenceChunkIdsPlugin"; + +class OccurrenceChunkIdsPlugin { + /** + * @param {OccurrenceChunkIdsPluginOptions=} options options object + */ + constructor(options = {}) { + validate(options); + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.chunkIds.tap(PLUGIN_NAME, (chunks) => { + const chunkGraph = compilation.chunkGraph; + + /** @type {Map} */ + const occursInInitialChunksMap = new Map(); + + const compareNatural = compareChunksNatural(chunkGraph); + + for (const c of chunks) { + let occurs = 0; + for (const chunkGroup of c.groupsIterable) { + for (const parent of chunkGroup.parentsIterable) { + if (parent.isInitial()) occurs++; + } + } + occursInInitialChunksMap.set(c, occurs); + } + + /** @type {Chunk[]} */ + const chunksInOccurrenceOrder = [...chunks].sort((a, b) => { + if (prioritiseInitial) { + const aEntryOccurs = + /** @type {number} */ + (occursInInitialChunksMap.get(a)); + const bEntryOccurs = + /** @type {number} */ + (occursInInitialChunksMap.get(b)); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = a.getNumberOfGroups(); + const bOccurs = b.getNumberOfGroups(); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + return compareNatural(a, b); + }); + assignAscendingChunkIds(chunksInOccurrenceOrder, compilation); + }); + }); + } +} + +module.exports = OccurrenceChunkIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/OccurrenceModuleIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/OccurrenceModuleIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..45ce2b599d10a823cca5c9cc8a569b57b254a682 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/OccurrenceModuleIdsPlugin.js @@ -0,0 +1,161 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + compareModulesByPreOrderIndexOrIdentifier +} = require("../util/comparators"); +const createSchemaValidation = require("../util/create-schema-validation"); +const { + assignAscendingModuleIds, + getUsedModuleIdsAndModules +} = require("./IdHelpers"); + +/** @typedef {import("../../declarations/plugins/ids/OccurrenceModuleIdsPlugin").OccurrenceModuleIdsPluginOptions} OccurrenceModuleIdsPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/ids/OccurrenceModuleIdsPlugin.check"), + () => require("../../schemas/plugins/ids/OccurrenceModuleIdsPlugin.json"), + { + name: "Occurrence Order Module Ids Plugin", + baseDataPath: "options" + } +); + +const PLUGIN_NAME = "OccurrenceModuleIdsPlugin"; + +class OccurrenceModuleIdsPlugin { + /** + * @param {OccurrenceModuleIdsPluginOptions=} options options object + */ + constructor(options = {}) { + validate(options); + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const moduleGraph = compilation.moduleGraph; + + compilation.hooks.moduleIds.tap(PLUGIN_NAME, () => { + const chunkGraph = compilation.chunkGraph; + + const [usedIds, modulesInOccurrenceOrder] = + getUsedModuleIdsAndModules(compilation); + + const occursInInitialChunksMap = new Map(); + const occursInAllChunksMap = new Map(); + + const initialChunkChunkMap = new Map(); + const entryCountMap = new Map(); + for (const m of modulesInOccurrenceOrder) { + let initial = 0; + let entry = 0; + for (const c of chunkGraph.getModuleChunksIterable(m)) { + if (c.canBeInitial()) initial++; + if (chunkGraph.isEntryModuleInChunk(m, c)) entry++; + } + initialChunkChunkMap.set(m, initial); + entryCountMap.set(m, entry); + } + + /** + * @param {Module} module module + * @returns {number} count of occurs + */ + const countOccursInEntry = (module) => { + let sum = 0; + for (const [ + originModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!originModule) continue; + if (!connections.some((c) => c.isTargetActive(undefined))) continue; + sum += initialChunkChunkMap.get(originModule) || 0; + } + return sum; + }; + + /** + * @param {Module} module module + * @returns {number} count of occurs + */ + const countOccurs = (module) => { + let sum = 0; + for (const [ + originModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!originModule) continue; + const chunkModules = + chunkGraph.getNumberOfModuleChunks(originModule); + for (const c of connections) { + if (!c.isTargetActive(undefined)) continue; + if (!c.dependency) continue; + const factor = c.dependency.getNumberOfIdOccurrences(); + if (factor === 0) continue; + sum += factor * chunkModules; + } + } + return sum; + }; + + if (prioritiseInitial) { + for (const m of modulesInOccurrenceOrder) { + const result = + countOccursInEntry(m) + + initialChunkChunkMap.get(m) + + entryCountMap.get(m); + occursInInitialChunksMap.set(m, result); + } + } + + for (const m of modulesInOccurrenceOrder) { + const result = + countOccurs(m) + + chunkGraph.getNumberOfModuleChunks(m) + + entryCountMap.get(m); + occursInAllChunksMap.set(m, result); + } + + const naturalCompare = compareModulesByPreOrderIndexOrIdentifier( + compilation.moduleGraph + ); + + modulesInOccurrenceOrder.sort((a, b) => { + if (prioritiseInitial) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = occursInAllChunksMap.get(a); + const bOccurs = occursInAllChunksMap.get(b); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + return naturalCompare(a, b); + }); + + assignAscendingModuleIds( + usedIds, + modulesInOccurrenceOrder, + compilation + ); + }); + }); + } +} + +module.exports = OccurrenceModuleIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/SyncModuleIdsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/SyncModuleIdsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..6b667390447efa5dbf4c8efb31dd33068fc531fd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/ids/SyncModuleIdsPlugin.js @@ -0,0 +1,150 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { WebpackError } = require(".."); +const { getUsedModuleIdsAndModules } = require("./IdHelpers"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ + +const plugin = "SyncModuleIdsPlugin"; + +/** + * @typedef {object} SyncModuleIdsPluginOptions + * @property {string} path path to file + * @property {string=} context context for module names + * @property {((module: Module) => boolean)=} test selector for modules + * @property {"read" | "create" | "merge" | "update"=} mode operation mode (defaults to merge) + */ + +class SyncModuleIdsPlugin { + /** + * @param {SyncModuleIdsPluginOptions} options options + */ + constructor({ path, context, test, mode }) { + this._path = path; + this._context = context; + this._test = test || (() => true); + const readAndWrite = !mode || mode === "merge" || mode === "update"; + this._read = readAndWrite || mode === "read"; + this._write = readAndWrite || mode === "create"; + this._prune = mode === "update"; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + /** @type {Map} */ + let data; + let dataChanged = false; + if (this._read) { + compiler.hooks.readRecords.tapAsync(plugin, (callback) => { + const fs = + /** @type {IntermediateFileSystem} */ + (compiler.intermediateFileSystem); + fs.readFile(this._path, (err, buffer) => { + if (err) { + if (err.code !== "ENOENT") { + return callback(err); + } + return callback(); + } + const json = JSON.parse(/** @type {Buffer} */ (buffer).toString()); + data = new Map(); + for (const key of Object.keys(json)) { + data.set(key, json[key]); + } + dataChanged = false; + return callback(); + }); + }); + } + if (this._write) { + compiler.hooks.emitRecords.tapAsync(plugin, (callback) => { + if (!data || !dataChanged) return callback(); + /** @type {{[key: string]: string | number}} */ + const json = {}; + const sorted = [...data].sort(([a], [b]) => (a < b ? -1 : 1)); + for (const [key, value] of sorted) { + json[key] = value; + } + const fs = + /** @type {IntermediateFileSystem} */ + (compiler.intermediateFileSystem); + fs.writeFile(this._path, JSON.stringify(json), callback); + }); + } + compiler.hooks.thisCompilation.tap(plugin, (compilation) => { + const associatedObjectForCache = compiler.root; + const context = this._context || compiler.context; + if (this._read) { + compilation.hooks.reviveModules.tap(plugin, (_1, _2) => { + if (!data) return; + const { chunkGraph } = compilation; + const [usedIds, modules] = getUsedModuleIdsAndModules( + compilation, + this._test + ); + for (const module of modules) { + const name = module.libIdent({ + context, + associatedObjectForCache + }); + if (!name) continue; + const id = data.get(name); + const idAsString = `${id}`; + if (usedIds.has(idAsString)) { + const err = new WebpackError( + `SyncModuleIdsPlugin: Unable to restore id '${id}' from '${this._path}' as it's already used.` + ); + err.module = module; + compilation.errors.push(err); + } + chunkGraph.setModuleId(module, /** @type {string | number} */ (id)); + usedIds.add(idAsString); + } + }); + } + if (this._write) { + compilation.hooks.recordModules.tap(plugin, (modules) => { + const { chunkGraph } = compilation; + let oldData = data; + if (!oldData) { + oldData = data = new Map(); + } else if (this._prune) { + data = new Map(); + } + for (const module of modules) { + if (this._test(module)) { + const name = module.libIdent({ + context, + associatedObjectForCache + }); + if (!name) continue; + const id = chunkGraph.getModuleId(module); + if (id === null) continue; + const oldId = oldData.get(name); + if (oldId !== id) { + dataChanged = true; + } else if (data === oldData) { + continue; + } + data.set(name, id); + } + } + if (data.size !== oldData.size) dataChanged = true; + }); + } + }); + } +} + +module.exports = SyncModuleIdsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/index.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1188576a90ec5c71df33906f68d2f26d7620fed2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/index.js @@ -0,0 +1,674 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const memoize = require("./util/memoize"); + +/** @typedef {import("../declarations/WebpackOptions").Entry} Entry */ +/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} EntryNormalized */ +/** @typedef {import("../declarations/WebpackOptions").EntryObject} EntryObject */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItem} ExternalItem */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunction} ExternalItemFunction */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunctionCallback} ExternalItemFunctionCallback */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunctionData} ExternalItemFunctionData */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunctionDataGetResolve} ExternalItemFunctionDataGetResolve */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunctionDataGetResolveCallbackResult} ExternalItemFunctionDataGetResolveCallbackResult */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunctionDataGetResolveResult} ExternalItemFunctionDataGetResolveResult */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunctionPromise} ExternalItemFunctionPromise */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemObjectKnown} ExternalItemObjectKnown */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemObjectUnknown} ExternalItemObjectUnknown */ +/** @typedef {import("../declarations/WebpackOptions").ExternalItemValue} ExternalItemValue */ +/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ +/** @typedef {import("../declarations/WebpackOptions").FileCacheOptions} FileCacheOptions */ +/** @typedef {import("../declarations/WebpackOptions").GeneratorOptionsByModuleTypeKnown} GeneratorOptionsByModuleTypeKnown */ +/** @typedef {import("../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../declarations/WebpackOptions").MemoryCacheOptions} MemoryCacheOptions */ +/** @typedef {import("../declarations/WebpackOptions").ModuleOptions} ModuleOptions */ +/** @typedef {import("../declarations/WebpackOptions").ParserOptionsByModuleTypeKnown} ParserOptionsByModuleTypeKnown */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetCondition} RuleSetCondition */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetConditionAbsolute} RuleSetConditionAbsolute */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetUse} RuleSetUse */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetUseFunction} RuleSetUseFunction */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetUseItem} RuleSetUseItem */ +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} Configuration */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Compilation").Asset} Asset */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").EntryOptions} EntryOptions */ +/** @typedef {import("./Compilation").PathData} PathData */ +/** @typedef {import("./Compiler").AssetEmittedInfo} AssetEmittedInfo */ +/** @typedef {import("./Entrypoint")} Entrypoint */ +/** @typedef {import("./MultiCompiler").MultiCompilerOptions} MultiCompilerOptions */ +/** @typedef {import("./MultiCompiler").MultiWebpackOptions} MultiConfiguration */ +/** @typedef {import("./MultiStats")} MultiStats */ +/** @typedef {import("./MultiStats").MultiStatsOptions} MultiStatsOptions */ +/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */ +/** @typedef {import("./Parser").ParserState} ParserState */ +/** @typedef {import("./ResolverFactory").ResolvePluginInstance} ResolvePluginInstance */ +/** @typedef {import("./ResolverFactory").Resolver} Resolver */ +/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */ +/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */ +/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("./Watching")} Watching */ +/** @typedef {import("./cli").Argument} Argument */ +/** @typedef {import("./cli").Problem} Problem */ +/** @typedef {import("./cli").Colors} Colors */ +/** @typedef {import("./cli").ColorsOptions} ColorsOptions */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkOrigin} StatsChunkOrigin */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLogging} StatsLogging */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLoggingEntry} StatsLoggingEntry */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleIssuer} StatsModuleIssuer */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceDependency} StatsModuleTraceDependency */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceItem} StatsModuleTraceItem */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsProfile} StatsProfile */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ + +/** + * @template {EXPECTED_FUNCTION} T + * @param {() => T} factory factory function + * @returns {T} function + */ +const lazyFunction = (factory) => { + const fac = memoize(factory); + const f = /** @type {unknown} */ ( + /** + * @param {...EXPECTED_ANY} args args + * @returns {T} result + */ + (...args) => fac()(...args) + ); + return /** @type {T} */ (f); +}; + +/** + * @template A + * @template B + * @param {A} obj input a + * @param {B} exports input b + * @returns {A & B} merged + */ +const mergeExports = (obj, exports) => { + const descriptors = Object.getOwnPropertyDescriptors(exports); + for (const name of Object.keys(descriptors)) { + const descriptor = descriptors[name]; + if (descriptor.get) { + const fn = descriptor.get; + Object.defineProperty(obj, name, { + configurable: false, + enumerable: true, + get: memoize(fn) + }); + } else if (typeof descriptor.value === "object") { + Object.defineProperty(obj, name, { + configurable: false, + enumerable: true, + writable: false, + value: mergeExports({}, descriptor.value) + }); + } else { + throw new Error( + "Exposed values must be either a getter or an nested object" + ); + } + } + return /** @type {A & B} */ (Object.freeze(obj)); +}; + +const fn = lazyFunction(() => require("./webpack")); + +module.exports = mergeExports(fn, { + get webpack() { + return require("./webpack"); + }, + /** + * @returns {(configuration: Configuration | MultiConfiguration) => void} validate fn + */ + get validate() { + const webpackOptionsSchemaCheck = + /** @type {(configuration: Configuration | MultiConfiguration) => boolean} */ + (require("../schemas/WebpackOptions.check")); + + const getRealValidate = memoize( + /** + * @returns {(configuration: Configuration | MultiConfiguration) => void} validate fn + */ + () => { + const validateSchema = require("./validateSchema"); + const webpackOptionsSchema = require("../schemas/WebpackOptions.json"); + + return (options) => validateSchema(webpackOptionsSchema, options); + } + ); + return (options) => { + if (!webpackOptionsSchemaCheck(options)) { + getRealValidate()(options); + } + }; + }, + get validateSchema() { + const validateSchema = require("./validateSchema"); + + return validateSchema; + }, + get version() { + return /** @type {string} */ (require("../package.json").version); + }, + + get cli() { + return require("./cli"); + }, + get AutomaticPrefetchPlugin() { + return require("./AutomaticPrefetchPlugin"); + }, + get AsyncDependenciesBlock() { + return require("./AsyncDependenciesBlock"); + }, + get BannerPlugin() { + return require("./BannerPlugin"); + }, + get Cache() { + return require("./Cache"); + }, + get Chunk() { + return require("./Chunk"); + }, + get ChunkGraph() { + return require("./ChunkGraph"); + }, + get CleanPlugin() { + return require("./CleanPlugin"); + }, + get Compilation() { + return require("./Compilation"); + }, + get Compiler() { + return require("./Compiler"); + }, + get ConcatenationScope() { + return require("./ConcatenationScope"); + }, + get ContextExclusionPlugin() { + return require("./ContextExclusionPlugin"); + }, + get ContextReplacementPlugin() { + return require("./ContextReplacementPlugin"); + }, + get DefinePlugin() { + return require("./DefinePlugin"); + }, + get DelegatedPlugin() { + return require("./DelegatedPlugin"); + }, + get Dependency() { + return require("./Dependency"); + }, + get DllPlugin() { + return require("./DllPlugin"); + }, + get DllReferencePlugin() { + return require("./DllReferencePlugin"); + }, + get DynamicEntryPlugin() { + return require("./DynamicEntryPlugin"); + }, + get EntryOptionPlugin() { + return require("./EntryOptionPlugin"); + }, + get EntryPlugin() { + return require("./EntryPlugin"); + }, + get EnvironmentPlugin() { + return require("./EnvironmentPlugin"); + }, + get EvalDevToolModulePlugin() { + return require("./EvalDevToolModulePlugin"); + }, + get EvalSourceMapDevToolPlugin() { + return require("./EvalSourceMapDevToolPlugin"); + }, + get ExternalModule() { + return require("./ExternalModule"); + }, + get ExternalsPlugin() { + return require("./ExternalsPlugin"); + }, + get Generator() { + return require("./Generator"); + }, + get HotUpdateChunk() { + return require("./HotUpdateChunk"); + }, + get HotModuleReplacementPlugin() { + return require("./HotModuleReplacementPlugin"); + }, + get InitFragment() { + return require("./InitFragment"); + }, + get IgnorePlugin() { + return require("./IgnorePlugin"); + }, + get JavascriptModulesPlugin() { + return util.deprecate( + () => require("./javascript/JavascriptModulesPlugin"), + "webpack.JavascriptModulesPlugin has moved to webpack.javascript.JavascriptModulesPlugin", + "DEP_WEBPACK_JAVASCRIPT_MODULES_PLUGIN" + )(); + }, + get LibManifestPlugin() { + return require("./LibManifestPlugin"); + }, + get LibraryTemplatePlugin() { + return util.deprecate( + () => require("./LibraryTemplatePlugin"), + "webpack.LibraryTemplatePlugin is deprecated and has been replaced by compilation.outputOptions.library or compilation.addEntry + passing a library option", + "DEP_WEBPACK_LIBRARY_TEMPLATE_PLUGIN" + )(); + }, + get LoaderOptionsPlugin() { + return require("./LoaderOptionsPlugin"); + }, + get LoaderTargetPlugin() { + return require("./LoaderTargetPlugin"); + }, + get Module() { + return require("./Module"); + }, + get ModuleFactory() { + return require("./ModuleFactory"); + }, + get ModuleFilenameHelpers() { + return require("./ModuleFilenameHelpers"); + }, + get ModuleGraph() { + return require("./ModuleGraph"); + }, + get ModuleGraphConnection() { + return require("./ModuleGraphConnection"); + }, + get NoEmitOnErrorsPlugin() { + return require("./NoEmitOnErrorsPlugin"); + }, + get NormalModule() { + return require("./NormalModule"); + }, + get NormalModuleReplacementPlugin() { + return require("./NormalModuleReplacementPlugin"); + }, + get MultiCompiler() { + return require("./MultiCompiler"); + }, + get OptimizationStages() { + return require("./OptimizationStages"); + }, + get Parser() { + return require("./Parser"); + }, + get PlatformPlugin() { + return require("./PlatformPlugin"); + }, + get PrefetchPlugin() { + return require("./PrefetchPlugin"); + }, + get ProgressPlugin() { + return require("./ProgressPlugin"); + }, + get ProvidePlugin() { + return require("./ProvidePlugin"); + }, + get RuntimeGlobals() { + return require("./RuntimeGlobals"); + }, + get RuntimeModule() { + return require("./RuntimeModule"); + }, + get SingleEntryPlugin() { + return util.deprecate( + () => require("./EntryPlugin"), + "SingleEntryPlugin was renamed to EntryPlugin", + "DEP_WEBPACK_SINGLE_ENTRY_PLUGIN" + )(); + }, + get SourceMapDevToolPlugin() { + return require("./SourceMapDevToolPlugin"); + }, + get Stats() { + return require("./Stats"); + }, + get Template() { + return require("./Template"); + }, + get UsageState() { + return require("./ExportsInfo").UsageState; + }, + get WatchIgnorePlugin() { + return require("./WatchIgnorePlugin"); + }, + get WebpackError() { + return require("./WebpackError"); + }, + get WebpackOptionsApply() { + return require("./WebpackOptionsApply"); + }, + get WebpackOptionsDefaulter() { + return util.deprecate( + () => require("./WebpackOptionsDefaulter"), + "webpack.WebpackOptionsDefaulter is deprecated and has been replaced by webpack.config.getNormalizedWebpackOptions and webpack.config.applyWebpackOptionsDefaults", + "DEP_WEBPACK_OPTIONS_DEFAULTER" + )(); + }, + // TODO webpack 6 deprecate + get WebpackOptionsValidationError() { + return require("schema-utils").ValidationError; + }, + get ValidationError() { + return require("schema-utils").ValidationError; + }, + + cache: { + get MemoryCachePlugin() { + return require("./cache/MemoryCachePlugin"); + } + }, + + config: { + get getNormalizedWebpackOptions() { + return require("./config/normalization").getNormalizedWebpackOptions; + }, + get applyWebpackOptionsDefaults() { + return require("./config/defaults").applyWebpackOptionsDefaults; + } + }, + + dependencies: { + get ModuleDependency() { + return require("./dependencies/ModuleDependency"); + }, + get HarmonyImportDependency() { + return require("./dependencies/HarmonyImportDependency"); + }, + get ConstDependency() { + return require("./dependencies/ConstDependency"); + }, + get NullDependency() { + return require("./dependencies/NullDependency"); + } + }, + + ids: { + get ChunkModuleIdRangePlugin() { + return require("./ids/ChunkModuleIdRangePlugin"); + }, + get NaturalModuleIdsPlugin() { + return require("./ids/NaturalModuleIdsPlugin"); + }, + get OccurrenceModuleIdsPlugin() { + return require("./ids/OccurrenceModuleIdsPlugin"); + }, + get NamedModuleIdsPlugin() { + return require("./ids/NamedModuleIdsPlugin"); + }, + get DeterministicChunkIdsPlugin() { + return require("./ids/DeterministicChunkIdsPlugin"); + }, + get DeterministicModuleIdsPlugin() { + return require("./ids/DeterministicModuleIdsPlugin"); + }, + get NamedChunkIdsPlugin() { + return require("./ids/NamedChunkIdsPlugin"); + }, + get OccurrenceChunkIdsPlugin() { + return require("./ids/OccurrenceChunkIdsPlugin"); + }, + get HashedModuleIdsPlugin() { + return require("./ids/HashedModuleIdsPlugin"); + } + }, + + javascript: { + get EnableChunkLoadingPlugin() { + return require("./javascript/EnableChunkLoadingPlugin"); + }, + get JavascriptModulesPlugin() { + return require("./javascript/JavascriptModulesPlugin"); + }, + get JavascriptParser() { + return require("./javascript/JavascriptParser"); + } + }, + + optimize: { + get AggressiveMergingPlugin() { + return require("./optimize/AggressiveMergingPlugin"); + }, + get AggressiveSplittingPlugin() { + return util.deprecate( + () => require("./optimize/AggressiveSplittingPlugin"), + "AggressiveSplittingPlugin is deprecated in favor of SplitChunksPlugin", + "DEP_WEBPACK_AGGRESSIVE_SPLITTING_PLUGIN" + )(); + }, + get InnerGraph() { + return require("./optimize/InnerGraph"); + }, + get LimitChunkCountPlugin() { + return require("./optimize/LimitChunkCountPlugin"); + }, + get MergeDuplicateChunksPlugin() { + return require("./optimize/MergeDuplicateChunksPlugin"); + }, + get MinChunkSizePlugin() { + return require("./optimize/MinChunkSizePlugin"); + }, + get ModuleConcatenationPlugin() { + return require("./optimize/ModuleConcatenationPlugin"); + }, + get RealContentHashPlugin() { + return require("./optimize/RealContentHashPlugin"); + }, + get RuntimeChunkPlugin() { + return require("./optimize/RuntimeChunkPlugin"); + }, + get SideEffectsFlagPlugin() { + return require("./optimize/SideEffectsFlagPlugin"); + }, + get SplitChunksPlugin() { + return require("./optimize/SplitChunksPlugin"); + } + }, + + runtime: { + get GetChunkFilenameRuntimeModule() { + return require("./runtime/GetChunkFilenameRuntimeModule"); + }, + get LoadScriptRuntimeModule() { + return require("./runtime/LoadScriptRuntimeModule"); + } + }, + + prefetch: { + get ChunkPrefetchPreloadPlugin() { + return require("./prefetch/ChunkPrefetchPreloadPlugin"); + } + }, + + web: { + get FetchCompileWasmPlugin() { + return require("./web/FetchCompileWasmPlugin"); + }, + get FetchCompileAsyncWasmPlugin() { + return require("./web/FetchCompileAsyncWasmPlugin"); + }, + get JsonpChunkLoadingRuntimeModule() { + return require("./web/JsonpChunkLoadingRuntimeModule"); + }, + get JsonpTemplatePlugin() { + return require("./web/JsonpTemplatePlugin"); + }, + get CssLoadingRuntimeModule() { + return require("./css/CssLoadingRuntimeModule"); + } + }, + + esm: { + get ModuleChunkLoadingRuntimeModule() { + return require("./esm/ModuleChunkLoadingRuntimeModule"); + } + }, + + webworker: { + get WebWorkerTemplatePlugin() { + return require("./webworker/WebWorkerTemplatePlugin"); + } + }, + + node: { + get NodeEnvironmentPlugin() { + return require("./node/NodeEnvironmentPlugin"); + }, + get NodeSourcePlugin() { + return require("./node/NodeSourcePlugin"); + }, + get NodeTargetPlugin() { + return require("./node/NodeTargetPlugin"); + }, + get NodeTemplatePlugin() { + return require("./node/NodeTemplatePlugin"); + }, + get ReadFileCompileWasmPlugin() { + return require("./node/ReadFileCompileWasmPlugin"); + }, + get ReadFileCompileAsyncWasmPlugin() { + return require("./node/ReadFileCompileAsyncWasmPlugin"); + } + }, + + electron: { + get ElectronTargetPlugin() { + return require("./electron/ElectronTargetPlugin"); + } + }, + + wasm: { + get AsyncWebAssemblyModulesPlugin() { + return require("./wasm-async/AsyncWebAssemblyModulesPlugin"); + }, + get EnableWasmLoadingPlugin() { + return require("./wasm/EnableWasmLoadingPlugin"); + } + }, + + css: { + get CssModulesPlugin() { + return require("./css/CssModulesPlugin"); + } + }, + + library: { + get AbstractLibraryPlugin() { + return require("./library/AbstractLibraryPlugin"); + }, + get EnableLibraryPlugin() { + return require("./library/EnableLibraryPlugin"); + } + }, + + container: { + get ContainerPlugin() { + return require("./container/ContainerPlugin"); + }, + get ContainerReferencePlugin() { + return require("./container/ContainerReferencePlugin"); + }, + get ModuleFederationPlugin() { + return require("./container/ModuleFederationPlugin"); + }, + get scope() { + return require("./container/options").scope; + } + }, + + sharing: { + get ConsumeSharedPlugin() { + return require("./sharing/ConsumeSharedPlugin"); + }, + get ProvideSharedPlugin() { + return require("./sharing/ProvideSharedPlugin"); + }, + get SharePlugin() { + return require("./sharing/SharePlugin"); + }, + get scope() { + return require("./container/options").scope; + } + }, + + debug: { + get ProfilingPlugin() { + return require("./debug/ProfilingPlugin"); + } + }, + + util: { + get createHash() { + return require("./util/createHash"); + }, + get comparators() { + return require("./util/comparators"); + }, + get runtime() { + return require("./util/runtime"); + }, + get serialization() { + return require("./util/serialization"); + }, + get cleverMerge() { + return require("./util/cleverMerge").cachedCleverMerge; + }, + get LazySet() { + return require("./util/LazySet"); + }, + get compileBooleanMatcher() { + return require("./util/compileBooleanMatcher"); + } + }, + + get sources() { + return require("webpack-sources"); + }, + + experiments: { + schemes: { + get HttpUriPlugin() { + return require("./schemes/HttpUriPlugin"); + }, + get VirtualUrlPlugin() { + return require("./schemes/VirtualUrlPlugin"); + } + }, + ids: { + get SyncModuleIdsPlugin() { + return require("./ids/SyncModuleIdsPlugin"); + } + } + } +}); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..c9b68c38a6cafe6bd8e2eef5ab6bc864cc068c26 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js @@ -0,0 +1,150 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource, PrefixSource, RawSource } = require("webpack-sources"); +const { RuntimeGlobals } = require(".."); +const HotUpdateChunk = require("../HotUpdateChunk"); +const Template = require("../Template"); +const { getCompilationHooks } = require("./JavascriptModulesPlugin"); +const { + generateEntryStartup, + updateHashForEntryStartup +} = require("./StartupHelpers"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../ChunkGraph").EntryModuleWithChunkGroup} EntryModuleWithChunkGroup */ + +const PLUGIN_NAME = "ArrayPushCallbackChunkFormatPlugin"; + +class ArrayPushCallbackChunkFormatPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set, { chunkGraph }) => { + if (chunk.hasRuntime()) return; + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { + set.add(RuntimeGlobals.onChunksLoaded); + set.add(RuntimeGlobals.exports); + set.add(RuntimeGlobals.require); + } + set.add(RuntimeGlobals.chunkCallback); + } + ); + const hooks = getCompilationHooks(compilation); + hooks.renderChunk.tap(PLUGIN_NAME, (modules, renderContext) => { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + const hotUpdateChunk = chunk instanceof HotUpdateChunk ? chunk : null; + const globalObject = runtimeTemplate.globalObject; + const source = new ConcatSource(); + const runtimeModules = chunkGraph.getChunkRuntimeModulesInOrder(chunk); + if (hotUpdateChunk) { + const hotUpdateGlobal = runtimeTemplate.outputOptions.hotUpdateGlobal; + source.add(`${globalObject}[${JSON.stringify(hotUpdateGlobal)}](`); + source.add(`${JSON.stringify(chunk.id)},`); + source.add(modules); + if (runtimeModules.length > 0) { + source.add(",\n"); + const runtimePart = Template.renderChunkRuntimeModules( + runtimeModules, + renderContext + ); + source.add(runtimePart); + } + source.add(")"); + } else { + const chunkLoadingGlobal = + runtimeTemplate.outputOptions.chunkLoadingGlobal; + source.add( + `(${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}] = ${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}] || []).push([` + ); + source.add(`${JSON.stringify(chunk.ids)},`); + source.add(modules); + /** @type {EntryModuleWithChunkGroup[]} */ + const entries = [ + ...chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ]; + if (runtimeModules.length > 0 || entries.length > 0) { + const runtime = new ConcatSource( + `${ + runtimeTemplate.supportsArrowFunction() + ? `${RuntimeGlobals.require} =>` + : `function(${RuntimeGlobals.require})` + } { // webpackRuntimeModules\n` + ); + if (runtimeModules.length > 0) { + runtime.add( + Template.renderRuntimeModules(runtimeModules, { + ...renderContext, + codeGenerationResults: compilation.codeGenerationResults + }) + ); + } + if (entries.length > 0) { + const startupSource = new RawSource( + generateEntryStartup( + chunkGraph, + runtimeTemplate, + entries, + chunk, + true + ) + ); + runtime.add( + hooks.renderStartup.call( + startupSource, + entries[entries.length - 1][0], + { + ...renderContext, + inlined: false + } + ) + ); + if ( + chunkGraph + .getChunkRuntimeRequirements(chunk) + .has(RuntimeGlobals.returnExportsFromRuntime) + ) { + runtime.add(`return ${RuntimeGlobals.exports};\n`); + } + } + runtime.add("}\n"); + source.add(",\n"); + source.add(new PrefixSource("/******/ ", runtime)); + } + source.add("])"); + } + return source; + }); + hooks.chunkHash.tap( + PLUGIN_NAME, + (chunk, hash, { chunkGraph, runtimeTemplate }) => { + if (chunk.hasRuntime()) return; + hash.update( + `${PLUGIN_NAME}1${runtimeTemplate.outputOptions.chunkLoadingGlobal}${runtimeTemplate.outputOptions.hotUpdateGlobal}${runtimeTemplate.globalObject}` + ); + /** @type {EntryModuleWithChunkGroup[]} */ + const entries = [ + ...chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ]; + updateHashForEntryStartup(hash, chunkGraph, entries, chunk); + } + ); + }); + } +} + +module.exports = ArrayPushCallbackChunkFormatPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/BasicEvaluatedExpression.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/BasicEvaluatedExpression.js new file mode 100644 index 0000000000000000000000000000000000000000..2318c8f91fb02be0c94d3cbe624686af0ab2ce02 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/BasicEvaluatedExpression.js @@ -0,0 +1,595 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("./JavascriptParser").Range} Range */ +/** @typedef {import("./JavascriptParser").VariableInfo} VariableInfo */ + +const TypeUnknown = 0; +const TypeUndefined = 1; +const TypeNull = 2; +const TypeString = 3; +const TypeNumber = 4; +const TypeBoolean = 5; +const TypeRegExp = 6; +const TypeConditional = 7; +const TypeArray = 8; +const TypeConstArray = 9; +const TypeIdentifier = 10; +const TypeWrapped = 11; +const TypeTemplateString = 12; +const TypeBigInt = 13; + +class BasicEvaluatedExpression { + constructor() { + this.type = TypeUnknown; + /** @type {Range | undefined} */ + this.range = undefined; + /** @type {boolean} */ + this.falsy = false; + /** @type {boolean} */ + this.truthy = false; + /** @type {boolean | undefined} */ + this.nullish = undefined; + /** @type {boolean} */ + this.sideEffects = true; + /** @type {boolean | undefined} */ + this.bool = undefined; + /** @type {number | undefined} */ + this.number = undefined; + /** @type {bigint | undefined} */ + this.bigint = undefined; + /** @type {RegExp | undefined} */ + this.regExp = undefined; + /** @type {string | undefined} */ + this.string = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.quasis = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.parts = undefined; + /** @type {EXPECTED_ANY[] | undefined} */ + this.array = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.items = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.options = undefined; + /** @type {BasicEvaluatedExpression | undefined | null} */ + this.prefix = undefined; + /** @type {BasicEvaluatedExpression | undefined | null} */ + this.postfix = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.wrappedInnerExpressions = undefined; + /** @type {string | VariableInfo | undefined} */ + this.identifier = undefined; + /** @type {string | VariableInfo | undefined} */ + this.rootInfo = undefined; + /** @type {(() => string[]) | undefined} */ + this.getMembers = undefined; + /** @type {(() => boolean[]) | undefined} */ + this.getMembersOptionals = undefined; + /** @type {(() => Range[]) | undefined} */ + this.getMemberRanges = undefined; + /** @type {Node | undefined} */ + this.expression = undefined; + } + + isUnknown() { + return this.type === TypeUnknown; + } + + isNull() { + return this.type === TypeNull; + } + + isUndefined() { + return this.type === TypeUndefined; + } + + isString() { + return this.type === TypeString; + } + + isNumber() { + return this.type === TypeNumber; + } + + isBigInt() { + return this.type === TypeBigInt; + } + + isBoolean() { + return this.type === TypeBoolean; + } + + isRegExp() { + return this.type === TypeRegExp; + } + + isConditional() { + return this.type === TypeConditional; + } + + isArray() { + return this.type === TypeArray; + } + + isConstArray() { + return this.type === TypeConstArray; + } + + isIdentifier() { + return this.type === TypeIdentifier; + } + + isWrapped() { + return this.type === TypeWrapped; + } + + isTemplateString() { + return this.type === TypeTemplateString; + } + + /** + * Is expression a primitive or an object type value? + * @returns {boolean | undefined} true: primitive type, false: object type, undefined: unknown/runtime-defined + */ + isPrimitiveType() { + switch (this.type) { + case TypeUndefined: + case TypeNull: + case TypeString: + case TypeNumber: + case TypeBoolean: + case TypeBigInt: + case TypeWrapped: + case TypeTemplateString: + return true; + case TypeRegExp: + case TypeArray: + case TypeConstArray: + return false; + default: + return undefined; + } + } + + /** + * Is expression a runtime or compile-time value? + * @returns {boolean} true: compile time value, false: runtime value + */ + isCompileTimeValue() { + switch (this.type) { + case TypeUndefined: + case TypeNull: + case TypeString: + case TypeNumber: + case TypeBoolean: + case TypeRegExp: + case TypeConstArray: + case TypeBigInt: + return true; + default: + return false; + } + } + + /** + * Gets the compile-time value of the expression + * @returns {undefined | null | string | number | boolean | RegExp | EXPECTED_ANY[] | bigint} the javascript value + */ + asCompileTimeValue() { + switch (this.type) { + case TypeUndefined: + return; + case TypeNull: + return null; + case TypeString: + return this.string; + case TypeNumber: + return this.number; + case TypeBoolean: + return this.bool; + case TypeRegExp: + return this.regExp; + case TypeConstArray: + return this.array; + case TypeBigInt: + return this.bigint; + default: + throw new Error( + "asCompileTimeValue must only be called for compile-time values" + ); + } + } + + isTruthy() { + return this.truthy; + } + + isFalsy() { + return this.falsy; + } + + isNullish() { + return this.nullish; + } + + /** + * Can this expression have side effects? + * @returns {boolean} false: never has side effects + */ + couldHaveSideEffects() { + return this.sideEffects; + } + + /** + * Creates a boolean representation of this evaluated expression. + * @returns {boolean | undefined} true: truthy, false: falsy, undefined: unknown + */ + asBool() { + if (this.truthy) return true; + if (this.falsy || this.nullish) return false; + if (this.isBoolean()) return this.bool; + if (this.isNull()) return false; + if (this.isUndefined()) return false; + if (this.isString()) return this.string !== ""; + if (this.isNumber()) return this.number !== 0; + if (this.isBigInt()) return this.bigint !== BigInt(0); + if (this.isRegExp()) return true; + if (this.isArray()) return true; + if (this.isConstArray()) return true; + if (this.isWrapped()) { + return (this.prefix && this.prefix.asBool()) || + (this.postfix && this.postfix.asBool()) + ? true + : undefined; + } + if (this.isTemplateString()) { + const str = this.asString(); + if (typeof str === "string") return str !== ""; + } + } + + /** + * Creates a nullish coalescing representation of this evaluated expression. + * @returns {boolean | undefined} true: nullish, false: not nullish, undefined: unknown + */ + asNullish() { + const nullish = this.isNullish(); + + if (nullish === true || this.isNull() || this.isUndefined()) return true; + + if (nullish === false) return false; + if (this.isTruthy()) return false; + if (this.isBoolean()) return false; + if (this.isString()) return false; + if (this.isNumber()) return false; + if (this.isBigInt()) return false; + if (this.isRegExp()) return false; + if (this.isArray()) return false; + if (this.isConstArray()) return false; + if (this.isTemplateString()) return false; + if (this.isRegExp()) return false; + } + + /** + * Creates a string representation of this evaluated expression. + * @returns {string | undefined} the string representation or undefined if not possible + */ + asString() { + if (this.isBoolean()) return `${this.bool}`; + if (this.isNull()) return "null"; + if (this.isUndefined()) return "undefined"; + if (this.isString()) return this.string; + if (this.isNumber()) return `${this.number}`; + if (this.isBigInt()) return `${this.bigint}`; + if (this.isRegExp()) return `${this.regExp}`; + if (this.isArray()) { + const array = []; + for (const item of /** @type {BasicEvaluatedExpression[]} */ ( + this.items + )) { + const itemStr = item.asString(); + if (itemStr === undefined) return; + array.push(itemStr); + } + return `${array}`; + } + if (this.isConstArray()) return `${this.array}`; + if (this.isTemplateString()) { + let str = ""; + for (const part of /** @type {BasicEvaluatedExpression[]} */ ( + this.parts + )) { + const partStr = part.asString(); + if (partStr === undefined) return; + str += partStr; + } + return str; + } + } + + /** + * @param {string} string value + * @returns {BasicEvaluatedExpression} basic evaluated expression + */ + setString(string) { + this.type = TypeString; + this.string = string; + this.sideEffects = false; + return this; + } + + setUndefined() { + this.type = TypeUndefined; + this.sideEffects = false; + return this; + } + + setNull() { + this.type = TypeNull; + this.sideEffects = false; + return this; + } + + /** + * Set's the value of this expression to a number + * @param {number} number number to set + * @returns {this} this + */ + setNumber(number) { + this.type = TypeNumber; + this.number = number; + this.sideEffects = false; + return this; + } + + /** + * Set's the value of this expression to a BigInt + * @param {bigint} bigint bigint to set + * @returns {this} this + */ + setBigInt(bigint) { + this.type = TypeBigInt; + this.bigint = bigint; + this.sideEffects = false; + return this; + } + + /** + * Set's the value of this expression to a boolean + * @param {boolean} bool boolean to set + * @returns {this} this + */ + setBoolean(bool) { + this.type = TypeBoolean; + this.bool = bool; + this.sideEffects = false; + return this; + } + + /** + * Set's the value of this expression to a regular expression + * @param {RegExp} regExp regular expression to set + * @returns {this} this + */ + setRegExp(regExp) { + this.type = TypeRegExp; + this.regExp = regExp; + this.sideEffects = false; + return this; + } + + /** + * Set's the value of this expression to a particular identifier and its members. + * @param {string | VariableInfo} identifier identifier to set + * @param {string | VariableInfo} rootInfo root info + * @param {() => string[]} getMembers members + * @param {() => boolean[]=} getMembersOptionals optional members + * @param {() => Range[]=} getMemberRanges ranges of progressively increasing sub-expressions + * @returns {this} this + */ + setIdentifier( + identifier, + rootInfo, + getMembers, + getMembersOptionals, + getMemberRanges + ) { + this.type = TypeIdentifier; + this.identifier = identifier; + this.rootInfo = rootInfo; + this.getMembers = getMembers; + this.getMembersOptionals = getMembersOptionals; + this.getMemberRanges = getMemberRanges; + this.sideEffects = true; + return this; + } + + /** + * Wraps an array of expressions with a prefix and postfix expression. + * @param {BasicEvaluatedExpression | null | undefined} prefix Expression to be added before the innerExpressions + * @param {BasicEvaluatedExpression | null | undefined} postfix Expression to be added after the innerExpressions + * @param {BasicEvaluatedExpression[] | undefined} innerExpressions Expressions to be wrapped + * @returns {this} this + */ + setWrapped(prefix, postfix, innerExpressions) { + this.type = TypeWrapped; + this.prefix = prefix; + this.postfix = postfix; + this.wrappedInnerExpressions = innerExpressions; + this.sideEffects = true; + return this; + } + + /** + * Stores the options of a conditional expression. + * @param {BasicEvaluatedExpression[]} options optional (consequent/alternate) expressions to be set + * @returns {this} this + */ + setOptions(options) { + this.type = TypeConditional; + this.options = options; + this.sideEffects = true; + return this; + } + + /** + * Adds options to a conditional expression. + * @param {BasicEvaluatedExpression[]} options optional (consequent/alternate) expressions to be added + * @returns {this} this + */ + addOptions(options) { + if (!this.options) { + this.type = TypeConditional; + this.options = []; + this.sideEffects = true; + } + for (const item of options) { + this.options.push(item); + } + return this; + } + + /** + * Set's the value of this expression to an array of expressions. + * @param {BasicEvaluatedExpression[]} items expressions to set + * @returns {this} this + */ + setItems(items) { + this.type = TypeArray; + this.items = items; + this.sideEffects = items.some((i) => i.couldHaveSideEffects()); + return this; + } + + /** + * Set's the value of this expression to an array of strings. + * @param {string[]} array array to set + * @returns {this} this + */ + setArray(array) { + this.type = TypeConstArray; + this.array = array; + this.sideEffects = false; + return this; + } + + /** + * Set's the value of this expression to a processed/unprocessed template string. Used + * for evaluating TemplateLiteral expressions in the JavaScript Parser. + * @param {BasicEvaluatedExpression[]} quasis template string quasis + * @param {BasicEvaluatedExpression[]} parts template string parts + * @param {"cooked" | "raw"} kind template string kind + * @returns {this} this + */ + setTemplateString(quasis, parts, kind) { + this.type = TypeTemplateString; + this.quasis = quasis; + this.parts = parts; + this.templateStringKind = kind; + this.sideEffects = parts.some((p) => p.sideEffects); + return this; + } + + setTruthy() { + this.falsy = false; + this.truthy = true; + this.nullish = false; + return this; + } + + setFalsy() { + this.falsy = true; + this.truthy = false; + return this; + } + + /** + * Set's the value of the expression to nullish. + * @param {boolean} value true, if the expression is nullish + * @returns {this} this + */ + setNullish(value) { + this.nullish = value; + + if (value) return this.setFalsy(); + + return this; + } + + /** + * Set's the range for the expression. + * @param {Range} range range to set + * @returns {this} this + */ + setRange(range) { + this.range = range; + return this; + } + + /** + * Set whether or not the expression has side effects. + * @param {boolean} sideEffects true, if the expression has side effects + * @returns {this} this + */ + setSideEffects(sideEffects = true) { + this.sideEffects = sideEffects; + return this; + } + + /** + * Set the expression node for the expression. + * @param {Node | undefined} expression expression + * @returns {this} this + */ + setExpression(expression) { + this.expression = expression; + return this; + } +} + +/** + * @param {string} flags regexp flags + * @returns {boolean} is valid flags + */ +BasicEvaluatedExpression.isValidRegExpFlags = (flags) => { + const len = flags.length; + + if (len === 0) return true; + if (len > 4) return false; + + // cspell:word gimy + let remaining = 0b0000; // bit per RegExp flag: gimy + + for (let i = 0; i < len; i++) { + switch (flags.charCodeAt(i)) { + case 103 /* g */: + if (remaining & 0b1000) return false; + remaining |= 0b1000; + break; + case 105 /* i */: + if (remaining & 0b0100) return false; + remaining |= 0b0100; + break; + case 109 /* m */: + if (remaining & 0b0010) return false; + remaining |= 0b0010; + break; + case 121 /* y */: + if (remaining & 0b0001) return false; + remaining |= 0b0001; + break; + default: + return false; + } + } + + return true; +}; + +module.exports = BasicEvaluatedExpression; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/ChunkFormatHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/ChunkFormatHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..24b05a9dd94969d7117c615cfcfb3054450c737a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/ChunkFormatHelpers.js @@ -0,0 +1,70 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx +*/ + +"use strict"; + +const { updateHashForEntryStartup } = require("./StartupHelpers"); + +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ + +/** + * Gets information about a chunk including its entries and runtime chunk + * @param {Chunk} chunk The chunk to get information for + * @param {ChunkGraph} chunkGraph The chunk graph containing the chunk + * @returns {{entries: Array<[Module, Entrypoint | undefined]>, runtimeChunk: Chunk|null}} Object containing chunk entries and runtime chunk + */ +function getChunkInfo(chunk, chunkGraph) { + const entries = [ + ...chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ]; + const runtimeChunk = + entries.length > 0 + ? /** @type {Entrypoint[][]} */ + (entries)[0][1].getRuntimeChunk() + : null; + + return { + entries, + runtimeChunk + }; +} + +/** + * Creates a chunk hash handler + * @param {string} name The name of the chunk + * @returns {(chunk: Chunk, hash: Hash, { chunkGraph }: ChunkHashContext) => void} The chunk hash handler + */ +function createChunkHashHandler(name) { + /** + * @param {Chunk} chunk The chunk to get information for + * @param {Hash} hash The hash to update + * @param {ChunkHashContext} chunkHashContext The chunk hash context + * @returns {void} + */ + return (chunk, hash, { chunkGraph }) => { + if (chunk.hasRuntime()) return; + const { entries, runtimeChunk } = getChunkInfo(chunk, chunkGraph); + hash.update(name); + hash.update("1"); + if (runtimeChunk && runtimeChunk.hash) { + // https://github.com/webpack/webpack/issues/19439 + // Any change to runtimeChunk should trigger a hash update, + // we shouldn't depend on or inspect its internal implementation. + // import __webpack_require__ from "./runtime-main.e9400aee33633a3973bd.js"; + hash.update(runtimeChunk.hash); + } + updateHashForEntryStartup(hash, chunkGraph, entries, chunk); + }; +} + +module.exports = { + createChunkHashHandler, + getChunkInfo +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/ChunkHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/ChunkHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..30c88653d557efc0d9857963acf00c39b0f42541 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/ChunkHelpers.js @@ -0,0 +1,34 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Entrypoint = require("../Entrypoint"); + +/** @typedef {import("../Chunk")} Chunk */ + +/** + * @param {Entrypoint} entrypoint a chunk group + * @param {(Chunk | null)=} excludedChunk1 current chunk which is excluded + * @param {(Chunk | null)=} excludedChunk2 runtime chunk which is excluded + * @returns {Set} chunks + */ +const getAllChunks = (entrypoint, excludedChunk1, excludedChunk2) => { + const queue = new Set([entrypoint]); + const chunks = new Set(); + for (const entrypoint of queue) { + for (const chunk of entrypoint.chunks) { + if (chunk === excludedChunk1) continue; + if (chunk === excludedChunk2) continue; + chunks.add(chunk); + } + for (const parent of entrypoint.parentsIterable) { + if (parent instanceof Entrypoint) queue.add(parent); + } + } + return chunks; +}; + +module.exports.getAllChunks = getAllChunks; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/CommonJsChunkFormatPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/CommonJsChunkFormatPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..a0bbe5f9368063a1335c6854d0f4ca533df34278 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/CommonJsChunkFormatPlugin.js @@ -0,0 +1,149 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource, RawSource } = require("webpack-sources"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const { getUndoPath } = require("../util/identifier"); +const { + createChunkHashHandler, + getChunkInfo +} = require("./ChunkFormatHelpers"); +const { + getChunkFilenameTemplate, + getCompilationHooks +} = require("./JavascriptModulesPlugin"); +const { generateEntryStartup } = require("./StartupHelpers"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint")} Entrypoint */ + +const PLUGIN_NAME = "CommonJsChunkFormatPlugin"; + +class CommonJsChunkFormatPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set, { chunkGraph }) => { + if (chunk.hasRuntime()) return; + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { + set.add(RuntimeGlobals.require); + set.add(RuntimeGlobals.startupEntrypoint); + set.add(RuntimeGlobals.externalInstallChunk); + } + } + ); + const hooks = getCompilationHooks(compilation); + hooks.renderChunk.tap(PLUGIN_NAME, (modules, renderContext) => { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + const source = new ConcatSource(); + source.add(`exports.id = ${JSON.stringify(chunk.id)};\n`); + source.add(`exports.ids = ${JSON.stringify(chunk.ids)};\n`); + source.add("exports.modules = "); + source.add(modules); + source.add(";\n"); + const runtimeModules = chunkGraph.getChunkRuntimeModulesInOrder(chunk); + if (runtimeModules.length > 0) { + source.add("exports.runtime =\n"); + source.add( + Template.renderChunkRuntimeModules(runtimeModules, renderContext) + ); + } + const { entries, runtimeChunk } = getChunkInfo(chunk, chunkGraph); + if (runtimeChunk) { + const currentOutputName = compilation + .getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ) + .replace(/^\/+/g, "") + .split("/"); + const runtimeOutputName = compilation + .getPath( + getChunkFilenameTemplate( + /** @type {Chunk} */ + (runtimeChunk), + compilation.outputOptions + ), + { + chunk: /** @type {Chunk} */ (runtimeChunk), + contentHashType: "javascript" + } + ) + .replace(/^\/+/g, "") + .split("/"); + + // remove common parts + while ( + currentOutputName.length > 1 && + runtimeOutputName.length > 1 && + currentOutputName[0] === runtimeOutputName[0] + ) { + currentOutputName.shift(); + runtimeOutputName.shift(); + } + const last = runtimeOutputName.join("/"); + // create final path + const runtimePath = + getUndoPath(currentOutputName.join("/"), last, true) + last; + + const entrySource = new ConcatSource(); + entrySource.add( + `(${ + runtimeTemplate.supportsArrowFunction() ? "() => " : "function() " + }{\n` + ); + entrySource.add("var exports = {};\n"); + entrySource.add(source); + entrySource.add(";\n\n// load runtime\n"); + entrySource.add( + `var ${RuntimeGlobals.require} = require(${JSON.stringify( + runtimePath + )});\n` + ); + entrySource.add(`${RuntimeGlobals.externalInstallChunk}(exports);\n`); + const startupSource = new RawSource( + generateEntryStartup( + chunkGraph, + runtimeTemplate, + entries, + chunk, + false + ) + ); + entrySource.add( + hooks.renderStartup.call( + startupSource, + entries[entries.length - 1][0], + { + ...renderContext, + inlined: false + } + ) + ); + entrySource.add("\n})()"); + return entrySource; + } + return source; + }); + + hooks.chunkHash.tap(PLUGIN_NAME, createChunkHashHandler(PLUGIN_NAME)); + }); + } +} + +module.exports = CommonJsChunkFormatPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/EnableChunkLoadingPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/EnableChunkLoadingPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f19c18f32ce999cdea2f177eea1c50ca2e40cc94 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/EnableChunkLoadingPlugin.js @@ -0,0 +1,124 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../../declarations/WebpackOptions").ChunkLoadingType} ChunkLoadingType */ +/** @typedef {import("../Compiler")} Compiler */ + +/** @type {WeakMap>} */ +const enabledTypes = new WeakMap(); + +/** + * @param {Compiler} compiler compiler + * @returns {Set} enabled types + */ +const getEnabledTypes = (compiler) => { + let set = enabledTypes.get(compiler); + if (set === undefined) { + set = new Set(); + enabledTypes.set(compiler, set); + } + return set; +}; + +class EnableChunkLoadingPlugin { + /** + * @param {ChunkLoadingType} type library type that should be available + */ + constructor(type) { + this.type = type; + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {ChunkLoadingType} type type of library + * @returns {void} + */ + static setEnabled(compiler, type) { + getEnabledTypes(compiler).add(type); + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {ChunkLoadingType} type type of library + * @returns {void} + */ + static checkEnabled(compiler, type) { + if (!getEnabledTypes(compiler).has(type)) { + throw new Error( + `Chunk loading type "${type}" is not enabled. ` + + "EnableChunkLoadingPlugin need to be used to enable this type of chunk loading. " + + 'This usually happens through the "output.enabledChunkLoadingTypes" option. ' + + 'If you are using a function as entry which sets "chunkLoading", you need to add all potential chunk loading types to "output.enabledChunkLoadingTypes". ' + + `These types are enabled: ${[...getEnabledTypes(compiler)].join(", ")}` + ); + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { type } = this; + + // Only enable once + const enabled = getEnabledTypes(compiler); + if (enabled.has(type)) return; + enabled.add(type); + + if (typeof type === "string") { + switch (type) { + case "jsonp": { + const JsonpChunkLoadingPlugin = require("../web/JsonpChunkLoadingPlugin"); + + new JsonpChunkLoadingPlugin().apply(compiler); + break; + } + case "import-scripts": { + const ImportScriptsChunkLoadingPlugin = require("../webworker/ImportScriptsChunkLoadingPlugin"); + + new ImportScriptsChunkLoadingPlugin().apply(compiler); + break; + } + case "require": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const CommonJsChunkLoadingPlugin = require("../node/CommonJsChunkLoadingPlugin"); + + new CommonJsChunkLoadingPlugin({ + asyncChunkLoading: false + }).apply(compiler); + break; + } + case "async-node": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const CommonJsChunkLoadingPlugin = require("../node/CommonJsChunkLoadingPlugin"); + + new CommonJsChunkLoadingPlugin({ + asyncChunkLoading: true + }).apply(compiler); + break; + } + case "import": + case "universal": { + const ModuleChunkLoadingPlugin = require("../esm/ModuleChunkLoadingPlugin"); + + new ModuleChunkLoadingPlugin().apply(compiler); + break; + } + default: + throw new Error(`Unsupported chunk loading type ${type}. +Plugins which provide custom chunk loading types must call EnableChunkLoadingPlugin.setEnabled(compiler, type) to disable this error.`); + } + } else { + // TODO support plugin instances here + // apply them to the compiler + } + } +} + +module.exports = EnableChunkLoadingPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptGenerator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..775fbf53b7e966e91a5b7dd28f2c2db84faa9ea8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptGenerator.js @@ -0,0 +1,277 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const { RawSource, ReplaceSource } = require("webpack-sources"); +const Generator = require("../Generator"); +const InitFragment = require("../InitFragment"); +const { JS_TYPES } = require("../ModuleSourceTypesConstants"); +const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate")} DependencyTemplate */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +const DEFAULT_SOURCE = { + source() { + return new RawSource("throw new Error('No source available');"); + }, + /** + * @returns {number} size of the DEFAULT_SOURCE.source() + */ + size() { + return 39; + } +}; + +// TODO: clean up this file +// replace with newer constructs + +const deprecatedGetInitFragments = util.deprecate( + /** + * @param {DependencyTemplate} template template + * @param {Dependency} dependency dependency + * @param {DependencyTemplateContext} templateContext template context + * @returns {InitFragment[]} init fragments + */ + (template, dependency, templateContext) => + /** @type {DependencyTemplate & { getInitFragments: (dependency: Dependency, dependencyTemplateContext: DependencyTemplateContext) => InitFragment[] }} */ + (template).getInitFragments(dependency, templateContext), + "DependencyTemplate.getInitFragment is deprecated (use apply(dep, source, { initFragments }) instead)", + "DEP_WEBPACK_JAVASCRIPT_GENERATOR_GET_INIT_FRAGMENTS" +); + +class JavascriptGenerator extends Generator { + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + return JS_TYPES; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + const originalSource = module.originalSource(); + if (!originalSource) { + return DEFAULT_SOURCE.size(); + } + return originalSource.size(); + } + + /** + * @param {NormalModule} module module for which the bailout reason should be determined + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(module, context) { + // Only harmony modules are valid for optimization + if ( + !module.buildMeta || + module.buildMeta.exportsType !== "namespace" || + module.presentationalDependencies === undefined || + !module.presentationalDependencies.some( + (d) => d instanceof HarmonyCompatibilityDependency + ) + ) { + return "Module is not an ECMAScript module"; + } + + // Some expressions are not compatible with module concatenation + // because they may produce unexpected results. The plugin bails out + // if some were detected upfront. + if (module.buildInfo && module.buildInfo.moduleConcatenationBailout) { + return `Module uses ${module.buildInfo.moduleConcatenationBailout}`; + } + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate(module, generateContext) { + const originalSource = module.originalSource(); + if (!originalSource) { + return DEFAULT_SOURCE.source(); + } + + const source = new ReplaceSource(originalSource); + /** @type {InitFragment[]} */ + const initFragments = []; + + this.sourceModule(module, initFragments, source, generateContext); + + return InitFragment.addToSource(source, initFragments, generateContext); + } + + /** + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generateError(error, module, generateContext) { + return new RawSource(`throw new Error(${JSON.stringify(error.message)});`); + } + + /** + * @param {Module} module the module to generate + * @param {InitFragment[]} initFragments mutable list of init fragments + * @param {ReplaceSource} source the current replace source which can be modified + * @param {GenerateContext} generateContext the generateContext + * @returns {void} + */ + sourceModule(module, initFragments, source, generateContext) { + for (const dependency of module.dependencies) { + this.sourceDependency( + module, + dependency, + initFragments, + source, + generateContext + ); + } + + if (module.presentationalDependencies !== undefined) { + for (const dependency of module.presentationalDependencies) { + this.sourceDependency( + module, + dependency, + initFragments, + source, + generateContext + ); + } + } + + for (const childBlock of module.blocks) { + this.sourceBlock( + module, + childBlock, + initFragments, + source, + generateContext + ); + } + } + + /** + * @param {Module} module the module to generate + * @param {DependenciesBlock} block the dependencies block which will be processed + * @param {InitFragment[]} initFragments mutable list of init fragments + * @param {ReplaceSource} source the current replace source which can be modified + * @param {GenerateContext} generateContext the generateContext + * @returns {void} + */ + sourceBlock(module, block, initFragments, source, generateContext) { + for (const dependency of block.dependencies) { + this.sourceDependency( + module, + dependency, + initFragments, + source, + generateContext + ); + } + + for (const childBlock of block.blocks) { + this.sourceBlock( + module, + childBlock, + initFragments, + source, + generateContext + ); + } + } + + /** + * @param {Module} module the current module + * @param {Dependency} dependency the dependency to generate + * @param {InitFragment[]} initFragments mutable list of init fragments + * @param {ReplaceSource} source the current replace source which can be modified + * @param {GenerateContext} generateContext the render context + * @returns {void} + */ + sourceDependency(module, dependency, initFragments, source, generateContext) { + const constructor = + /** @type {new (...args: EXPECTED_ANY[]) => Dependency} */ + (dependency.constructor); + const template = generateContext.dependencyTemplates.get(constructor); + if (!template) { + throw new Error( + `No template for dependency: ${dependency.constructor.name}` + ); + } + + /** @type {InitFragment[] | undefined} */ + let chunkInitFragments; + + /** @type {DependencyTemplateContext} */ + const templateContext = { + runtimeTemplate: generateContext.runtimeTemplate, + dependencyTemplates: generateContext.dependencyTemplates, + moduleGraph: generateContext.moduleGraph, + chunkGraph: generateContext.chunkGraph, + module, + runtime: generateContext.runtime, + runtimeRequirements: generateContext.runtimeRequirements, + concatenationScope: generateContext.concatenationScope, + codeGenerationResults: + /** @type {NonNullable} */ + (generateContext.codeGenerationResults), + initFragments, + get chunkInitFragments() { + if (!chunkInitFragments) { + const data = + /** @type {NonNullable} */ + (generateContext.getData)(); + chunkInitFragments = data.get("chunkInitFragments"); + if (!chunkInitFragments) { + chunkInitFragments = []; + data.set("chunkInitFragments", chunkInitFragments); + } + } + + return chunkInitFragments; + } + }; + + template.apply(dependency, source, templateContext); + + // TODO remove in webpack 6 + if ("getInitFragments" in template) { + const fragments = deprecatedGetInitFragments( + template, + dependency, + templateContext + ); + + if (fragments) { + for (const fragment of fragments) { + initFragments.push(fragment); + } + } + } + } +} + +module.exports = JavascriptGenerator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..86e421b2267317691ea5ea2be98d7e96d9c31d48 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptModulesPlugin.js @@ -0,0 +1,1766 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const vm = require("vm"); +const eslintScope = require("eslint-scope"); +const { SyncBailHook, SyncHook, SyncWaterfallHook } = require("tapable"); +const { + CachedSource, + ConcatSource, + OriginalSource, + PrefixSource, + RawSource, + ReplaceSource +} = require("webpack-sources"); +const Compilation = require("../Compilation"); +const { tryRunOrWebpackError } = require("../HookWebpackError"); +const HotUpdateChunk = require("../HotUpdateChunk"); +const InitFragment = require("../InitFragment"); +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM, + WEBPACK_MODULE_TYPE_RUNTIME +} = require("../ModuleTypeConstants"); +const NormalModule = require("../NormalModule"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const { last, someInIterable } = require("../util/IterableHelpers"); +const StringXor = require("../util/StringXor"); +const { compareModulesByIdOrIdentifier } = require("../util/comparators"); +const { + RESERVED_NAMES, + addScopeSymbols, + findNewName, + getAllReferences, + getPathInAst, + getUsedNamesInScopeInfo +} = require("../util/concatenate"); +const createHash = require("../util/createHash"); +const nonNumericOnlyHash = require("../util/nonNumericOnlyHash"); +const removeBOM = require("../util/removeBOM"); +const { intersectRuntime } = require("../util/runtime"); +const JavascriptGenerator = require("./JavascriptGenerator"); +const JavascriptParser = require("./JavascriptParser"); + +/** @typedef {import("eslint-scope").Reference} Reference */ +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("estree").Program} Program */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compilation").ExecuteModuleObject} ExecuteModuleObject */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../util/Hash")} Hash */ + +/** + * @param {Chunk} chunk a chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {boolean} true, when a JS file is needed for this chunk + */ +const chunkHasJs = (chunk, chunkGraph) => { + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) return true; + + return Boolean( + chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript") + ); +}; + +/** + * @param {Chunk} chunk a chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {boolean} true, when a JS file is needed for this chunk + */ +const chunkHasRuntimeOrJs = (chunk, chunkGraph) => { + if ( + chunkGraph.getChunkModulesIterableBySourceType( + chunk, + WEBPACK_MODULE_TYPE_RUNTIME + ) + ) { + return true; + } + + return Boolean( + chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript") + ); +}; + +/** + * @param {Module} module a module + * @param {string} code the code + * @returns {string} generated code for the stack + */ +const printGeneratedCodeForStack = (module, code) => { + const lines = code.split("\n"); + const n = `${lines.length}`.length; + return `\n\nGenerated code for ${module.identifier()}\n${lines + .map( + /** + * @param {string} line the line + * @param {number} i the index + * @param {string[]} _lines the lines + * @returns {string} the line with line number + */ + (line, i, _lines) => { + const iStr = `${i + 1}`; + return `${" ".repeat(n - iStr.length)}${iStr} | ${line}`; + } + ) + .join("\n")}`; +}; + +/** + * @typedef {object} RenderContext + * @property {Chunk} chunk the chunk + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {boolean | undefined} strictMode rendering in strict context + */ + +/** + * @typedef {object} MainRenderContext + * @property {Chunk} chunk the chunk + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {string} hash hash to be used for render call + * @property {boolean | undefined} strictMode rendering in strict context + */ + +/** + * @typedef {object} ChunkRenderContext + * @property {Chunk} chunk the chunk + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {InitFragment[]} chunkInitFragments init fragments for the chunk + * @property {boolean | undefined} strictMode rendering in strict context + */ + +/** + * @typedef {object} RenderBootstrapContext + * @property {Chunk} chunk the chunk + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {string} hash hash to be used for render call + */ + +/** + * @typedef {object} StartupRenderContext + * @property {Chunk} chunk the chunk + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {boolean | undefined} strictMode rendering in strict context + * @property {boolean } inlined inlined + * @property {boolean=} inlinedInIIFE the inlined entry module is wrapped in an IIFE + */ + +/** + * @typedef {object} ModuleRenderContext + * @property {Chunk} chunk the chunk + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {InitFragment[]} chunkInitFragments init fragments for the chunk + * @property {boolean | undefined} strictMode rendering in strict context + * @property {boolean} factory true: renders as factory method, false: pure module content + * @property {boolean=} inlinedInIIFE the inlined entry module is wrapped in an IIFE, existing only when `factory` is set to false + */ + +/** + * @typedef {object} CompilationHooks + * @property {SyncWaterfallHook<[Source, Module, ModuleRenderContext]>} renderModuleContent + * @property {SyncWaterfallHook<[Source, Module, ModuleRenderContext]>} renderModuleContainer + * @property {SyncWaterfallHook<[Source, Module, ModuleRenderContext]>} renderModulePackage + * @property {SyncWaterfallHook<[Source, RenderContext]>} renderChunk + * @property {SyncWaterfallHook<[Source, RenderContext]>} renderMain + * @property {SyncWaterfallHook<[Source, RenderContext]>} renderContent + * @property {SyncWaterfallHook<[Source, RenderContext]>} render + * @property {SyncWaterfallHook<[Source, Module, StartupRenderContext]>} renderStartup + * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire + * @property {SyncBailHook<[Module, Partial], string | void>} inlineInRuntimeBailout + * @property {SyncBailHook<[Module, RenderContext], string | void>} embedInRuntimeBailout + * @property {SyncBailHook<[RenderContext], string | void>} strictRuntimeBailout + * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash + * @property {SyncBailHook<[Chunk, RenderContext], boolean | void>} useSourceMap + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +const PLUGIN_NAME = "JavascriptModulesPlugin"; + +/** @typedef {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} Bootstrap */ + +class JavascriptModulesPlugin { + /** + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} the attached hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + renderModuleContent: new SyncWaterfallHook([ + "source", + "module", + "moduleRenderContext" + ]), + renderModuleContainer: new SyncWaterfallHook([ + "source", + "module", + "moduleRenderContext" + ]), + renderModulePackage: new SyncWaterfallHook([ + "source", + "module", + "moduleRenderContext" + ]), + render: new SyncWaterfallHook(["source", "renderContext"]), + renderContent: new SyncWaterfallHook(["source", "renderContext"]), + renderStartup: new SyncWaterfallHook([ + "source", + "module", + "startupRenderContext" + ]), + renderChunk: new SyncWaterfallHook(["source", "renderContext"]), + renderMain: new SyncWaterfallHook(["source", "renderContext"]), + renderRequire: new SyncWaterfallHook(["code", "renderContext"]), + inlineInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), + embedInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), + strictRuntimeBailout: new SyncBailHook(["renderContext"]), + chunkHash: new SyncHook(["chunk", "hash", "context"]), + useSourceMap: new SyncBailHook(["chunk", "renderContext"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + constructor(options = {}) { + this.options = options; + /** @type {WeakMap} */ + this._moduleFactoryCache = new WeakMap(); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + + for (const type of [ + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM + ]) { + normalModuleFactory.hooks.createParser + .for(type) + .tap(PLUGIN_NAME, (_options) => { + switch (type) { + case JAVASCRIPT_MODULE_TYPE_AUTO: { + return new JavascriptParser("auto"); + } + case JAVASCRIPT_MODULE_TYPE_DYNAMIC: { + return new JavascriptParser("script"); + } + case JAVASCRIPT_MODULE_TYPE_ESM: { + return new JavascriptParser("module"); + } + } + }); + normalModuleFactory.hooks.createGenerator + .for(type) + .tap(PLUGIN_NAME, () => new JavascriptGenerator()); + + NormalModule.getCompilationHooks(compilation).processResult.tap( + PLUGIN_NAME, + (result, module) => { + if (module.type === type) { + const [source, ...rest] = result; + + return [removeBOM(source), ...rest]; + } + + return result; + } + ); + } + + compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => { + const { + hash, + chunk, + chunkGraph, + moduleGraph, + runtimeTemplate, + dependencyTemplates, + outputOptions, + codeGenerationResults + } = options; + + const hotUpdateChunk = chunk instanceof HotUpdateChunk ? chunk : null; + const filenameTemplate = + JavascriptModulesPlugin.getChunkFilenameTemplate( + chunk, + outputOptions + ); + + let render; + + if (hotUpdateChunk) { + render = () => + this.renderChunk( + { + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults, + strictMode: runtimeTemplate.isModule() + }, + hooks + ); + } else if (chunk.hasRuntime()) { + if (!chunkHasRuntimeOrJs(chunk, chunkGraph)) { + return result; + } + + render = () => + this.renderMain( + { + hash, + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults, + strictMode: runtimeTemplate.isModule() + }, + hooks, + compilation + ); + } else { + if (!chunkHasJs(chunk, chunkGraph)) { + return result; + } + + render = () => + this.renderChunk( + { + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults, + strictMode: runtimeTemplate.isModule() + }, + hooks + ); + } + + result.push({ + render, + filenameTemplate, + pathOptions: { + hash, + runtime: chunk.runtime, + chunk, + contentHashType: "javascript" + }, + info: { + javascriptModule: compilation.runtimeTemplate.isModule() + }, + identifier: hotUpdateChunk + ? `hotupdatechunk${chunk.id}` + : `chunk${chunk.id}`, + hash: chunk.contentHash.javascript + }); + + return result; + }); + compilation.hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash, context) => { + hooks.chunkHash.call(chunk, hash, context); + if (chunk.hasRuntime()) { + this.updateHashWithBootstrap( + hash, + { + hash: "0000", + chunk, + codeGenerationResults: context.codeGenerationResults, + chunkGraph: context.chunkGraph, + moduleGraph: context.moduleGraph, + runtimeTemplate: context.runtimeTemplate + }, + hooks + ); + } + }); + compilation.hooks.contentHash.tap(PLUGIN_NAME, (chunk) => { + const { + chunkGraph, + codeGenerationResults, + moduleGraph, + runtimeTemplate, + outputOptions: { + hashSalt, + hashDigest, + hashDigestLength, + hashFunction + } + } = compilation; + const hash = createHash(/** @type {HashFunction} */ (hashFunction)); + if (hashSalt) hash.update(hashSalt); + if (chunk.hasRuntime()) { + this.updateHashWithBootstrap( + hash, + { + hash: "0000", + chunk, + codeGenerationResults, + chunkGraph: compilation.chunkGraph, + moduleGraph: compilation.moduleGraph, + runtimeTemplate: compilation.runtimeTemplate + }, + hooks + ); + } else { + hash.update(`${chunk.id} `); + hash.update(chunk.ids ? chunk.ids.join(",") : ""); + } + hooks.chunkHash.call(chunk, hash, { + chunkGraph, + codeGenerationResults, + moduleGraph, + runtimeTemplate + }); + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "javascript" + ); + if (modules) { + const xor = new StringXor(); + for (const m of modules) { + xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); + } + xor.updateHash(hash); + } + const runtimeModules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + WEBPACK_MODULE_TYPE_RUNTIME + ); + if (runtimeModules) { + const xor = new StringXor(); + for (const m of runtimeModules) { + xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); + } + xor.updateHash(hash); + } + const digest = /** @type {string} */ (hash.digest(hashDigest)); + chunk.contentHash.javascript = nonNumericOnlyHash( + digest, + /** @type {number} */ + (hashDigestLength) + ); + }); + compilation.hooks.additionalTreeRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set, { chunkGraph }) => { + if ( + !set.has(RuntimeGlobals.startupNoDefault) && + chunkGraph.hasChunkEntryDependentChunks(chunk) + ) { + set.add(RuntimeGlobals.onChunksLoaded); + set.add(RuntimeGlobals.exports); + set.add(RuntimeGlobals.require); + } + } + ); + compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => { + const source = options.codeGenerationResult.sources.get("javascript"); + if (source === undefined) return; + const { module } = options; + const code = source.source(); + + const fn = vm.runInThisContext( + `(function(${module.moduleArgument}, ${module.exportsArgument}, ${RuntimeGlobals.require}) {\n${code}\n/**/})`, + { + filename: module.identifier(), + lineOffset: -1 + } + ); + + const moduleObject = + /** @type {ExecuteModuleObject} */ + (options.moduleObject); + + try { + fn.call( + moduleObject.exports, + moduleObject, + moduleObject.exports, + context.__webpack_require__ + ); + } catch (err) { + /** @type {Error} */ + (err).stack += printGeneratedCodeForStack( + options.module, + /** @type {string} */ (code) + ); + throw err; + } + }); + compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => { + const source = options.codeGenerationResult.sources.get("runtime"); + if (source === undefined) return; + let code = source.source(); + if (typeof code !== "string") code = code.toString(); + + const fn = vm.runInThisContext( + `(function(${RuntimeGlobals.require}) {\n${code}\n/**/})`, + { + filename: options.module.identifier(), + lineOffset: -1 + } + ); + try { + // eslint-disable-next-line no-useless-call + fn.call(null, context.__webpack_require__); + } catch (err) { + /** @type {Error} */ + (err).stack += printGeneratedCodeForStack(options.module, code); + throw err; + } + }); + } + ); + } + + /** + * @param {Chunk} chunk chunk + * @param {OutputOptions} outputOptions output options + * @returns {TemplatePath} used filename template + */ + static getChunkFilenameTemplate(chunk, outputOptions) { + if (chunk.filenameTemplate) { + return chunk.filenameTemplate; + } else if (chunk instanceof HotUpdateChunk) { + return /** @type {TemplatePath} */ (outputOptions.hotUpdateChunkFilename); + } else if (chunk.canBeInitial()) { + return /** @type {TemplatePath} */ (outputOptions.filename); + } + return /** @type {TemplatePath} */ (outputOptions.chunkFilename); + } + + /** + * @param {Module} module the rendered module + * @param {ModuleRenderContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @returns {Source | null} the newly generated source from rendering + */ + renderModule(module, renderContext, hooks) { + const { + chunk, + chunkGraph, + runtimeTemplate, + codeGenerationResults, + strictMode, + factory + } = renderContext; + try { + const codeGenResult = codeGenerationResults.get(module, chunk.runtime); + const moduleSource = codeGenResult.sources.get("javascript"); + if (!moduleSource) return null; + if (codeGenResult.data !== undefined) { + const chunkInitFragments = codeGenResult.data.get("chunkInitFragments"); + if (chunkInitFragments) { + for (const i of chunkInitFragments) { + renderContext.chunkInitFragments.push(i); + } + } + } + const moduleSourcePostContent = tryRunOrWebpackError( + () => + hooks.renderModuleContent.call(moduleSource, module, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderModuleContent" + ); + let moduleSourcePostContainer; + if (factory) { + const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( + module, + chunk.runtime + ); + const needModule = runtimeRequirements.has(RuntimeGlobals.module); + const needExports = runtimeRequirements.has(RuntimeGlobals.exports); + const needRequire = + runtimeRequirements.has(RuntimeGlobals.require) || + runtimeRequirements.has(RuntimeGlobals.requireScope); + const needThisAsExports = runtimeRequirements.has( + RuntimeGlobals.thisAsExports + ); + const needStrict = + /** @type {BuildInfo} */ + (module.buildInfo).strict && !strictMode; + const cacheEntry = this._moduleFactoryCache.get( + moduleSourcePostContent + ); + let source; + if ( + cacheEntry && + cacheEntry.needModule === needModule && + cacheEntry.needExports === needExports && + cacheEntry.needRequire === needRequire && + cacheEntry.needThisAsExports === needThisAsExports && + cacheEntry.needStrict === needStrict + ) { + source = cacheEntry.source; + } else { + const factorySource = new ConcatSource(); + const args = []; + if (needExports || needRequire || needModule) { + args.push( + needModule + ? module.moduleArgument + : `__unused_webpack_${module.moduleArgument}` + ); + } + if (needExports || needRequire) { + args.push( + needExports + ? module.exportsArgument + : `__unused_webpack_${module.exportsArgument}` + ); + } + if (needRequire) args.push(RuntimeGlobals.require); + if (!needThisAsExports && runtimeTemplate.supportsArrowFunction()) { + factorySource.add(`/***/ ((${args.join(", ")}) => {\n\n`); + } else { + factorySource.add(`/***/ (function(${args.join(", ")}) {\n\n`); + } + if (needStrict) { + factorySource.add('"use strict";\n'); + } + factorySource.add(moduleSourcePostContent); + factorySource.add("\n\n/***/ })"); + source = new CachedSource(factorySource); + this._moduleFactoryCache.set(moduleSourcePostContent, { + source, + needModule, + needExports, + needRequire, + needThisAsExports, + needStrict + }); + } + moduleSourcePostContainer = tryRunOrWebpackError( + () => hooks.renderModuleContainer.call(source, module, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer" + ); + } else { + moduleSourcePostContainer = moduleSourcePostContent; + } + return tryRunOrWebpackError( + () => + hooks.renderModulePackage.call( + moduleSourcePostContainer, + module, + renderContext + ), + "JavascriptModulesPlugin.getCompilationHooks().renderModulePackage" + ); + } catch (err) { + /** @type {WebpackError} */ + (err).module = module; + throw err; + } + } + + /** + * @param {RenderContext} renderContext the render context + * @param {CompilationHooks} hooks hooks + * @returns {Source} the rendered source + */ + renderChunk(renderContext, hooks) { + const { chunk, chunkGraph } = renderContext; + const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "javascript", + compareModulesByIdOrIdentifier(chunkGraph) + ); + const allModules = modules ? [...modules] : []; + let strictHeader; + let allStrict = renderContext.strictMode; + if ( + !allStrict && + allModules.every((m) => /** @type {BuildInfo} */ (m.buildInfo).strict) + ) { + const strictBailout = hooks.strictRuntimeBailout.call(renderContext); + strictHeader = strictBailout + ? `// runtime can't be in strict mode because ${strictBailout}.\n` + : '"use strict";\n'; + if (!strictBailout) allStrict = true; + } + /** @type {ChunkRenderContext} */ + const chunkRenderContext = { + ...renderContext, + chunkInitFragments: [], + strictMode: allStrict + }; + const moduleSources = + Template.renderChunkModules(chunkRenderContext, allModules, (module) => + this.renderModule( + module, + { ...chunkRenderContext, factory: true }, + hooks + ) + ) || new RawSource("{}"); + let source = tryRunOrWebpackError( + () => hooks.renderChunk.call(moduleSources, chunkRenderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderChunk" + ); + source = tryRunOrWebpackError( + () => hooks.renderContent.call(source, chunkRenderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderContent" + ); + if (!source) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" + ); + } + source = InitFragment.addToSource( + source, + chunkRenderContext.chunkInitFragments, + chunkRenderContext + ); + source = tryRunOrWebpackError( + () => hooks.render.call(source, chunkRenderContext), + "JavascriptModulesPlugin.getCompilationHooks().render" + ); + if (!source) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" + ); + } + chunk.rendered = true; + return strictHeader + ? new ConcatSource(strictHeader, source, ";") + : renderContext.runtimeTemplate.isModule() + ? source + : new ConcatSource(source, ";"); + } + + /** + * @param {MainRenderContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @param {Compilation} compilation the compilation + * @returns {Source} the newly generated source from rendering + */ + renderMain(renderContext, hooks, compilation) { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + const iife = runtimeTemplate.isIIFE(); + + const bootstrap = this.renderBootstrap(renderContext, hooks); + const useSourceMap = hooks.useSourceMap.call(chunk, renderContext); + + /** @type {Module[]} */ + const allModules = [ + ...(chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "javascript", + compareModulesByIdOrIdentifier(chunkGraph) + ) || []) + ]; + + const hasEntryModules = chunkGraph.getNumberOfEntryModules(chunk) > 0; + /** @type {Set | undefined} */ + let inlinedModules; + if (bootstrap.allowInlineStartup && hasEntryModules) { + inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk)); + } + + const source = new ConcatSource(); + let prefix; + if (iife) { + if (runtimeTemplate.supportsArrowFunction()) { + source.add("/******/ (() => { // webpackBootstrap\n"); + } else { + source.add("/******/ (function() { // webpackBootstrap\n"); + } + prefix = "/******/ \t"; + } else { + prefix = "/******/ "; + } + let allStrict = renderContext.strictMode; + if ( + !allStrict && + allModules.every((m) => /** @type {BuildInfo} */ (m.buildInfo).strict) + ) { + const strictBailout = hooks.strictRuntimeBailout.call(renderContext); + if (strictBailout) { + source.add( + `${ + prefix + }// runtime can't be in strict mode because ${strictBailout}.\n` + ); + } else { + allStrict = true; + source.add(`${prefix}"use strict";\n`); + } + } + + /** @type {ChunkRenderContext} */ + const chunkRenderContext = { + ...renderContext, + chunkInitFragments: [], + strictMode: allStrict + }; + + const chunkModules = Template.renderChunkModules( + chunkRenderContext, + inlinedModules + ? allModules.filter( + (m) => !(/** @type {Set} */ (inlinedModules).has(m)) + ) + : allModules, + (module) => + this.renderModule( + module, + { ...chunkRenderContext, factory: true }, + hooks + ), + prefix + ); + if ( + chunkModules || + runtimeRequirements.has(RuntimeGlobals.moduleFactories) || + runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) || + runtimeRequirements.has(RuntimeGlobals.require) + ) { + source.add(`${prefix}var __webpack_modules__ = (`); + source.add(chunkModules || "{}"); + source.add(");\n"); + source.add( + "/************************************************************************/\n" + ); + } + + if (bootstrap.header.length > 0) { + const header = `${Template.asString(bootstrap.header)}\n`; + source.add( + new PrefixSource( + prefix, + useSourceMap + ? new OriginalSource(header, "webpack/bootstrap") + : new RawSource(header) + ) + ); + source.add( + "/************************************************************************/\n" + ); + } + + const runtimeModules = + renderContext.chunkGraph.getChunkRuntimeModulesInOrder(chunk); + + if (runtimeModules.length > 0) { + source.add( + new PrefixSource( + prefix, + Template.renderRuntimeModules(runtimeModules, chunkRenderContext) + ) + ); + source.add( + "/************************************************************************/\n" + ); + // runtimeRuntimeModules calls codeGeneration + for (const module of runtimeModules) { + compilation.codeGeneratedModules.add(module); + } + } + if (inlinedModules) { + if (bootstrap.beforeStartup.length > 0) { + const beforeStartup = `${Template.asString(bootstrap.beforeStartup)}\n`; + source.add( + new PrefixSource( + prefix, + useSourceMap + ? new OriginalSource(beforeStartup, "webpack/before-startup") + : new RawSource(beforeStartup) + ) + ); + } + const lastInlinedModule = /** @type {Module} */ (last(inlinedModules)); + const startupSource = new ConcatSource(); + + if (runtimeRequirements.has(RuntimeGlobals.exports)) { + startupSource.add(`var ${RuntimeGlobals.exports} = {};\n`); + } + + const avoidEntryIife = compilation.options.optimization.avoidEntryIife; + /** @type {Map | false} */ + let renamedInlinedModule = false; + let inlinedInIIFE = false; + + if (avoidEntryIife) { + renamedInlinedModule = this.getRenamedInlineModule( + allModules, + renderContext, + inlinedModules, + chunkRenderContext, + hooks, + allStrict, + Boolean(chunkModules) + ); + } + + for (const m of inlinedModules) { + const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( + m, + chunk.runtime + ); + const exports = runtimeRequirements.has(RuntimeGlobals.exports); + const webpackExports = + exports && m.exportsArgument === RuntimeGlobals.exports; + + const innerStrict = + !allStrict && /** @type {BuildInfo} */ (m.buildInfo).strict; + + const iife = innerStrict + ? "it needs to be in strict mode." + : inlinedModules.size > 1 + ? // TODO check globals and top-level declarations of other entries and chunk modules + // to make a better decision + "it needs to be isolated against other entry modules." + : chunkModules && !renamedInlinedModule + ? "it needs to be isolated against other modules in the chunk." + : exports && !webpackExports + ? `it uses a non-standard name for the exports (${m.exportsArgument}).` + : hooks.embedInRuntimeBailout.call(m, renderContext); + + if (iife) { + inlinedInIIFE = true; + } + + const renderedModule = renamedInlinedModule + ? renamedInlinedModule.get(m) + : this.renderModule( + m, + { + ...chunkRenderContext, + factory: false, + inlinedInIIFE + }, + hooks + ); + + if (renderedModule) { + let footer; + if (iife !== undefined) { + startupSource.add( + `// This entry needs to be wrapped in an IIFE because ${iife}\n` + ); + const arrow = runtimeTemplate.supportsArrowFunction(); + if (arrow) { + startupSource.add("(() => {\n"); + footer = "\n})();\n\n"; + } else { + startupSource.add("!function() {\n"); + footer = "\n}();\n"; + } + if (innerStrict) startupSource.add('"use strict";\n'); + } else { + footer = "\n"; + } + if (exports) { + if (m !== lastInlinedModule) { + startupSource.add(`var ${m.exportsArgument} = {};\n`); + } else if (m.exportsArgument !== RuntimeGlobals.exports) { + startupSource.add( + `var ${m.exportsArgument} = ${RuntimeGlobals.exports};\n` + ); + } + } + startupSource.add(renderedModule); + startupSource.add(footer); + } + } + if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { + startupSource.add( + `${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});\n` + ); + } + source.add( + hooks.renderStartup.call(startupSource, lastInlinedModule, { + ...renderContext, + inlined: true, + inlinedInIIFE + }) + ); + if (bootstrap.afterStartup.length > 0) { + const afterStartup = `${Template.asString(bootstrap.afterStartup)}\n`; + source.add( + new PrefixSource( + prefix, + useSourceMap + ? new OriginalSource(afterStartup, "webpack/after-startup") + : new RawSource(afterStartup) + ) + ); + } + } else { + const lastEntryModule = + /** @type {Module} */ + (last(chunkGraph.getChunkEntryModulesIterable(chunk))); + /** @type {(content: string[], name: string) => Source} */ + const toSource = useSourceMap + ? (content, name) => + new OriginalSource(Template.asString(content), name) + : (content) => new RawSource(Template.asString(content)); + source.add( + new PrefixSource( + prefix, + new ConcatSource( + toSource(bootstrap.beforeStartup, "webpack/before-startup"), + "\n", + hooks.renderStartup.call( + toSource([...bootstrap.startup, ""], "webpack/startup"), + lastEntryModule, + { + ...renderContext, + inlined: false + } + ), + toSource(bootstrap.afterStartup, "webpack/after-startup"), + "\n" + ) + ) + ); + } + if ( + hasEntryModules && + runtimeRequirements.has(RuntimeGlobals.returnExportsFromRuntime) + ) { + source.add(`${prefix}return ${RuntimeGlobals.exports};\n`); + } + if (iife) { + source.add("/******/ })()\n"); + } + + /** @type {Source} */ + let finalSource = tryRunOrWebpackError( + () => hooks.renderMain.call(source, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderMain" + ); + if (!finalSource) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderMain plugins should return something" + ); + } + finalSource = tryRunOrWebpackError( + () => hooks.renderContent.call(finalSource, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderContent" + ); + if (!finalSource) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" + ); + } + + finalSource = InitFragment.addToSource( + finalSource, + chunkRenderContext.chunkInitFragments, + chunkRenderContext + ); + finalSource = tryRunOrWebpackError( + () => hooks.render.call(finalSource, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().render" + ); + if (!finalSource) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" + ); + } + chunk.rendered = true; + return iife ? new ConcatSource(finalSource, ";") : finalSource; + } + + /** + * @param {Hash} hash the hash to be updated + * @param {RenderBootstrapContext} renderContext options object + * @param {CompilationHooks} hooks hooks + */ + updateHashWithBootstrap(hash, renderContext, hooks) { + const bootstrap = this.renderBootstrap(renderContext, hooks); + for (const _k of Object.keys(bootstrap)) { + const key = /** @type {keyof Bootstrap} */ (_k); + hash.update(key); + if (Array.isArray(bootstrap[key])) { + for (const line of bootstrap[key]) { + hash.update(line); + } + } else { + hash.update(JSON.stringify(bootstrap[key])); + } + } + } + + /** + * @param {RenderBootstrapContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @returns {Bootstrap} the generated source of the bootstrap code + */ + renderBootstrap(renderContext, hooks) { + const { + chunkGraph, + codeGenerationResults, + moduleGraph, + chunk, + runtimeTemplate + } = renderContext; + + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + + const requireFunction = runtimeRequirements.has(RuntimeGlobals.require); + const moduleCache = runtimeRequirements.has(RuntimeGlobals.moduleCache); + const moduleFactories = runtimeRequirements.has( + RuntimeGlobals.moduleFactories + ); + const moduleUsed = runtimeRequirements.has(RuntimeGlobals.module); + const requireScopeUsed = runtimeRequirements.has( + RuntimeGlobals.requireScope + ); + const interceptModuleExecution = runtimeRequirements.has( + RuntimeGlobals.interceptModuleExecution + ); + + const useRequire = + requireFunction || interceptModuleExecution || moduleUsed; + + /** + * @type {{startup: string[], beforeStartup: string[], header: string[], afterStartup: string[], allowInlineStartup: boolean}} + */ + const result = { + header: [], + beforeStartup: [], + startup: [], + afterStartup: [], + allowInlineStartup: true + }; + + const { header: buf, startup, beforeStartup, afterStartup } = result; + + if (result.allowInlineStartup && moduleFactories) { + startup.push( + "// module factories are used so entry inlining is disabled" + ); + result.allowInlineStartup = false; + } + if (result.allowInlineStartup && moduleCache) { + startup.push("// module cache are used so entry inlining is disabled"); + result.allowInlineStartup = false; + } + if (result.allowInlineStartup && interceptModuleExecution) { + startup.push( + "// module execution is intercepted so entry inlining is disabled" + ); + result.allowInlineStartup = false; + } + + if (useRequire || moduleCache) { + buf.push("// The module cache"); + buf.push("var __webpack_module_cache__ = {};"); + buf.push(""); + } + + if (runtimeRequirements.has(RuntimeGlobals.makeDeferredNamespaceObject)) { + // in order to optimize of DeferredNamespaceObject, we remove all proxy handlers after the module initialize + // (see MakeDeferredNamespaceObjectRuntimeModule) + // This requires all deferred imports to a module can get the module export object before the module + // is evaluated. + buf.push("// The deferred module cache"); + buf.push("var __webpack_module_deferred_exports__ = {};"); + buf.push(""); + } + + if (useRequire) { + buf.push("// The require function"); + buf.push(`function ${RuntimeGlobals.require}(moduleId) {`); + buf.push(Template.indent(this.renderRequire(renderContext, hooks))); + buf.push("}"); + buf.push(""); + } else if (runtimeRequirements.has(RuntimeGlobals.requireScope)) { + buf.push("// The require scope"); + buf.push(`var ${RuntimeGlobals.require} = {};`); + buf.push(""); + } + + if ( + moduleFactories || + runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) + ) { + buf.push("// expose the modules object (__webpack_modules__)"); + buf.push(`${RuntimeGlobals.moduleFactories} = __webpack_modules__;`); + buf.push(""); + } + + if (moduleCache) { + buf.push("// expose the module cache"); + buf.push(`${RuntimeGlobals.moduleCache} = __webpack_module_cache__;`); + buf.push(""); + } + + if (interceptModuleExecution) { + buf.push("// expose the module execution interceptor"); + buf.push(`${RuntimeGlobals.interceptModuleExecution} = [];`); + buf.push(""); + } + + if (!runtimeRequirements.has(RuntimeGlobals.startupNoDefault)) { + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { + /** @type {string[]} */ + const buf2 = []; + const runtimeRequirements = + chunkGraph.getTreeRuntimeRequirements(chunk); + buf2.push("// Load entry module and return exports"); + let i = chunkGraph.getNumberOfEntryModules(chunk); + for (const [ + entryModule, + entrypoint + ] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) { + if (!chunkGraph.getModuleSourceTypes(entryModule).has("javascript")) { + i--; + continue; + } + const chunks = + /** @type {Entrypoint} */ + (entrypoint).chunks.filter((c) => c !== chunk); + if (result.allowInlineStartup && chunks.length > 0) { + buf2.push( + "// This entry module depends on other loaded chunks and execution need to be delayed" + ); + result.allowInlineStartup = false; + } + if ( + result.allowInlineStartup && + someInIterable( + moduleGraph.getIncomingConnectionsByOriginModule(entryModule), + ([originModule, connections]) => + originModule && + connections.some((c) => c.isTargetActive(chunk.runtime)) && + someInIterable( + chunkGraph.getModuleRuntimes(originModule), + (runtime) => + intersectRuntime(runtime, chunk.runtime) !== undefined + ) + ) + ) { + buf2.push( + "// This entry module is referenced by other modules so it can't be inlined" + ); + result.allowInlineStartup = false; + } + + let data; + if (codeGenerationResults.has(entryModule, chunk.runtime)) { + const result = codeGenerationResults.get( + entryModule, + chunk.runtime + ); + data = result.data; + } + if ( + result.allowInlineStartup && + (!data || !data.get("topLevelDeclarations")) && + (!entryModule.buildInfo || + !entryModule.buildInfo.topLevelDeclarations) + ) { + buf2.push( + "// This entry module doesn't tell about it's top-level declarations so it can't be inlined" + ); + result.allowInlineStartup = false; + } + if (result.allowInlineStartup) { + const bailout = hooks.inlineInRuntimeBailout.call( + entryModule, + renderContext + ); + if (bailout !== undefined) { + buf2.push( + `// This entry module can't be inlined because ${bailout}` + ); + result.allowInlineStartup = false; + } + } + i--; + const moduleId = chunkGraph.getModuleId(entryModule); + const entryRuntimeRequirements = + chunkGraph.getModuleRuntimeRequirements(entryModule, chunk.runtime); + let moduleIdExpr = JSON.stringify(moduleId); + if (runtimeRequirements.has(RuntimeGlobals.entryModuleId)) { + moduleIdExpr = `${RuntimeGlobals.entryModuleId} = ${moduleIdExpr}`; + } + if ( + result.allowInlineStartup && + entryRuntimeRequirements.has(RuntimeGlobals.module) + ) { + result.allowInlineStartup = false; + buf2.push( + "// This entry module used 'module' so it can't be inlined" + ); + } + if (chunks.length > 0) { + buf2.push( + `${i === 0 ? `var ${RuntimeGlobals.exports} = ` : ""}${ + RuntimeGlobals.onChunksLoaded + }(undefined, ${JSON.stringify( + chunks.map((c) => c.id) + )}, ${runtimeTemplate.returningFunction( + `${RuntimeGlobals.require}(${moduleIdExpr})` + )})` + ); + } else if (useRequire) { + buf2.push( + `${i === 0 ? `var ${RuntimeGlobals.exports} = ` : ""}${ + RuntimeGlobals.require + }(${moduleIdExpr});` + ); + } else { + if (i === 0) buf2.push(`var ${RuntimeGlobals.exports} = {};`); + if (requireScopeUsed) { + buf2.push( + `__webpack_modules__[${moduleIdExpr}](0, ${ + i === 0 ? RuntimeGlobals.exports : "{}" + }, ${RuntimeGlobals.require});` + ); + } else if (entryRuntimeRequirements.has(RuntimeGlobals.exports)) { + buf2.push( + `__webpack_modules__[${moduleIdExpr}](0, ${ + i === 0 ? RuntimeGlobals.exports : "{}" + });` + ); + } else { + buf2.push(`__webpack_modules__[${moduleIdExpr}]();`); + } + } + } + if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { + buf2.push( + `${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});` + ); + } + if ( + runtimeRequirements.has(RuntimeGlobals.startup) || + (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) && + runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) + ) { + result.allowInlineStartup = false; + buf.push("// the startup function"); + buf.push( + `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction("", [ + ...buf2, + `return ${RuntimeGlobals.exports};` + ])};` + ); + buf.push(""); + startup.push("// run startup"); + startup.push( + `var ${RuntimeGlobals.exports} = ${RuntimeGlobals.startup}();` + ); + } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore)) { + buf.push("// the startup function"); + buf.push( + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` + ); + beforeStartup.push("// run runtime startup"); + beforeStartup.push(`${RuntimeGlobals.startup}();`); + startup.push("// startup"); + startup.push(Template.asString(buf2)); + } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) { + buf.push("// the startup function"); + buf.push( + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` + ); + startup.push("// startup"); + startup.push(Template.asString(buf2)); + afterStartup.push("// run runtime startup"); + afterStartup.push(`${RuntimeGlobals.startup}();`); + } else { + startup.push("// startup"); + startup.push(Template.asString(buf2)); + } + } else if ( + runtimeRequirements.has(RuntimeGlobals.startup) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) + ) { + buf.push( + "// the startup function", + "// It's empty as no entry modules are in this chunk", + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`, + "" + ); + } + } else if ( + runtimeRequirements.has(RuntimeGlobals.startup) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) + ) { + result.allowInlineStartup = false; + buf.push( + "// the startup function", + "// It's empty as some runtime module handles the default behavior", + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` + ); + startup.push("// run startup"); + startup.push( + `var ${RuntimeGlobals.exports} = ${RuntimeGlobals.startup}();` + ); + } + return result; + } + + /** + * @param {RenderBootstrapContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @returns {string} the generated source of the require function + */ + renderRequire(renderContext, hooks) { + const { + chunk, + chunkGraph, + runtimeTemplate: { outputOptions } + } = renderContext; + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + const moduleExecution = runtimeRequirements.has( + RuntimeGlobals.interceptModuleExecution + ) + ? Template.asString([ + `var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: ${RuntimeGlobals.require} };`, + `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`, + "module = execOptions.module;", + "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);" + ]) + : runtimeRequirements.has(RuntimeGlobals.thisAsExports) + ? Template.asString([ + `__webpack_modules__[moduleId].call(module.exports, module, module.exports, ${RuntimeGlobals.require});` + ]) + : Template.asString([ + `__webpack_modules__[moduleId](module, module.exports, ${RuntimeGlobals.require});` + ]); + const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId); + const needModuleLoaded = runtimeRequirements.has( + RuntimeGlobals.moduleLoaded + ); + const needModuleDefer = runtimeRequirements.has( + RuntimeGlobals.makeDeferredNamespaceObject + ); + const content = Template.asString([ + "// Check if module is in cache", + "var cachedModule = __webpack_module_cache__[moduleId];", + "if (cachedModule !== undefined) {", + outputOptions.strictModuleErrorHandling + ? Template.indent([ + "if (cachedModule.error !== undefined) throw cachedModule.error;", + "return cachedModule.exports;" + ]) + : Template.indent("return cachedModule.exports;"), + "}", + "// Create a new module (and put it into the cache)", + "var module = __webpack_module_cache__[moduleId] = {", + Template.indent([ + needModuleId ? "id: moduleId," : "// no module.id needed", + needModuleLoaded ? "loaded: false," : "// no module.loaded needed", + needModuleDefer + ? "exports: __webpack_module_deferred_exports__[moduleId] || {}" + : "exports: {}" + ]), + "};", + "", + outputOptions.strictModuleExceptionHandling + ? Template.asString([ + "// Execute the module function", + "var threw = true;", + "try {", + Template.indent([ + moduleExecution, + "threw = false;", + ...(needModuleDefer + ? ["delete __webpack_module_deferred_exports__[moduleId];"] + : []) + ]), + "} finally {", + Template.indent([ + "if(threw) delete __webpack_module_cache__[moduleId];" + ]), + "}" + ]) + : outputOptions.strictModuleErrorHandling + ? Template.asString([ + "// Execute the module function", + "try {", + Template.indent( + needModuleDefer + ? [ + moduleExecution, + "delete __webpack_module_deferred_exports__[moduleId];" + ] + : moduleExecution + ), + "} catch(e) {", + Template.indent(["module.error = e;", "throw e;"]), + "}" + ]) + : Template.asString([ + "// Execute the module function", + moduleExecution, + ...(needModuleDefer + ? [ + "// delete __webpack_module_deferred_exports__[module];", + "// skipped because strictModuleErrorHandling is not enabled." + ] + : []) + ]), + needModuleLoaded + ? Template.asString([ + "", + "// Flag the module as loaded", + `${RuntimeGlobals.moduleLoaded} = true;`, + "" + ]) + : "", + "// Return the exports of the module", + "return module.exports;" + ]); + return tryRunOrWebpackError( + () => hooks.renderRequire.call(content, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderRequire" + ); + } + + /** + * @param {Module[]} allModules allModules + * @param {MainRenderContext} renderContext renderContext + * @param {Set} inlinedModules inlinedModules + * @param {ChunkRenderContext} chunkRenderContext chunkRenderContext + * @param {CompilationHooks} hooks hooks + * @param {boolean | undefined} allStrict allStrict + * @param {boolean} hasChunkModules hasChunkModules + * @returns {Map | false} renamed inlined modules + */ + getRenamedInlineModule( + allModules, + renderContext, + inlinedModules, + chunkRenderContext, + hooks, + allStrict, + hasChunkModules + ) { + const innerStrict = + !allStrict && + allModules.every((m) => /** @type {BuildInfo} */ (m.buildInfo).strict); + const isMultipleEntries = inlinedModules.size > 1; + const singleEntryWithModules = inlinedModules.size === 1 && hasChunkModules; + // TODO: + // This step is before the IIFE reason calculation. Ideally, it should only be executed when this function can optimize the + // IIFE reason. Otherwise, it should directly return false. There are four reasons now, we have skipped two already, the left + // one is 'it uses a non-standard name for the exports'. + if (isMultipleEntries || innerStrict || !singleEntryWithModules) { + return false; + } + + /** @type {Map} */ + const renamedInlinedModules = new Map(); + const { runtimeTemplate } = renderContext; + + /** @typedef {{ source: Source, module: Module, ast: Program, variables: Set, through: Set, usedInNonInlined: Set, moduleScope: Scope }} Info */ + /** @type {Map} */ + const inlinedModulesToInfo = new Map(); + /** @type {Set} */ + const nonInlinedModuleThroughIdentifiers = new Set(); + /** @type {Map} */ + + for (const m of allModules) { + const isInlinedModule = inlinedModules && inlinedModules.has(m); + const moduleSource = this.renderModule( + m, + { + ...chunkRenderContext, + factory: !isInlinedModule, + inlinedInIIFE: false + }, + hooks + ); + + if (!moduleSource) continue; + const code = /** @type {string} */ (moduleSource.source()); + const ast = JavascriptParser._parse(code, { + sourceType: "auto" + }); + + const scopeManager = eslintScope.analyze(ast, { + ecmaVersion: 6, + sourceType: "module", + optimistic: true, + ignoreEval: true + }); + + const globalScope = /** @type {Scope} */ (scopeManager.acquire(ast)); + if (inlinedModules && inlinedModules.has(m)) { + const moduleScope = globalScope.childScopes[0]; + inlinedModulesToInfo.set(m, { + source: moduleSource, + ast, + module: m, + variables: new Set(moduleScope.variables), + through: new Set(moduleScope.through), + usedInNonInlined: new Set(), + moduleScope + }); + } else { + for (const ref of globalScope.through) { + nonInlinedModuleThroughIdentifiers.add(ref.identifier.name); + } + } + } + + for (const [, { variables, usedInNonInlined }] of inlinedModulesToInfo) { + for (const variable of variables) { + if ( + nonInlinedModuleThroughIdentifiers.has(variable.name) || + RESERVED_NAMES.has(variable.name) + ) { + usedInNonInlined.add(variable); + } + } + } + + for (const [m, moduleInfo] of inlinedModulesToInfo) { + const { ast, source: _source, usedInNonInlined } = moduleInfo; + const source = new ReplaceSource(_source); + if (usedInNonInlined.size === 0) { + renamedInlinedModules.set(m, source); + continue; + } + + const info = /** @type {Info} */ (inlinedModulesToInfo.get(m)); + const allUsedNames = new Set( + Array.from(info.through, (v) => v.identifier.name) + ); + + for (const variable of usedInNonInlined) { + allUsedNames.add(variable.name); + } + + for (const variable of info.variables) { + const usedNamesInScopeInfo = new Map(); + const ignoredScopes = new Set(); + + const name = variable.name; + const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo( + usedNamesInScopeInfo, + info.module.identifier(), + name + ); + + if (allUsedNames.has(name) || usedNames.has(name)) { + const references = getAllReferences(variable); + const allIdentifiers = new Set([ + ...references.map((r) => r.identifier), + ...variable.identifiers + ]); + for (const ref of references) { + addScopeSymbols( + ref.from, + usedNames, + alreadyCheckedScopes, + ignoredScopes + ); + } + + const newName = findNewName( + variable.name, + allUsedNames, + usedNames, + m.readableIdentifier(runtimeTemplate.requestShortener) + ); + allUsedNames.add(newName); + for (const identifier of allIdentifiers) { + const r = /** @type {Range} */ (identifier.range); + const path = getPathInAst(ast, identifier); + if (path && path.length > 1) { + const maybeProperty = + path[1].type === "AssignmentPattern" && path[1].left === path[0] + ? path[2] + : path[1]; + if ( + maybeProperty.type === "Property" && + maybeProperty.shorthand + ) { + source.insert(r[1], `: ${newName}`); + continue; + } + } + source.replace(r[0], r[1] - 1, newName); + } + } + allUsedNames.add(name); + } + + renamedInlinedModules.set(m, source); + } + + return renamedInlinedModules; + } +} + +module.exports = JavascriptModulesPlugin; +module.exports.chunkHasJs = chunkHasJs; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptParser.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptParser.js new file mode 100644 index 0000000000000000000000000000000000000000..995a45bee0fef6b8f32f17b6caca8e0d5c177d65 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptParser.js @@ -0,0 +1,5261 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const vm = require("vm"); +const { Parser: AcornParser, tokTypes } = require("acorn"); +const { HookMap, SyncBailHook } = require("tapable"); +const Parser = require("../Parser"); +const StackedMap = require("../util/StackedMap"); +const binarySearchBounds = require("../util/binarySearchBounds"); +const { + createMagicCommentContext, + webpackCommentRegExp +} = require("../util/magicComment"); +const memoize = require("../util/memoize"); +const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); + +/** @typedef {import("acorn").Options} AcornOptions */ +/** @typedef {import("estree").AssignmentExpression} AssignmentExpression */ +/** @typedef {import("estree").BinaryExpression} BinaryExpression */ +/** @typedef {import("estree").BlockStatement} BlockStatement */ +/** @typedef {import("estree").SequenceExpression} SequenceExpression */ +/** @typedef {import("estree").CallExpression} CallExpression */ +/** @typedef {import("estree").BaseCallExpression} BaseCallExpression */ +/** @typedef {import("estree").StaticBlock} StaticBlock */ +/** @typedef {import("estree").ClassDeclaration} ClassDeclaration */ +/** @typedef {import("estree").ForStatement} ForStatement */ +/** @typedef {import("estree").SwitchStatement} SwitchStatement */ +/** @typedef {import("estree").ClassExpression} ClassExpression */ +/** @typedef {import("estree").Comment} Comment */ +/** @typedef {import("estree").ConditionalExpression} ConditionalExpression */ +/** @typedef {import("estree").Declaration} Declaration */ +/** @typedef {import("estree").PrivateIdentifier} PrivateIdentifier */ +/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").VariableDeclaration} VariableDeclaration */ +/** @typedef {import("estree").IfStatement} IfStatement */ +/** @typedef {import("estree").LabeledStatement} LabeledStatement */ +/** @typedef {import("estree").Literal} Literal */ +/** @typedef {import("estree").LogicalExpression} LogicalExpression */ +/** @typedef {import("estree").ChainExpression} ChainExpression */ +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("estree").YieldExpression} YieldExpression */ +/** @typedef {import("estree").MetaProperty} MetaProperty */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").AssignmentPattern} AssignmentPattern */ +/** @typedef {import("estree").ChainElement} ChainElement */ +/** @typedef {import("estree").Pattern} Pattern */ +/** @typedef {import("estree").UpdateExpression} UpdateExpression */ +/** @typedef {import("estree").ObjectExpression} ObjectExpression */ +/** @typedef {import("estree").UnaryExpression} UnaryExpression */ +/** @typedef {import("estree").ArrayExpression} ArrayExpression */ +/** @typedef {import("estree").ArrayPattern} ArrayPattern */ +/** @typedef {import("estree").AwaitExpression} AwaitExpression */ +/** @typedef {import("estree").ThisExpression} ThisExpression */ +/** @typedef {import("estree").RestElement} RestElement */ +/** @typedef {import("estree").ObjectPattern} ObjectPattern */ +/** @typedef {import("estree").SwitchCase} SwitchCase */ +/** @typedef {import("estree").CatchClause} CatchClause */ +/** @typedef {import("estree").VariableDeclarator} VariableDeclarator */ +/** @typedef {import("estree").ForInStatement} ForInStatement */ +/** @typedef {import("estree").ForOfStatement} ForOfStatement */ +/** @typedef {import("estree").ReturnStatement} ReturnStatement */ +/** @typedef {import("estree").WithStatement} WithStatement */ +/** @typedef {import("estree").ThrowStatement} ThrowStatement */ +/** @typedef {import("estree").MethodDefinition} MethodDefinition */ +/** @typedef {import("estree").NewExpression} NewExpression */ +/** @typedef {import("estree").SpreadElement} SpreadElement */ +/** @typedef {import("estree").FunctionExpression} FunctionExpression */ +/** @typedef {import("estree").WhileStatement} WhileStatement */ +/** @typedef {import("estree").ArrowFunctionExpression} ArrowFunctionExpression */ +/** @typedef {import("estree").ExpressionStatement} ExpressionStatement */ +/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */ +/** @typedef {import("estree").DoWhileStatement} DoWhileStatement */ +/** @typedef {import("estree").TryStatement} TryStatement */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").Program} Program */ +/** @typedef {import("estree").Directive} Directive */ +/** @typedef {import("estree").Statement} Statement */ +/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */ +/** @typedef {import("estree").Super} Super */ +/** @typedef {import("estree").ImportSpecifier} ImportSpecifier */ +/** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpression */ +/** @typedef {import("estree").TemplateLiteral} TemplateLiteral */ +/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */ +/** @typedef {import("estree").MaybeNamedFunctionDeclaration} MaybeNamedFunctionDeclaration */ +/** @typedef {import("estree").MaybeNamedClassDeclaration} MaybeNamedClassDeclaration */ +/** + * @template T + * @typedef {import("tapable").AsArray} AsArray + */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[] }} GetInfoResult */ +/** @typedef {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} StatementPathItem */ +/** @typedef {(ident: string) => void} OnIdentString */ +/** @typedef {(ident: string, identifier: Identifier) => void} OnIdent */ +/** @typedef {StatementPathItem[]} StatementPath */ + +// TODO remove cast when @types/estree has been updated to import assertions +/** @typedef {import("estree").BaseNode & { type: "ImportAttribute", key: Identifier | Literal, value: Literal }} ImportAttribute */ +/** @typedef {import("estree").ImportDeclaration & { attributes?: Array, phase?: "defer" }} ImportDeclaration */ +/** @typedef {import("estree").ExportNamedDeclaration & { attributes?: Array }} ExportNamedDeclaration */ +/** @typedef {import("estree").ExportAllDeclaration & { attributes?: Array }} ExportAllDeclaration */ +/** @typedef {import("estree").ImportExpression & { options?: Expression | null, phase?: "defer" }} ImportExpression */ +/** @typedef {ImportDeclaration | ExportNamedDeclaration | ExportDefaultDeclaration | ExportAllDeclaration} ModuleDeclaration */ + +/** @type {string[]} */ +const EMPTY_ARRAY = []; +const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01; +const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10; +const ALLOWED_MEMBER_TYPES_ALL = 0b11; + +const LEGACY_ASSERT_ATTRIBUTES = Symbol("assert"); + +/** @type {(BaseParser: typeof AcornParser) => typeof AcornParser} */ +const importAssertions = (Parser) => + class extends Parser { + /** + * @this {InstanceType} + * @returns {ImportAttribute[]} import attributes + */ + parseWithClause() { + /** @type {ImportAttribute[]} */ + const nodes = []; + + const isAssertLegacy = this.value === "assert"; + + if (isAssertLegacy) { + if (!this.eat(tokTypes.name)) { + return nodes; + } + } else if (!this.eat(tokTypes._with)) { + return nodes; + } + + this.expect(tokTypes.braceL); + + /** @type {Record} */ + const attributeKeys = {}; + let first = true; + + while (!this.eat(tokTypes.braceR)) { + if (!first) { + this.expect(tokTypes.comma); + if (this.afterTrailingComma(tokTypes.braceR)) { + break; + } + } else { + first = false; + } + + const attr = + /** @type {ImportAttribute} */ + this.parseImportAttribute(); + const keyName = + attr.key.type === "Identifier" ? attr.key.name : attr.key.value; + + if (Object.prototype.hasOwnProperty.call(attributeKeys, keyName)) { + this.raiseRecoverable( + attr.key.start, + `Duplicate attribute key '${keyName}'` + ); + } + + attributeKeys[keyName] = true; + nodes.push(attr); + } + + if (isAssertLegacy) { + /** @type {EXPECTED_ANY} */ + (nodes)[LEGACY_ASSERT_ATTRIBUTES] = true; + } + + return nodes; + } + }; + +// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API +let parser = AcornParser.extend(importAssertions); + +/** @typedef {Record & { _isLegacyAssert?: boolean }} ImportAttributes */ + +/** + * @param {ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | ImportExpression} node node with assertions + * @returns {ImportAttributes | undefined} import attributes + */ +const getImportAttributes = (node) => { + if (node.type === "ImportExpression") { + if ( + node.options && + node.options.type === "ObjectExpression" && + node.options.properties[0] && + node.options.properties[0].type === "Property" && + node.options.properties[0].key.type === "Identifier" && + (node.options.properties[0].key.name === "with" || + node.options.properties[0].key.name === "assert") && + node.options.properties[0].value.type === "ObjectExpression" && + node.options.properties[0].value.properties.length > 0 + ) { + const properties = + /** @type {Property[]} */ + (node.options.properties[0].value.properties); + const result = /** @type {ImportAttributes} */ ({}); + for (const property of properties) { + const key = + /** @type {string} */ + ( + property.key.type === "Identifier" + ? property.key.name + : /** @type {Literal} */ (property.key).value + ); + result[key] = + /** @type {string} */ + (/** @type {Literal} */ (property.value).value); + } + const key = + node.options.properties[0].key.type === "Identifier" + ? node.options.properties[0].key.name + : /** @type {Literal} */ (node.options.properties[0].key).value; + + if (key === "assert") { + result._isLegacyAssert = true; + } + + return result; + } + + return; + } + + if (node.attributes === undefined || node.attributes.length === 0) { + return; + } + + const result = /** @type {ImportAttributes} */ ({}); + + for (const attribute of node.attributes) { + const key = + /** @type {string} */ + ( + attribute.key.type === "Identifier" + ? attribute.key.name + : attribute.key.value + ); + + result[key] = /** @type {string} */ (attribute.value.value); + } + + if (/** @type {EXPECTED_ANY} */ (node.attributes)[LEGACY_ASSERT_ATTRIBUTES]) { + result._isLegacyAssert = true; + } + + return result; +}; + +/** @typedef {typeof VariableInfoFlags.Evaluated | typeof VariableInfoFlags.Free | typeof VariableInfoFlags.Normal | typeof VariableInfoFlags.Tagged} VariableInfoFlagsType */ + +const VariableInfoFlags = Object.freeze({ + Evaluated: 0b000, + Free: 0b001, + Normal: 0b010, + Tagged: 0b100 +}); + +class VariableInfo { + /** + * @param {ScopeInfo} declaredScope scope in which the variable is declared + * @param {string | undefined} name which name the variable use, defined name or free name or tagged name + * @param {VariableInfoFlagsType} flags how the variable is created + * @param {TagInfo | undefined} tagInfo info about tags + */ + constructor(declaredScope, name, flags, tagInfo) { + this.declaredScope = declaredScope; + this.name = name; + this.flags = flags; + this.tagInfo = tagInfo; + } + + /** + * @returns {boolean} the variable is free or not + */ + isFree() { + return (this.flags & VariableInfoFlags.Free) > 0; + } + + /** + * @returns {boolean} the variable is tagged by tagVariable or not + */ + isTagged() { + return (this.flags & VariableInfoFlags.Tagged) > 0; + } +} + +/** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */ +/** @typedef {Literal | string | null | undefined} ImportSource */ +/** @typedef {Omit & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */ + +/** @typedef {symbol} Tag */ +/** @typedef {Record} TagData */ + +/** + * @typedef {object} TagInfo + * @property {Tag} tag + * @property {TagData=} data + * @property {TagInfo | undefined} next + */ + +const SCOPE_INFO_TERMINATED_RETURN = 1; +const SCOPE_INFO_TERMINATED_THROW = 2; + +/** + * @typedef {object} ScopeInfo + * @property {StackedMap} definitions + * @property {boolean | "arrow"} topLevelScope + * @property {boolean | string} inShorthand + * @property {boolean} inTaggedTemplateTag + * @property {boolean} inTry + * @property {boolean} isStrict + * @property {boolean} isAsmJs + * @property {undefined | 1 | 2} terminated + */ + +/** @typedef {[number, number]} Range */ + +/** + * @typedef {object} DestructuringAssignmentProperty + * @property {string} id + * @property {Range | undefined=} range + * @property {boolean | string} shorthand + */ + +/** + * Helper function for joining two ranges into a single range. This is useful + * when working with AST nodes, as it allows you to combine the ranges of child nodes + * to create the range of the _parent node_. + * @param {Range} startRange start range to join + * @param {Range} endRange end range to join + * @returns {Range} joined range + * @example + * ```js + * const startRange = [0, 5]; + * const endRange = [10, 15]; + * const joinedRange = joinRanges(startRange, endRange); + * console.log(joinedRange); // [0, 15] + * ``` + */ +const joinRanges = (startRange, endRange) => { + if (!endRange) return startRange; + if (!startRange) return endRange; + return [startRange[0], endRange[1]]; +}; + +/** + * Helper function used to generate a string representation of a + * [member expression](https://github.com/estree/estree/blob/master/es5.md#memberexpression). + * @param {string} object object to name + * @param {string[]} membersReversed reversed list of members + * @returns {string} member expression as a string + * @example + * ```js + * const membersReversed = ["property1", "property2", "property3"]; // Members parsed from the AST + * const name = objectAndMembersToName("myObject", membersReversed); + * + * console.log(name); // "myObject.property1.property2.property3" + * ``` + */ +const objectAndMembersToName = (object, membersReversed) => { + let name = object; + for (let i = membersReversed.length - 1; i >= 0; i--) { + name = `${name}.${membersReversed[i]}`; + } + return name; +}; + +/** + * Grabs the name of a given expression and returns it as a string or undefined. Has particular + * handling for [Identifiers](https://github.com/estree/estree/blob/master/es5.md#identifier), + * [ThisExpressions](https://github.com/estree/estree/blob/master/es5.md#identifier), and + * [MetaProperties](https://github.com/estree/estree/blob/master/es2015.md#metaproperty) which is + * specifically for handling the `new.target` meta property. + * @param {Expression | SpreadElement | Super} expression expression + * @returns {string | "this" | undefined} name or variable info + */ +const getRootName = (expression) => { + switch (expression.type) { + case "Identifier": + return expression.name; + case "ThisExpression": + return "this"; + case "MetaProperty": + return `${expression.meta.name}.${expression.property.name}`; + default: + return undefined; + } +}; + +/** @type {AcornOptions} */ +const defaultParserOptions = { + ranges: true, + locations: true, + ecmaVersion: "latest", + sourceType: "module", + // https://github.com/tc39/proposal-hashbang + allowHashBang: true, + onComment: undefined +}; + +const EMPTY_COMMENT_OPTIONS = { + options: null, + errors: null +}; + +const CLASS_NAME = "JavascriptParser"; + +class JavascriptParser extends Parser { + /** + * @param {"module" | "script" | "auto"} sourceType default source type + */ + constructor(sourceType = "auto") { + super(); + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + evaluate: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + evaluateDefinedIdentifier: new HookMap( + () => new SyncBailHook(["expression"]) + ), + /** @type {HookMap>} */ + evaluateNewExpression: new HookMap( + () => new SyncBailHook(["expression"]) + ), + /** @type {HookMap>} */ + evaluateCallExpression: new HookMap( + () => new SyncBailHook(["expression"]) + ), + /** @type {HookMap>} */ + evaluateCallExpressionMember: new HookMap( + () => new SyncBailHook(["expression", "param"]) + ), + /** @type {HookMap>} */ + isPure: new HookMap( + () => new SyncBailHook(["expression", "commentsStartPosition"]) + ), + /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>} */ + preStatement: new SyncBailHook(["statement"]), + + /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>} */ + blockPreStatement: new SyncBailHook(["declaration"]), + /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration], boolean | void>} */ + statement: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[IfStatement], boolean | void>} */ + statementIf: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[Expression, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */ + classExtendsExpression: new SyncBailHook([ + "expression", + "classDefinition" + ]), + /** @type {SyncBailHook<[MethodDefinition | PropertyDefinition | StaticBlock, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */ + classBodyElement: new SyncBailHook(["element", "classDefinition"]), + /** @type {SyncBailHook<[Expression, MethodDefinition | PropertyDefinition, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */ + classBodyValue: new SyncBailHook([ + "expression", + "element", + "classDefinition" + ]), + /** @type {HookMap>} */ + label: new HookMap(() => new SyncBailHook(["statement"])), + /** @type {SyncBailHook<[ImportDeclaration, ImportSource], boolean | void>} */ + import: new SyncBailHook(["statement", "source"]), + /** @type {SyncBailHook<[ImportDeclaration, ImportSource, string | null, string], boolean | void>} */ + importSpecifier: new SyncBailHook([ + "statement", + "source", + "exportName", + "identifierName" + ]), + /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration], boolean | void>} */ + export: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource], boolean | void>} */ + exportImport: new SyncBailHook(["statement", "source"]), + /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, Declaration], boolean | void>} */ + exportDeclaration: new SyncBailHook(["statement", "declaration"]), + /** @type {SyncBailHook<[ExportDefaultDeclaration, MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression], boolean | void>} */ + exportExpression: new SyncBailHook(["statement", "node"]), + /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, string, string, number | undefined], boolean | void>} */ + exportSpecifier: new SyncBailHook([ + "statement", + "identifierName", + "exportName", + "index" + ]), + /** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource, string | null, string | null, number | undefined], boolean | void>} */ + exportImportSpecifier: new SyncBailHook([ + "statement", + "source", + "identifierName", + "exportName", + "index" + ]), + /** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */ + preDeclarator: new SyncBailHook(["declarator", "statement"]), + /** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */ + declarator: new SyncBailHook(["declarator", "statement"]), + /** @type {HookMap>} */ + varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationUsing: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + pattern: new HookMap(() => new SyncBailHook(["pattern"])), + /** @type {SyncBailHook<[Expression], boolean | void>} */ + collectDestructuringAssignmentProperties: new SyncBailHook([ + "expression" + ]), + /** @type {HookMap>} */ + canRename: new HookMap(() => new SyncBailHook(["initExpression"])), + /** @type {HookMap>} */ + rename: new HookMap(() => new SyncBailHook(["initExpression"])), + /** @type {HookMap>} */ + assign: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + assignMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** @type {HookMap>} */ + typeof: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {SyncBailHook<[ImportExpression], boolean | void>} */ + importCall: new SyncBailHook(["expression"]), + /** @type {SyncBailHook<[Expression | ForOfStatement], boolean | void>} */ + topLevelAwait: new SyncBailHook(["expression"]), + /** @type {HookMap>} */ + call: new HookMap(() => new SyncBailHook(["expression"])), + /** Something like "a.b()" */ + /** @type {HookMap>} */ + callMemberChain: new HookMap( + () => + new SyncBailHook([ + "expression", + "members", + "membersOptionals", + "memberRanges" + ]) + ), + /** Something like "a.b().c.d" */ + /** @type {HookMap>} */ + memberChainOfCallMemberChain: new HookMap( + () => + new SyncBailHook([ + "expression", + "calleeMembers", + "callExpression", + "members", + "memberRanges" + ]) + ), + /** Something like "a.b().c.d()"" */ + /** @type {HookMap>} */ + callMemberChainOfCallMemberChain: new HookMap( + () => + new SyncBailHook([ + "expression", + "calleeMembers", + "innerCallExpression", + "members", + "memberRanges" + ]) + ), + /** @type {SyncBailHook<[ChainExpression], boolean | void>} */ + optionalChaining: new SyncBailHook(["optionalChaining"]), + /** @type {HookMap>} */ + new: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {SyncBailHook<[BinaryExpression], boolean | void>} */ + binaryExpression: new SyncBailHook(["binaryExpression"]), + /** @type {HookMap>} */ + expression: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + expressionMemberChain: new HookMap( + () => + new SyncBailHook([ + "expression", + "members", + "membersOptionals", + "memberRanges" + ]) + ), + /** @type {HookMap>} */ + unhandledExpressionMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** @type {SyncBailHook<[ConditionalExpression], boolean | void>} */ + expressionConditionalOperator: new SyncBailHook(["expression"]), + /** @type {SyncBailHook<[LogicalExpression], boolean | void>} */ + expressionLogicalOperator: new SyncBailHook(["expression"]), + /** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */ + program: new SyncBailHook(["ast", "comments"]), + /** @type {SyncBailHook<[ThrowStatement | ReturnStatement], boolean | void>} */ + terminate: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */ + finish: new SyncBailHook(["ast", "comments"]), + /** @type {SyncBailHook<[Statement], boolean | void>} */ + unusedStatement: new SyncBailHook(["statement"]) + }); + this.sourceType = sourceType; + /** @type {ScopeInfo} */ + this.scope = /** @type {TODO} */ (undefined); + /** @type {ParserState} */ + this.state = /** @type {TODO} */ (undefined); + /** @type {Comment[] | undefined} */ + this.comments = undefined; + /** @type {Set | undefined} */ + this.semicolons = undefined; + /** @type {StatementPath | undefined} */ + this.statementPath = undefined; + /** @type {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | undefined} */ + this.prevStatement = undefined; + /** @type {WeakMap> | undefined} */ + this.destructuringAssignmentProperties = undefined; + /** @type {TagData | undefined} */ + this.currentTagData = undefined; + this.magicCommentContext = createMagicCommentContext(); + this._initializeEvaluating(); + } + + _initializeEvaluating() { + this.hooks.evaluate.for("Literal").tap(CLASS_NAME, (_expr) => { + const expr = /** @type {Literal} */ (_expr); + + switch (typeof expr.value) { + case "number": + return new BasicEvaluatedExpression() + .setNumber(expr.value) + .setRange(/** @type {Range} */ (expr.range)); + case "bigint": + return new BasicEvaluatedExpression() + .setBigInt(expr.value) + .setRange(/** @type {Range} */ (expr.range)); + case "string": + return new BasicEvaluatedExpression() + .setString(expr.value) + .setRange(/** @type {Range} */ (expr.range)); + case "boolean": + return new BasicEvaluatedExpression() + .setBoolean(expr.value) + .setRange(/** @type {Range} */ (expr.range)); + } + if (expr.value === null) { + return new BasicEvaluatedExpression() + .setNull() + .setRange(/** @type {Range} */ (expr.range)); + } + if (expr.value instanceof RegExp) { + return new BasicEvaluatedExpression() + .setRegExp(expr.value) + .setRange(/** @type {Range} */ (expr.range)); + } + }); + this.hooks.evaluate.for("NewExpression").tap(CLASS_NAME, (_expr) => { + const expr = /** @type {NewExpression} */ (_expr); + const callee = expr.callee; + if (callee.type !== "Identifier") return; + if (callee.name !== "RegExp") { + return this.callHooksForName( + this.hooks.evaluateNewExpression, + callee.name, + expr + ); + } else if ( + expr.arguments.length > 2 || + this.getVariableInfo("RegExp") !== "RegExp" + ) { + return; + } + + let regExp; + const arg1 = expr.arguments[0]; + + if (arg1) { + if (arg1.type === "SpreadElement") return; + + const evaluatedRegExp = this.evaluateExpression(arg1); + + if (!evaluatedRegExp) return; + + regExp = evaluatedRegExp.asString(); + + if (!regExp) return; + } else { + return ( + new BasicEvaluatedExpression() + // eslint-disable-next-line prefer-regex-literals + .setRegExp(new RegExp("")) + .setRange(/** @type {Range} */ (expr.range)) + ); + } + + let flags; + const arg2 = expr.arguments[1]; + + if (arg2) { + if (arg2.type === "SpreadElement") return; + + const evaluatedFlags = this.evaluateExpression(arg2); + + if (!evaluatedFlags) return; + + if (!evaluatedFlags.isUndefined()) { + flags = evaluatedFlags.asString(); + + if ( + flags === undefined || + !BasicEvaluatedExpression.isValidRegExpFlags(flags) + ) { + return; + } + } + } + + return new BasicEvaluatedExpression() + .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp)) + .setRange(/** @type {Range} */ (expr.range)); + }); + this.hooks.evaluate.for("LogicalExpression").tap(CLASS_NAME, (_expr) => { + const expr = /** @type {LogicalExpression} */ (_expr); + + const left = this.evaluateExpression(expr.left); + let returnRight = false; + /** @type {boolean | undefined} */ + let allowedRight; + if (expr.operator === "&&") { + const leftAsBool = left.asBool(); + if (leftAsBool === false) { + return left.setRange(/** @type {Range} */ (expr.range)); + } + returnRight = leftAsBool === true; + allowedRight = false; + } else if (expr.operator === "||") { + const leftAsBool = left.asBool(); + if (leftAsBool === true) { + return left.setRange(/** @type {Range} */ (expr.range)); + } + returnRight = leftAsBool === false; + allowedRight = true; + } else if (expr.operator === "??") { + const leftAsNullish = left.asNullish(); + if (leftAsNullish === false) { + return left.setRange(/** @type {Range} */ (expr.range)); + } + if (leftAsNullish !== true) return; + returnRight = true; + } else { + return; + } + const right = this.evaluateExpression(expr.right); + if (returnRight) { + if (left.couldHaveSideEffects()) right.setSideEffects(); + return right.setRange(/** @type {Range} */ (expr.range)); + } + + const asBool = right.asBool(); + + if (allowedRight === true && asBool === true) { + return new BasicEvaluatedExpression() + .setRange(/** @type {Range} */ (expr.range)) + .setTruthy(); + } else if (allowedRight === false && asBool === false) { + return new BasicEvaluatedExpression() + .setRange(/** @type {Range} */ (expr.range)) + .setFalsy(); + } + }); + + /** + * In simple logical cases, we can use valueAsExpression to assist us in evaluating the expression on + * either side of a [BinaryExpression](https://github.com/estree/estree/blob/master/es5.md#binaryexpression). + * This supports scenarios in webpack like conditionally `import()`'ing modules based on some simple evaluation: + * + * ```js + * if (1 === 3) { + * import("./moduleA"); // webpack will auto evaluate this and not import the modules + * } + * ``` + * + * Additional scenarios include evaluation of strings inside of dynamic import statements: + * + * ```js + * const foo = "foo"; + * const bar = "bar"; + * + * import("./" + foo + bar); // webpack will auto evaluate this into import("./foobar") + * ``` + * @param {boolean | number | bigint | string} value the value to convert to an expression + * @param {BinaryExpression | UnaryExpression} expr the expression being evaluated + * @param {boolean} sideEffects whether the expression has side effects + * @returns {BasicEvaluatedExpression | undefined} the evaluated expression + * @example + * + * ```js + * const binaryExpr = new BinaryExpression("+", + * { type: "Literal", value: 2 }, + * { type: "Literal", value: 3 } + * ); + * + * const leftValue = 2; + * const rightValue = 3; + * + * const leftExpr = valueAsExpression(leftValue, binaryExpr.left, false); + * const rightExpr = valueAsExpression(rightValue, binaryExpr.right, false); + * const result = new BasicEvaluatedExpression() + * .setNumber(leftExpr.number + rightExpr.number) + * .setRange(binaryExpr.range); + * + * console.log(result.number); // Output: 5 + * ``` + */ + const valueAsExpression = (value, expr, sideEffects) => { + switch (typeof value) { + case "boolean": + return new BasicEvaluatedExpression() + .setBoolean(value) + .setSideEffects(sideEffects) + .setRange(/** @type {Range} */ (expr.range)); + case "number": + return new BasicEvaluatedExpression() + .setNumber(value) + .setSideEffects(sideEffects) + .setRange(/** @type {Range} */ (expr.range)); + case "bigint": + return new BasicEvaluatedExpression() + .setBigInt(value) + .setSideEffects(sideEffects) + .setRange(/** @type {Range} */ (expr.range)); + case "string": + return new BasicEvaluatedExpression() + .setString(value) + .setSideEffects(sideEffects) + .setRange(/** @type {Range} */ (expr.range)); + } + }; + + this.hooks.evaluate.for("BinaryExpression").tap(CLASS_NAME, (_expr) => { + const expr = /** @type {BinaryExpression} */ (_expr); + + /** + * Evaluates a binary expression if and only if it is a const operation (e.g. 1 + 2, "a" + "b", etc.). + * @template T + * @param {(leftOperand: T, rightOperand: T) => boolean | number | bigint | string} operandHandler the handler for the operation (e.g. (a, b) => a + b) + * @returns {BasicEvaluatedExpression | undefined} the evaluated expression + */ + const handleConstOperation = (operandHandler) => { + const left = this.evaluateExpression(expr.left); + if (!left.isCompileTimeValue()) return; + + const right = this.evaluateExpression(expr.right); + if (!right.isCompileTimeValue()) return; + + const result = operandHandler( + /** @type {T} */ (left.asCompileTimeValue()), + /** @type {T} */ (right.asCompileTimeValue()) + ); + return valueAsExpression( + result, + expr, + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + }; + + /** + * Helper function to determine if two booleans are always different. This is used in `handleStrictEqualityComparison` + * to determine if an expressions boolean or nullish conversion is equal or not. + * @param {boolean} a first boolean to compare + * @param {boolean} b second boolean to compare + * @returns {boolean} true if the two booleans are always different, false otherwise + */ + const isAlwaysDifferent = (a, b) => + (a === true && b === false) || (a === false && b === true); + + /** + * @param {BasicEvaluatedExpression} left left + * @param {BasicEvaluatedExpression} right right + * @param {BasicEvaluatedExpression} res res + * @param {boolean} eql true for "===" and false for "!==" + * @returns {BasicEvaluatedExpression | undefined} result + */ + const handleTemplateStringCompare = (left, right, res, eql) => { + /** + * @param {BasicEvaluatedExpression[]} parts parts + * @returns {string} value + */ + const getPrefix = (parts) => { + let value = ""; + for (const p of parts) { + const v = p.asString(); + if (v !== undefined) value += v; + else break; + } + return value; + }; + /** + * @param {BasicEvaluatedExpression[]} parts parts + * @returns {string} value + */ + const getSuffix = (parts) => { + let value = ""; + for (let i = parts.length - 1; i >= 0; i--) { + const v = parts[i].asString(); + if (v !== undefined) value = v + value; + else break; + } + return value; + }; + const leftPrefix = getPrefix( + /** @type {BasicEvaluatedExpression[]} */ (left.parts) + ); + const rightPrefix = getPrefix( + /** @type {BasicEvaluatedExpression[]} */ (right.parts) + ); + const leftSuffix = getSuffix( + /** @type {BasicEvaluatedExpression[]} */ (left.parts) + ); + const rightSuffix = getSuffix( + /** @type {BasicEvaluatedExpression[]} */ (right.parts) + ); + const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length); + const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length); + const prefixMismatch = + lenPrefix > 0 && + leftPrefix.slice(0, lenPrefix) !== rightPrefix.slice(0, lenPrefix); + const suffixMismatch = + lenSuffix > 0 && + leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix); + if (prefixMismatch || suffixMismatch) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + }; + + /** + * Helper function to handle BinaryExpressions using strict equality comparisons (e.g. "===" and "!=="). + * @param {boolean} eql true for "===" and false for "!==" + * @returns {BasicEvaluatedExpression | undefined} the evaluated expression + */ + const handleStrictEqualityComparison = (eql) => { + const left = this.evaluateExpression(expr.left); + const right = this.evaluateExpression(expr.right); + const res = new BasicEvaluatedExpression(); + res.setRange(/** @type {Range} */ (expr.range)); + + const leftConst = left.isCompileTimeValue(); + const rightConst = right.isCompileTimeValue(); + + if (leftConst && rightConst) { + return res + .setBoolean( + eql === (left.asCompileTimeValue() === right.asCompileTimeValue()) + ) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + + if (left.isArray() && right.isArray()) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + if (left.isTemplateString() && right.isTemplateString()) { + return handleTemplateStringCompare(left, right, res, eql); + } + + const leftPrimitive = left.isPrimitiveType(); + const rightPrimitive = right.isPrimitiveType(); + + if ( + // Primitive !== Object or + // compile-time object types are never equal to something at runtime + (leftPrimitive === false && (leftConst || rightPrimitive === true)) || + (rightPrimitive === false && + (rightConst || leftPrimitive === true)) || + // Different nullish or boolish status also means not equal + isAlwaysDifferent( + /** @type {boolean} */ (left.asBool()), + /** @type {boolean} */ (right.asBool()) + ) || + isAlwaysDifferent( + /** @type {boolean} */ (left.asNullish()), + /** @type {boolean} */ (right.asNullish()) + ) + ) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + }; + + /** + * Helper function to handle BinaryExpressions using abstract equality comparisons (e.g. "==" and "!="). + * @param {boolean} eql true for "==" and false for "!=" + * @returns {BasicEvaluatedExpression | undefined} the evaluated expression + */ + const handleAbstractEqualityComparison = (eql) => { + const left = this.evaluateExpression(expr.left); + const right = this.evaluateExpression(expr.right); + const res = new BasicEvaluatedExpression(); + res.setRange(/** @type {Range} */ (expr.range)); + + const leftConst = left.isCompileTimeValue(); + const rightConst = right.isCompileTimeValue(); + + if (leftConst && rightConst) { + return res + .setBoolean( + eql === + // eslint-disable-next-line eqeqeq + (left.asCompileTimeValue() == right.asCompileTimeValue()) + ) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + + if (left.isArray() && right.isArray()) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + if (left.isTemplateString() && right.isTemplateString()) { + return handleTemplateStringCompare(left, right, res, eql); + } + }; + + if (expr.operator === "+") { + const left = this.evaluateExpression(expr.left); + const right = this.evaluateExpression(expr.right); + const res = new BasicEvaluatedExpression(); + if (left.isString()) { + if (right.isString()) { + res.setString( + /** @type {string} */ (left.string) + + /** @type {string} */ (right.string) + ); + } else if (right.isNumber()) { + res.setString(/** @type {string} */ (left.string) + right.number); + } else if ( + right.isWrapped() && + right.prefix && + right.prefix.isString() + ) { + // "left" + ("prefix" + inner + "postfix") + // => ("leftPrefix" + inner + "postfix") + res.setWrapped( + new BasicEvaluatedExpression() + .setString( + /** @type {string} */ (left.string) + + /** @type {string} */ (right.prefix.string) + ) + .setRange( + joinRanges( + /** @type {Range} */ (left.range), + /** @type {Range} */ (right.prefix.range) + ) + ), + right.postfix, + right.wrappedInnerExpressions + ); + } else if (right.isWrapped()) { + // "left" + ([null] + inner + "postfix") + // => ("left" + inner + "postfix") + res.setWrapped(left, right.postfix, right.wrappedInnerExpressions); + } else { + // "left" + expr + // => ("left" + expr + "") + res.setWrapped(left, null, [right]); + } + } else if (left.isNumber()) { + if (right.isString()) { + res.setString(left.number + /** @type {string} */ (right.string)); + } else if (right.isNumber()) { + res.setNumber( + /** @type {number} */ (left.number) + + /** @type {number} */ (right.number) + ); + } else { + return; + } + } else if (left.isBigInt()) { + if (right.isBigInt()) { + res.setBigInt( + /** @type {bigint} */ (left.bigint) + + /** @type {bigint} */ (right.bigint) + ); + } + } else if (left.isWrapped()) { + if (left.postfix && left.postfix.isString() && right.isString()) { + // ("prefix" + inner + "postfix") + "right" + // => ("prefix" + inner + "postfixRight") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString( + /** @type {string} */ (left.postfix.string) + + /** @type {string} */ (right.string) + ) + .setRange( + joinRanges( + /** @type {Range} */ (left.postfix.range), + /** @type {Range} */ (right.range) + ) + ), + left.wrappedInnerExpressions + ); + } else if ( + left.postfix && + left.postfix.isString() && + right.isNumber() + ) { + // ("prefix" + inner + "postfix") + 123 + // => ("prefix" + inner + "postfix123") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString( + /** @type {string} */ (left.postfix.string) + + /** @type {number} */ (right.number) + ) + .setRange( + joinRanges( + /** @type {Range} */ (left.postfix.range), + /** @type {Range} */ (right.range) + ) + ), + left.wrappedInnerExpressions + ); + } else if (right.isString()) { + // ("prefix" + inner + [null]) + "right" + // => ("prefix" + inner + "right") + res.setWrapped(left.prefix, right, left.wrappedInnerExpressions); + } else if (right.isNumber()) { + // ("prefix" + inner + [null]) + 123 + // => ("prefix" + inner + "123") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(String(right.number)) + .setRange(/** @type {Range} */ (right.range)), + left.wrappedInnerExpressions + ); + } else if (right.isWrapped()) { + // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2") + // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2") + res.setWrapped( + left.prefix, + right.postfix, + left.wrappedInnerExpressions && + right.wrappedInnerExpressions && [ + ...left.wrappedInnerExpressions, + ...(left.postfix ? [left.postfix] : []), + ...(right.prefix ? [right.prefix] : []), + ...right.wrappedInnerExpressions + ] + ); + } else { + // ("prefix" + inner + postfix) + expr + // => ("prefix" + inner + postfix + expr + [null]) + res.setWrapped( + left.prefix, + null, + left.wrappedInnerExpressions && [ + ...left.wrappedInnerExpressions, + ...(left.postfix ? [left.postfix, right] : [right]) + ] + ); + } + } else if (right.isString()) { + // left + "right" + // => ([null] + left + "right") + res.setWrapped(null, right, [left]); + } else if (right.isWrapped()) { + // left + (prefix + inner + "postfix") + // => ([null] + left + prefix + inner + "postfix") + res.setWrapped( + null, + right.postfix, + right.wrappedInnerExpressions && [ + ...(right.prefix ? [left, right.prefix] : [left]), + ...right.wrappedInnerExpressions + ] + ); + } else { + return; + } + if (left.couldHaveSideEffects() || right.couldHaveSideEffects()) { + res.setSideEffects(); + } + res.setRange(/** @type {Range} */ (expr.range)); + return res; + } else if (expr.operator === "-") { + return handleConstOperation((l, r) => l - r); + } else if (expr.operator === "*") { + return handleConstOperation((l, r) => l * r); + } else if (expr.operator === "/") { + return handleConstOperation((l, r) => l / r); + } else if (expr.operator === "**") { + return handleConstOperation((l, r) => l ** r); + } else if (expr.operator === "===") { + return handleStrictEqualityComparison(true); + } else if (expr.operator === "==") { + return handleAbstractEqualityComparison(true); + } else if (expr.operator === "!==") { + return handleStrictEqualityComparison(false); + } else if (expr.operator === "!=") { + return handleAbstractEqualityComparison(false); + } else if (expr.operator === "&") { + return handleConstOperation((l, r) => l & r); + } else if (expr.operator === "|") { + return handleConstOperation((l, r) => l | r); + } else if (expr.operator === "^") { + return handleConstOperation((l, r) => l ^ r); + } else if (expr.operator === ">>>") { + return handleConstOperation((l, r) => l >>> r); + } else if (expr.operator === ">>") { + return handleConstOperation((l, r) => l >> r); + } else if (expr.operator === "<<") { + return handleConstOperation((l, r) => l << r); + } else if (expr.operator === "<") { + return handleConstOperation((l, r) => l < r); + } else if (expr.operator === ">") { + return handleConstOperation((l, r) => l > r); + } else if (expr.operator === "<=") { + return handleConstOperation((l, r) => l <= r); + } else if (expr.operator === ">=") { + return handleConstOperation((l, r) => l >= r); + } + }); + this.hooks.evaluate.for("UnaryExpression").tap(CLASS_NAME, (_expr) => { + const expr = /** @type {UnaryExpression} */ (_expr); + + /** + * Evaluates a UnaryExpression if and only if it is a basic const operator (e.g. +a, -a, ~a). + * @template T + * @param {(operand: T) => boolean | number | bigint | string} operandHandler handler for the operand + * @returns {BasicEvaluatedExpression | undefined} evaluated expression + */ + const handleConstOperation = (operandHandler) => { + const argument = this.evaluateExpression(expr.argument); + if (!argument.isCompileTimeValue()) return; + const result = operandHandler( + /** @type {T} */ (argument.asCompileTimeValue()) + ); + return valueAsExpression(result, expr, argument.couldHaveSideEffects()); + }; + + if (expr.operator === "typeof") { + switch (expr.argument.type) { + case "Identifier": { + const res = this.callHooksForName( + this.hooks.evaluateTypeof, + expr.argument.name, + expr + ); + if (res !== undefined) return res; + break; + } + case "MetaProperty": { + const res = this.callHooksForName( + this.hooks.evaluateTypeof, + /** @type {string} */ + (getRootName(expr.argument)), + expr + ); + if (res !== undefined) return res; + break; + } + case "MemberExpression": { + const res = this.callHooksForExpression( + this.hooks.evaluateTypeof, + expr.argument, + expr + ); + if (res !== undefined) return res; + break; + } + case "ChainExpression": { + const res = this.callHooksForExpression( + this.hooks.evaluateTypeof, + expr.argument.expression, + expr + ); + if (res !== undefined) return res; + break; + } + case "FunctionExpression": { + return new BasicEvaluatedExpression() + .setString("function") + .setRange(/** @type {Range} */ (expr.range)); + } + } + const arg = this.evaluateExpression(expr.argument); + if (arg.isUnknown()) return; + if (arg.isString()) { + return new BasicEvaluatedExpression() + .setString("string") + .setRange(/** @type {Range} */ (expr.range)); + } + if (arg.isWrapped()) { + return new BasicEvaluatedExpression() + .setString("string") + .setSideEffects() + .setRange(/** @type {Range} */ (expr.range)); + } + if (arg.isUndefined()) { + return new BasicEvaluatedExpression() + .setString("undefined") + .setRange(/** @type {Range} */ (expr.range)); + } + if (arg.isNumber()) { + return new BasicEvaluatedExpression() + .setString("number") + .setRange(/** @type {Range} */ (expr.range)); + } + if (arg.isBigInt()) { + return new BasicEvaluatedExpression() + .setString("bigint") + .setRange(/** @type {Range} */ (expr.range)); + } + if (arg.isBoolean()) { + return new BasicEvaluatedExpression() + .setString("boolean") + .setRange(/** @type {Range} */ (expr.range)); + } + if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) { + return new BasicEvaluatedExpression() + .setString("object") + .setRange(/** @type {Range} */ (expr.range)); + } + if (arg.isArray()) { + return new BasicEvaluatedExpression() + .setString("object") + .setSideEffects(arg.couldHaveSideEffects()) + .setRange(/** @type {Range} */ (expr.range)); + } + } else if (expr.operator === "!") { + const argument = this.evaluateExpression(expr.argument); + const bool = argument.asBool(); + if (typeof bool !== "boolean") return; + return new BasicEvaluatedExpression() + .setBoolean(!bool) + .setSideEffects(argument.couldHaveSideEffects()) + .setRange(/** @type {Range} */ (expr.range)); + } else if (expr.operator === "~") { + return handleConstOperation((v) => ~v); + } else if (expr.operator === "+") { + // eslint-disable-next-line no-implicit-coercion + return handleConstOperation((v) => +v); + } else if (expr.operator === "-") { + return handleConstOperation((v) => -v); + } + }); + this.hooks.evaluateTypeof + .for("undefined") + .tap(CLASS_NAME, (expr) => + new BasicEvaluatedExpression() + .setString("undefined") + .setRange(/** @type {Range} */ (expr.range)) + ); + this.hooks.evaluate.for("Identifier").tap(CLASS_NAME, (expr) => { + if (/** @type {Identifier} */ (expr).name === "undefined") { + return new BasicEvaluatedExpression() + .setUndefined() + .setRange(/** @type {Range} */ (expr.range)); + } + }); + /** + * @param {"Identifier" | "ThisExpression" | "MemberExpression"} exprType expression type name + * @param {(node: Expression | SpreadElement) => GetInfoResult | undefined} getInfo get info + * @returns {void} + */ + const tapEvaluateWithVariableInfo = (exprType, getInfo) => { + /** @type {Expression | undefined} */ + let cachedExpression; + /** @type {GetInfoResult | undefined} */ + let cachedInfo; + this.hooks.evaluate.for(exprType).tap(CLASS_NAME, (expr) => { + const expression = + /** @type {Identifier | ThisExpression | MemberExpression} */ (expr); + + const info = getInfo(expression); + if (info !== undefined) { + return this.callHooksForInfoWithFallback( + this.hooks.evaluateIdentifier, + info.name, + (_name) => { + cachedExpression = expression; + cachedInfo = info; + return undefined; + }, + (name) => { + const hook = this.hooks.evaluateDefinedIdentifier.get(name); + if (hook !== undefined) { + return hook.call(expression); + } + }, + expression + ); + } + }); + this.hooks.evaluate + .for(exprType) + .tap({ name: CLASS_NAME, stage: 100 }, (expr) => { + const expression = + /** @type {Identifier | ThisExpression | MemberExpression} */ + (expr); + const info = + cachedExpression === expression ? cachedInfo : getInfo(expression); + if (info !== undefined) { + return new BasicEvaluatedExpression() + .setIdentifier( + info.name, + info.rootInfo, + info.getMembers, + info.getMembersOptionals, + info.getMemberRanges + ) + .setRange(/** @type {Range} */ (expression.range)); + } + }); + this.hooks.finish.tap(CLASS_NAME, () => { + // Cleanup for GC + cachedExpression = cachedInfo = undefined; + }); + }; + tapEvaluateWithVariableInfo("Identifier", (expr) => { + const info = this.getVariableInfo(/** @type {Identifier} */ (expr).name); + if ( + typeof info === "string" || + (info instanceof VariableInfo && (info.isFree() || info.isTagged())) + ) { + return { + name: info, + rootInfo: info, + getMembers: () => [], + getMembersOptionals: () => [], + getMemberRanges: () => [] + }; + } + }); + tapEvaluateWithVariableInfo("ThisExpression", (_expr) => { + const info = this.getVariableInfo("this"); + if ( + typeof info === "string" || + (info instanceof VariableInfo && (info.isFree() || info.isTagged())) + ) { + return { + name: info, + rootInfo: info, + getMembers: () => [], + getMembersOptionals: () => [], + getMemberRanges: () => [] + }; + } + }); + this.hooks.evaluate.for("MetaProperty").tap(CLASS_NAME, (expr) => { + const metaProperty = /** @type {MetaProperty} */ (expr); + + return this.callHooksForName( + this.hooks.evaluateIdentifier, + /** @type {string} */ + (getRootName(metaProperty)), + metaProperty + ); + }); + tapEvaluateWithVariableInfo("MemberExpression", (expr) => + this.getMemberExpressionInfo( + /** @type {MemberExpression} */ (expr), + ALLOWED_MEMBER_TYPES_EXPRESSION + ) + ); + + this.hooks.evaluate.for("CallExpression").tap(CLASS_NAME, (_expr) => { + const expr = /** @type {CallExpression} */ (_expr); + if ( + expr.callee.type === "MemberExpression" && + expr.callee.property.type === + (expr.callee.computed ? "Literal" : "Identifier") + ) { + // type Super also possible here + const param = this.evaluateExpression( + /** @type {Expression} */ (expr.callee.object) + ); + const property = + expr.callee.property.type === "Literal" + ? `${expr.callee.property.value}` + : expr.callee.property.name; + const hook = this.hooks.evaluateCallExpressionMember.get(property); + if (hook !== undefined) { + return hook.call(expr, param); + } + } else if (expr.callee.type === "Identifier") { + return this.callHooksForName( + this.hooks.evaluateCallExpression, + expr.callee.name, + expr + ); + } + }); + this.hooks.evaluateCallExpressionMember + .for("indexOf") + .tap(CLASS_NAME, (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length === 0) return; + const [arg1, arg2] = expr.arguments; + if (arg1.type === "SpreadElement") return; + const arg1Eval = this.evaluateExpression(arg1); + if (!arg1Eval.isString()) return; + const arg1Value = /** @type {string} */ (arg1Eval.string); + + let result; + if (arg2) { + if (arg2.type === "SpreadElement") return; + const arg2Eval = this.evaluateExpression(arg2); + if (!arg2Eval.isNumber()) return; + result = /** @type {string} */ (param.string).indexOf( + arg1Value, + arg2Eval.number + ); + } else { + result = /** @type {string} */ (param.string).indexOf(arg1Value); + } + return new BasicEvaluatedExpression() + .setNumber(result) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(/** @type {Range} */ (expr.range)); + }); + this.hooks.evaluateCallExpressionMember + .for("replace") + .tap(CLASS_NAME, (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 2) return; + if (expr.arguments[0].type === "SpreadElement") return; + if (expr.arguments[1].type === "SpreadElement") return; + const arg1 = this.evaluateExpression(expr.arguments[0]); + const arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isString() && !arg1.isRegExp()) return; + const arg1Value = /** @type {string | RegExp} */ ( + arg1.regExp || arg1.string + ); + if (!arg2.isString()) return; + const arg2Value = /** @type {string} */ (arg2.string); + return new BasicEvaluatedExpression() + .setString( + /** @type {string} */ (param.string).replace(arg1Value, arg2Value) + ) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(/** @type {Range} */ (expr.range)); + }); + for (const fn of ["substr", "substring", "slice"]) { + this.hooks.evaluateCallExpressionMember + .for(fn) + .tap(CLASS_NAME, (expr, param) => { + if (!param.isString()) return; + let arg1; + let result; + const str = /** @type {string} */ (param.string); + switch (expr.arguments.length) { + case 1: + if (expr.arguments[0].type === "SpreadElement") return; + arg1 = this.evaluateExpression(expr.arguments[0]); + if (!arg1.isNumber()) return; + result = str[ + /** @type {"substr" | "substring" | "slice"} */ (fn) + ](/** @type {number} */ (arg1.number)); + break; + case 2: { + if (expr.arguments[0].type === "SpreadElement") return; + if (expr.arguments[1].type === "SpreadElement") return; + arg1 = this.evaluateExpression(expr.arguments[0]); + const arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isNumber()) return; + if (!arg2.isNumber()) return; + result = str[ + /** @type {"substr" | "substring" | "slice"} */ (fn) + ]( + /** @type {number} */ (arg1.number), + /** @type {number} */ (arg2.number) + ); + break; + } + default: + return; + } + return new BasicEvaluatedExpression() + .setString(result) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(/** @type {Range} */ (expr.range)); + }); + } + + /** + * @param {"cooked" | "raw"} kind kind of values to get + * @param {TemplateLiteral} templateLiteralExpr TemplateLiteral expr + * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template + */ + const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { + /** @type {BasicEvaluatedExpression[]} */ + const quasis = []; + /** @type {BasicEvaluatedExpression[]} */ + const parts = []; + + for (let i = 0; i < templateLiteralExpr.quasis.length; i++) { + const quasiExpr = templateLiteralExpr.quasis[i]; + const quasi = quasiExpr.value[kind]; + + if (i > 0) { + const prevExpr = parts[parts.length - 1]; + const expr = this.evaluateExpression( + templateLiteralExpr.expressions[i - 1] + ); + const exprAsString = expr.asString(); + if ( + typeof exprAsString === "string" && + !expr.couldHaveSideEffects() + ) { + // We can merge quasi + expr + quasi when expr + // is a const string + + prevExpr.setString(prevExpr.string + exprAsString + quasi); + prevExpr.setRange([ + /** @type {Range} */ (prevExpr.range)[0], + /** @type {Range} */ (quasiExpr.range)[1] + ]); + // We unset the expression as it doesn't match to a single expression + prevExpr.setExpression(undefined); + continue; + } + parts.push(expr); + } + + const part = new BasicEvaluatedExpression() + .setString(/** @type {string} */ (quasi)) + .setRange(/** @type {Range} */ (quasiExpr.range)) + .setExpression(quasiExpr); + quasis.push(part); + parts.push(part); + } + return { + quasis, + parts + }; + }; + + this.hooks.evaluate.for("TemplateLiteral").tap(CLASS_NAME, (_node) => { + const node = /** @type {TemplateLiteral} */ (_node); + + const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); + if (parts.length === 1) { + return parts[0].setRange(/** @type {Range} */ (node.range)); + } + return new BasicEvaluatedExpression() + .setTemplateString(quasis, parts, "cooked") + .setRange(/** @type {Range} */ (node.range)); + }); + this.hooks.evaluate + .for("TaggedTemplateExpression") + .tap(CLASS_NAME, (_node) => { + const node = /** @type {TaggedTemplateExpression} */ (_node); + const tag = this.evaluateExpression(node.tag); + + if (tag.isIdentifier() && tag.identifier === "String.raw") { + const { quasis, parts } = getSimplifiedTemplateResult( + "raw", + node.quasi + ); + return new BasicEvaluatedExpression() + .setTemplateString(quasis, parts, "raw") + .setRange(/** @type {Range} */ (node.range)); + } + }); + + this.hooks.evaluateCallExpressionMember + .for("concat") + .tap(CLASS_NAME, (expr, param) => { + if (!param.isString() && !param.isWrapped()) return; + let stringSuffix = null; + let hasUnknownParams = false; + /** @type {BasicEvaluatedExpression[]} */ + const innerExpressions = []; + for (let i = expr.arguments.length - 1; i >= 0; i--) { + const arg = expr.arguments[i]; + if (arg.type === "SpreadElement") return; + const argExpr = this.evaluateExpression(arg); + if ( + hasUnknownParams || + (!argExpr.isString() && !argExpr.isNumber()) + ) { + hasUnknownParams = true; + innerExpressions.push(argExpr); + continue; + } + + const value = argExpr.isString() + ? /** @type {string} */ (argExpr.string) + : String(argExpr.number); + + /** @type {string} */ + const newString = + value + + (stringSuffix ? /** @type {string} */ (stringSuffix.string) : ""); + const newRange = /** @type {Range} */ ([ + /** @type {Range} */ (argExpr.range)[0], + /** @type {Range} */ ((stringSuffix || argExpr).range)[1] + ]); + stringSuffix = new BasicEvaluatedExpression() + .setString(newString) + .setSideEffects( + (stringSuffix && stringSuffix.couldHaveSideEffects()) || + argExpr.couldHaveSideEffects() + ) + .setRange(newRange); + } + + if (hasUnknownParams) { + const prefix = param.isString() ? param : param.prefix; + const inner = + param.isWrapped() && param.wrappedInnerExpressions + ? [ + ...param.wrappedInnerExpressions, + ...innerExpressions.reverse() + ] + : innerExpressions.reverse(); + return new BasicEvaluatedExpression() + .setWrapped(prefix, stringSuffix, inner) + .setRange(/** @type {Range} */ (expr.range)); + } else if (param.isWrapped()) { + const postfix = stringSuffix || param.postfix; + const inner = param.wrappedInnerExpressions + ? [...param.wrappedInnerExpressions, ...innerExpressions.reverse()] + : innerExpressions.reverse(); + return new BasicEvaluatedExpression() + .setWrapped(param.prefix, postfix, inner) + .setRange(/** @type {Range} */ (expr.range)); + } + const newString = + /** @type {string} */ (param.string) + + (stringSuffix ? stringSuffix.string : ""); + return new BasicEvaluatedExpression() + .setString(newString) + .setSideEffects( + (stringSuffix && stringSuffix.couldHaveSideEffects()) || + param.couldHaveSideEffects() + ) + .setRange(/** @type {Range} */ (expr.range)); + }); + this.hooks.evaluateCallExpressionMember + .for("split") + .tap(CLASS_NAME, (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 1) return; + if (expr.arguments[0].type === "SpreadElement") return; + let result; + const arg = this.evaluateExpression(expr.arguments[0]); + if (arg.isString()) { + result = + /** @type {string} */ + (param.string).split(/** @type {string} */ (arg.string)); + } else if (arg.isRegExp()) { + result = /** @type {string} */ (param.string).split( + /** @type {RegExp} */ (arg.regExp) + ); + } else { + return; + } + return new BasicEvaluatedExpression() + .setArray(result) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(/** @type {Range} */ (expr.range)); + }); + this.hooks.evaluate + .for("ConditionalExpression") + .tap(CLASS_NAME, (_expr) => { + const expr = /** @type {ConditionalExpression} */ (_expr); + + const condition = this.evaluateExpression(expr.test); + const conditionValue = condition.asBool(); + let res; + if (conditionValue === undefined) { + const consequent = this.evaluateExpression(expr.consequent); + const alternate = this.evaluateExpression(expr.alternate); + res = new BasicEvaluatedExpression(); + if (consequent.isConditional()) { + res.setOptions( + /** @type {BasicEvaluatedExpression[]} */ (consequent.options) + ); + } else { + res.setOptions([consequent]); + } + if (alternate.isConditional()) { + res.addOptions( + /** @type {BasicEvaluatedExpression[]} */ (alternate.options) + ); + } else { + res.addOptions([alternate]); + } + } else { + res = this.evaluateExpression( + conditionValue ? expr.consequent : expr.alternate + ); + if (condition.couldHaveSideEffects()) res.setSideEffects(); + } + res.setRange(/** @type {Range} */ (expr.range)); + return res; + }); + this.hooks.evaluate.for("ArrayExpression").tap(CLASS_NAME, (_expr) => { + const expr = /** @type {ArrayExpression} */ (_expr); + + const items = expr.elements.map( + (element) => + element !== null && + element.type !== "SpreadElement" && + this.evaluateExpression(element) + ); + if (!items.every(Boolean)) return; + return new BasicEvaluatedExpression() + .setItems(/** @type {BasicEvaluatedExpression[]} */ (items)) + .setRange(/** @type {Range} */ (expr.range)); + }); + this.hooks.evaluate.for("ChainExpression").tap(CLASS_NAME, (_expr) => { + const expr = /** @type {ChainExpression} */ (_expr); + /** @type {Expression[]} */ + const optionalExpressionsStack = []; + /** @type {Expression|Super} */ + let next = expr.expression; + + while ( + next.type === "MemberExpression" || + next.type === "CallExpression" + ) { + if (next.type === "MemberExpression") { + if (next.optional) { + // SuperNode can not be optional + optionalExpressionsStack.push( + /** @type {Expression} */ (next.object) + ); + } + next = next.object; + } else { + if (next.optional) { + // SuperNode can not be optional + optionalExpressionsStack.push( + /** @type {Expression} */ (next.callee) + ); + } + next = next.callee; + } + } + + while (optionalExpressionsStack.length > 0) { + const expression = + /** @type {Expression} */ + (optionalExpressionsStack.pop()); + const evaluated = this.evaluateExpression(expression); + + if (evaluated.asNullish()) { + return evaluated.setRange(/** @type {Range} */ (_expr.range)); + } + } + return this.evaluateExpression(expr.expression); + }); + } + + /** + * @param {Expression} node node + * @returns {Set | undefined} destructured identifiers + */ + destructuringAssignmentPropertiesFor(node) { + if (!this.destructuringAssignmentProperties) return; + return this.destructuringAssignmentProperties.get(node); + } + + /** + * @param {Expression | SpreadElement} expr expression + * @returns {string | VariableInfo | undefined} identifier + */ + getRenameIdentifier(expr) { + const result = this.evaluateExpression(expr); + if (result.isIdentifier()) { + return result.identifier; + } + } + + /** + * @param {ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration} classy a class node + * @returns {void} + */ + walkClass(classy) { + if ( + classy.superClass && + !this.hooks.classExtendsExpression.call(classy.superClass, classy) + ) { + this.walkExpression(classy.superClass); + } + if (classy.body && classy.body.type === "ClassBody") { + const scopeParams = []; + // Add class name in scope for recursive calls + if (classy.id) { + scopeParams.push(classy.id); + } + this.inClassScope(true, scopeParams, () => { + for (const classElement of classy.body.body) { + if (!this.hooks.classBodyElement.call(classElement, classy)) { + if (classElement.type === "StaticBlock") { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.walkBlockStatement(classElement); + this.scope.topLevelScope = wasTopLevel; + } else { + if (classElement.computed && classElement.key) { + this.walkExpression(classElement.key); + } + + if ( + classElement.value && + !this.hooks.classBodyValue.call( + classElement.value, + classElement, + classy + ) + ) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.walkExpression(classElement.value); + this.scope.topLevelScope = wasTopLevel; + } + } + } + } + }); + } + } + + /** + * Module pre walking iterates the scope for import entries + * @param {(Statement | ModuleDeclaration)[]} statements statements + */ + modulePreWalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + /** @type {StatementPath} */ + (this.statementPath).push(statement); + switch (statement.type) { + case "ImportDeclaration": + this.modulePreWalkImportDeclaration(statement); + break; + case "ExportAllDeclaration": + this.modulePreWalkExportAllDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.modulePreWalkExportNamedDeclaration(statement); + break; + } + this.prevStatement = + /** @type {StatementPath} */ + (this.statementPath).pop(); + } + } + + /** + * Pre walking iterates the scope for variable declarations + * @param {(Statement | ModuleDeclaration)[]} statements statements + */ + preWalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.preWalkStatement(statement); + } + } + + /** + * Block pre walking iterates the scope for block variable declarations + * @param {(Statement | ModuleDeclaration)[]} statements statements + */ + blockPreWalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.blockPreWalkStatement(statement); + } + } + + /** + * Walking iterates the statements and expressions and processes them + * @param {(Statement | ModuleDeclaration)[]} statements statements + */ + walkStatements(statements) { + let onlyFunctionDeclaration = false; + + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + + if ( + onlyFunctionDeclaration && + statement.type !== "FunctionDeclaration" && + this.hooks.unusedStatement.call(/** @type {Statement} */ (statement)) + ) { + continue; + } + + this.walkStatement(statement); + + if (this.scope.terminated) { + onlyFunctionDeclaration = true; + } + } + } + + /** + * Walking iterates the statements and expressions and processes them + * @param {Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration} statement statement + */ + preWalkStatement(statement) { + /** @type {StatementPath} */ + (this.statementPath).push(statement); + if (this.hooks.preStatement.call(statement)) { + this.prevStatement = + /** @type {StatementPath} */ + (this.statementPath).pop(); + return; + } + switch (statement.type) { + case "BlockStatement": + this.preWalkBlockStatement(statement); + break; + case "DoWhileStatement": + this.preWalkDoWhileStatement(statement); + break; + case "ForInStatement": + this.preWalkForInStatement(statement); + break; + case "ForOfStatement": + this.preWalkForOfStatement(statement); + break; + case "ForStatement": + this.preWalkForStatement(statement); + break; + case "FunctionDeclaration": + this.preWalkFunctionDeclaration(statement); + break; + case "IfStatement": + this.preWalkIfStatement(statement); + break; + case "LabeledStatement": + this.preWalkLabeledStatement(statement); + break; + case "SwitchStatement": + this.preWalkSwitchStatement(statement); + break; + case "TryStatement": + this.preWalkTryStatement(statement); + break; + case "VariableDeclaration": + this.preWalkVariableDeclaration(statement); + break; + case "WhileStatement": + this.preWalkWhileStatement(statement); + break; + case "WithStatement": + this.preWalkWithStatement(statement); + break; + } + this.prevStatement = + /** @type {StatementPath} */ + (this.statementPath).pop(); + } + + /** + * @param {Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration} statement statement + */ + blockPreWalkStatement(statement) { + /** @type {StatementPath} */ + (this.statementPath).push(statement); + if (this.hooks.blockPreStatement.call(statement)) { + this.prevStatement = + /** @type {StatementPath} */ + (this.statementPath).pop(); + return; + } + switch (statement.type) { + case "ExportDefaultDeclaration": + this.blockPreWalkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.blockPreWalkExportNamedDeclaration(statement); + break; + case "VariableDeclaration": + this.blockPreWalkVariableDeclaration(statement); + break; + case "ClassDeclaration": + this.blockPreWalkClassDeclaration(statement); + break; + case "ExpressionStatement": + this.blockPreWalkExpressionStatement(statement); + } + this.prevStatement = + /** @type {StatementPath} */ + (this.statementPath).pop(); + } + + /** + * @param {Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} statement statement + */ + walkStatement(statement) { + /** @type {StatementPath} */ + (this.statementPath).push(statement); + if (this.hooks.statement.call(statement) !== undefined) { + this.prevStatement = + /** @type {StatementPath} */ + (this.statementPath).pop(); + return; + } + switch (statement.type) { + case "BlockStatement": + this.walkBlockStatement(statement); + break; + case "ClassDeclaration": + this.walkClassDeclaration(statement); + break; + case "DoWhileStatement": + this.walkDoWhileStatement(statement); + break; + case "ExportDefaultDeclaration": + this.walkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.walkExportNamedDeclaration(statement); + break; + case "ExpressionStatement": + this.walkExpressionStatement(statement); + break; + case "ForInStatement": + this.walkForInStatement(statement); + break; + case "ForOfStatement": + this.walkForOfStatement(statement); + break; + case "ForStatement": + this.walkForStatement(statement); + break; + case "FunctionDeclaration": + this.walkFunctionDeclaration(statement); + break; + case "IfStatement": + this.walkIfStatement(statement); + break; + case "LabeledStatement": + this.walkLabeledStatement(statement); + break; + case "ReturnStatement": + this.walkReturnStatement(statement); + break; + case "SwitchStatement": + this.walkSwitchStatement(statement); + break; + case "ThrowStatement": + this.walkThrowStatement(statement); + break; + case "TryStatement": + this.walkTryStatement(statement); + break; + case "VariableDeclaration": + this.walkVariableDeclaration(statement); + break; + case "WhileStatement": + this.walkWhileStatement(statement); + break; + case "WithStatement": + this.walkWithStatement(statement); + break; + } + this.prevStatement = + /** @type {StatementPath} */ + (this.statementPath).pop(); + } + + /** + * Walks a statements that is nested within a parent statement + * and can potentially be a non-block statement. + * This enforces the nested statement to never be in ASI position. + * @param {Statement} statement the nested statement + */ + walkNestedStatement(statement) { + this.prevStatement = undefined; + this.walkStatement(statement); + } + + // Real Statements + /** + * @param {BlockStatement} statement block statement + */ + preWalkBlockStatement(statement) { + this.preWalkStatements(statement.body); + } + + /** + * @param {BlockStatement | StaticBlock} statement block statement + */ + walkBlockStatement(statement) { + this.inBlockScope(() => { + const body = statement.body; + const prev = this.prevStatement; + this.blockPreWalkStatements(body); + this.prevStatement = prev; + this.walkStatements(body); + }, true); + } + + /** + * @param {ExpressionStatement} statement expression statement + */ + walkExpressionStatement(statement) { + this.walkExpression(statement.expression); + } + + /** + * @param {IfStatement} statement if statement + */ + preWalkIfStatement(statement) { + this.preWalkStatement(statement.consequent); + if (statement.alternate) { + this.preWalkStatement(statement.alternate); + } + } + + /** + * @param {IfStatement} statement if statement + */ + walkIfStatement(statement) { + const result = this.hooks.statementIf.call(statement); + if (result === undefined) { + this.walkExpression(statement.test); + this.walkNestedStatement(statement.consequent); + + const consequentTerminated = this.scope.terminated; + this.scope.terminated = undefined; + + if (statement.alternate) { + this.walkNestedStatement(statement.alternate); + } + + const alternateTerminated = this.scope.terminated; + + this.scope.terminated = + consequentTerminated && alternateTerminated + ? alternateTerminated + : undefined; + } else if (result) { + this.walkNestedStatement(statement.consequent); + } else if (statement.alternate) { + this.walkNestedStatement(statement.alternate); + } + } + + /** + * @param {LabeledStatement} statement with statement + */ + preWalkLabeledStatement(statement) { + this.preWalkStatement(statement.body); + } + + /** + * @param {LabeledStatement} statement with statement + */ + walkLabeledStatement(statement) { + const hook = this.hooks.label.get(statement.label.name); + if (hook !== undefined) { + const result = hook.call(statement); + if (result === true) return; + } + this.inBlockScope(() => { + this.walkNestedStatement(statement.body); + }); + } + + /** + * @param {WithStatement} statement with statement + */ + preWalkWithStatement(statement) { + this.preWalkStatement(statement.body); + } + + /** + * @param {WithStatement} statement with statement + */ + walkWithStatement(statement) { + this.inBlockScope(() => { + this.walkExpression(statement.object); + this.walkNestedStatement(statement.body); + }); + } + + /** + * @param {SwitchStatement} statement switch statement + */ + preWalkSwitchStatement(statement) { + this.preWalkSwitchCases(statement.cases); + } + + /** + * @param {SwitchStatement} statement switch statement + */ + walkSwitchStatement(statement) { + this.walkExpression(statement.discriminant); + this.walkSwitchCases(statement.cases); + } + + /** + * @param {ReturnStatement | ThrowStatement} statement return or throw statement + */ + walkTerminatingStatement(statement) { + if (statement.argument) this.walkExpression(statement.argument); + // Skip top level scope because to handle `export` and `module.exports` after terminate + if (this.scope.topLevelScope === true) return; + if (this.hooks.terminate.call(statement)) { + this.scope.terminated = + statement.type === "ReturnStatement" + ? SCOPE_INFO_TERMINATED_RETURN + : SCOPE_INFO_TERMINATED_THROW; + } + } + + /** + * @param {ReturnStatement} statement return statement + */ + walkReturnStatement(statement) { + this.walkTerminatingStatement(statement); + } + + /** + * @param {ThrowStatement} statement return statement + */ + walkThrowStatement(statement) { + this.walkTerminatingStatement(statement); + } + + /** + * @param {TryStatement} statement try statement + */ + preWalkTryStatement(statement) { + this.preWalkStatement(statement.block); + if (statement.handler) this.preWalkCatchClause(statement.handler); + if (statement.finalizer) this.preWalkStatement(statement.finalizer); + } + + /** + * @param {TryStatement} statement try statement + */ + walkTryStatement(statement) { + if (this.scope.inTry) { + this.walkStatement(statement.block); + } else { + this.scope.inTry = true; + this.walkStatement(statement.block); + this.scope.inTry = false; + } + + const tryTerminated = this.scope.terminated; + this.scope.terminated = undefined; + + if (statement.handler) this.walkCatchClause(statement.handler); + + const handlerTerminated = this.scope.terminated; + this.scope.terminated = undefined; + + if (statement.finalizer) { + this.walkStatement(statement.finalizer); + } + + const finalizerTerminated = this.scope.terminated; + this.scope.terminated = undefined; + + if (finalizerTerminated) { + this.scope.terminated = finalizerTerminated; + } else if ( + tryTerminated && + (statement.handler ? handlerTerminated : true) + ) { + this.scope.terminated = handlerTerminated || tryTerminated; + } + } + + /** + * @param {WhileStatement} statement while statement + */ + preWalkWhileStatement(statement) { + this.preWalkStatement(statement.body); + } + + /** + * @param {WhileStatement} statement while statement + */ + walkWhileStatement(statement) { + this.inBlockScope(() => { + this.walkExpression(statement.test); + this.walkNestedStatement(statement.body); + }); + } + + /** + * @param {DoWhileStatement} statement do while statement + */ + preWalkDoWhileStatement(statement) { + this.preWalkStatement(statement.body); + } + + /** + * @param {DoWhileStatement} statement do while statement + */ + walkDoWhileStatement(statement) { + this.inBlockScope(() => { + this.walkNestedStatement(statement.body); + this.walkExpression(statement.test); + }); + } + + /** + * @param {ForStatement} statement for statement + */ + preWalkForStatement(statement) { + if (statement.init && statement.init.type === "VariableDeclaration") { + this.preWalkStatement(statement.init); + } + this.preWalkStatement(statement.body); + } + + /** + * @param {ForStatement} statement for statement + */ + walkForStatement(statement) { + this.inBlockScope(() => { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.blockPreWalkVariableDeclaration(statement.init); + this.prevStatement = undefined; + this.walkStatement(statement.init); + } else { + this.walkExpression(statement.init); + } + } + if (statement.test) { + this.walkExpression(statement.test); + } + if (statement.update) { + this.walkExpression(statement.update); + } + + const body = statement.body; + + if (body.type === "BlockStatement") { + // no need to add additional scope + const prev = this.prevStatement; + this.blockPreWalkStatements(body.body); + this.prevStatement = prev; + this.walkStatements(body.body); + } else { + this.walkNestedStatement(body); + } + }); + } + + /** + * @param {ForInStatement} statement for statement + */ + preWalkForInStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.preWalkVariableDeclaration(statement.left); + } + this.preWalkStatement(statement.body); + } + + /** + * @param {ForInStatement} statement for statement + */ + walkForInStatement(statement) { + this.inBlockScope(() => { + if (statement.left.type === "VariableDeclaration") { + this.blockPreWalkVariableDeclaration(statement.left); + this.walkVariableDeclaration(statement.left); + } else { + this.walkPattern(statement.left); + } + + this.walkExpression(statement.right); + + const body = statement.body; + + if (body.type === "BlockStatement") { + // no need to add additional scope + const prev = this.prevStatement; + this.blockPreWalkStatements(body.body); + this.prevStatement = prev; + this.walkStatements(body.body); + } else { + this.walkNestedStatement(body); + } + }); + } + + /** + * @param {ForOfStatement} statement statement + */ + preWalkForOfStatement(statement) { + if (statement.await && this.scope.topLevelScope === true) { + this.hooks.topLevelAwait.call(statement); + } + if (statement.left.type === "VariableDeclaration") { + this.preWalkVariableDeclaration(statement.left); + } + this.preWalkStatement(statement.body); + } + + /** + * @param {ForOfStatement} statement for statement + */ + walkForOfStatement(statement) { + this.inBlockScope(() => { + if (statement.left.type === "VariableDeclaration") { + this.blockPreWalkVariableDeclaration(statement.left); + this.walkVariableDeclaration(statement.left); + } else { + this.walkPattern(statement.left); + } + + this.walkExpression(statement.right); + + const body = statement.body; + + if (body.type === "BlockStatement") { + // no need to add additional scope + const prev = this.prevStatement; + this.blockPreWalkStatements(body.body); + this.prevStatement = prev; + this.walkStatements(body.body); + } else { + this.walkNestedStatement(body); + } + }); + } + + /** + * @param {FunctionDeclaration | MaybeNamedFunctionDeclaration} statement function declaration + */ + preWalkFunctionDeclaration(statement) { + if (statement.id) { + this.defineVariable(statement.id.name); + } + } + + /** + * @param {FunctionDeclaration | MaybeNamedFunctionDeclaration} statement function declaration + */ + walkFunctionDeclaration(statement) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.inFunctionScope(true, statement.params, () => { + for (const param of statement.params) { + this.walkPattern(param); + } + + this.detectMode(statement.body.body); + + const prev = this.prevStatement; + + this.preWalkStatement(statement.body); + this.prevStatement = prev; + this.walkStatement(statement.body); + }); + this.scope.topLevelScope = wasTopLevel; + } + + /** + * @param {ExpressionStatement} statement expression statement + */ + blockPreWalkExpressionStatement(statement) { + const expression = statement.expression; + switch (expression.type) { + case "AssignmentExpression": + this.preWalkAssignmentExpression(expression); + } + } + + /** + * @param {AssignmentExpression} expression assignment expression + */ + preWalkAssignmentExpression(expression) { + this.enterDestructuringAssignment(expression.left, expression.right); + } + + /** + * @param {Pattern} pattern pattern + * @param {Expression} expression assignment expression + * @returns {Expression | undefined} destructuring expression + */ + enterDestructuringAssignment(pattern, expression) { + if ( + pattern.type !== "ObjectPattern" || + !this.destructuringAssignmentProperties + ) { + return; + } + + const expr = + expression.type === "AwaitExpression" ? expression.argument : expression; + + const destructuring = + expr.type === "AssignmentExpression" + ? this.enterDestructuringAssignment(expr.left, expr.right) + : this.hooks.collectDestructuringAssignmentProperties.call(expr) + ? expr + : undefined; + + if (destructuring) { + const keys = this._preWalkObjectPattern(pattern); + if (!keys) return; + + // check multiple assignments + if (this.destructuringAssignmentProperties.has(destructuring)) { + const set = + /** @type {Set} */ + (this.destructuringAssignmentProperties.get(destructuring)); + for (const id of keys) set.add(id); + } else { + this.destructuringAssignmentProperties.set(destructuring, keys); + } + } + + return destructuring; + } + + /** + * @param {ImportDeclaration} statement statement + */ + modulePreWalkImportDeclaration(statement) { + const source = /** @type {ImportSource} */ (statement.source.value); + this.hooks.import.call(statement, source); + for (const specifier of statement.specifiers) { + const name = specifier.local.name; + switch (specifier.type) { + case "ImportDefaultSpecifier": + if ( + !this.hooks.importSpecifier.call(statement, source, "default", name) + ) { + this.defineVariable(name); + } + break; + case "ImportSpecifier": + if ( + !this.hooks.importSpecifier.call( + statement, + source, + /** @type {Identifier} */ + (specifier.imported).name || + /** @type {string} */ + ( + /** @type {Literal} */ + (specifier.imported).value + ), + name + ) + ) { + this.defineVariable(name); + } + break; + case "ImportNamespaceSpecifier": + if (!this.hooks.importSpecifier.call(statement, source, null, name)) { + this.defineVariable(name); + } + break; + default: + this.defineVariable(name); + } + } + } + + /** + * @param {Declaration} declaration declaration + * @param {OnIdent} onIdent on ident callback + */ + enterDeclaration(declaration, onIdent) { + switch (declaration.type) { + case "VariableDeclaration": + for (const declarator of declaration.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + this.enterPattern(declarator.id, onIdent); + break; + } + } + } + break; + case "FunctionDeclaration": + this.enterPattern(declaration.id, onIdent); + break; + case "ClassDeclaration": + this.enterPattern(declaration.id, onIdent); + break; + } + } + + /** + * @param {ExportNamedDeclaration} statement statement + */ + modulePreWalkExportNamedDeclaration(statement) { + if (!statement.source) return; + const source = /** @type {ImportSource} */ (statement.source.value); + this.hooks.exportImport.call(statement, source); + if (statement.specifiers) { + for ( + let specifierIndex = 0; + specifierIndex < statement.specifiers.length; + specifierIndex++ + ) { + const specifier = statement.specifiers[specifierIndex]; + switch (specifier.type) { + case "ExportSpecifier": { + const localName = + /** @type {Identifier} */ (specifier.local).name || + /** @type {string} */ ( + /** @type {Literal} */ (specifier.local).value + ); + const name = + /** @type {Identifier} */ + (specifier.exported).name || + /** @type {string} */ + (/** @type {Literal} */ (specifier.exported).value); + this.hooks.exportImportSpecifier.call( + statement, + source, + localName, + name, + specifierIndex + ); + break; + } + } + } + } + } + + /** + * @param {ExportNamedDeclaration} statement statement + */ + blockPreWalkExportNamedDeclaration(statement) { + if (statement.source) return; + this.hooks.export.call(statement); + if ( + statement.declaration && + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + const prev = this.prevStatement; + this.preWalkStatement(statement.declaration); + this.prevStatement = prev; + this.blockPreWalkStatement(statement.declaration); + let index = 0; + this.enterDeclaration(statement.declaration, (def) => { + this.hooks.exportSpecifier.call(statement, def, def, index++); + }); + } + if (statement.specifiers) { + for ( + let specifierIndex = 0; + specifierIndex < statement.specifiers.length; + specifierIndex++ + ) { + const specifier = statement.specifiers[specifierIndex]; + switch (specifier.type) { + case "ExportSpecifier": { + const localName = + /** @type {Identifier} */ (specifier.local).name || + /** @type {string} */ ( + /** @type {Literal} */ (specifier.local).value + ); + const name = + /** @type {Identifier} */ + (specifier.exported).name || + /** @type {string} */ + (/** @type {Literal} */ (specifier.exported).value); + this.hooks.exportSpecifier.call( + statement, + localName, + name, + specifierIndex + ); + break; + } + } + } + } + } + + /** + * @param {ExportNamedDeclaration} statement the statement + */ + walkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.walkStatement(statement.declaration); + } + } + + /** + * @param {ExportDefaultDeclaration} statement statement + */ + blockPreWalkExportDefaultDeclaration(statement) { + const prev = this.prevStatement; + + this.preWalkStatement(/** @type {TODO} */ (statement.declaration)); + this.prevStatement = prev; + this.blockPreWalkStatement(/** @type {TODO} */ (statement.declaration)); + + if ( + /** @type {MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */ + (statement.declaration).id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + const declaration = + /** @type {MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */ + (statement.declaration); + + this.hooks.exportSpecifier.call( + statement, + /** @type {Identifier} */ + (declaration.id).name, + "default", + undefined + ); + } + } + + /** + * @param {ExportDefaultDeclaration} statement statement + */ + walkExportDefaultDeclaration(statement) { + this.hooks.export.call(statement); + if ( + /** @type {FunctionDeclaration | ClassDeclaration} */ + (statement.declaration).id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + const declaration = + /** @type {FunctionDeclaration | ClassDeclaration} */ + (statement.declaration); + if (!this.hooks.exportDeclaration.call(statement, declaration)) { + this.walkStatement(declaration); + } + } else { + // Acorn parses `export default function() {}` as `FunctionDeclaration` and + // `export default class {}` as `ClassDeclaration`, both with `id = null`. + // These nodes must be treated as expressions. + if ( + statement.declaration.type === "FunctionDeclaration" || + statement.declaration.type === "ClassDeclaration" + ) { + this.walkStatement(statement.declaration); + } else { + this.walkExpression(statement.declaration); + } + + if (!this.hooks.exportExpression.call(statement, statement.declaration)) { + this.hooks.exportSpecifier.call( + statement, + /** @type {TODO} */ + (statement.declaration), + "default", + undefined + ); + } + } + } + + /** + * @param {ExportAllDeclaration} statement statement + */ + modulePreWalkExportAllDeclaration(statement) { + const source = /** @type {ImportSource} */ (statement.source.value); + const name = statement.exported + ? /** @type {Identifier} */ + (statement.exported).name || + /** @type {string} */ + (/** @type {Literal} */ (statement.exported).value) + : null; + this.hooks.exportImport.call(statement, source); + this.hooks.exportImportSpecifier.call(statement, source, null, name, 0); + } + + /** + * @param {VariableDeclaration} statement variable declaration + */ + preWalkVariableDeclaration(statement) { + if (statement.kind !== "var") return; + this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar); + } + + /** + * @param {VariableDeclaration} statement variable declaration + */ + blockPreWalkVariableDeclaration(statement) { + if (statement.kind === "var") return; + + const hookMap = + statement.kind === "const" + ? this.hooks.varDeclarationConst + : statement.kind === "using" || statement.kind === "await using" + ? this.hooks.varDeclarationUsing + : this.hooks.varDeclarationLet; + this._preWalkVariableDeclaration(statement, hookMap); + } + + /** + * @param {VariableDeclaration} statement variable declaration + * @param {HookMap>} hookMap map of hooks + */ + _preWalkVariableDeclaration(statement, hookMap) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + this.preWalkVariableDeclarator(declarator); + if (!this.hooks.preDeclarator.call(declarator, statement)) { + this.enterPattern(declarator.id, (name, ident) => { + let hook = hookMap.get(name); + if (hook === undefined || !hook.call(ident)) { + hook = this.hooks.varDeclaration.get(name); + if (hook === undefined || !hook.call(ident)) { + this.defineVariable(name); + } + } + }); + } + break; + } + } + } + } + + /** + * @param {ObjectPattern} objectPattern object pattern + * @returns {Set | undefined} set of names or undefined if not all keys are identifiers + */ + _preWalkObjectPattern(objectPattern) { + /** @type {Set} */ + const props = new Set(); + const properties = objectPattern.properties; + for (let i = 0; i < properties.length; i++) { + const property = properties[i]; + if (property.type !== "Property") return; + if (property.shorthand) { + if (property.value.type === "Identifier") { + this.scope.inShorthand = property.value.name; + } else if ( + property.value.type === "AssignmentPattern" && + property.value.left.type === "Identifier" + ) { + this.scope.inShorthand = property.value.left.name; + } + } + const key = property.key; + if (key.type === "Identifier" && !property.computed) { + props.add({ + id: key.name, + range: key.range, + shorthand: this.scope.inShorthand + }); + } else { + const id = this.evaluateExpression(key); + const str = id.asString(); + if (str) { + props.add({ + id: str, + range: key.range, + shorthand: this.scope.inShorthand + }); + } else { + // could not evaluate key + return; + } + } + this.scope.inShorthand = false; + } + + return props; + } + + /** + * @param {VariableDeclarator} declarator variable declarator + */ + preWalkVariableDeclarator(declarator) { + if (declarator.init) { + this.enterDestructuringAssignment(declarator.id, declarator.init); + } + } + + /** + * @param {VariableDeclaration} statement variable declaration + */ + walkVariableDeclaration(statement) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + const renameIdentifier = + declarator.init && this.getRenameIdentifier(declarator.init); + if (renameIdentifier && declarator.id.type === "Identifier") { + const hook = this.hooks.canRename.get(renameIdentifier); + if ( + hook !== undefined && + hook.call(/** @type {Expression} */ (declarator.init)) + ) { + // renaming with "var a = b;" + const hook = this.hooks.rename.get(renameIdentifier); + if ( + hook === undefined || + !hook.call(/** @type {Expression} */ (declarator.init)) + ) { + this.setVariable(declarator.id.name, renameIdentifier); + } + break; + } + } + if (!this.hooks.declarator.call(declarator, statement)) { + this.walkPattern(declarator.id); + if (declarator.init) this.walkExpression(declarator.init); + } + break; + } + } + } + } + + /** + * @param {ClassDeclaration | MaybeNamedClassDeclaration} statement class declaration + */ + blockPreWalkClassDeclaration(statement) { + if (statement.id) { + this.defineVariable(statement.id.name); + } + } + + /** + * @param {ClassDeclaration | MaybeNamedClassDeclaration} statement class declaration + */ + walkClassDeclaration(statement) { + this.walkClass(statement); + } + + /** + * @param {SwitchCase[]} switchCases switch statement + */ + preWalkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; + this.preWalkStatements(switchCase.consequent); + } + } + + /** + * @param {SwitchCase[]} switchCases switch statement + */ + walkSwitchCases(switchCases) { + this.inBlockScope(() => { + const len = switchCases.length; + + // we need to pre walk all statements first since we can have invalid code + // import A from "module"; + // switch(1) { + // case 1: + // console.log(A); // should fail at runtime + // case 2: + // const A = 1; + // } + for (let index = 0; index < len; index++) { + const switchCase = switchCases[index]; + + if (switchCase.consequent.length > 0) { + const prev = this.prevStatement; + this.blockPreWalkStatements(switchCase.consequent); + this.prevStatement = prev; + } + } + + for (let index = 0; index < len; index++) { + const switchCase = switchCases[index]; + + if (switchCase.test) { + this.walkExpression(switchCase.test); + } + + if (switchCase.consequent.length > 0) { + this.walkStatements(switchCase.consequent); + this.scope.terminated = undefined; + } + } + }); + } + + /** + * @param {CatchClause} catchClause catch clause + */ + preWalkCatchClause(catchClause) { + this.preWalkStatement(catchClause.body); + } + + /** + * @param {CatchClause} catchClause catch clause + */ + walkCatchClause(catchClause) { + this.inBlockScope(() => { + // Error binding is optional in catch clause since ECMAScript 2019 + if (catchClause.param !== null) { + this.enterPattern(catchClause.param, (ident) => { + this.defineVariable(ident); + }); + this.walkPattern(catchClause.param); + } + const prev = this.prevStatement; + this.blockPreWalkStatement(catchClause.body); + this.prevStatement = prev; + this.walkStatement(catchClause.body); + }, true); + } + + /** + * @param {Pattern} pattern pattern + */ + walkPattern(pattern) { + switch (pattern.type) { + case "ArrayPattern": + this.walkArrayPattern(pattern); + break; + case "AssignmentPattern": + this.walkAssignmentPattern(pattern); + break; + case "MemberExpression": + this.walkMemberExpression(pattern); + break; + case "ObjectPattern": + this.walkObjectPattern(pattern); + break; + case "RestElement": + this.walkRestElement(pattern); + break; + } + } + + /** + * @param {AssignmentPattern} pattern assignment pattern + */ + walkAssignmentPattern(pattern) { + this.walkExpression(pattern.right); + this.walkPattern(pattern.left); + } + + /** + * @param {ObjectPattern} pattern pattern + */ + walkObjectPattern(pattern) { + for (let i = 0, len = pattern.properties.length; i < len; i++) { + const prop = pattern.properties[i]; + if (prop) { + if (prop.type === "RestElement") { + continue; + } + if (prop.computed) this.walkExpression(prop.key); + if (prop.value) this.walkPattern(prop.value); + } + } + } + + /** + * @param {ArrayPattern} pattern array pattern + */ + walkArrayPattern(pattern) { + for (let i = 0, len = pattern.elements.length; i < len; i++) { + const element = pattern.elements[i]; + if (element) this.walkPattern(element); + } + } + + /** + * @param {RestElement} pattern rest element + */ + walkRestElement(pattern) { + this.walkPattern(pattern.argument); + } + + /** + * @param {(Expression | SpreadElement | null)[]} expressions expressions + */ + walkExpressions(expressions) { + for (const expression of expressions) { + if (expression) { + this.walkExpression(expression); + } + } + } + + /** + * @param {Expression | SpreadElement | PrivateIdentifier | Super} expression expression + */ + walkExpression(expression) { + switch (expression.type) { + case "ArrayExpression": + this.walkArrayExpression(expression); + break; + case "ArrowFunctionExpression": + this.walkArrowFunctionExpression(expression); + break; + case "AssignmentExpression": + this.walkAssignmentExpression(expression); + break; + case "AwaitExpression": + this.walkAwaitExpression(expression); + break; + case "BinaryExpression": + this.walkBinaryExpression(expression); + break; + case "CallExpression": + this.walkCallExpression(expression); + break; + case "ChainExpression": + this.walkChainExpression(expression); + break; + case "ClassExpression": + this.walkClassExpression(expression); + break; + case "ConditionalExpression": + this.walkConditionalExpression(expression); + break; + case "FunctionExpression": + this.walkFunctionExpression(expression); + break; + case "Identifier": + this.walkIdentifier(expression); + break; + case "ImportExpression": + this.walkImportExpression(expression); + break; + case "LogicalExpression": + this.walkLogicalExpression(expression); + break; + case "MetaProperty": + this.walkMetaProperty(expression); + break; + case "MemberExpression": + this.walkMemberExpression(expression); + break; + case "NewExpression": + this.walkNewExpression(expression); + break; + case "ObjectExpression": + this.walkObjectExpression(expression); + break; + case "SequenceExpression": + this.walkSequenceExpression(expression); + break; + case "SpreadElement": + this.walkSpreadElement(expression); + break; + case "TaggedTemplateExpression": + this.walkTaggedTemplateExpression(expression); + break; + case "TemplateLiteral": + this.walkTemplateLiteral(expression); + break; + case "ThisExpression": + this.walkThisExpression(expression); + break; + case "UnaryExpression": + this.walkUnaryExpression(expression); + break; + case "UpdateExpression": + this.walkUpdateExpression(expression); + break; + case "YieldExpression": + this.walkYieldExpression(expression); + break; + } + } + + /** + * @param {AwaitExpression} expression await expression + */ + walkAwaitExpression(expression) { + if (this.scope.topLevelScope === true) { + this.hooks.topLevelAwait.call(expression); + } + this.walkExpression(expression.argument); + } + + /** + * @param {ArrayExpression} expression array expression + */ + walkArrayExpression(expression) { + if (expression.elements) { + this.walkExpressions(expression.elements); + } + } + + /** + * @param {SpreadElement} expression spread element + */ + walkSpreadElement(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } + } + + /** + * @param {ObjectExpression} expression object expression + */ + walkObjectExpression(expression) { + for ( + let propIndex = 0, len = expression.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = expression.properties[propIndex]; + this.walkProperty(prop); + } + } + + /** + * @param {Property | SpreadElement} prop property or spread element + */ + walkProperty(prop) { + if (prop.type === "SpreadElement") { + this.walkExpression(prop.argument); + return; + } + if (prop.computed) { + this.walkExpression(prop.key); + } + if (prop.shorthand && prop.value && prop.value.type === "Identifier") { + this.scope.inShorthand = prop.value.name; + this.walkIdentifier(prop.value); + this.scope.inShorthand = false; + } else { + this.walkExpression( + /** @type {Exclude} */ + (prop.value) + ); + } + } + + /** + * @param {FunctionExpression} expression arrow function expression + */ + walkFunctionExpression(expression) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + const scopeParams = [...expression.params]; + + // Add function name in scope for recursive calls + if (expression.id) { + scopeParams.push(expression.id); + } + + this.inFunctionScope(true, scopeParams, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + + this.detectMode(expression.body.body); + + const prev = this.prevStatement; + + this.preWalkStatement(expression.body); + this.prevStatement = prev; + this.walkStatement(expression.body); + }); + this.scope.topLevelScope = wasTopLevel; + } + + /** + * @param {ArrowFunctionExpression} expression arrow function expression + */ + walkArrowFunctionExpression(expression) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = wasTopLevel ? "arrow" : false; + this.inFunctionScope(false, expression.params, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectMode(expression.body.body); + const prev = this.prevStatement; + this.preWalkStatement(expression.body); + this.prevStatement = prev; + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + + /** + * @param {SequenceExpression} expression the sequence + */ + walkSequenceExpression(expression) { + if (!expression.expressions) return; + // We treat sequence expressions like statements when they are one statement level + // This has some benefits for optimizations that only work on statement level + const currentStatement = + /** @type {StatementPath} */ + (this.statementPath)[ + /** @type {StatementPath} */ + (this.statementPath).length - 1 + ]; + if ( + currentStatement === expression || + (currentStatement.type === "ExpressionStatement" && + currentStatement.expression === expression) + ) { + const old = + /** @type {StatementPathItem} */ + (/** @type {StatementPath} */ (this.statementPath).pop()); + const prev = this.prevStatement; + for (const expr of expression.expressions) { + /** @type {StatementPath} */ + (this.statementPath).push(expr); + this.walkExpression(expr); + this.prevStatement = + /** @type {StatementPath} */ + (this.statementPath).pop(); + } + this.prevStatement = prev; + /** @type {StatementPath} */ + (this.statementPath).push(old); + } else { + this.walkExpressions(expression.expressions); + } + } + + /** + * @param {UpdateExpression} expression the update expression + */ + walkUpdateExpression(expression) { + this.walkExpression(expression.argument); + } + + /** + * @param {UnaryExpression} expression the unary expression + */ + walkUnaryExpression(expression) { + if (expression.operator === "typeof") { + const result = this.callHooksForExpression( + this.hooks.typeof, + expression.argument, + expression + ); + if (result === true) return; + if (expression.argument.type === "ChainExpression") { + const result = this.callHooksForExpression( + this.hooks.typeof, + expression.argument.expression, + expression + ); + if (result === true) return; + } + } + this.walkExpression(expression.argument); + } + + /** + * @param {LogicalExpression | BinaryExpression} expression the expression + */ + walkLeftRightExpression(expression) { + this.walkExpression(expression.left); + this.walkExpression(expression.right); + } + + /** + * @param {BinaryExpression} expression the binary expression + */ + walkBinaryExpression(expression) { + if (this.hooks.binaryExpression.call(expression) === undefined) { + this.walkLeftRightExpression(expression); + } + } + + /** + * @param {LogicalExpression} expression the logical expression + */ + walkLogicalExpression(expression) { + const result = this.hooks.expressionLogicalOperator.call(expression); + if (result === undefined) { + this.walkLeftRightExpression(expression); + } else if (result) { + this.walkExpression(expression.right); + } + } + + /** + * @param {AssignmentExpression} expression assignment expression + */ + walkAssignmentExpression(expression) { + if (expression.left.type === "Identifier") { + const renameIdentifier = this.getRenameIdentifier(expression.right); + if ( + renameIdentifier && + this.callHooksForInfo( + this.hooks.canRename, + renameIdentifier, + expression.right + ) + ) { + // renaming "a = b;" + if ( + !this.callHooksForInfo( + this.hooks.rename, + renameIdentifier, + expression.right + ) + ) { + this.setVariable( + expression.left.name, + typeof renameIdentifier === "string" + ? this.getVariableInfo(renameIdentifier) + : renameIdentifier + ); + } + return; + } + this.walkExpression(expression.right); + this.enterPattern(expression.left, (name, _decl) => { + if (!this.callHooksForName(this.hooks.assign, name, expression)) { + this.walkExpression( + /** @type {MemberExpression} */ + (expression.left) + ); + } + }); + } else if (expression.left.type.endsWith("Pattern")) { + this.walkExpression(expression.right); + this.enterPattern(expression.left, (name, _decl) => { + if (!this.callHooksForName(this.hooks.assign, name, expression)) { + this.defineVariable(name); + } + }); + this.walkPattern(expression.left); + } else if (expression.left.type === "MemberExpression") { + const exprName = this.getMemberExpressionInfo( + expression.left, + ALLOWED_MEMBER_TYPES_EXPRESSION + ); + if ( + exprName && + this.callHooksForInfo( + this.hooks.assignMemberChain, + exprName.rootInfo, + expression, + exprName.getMembers() + ) + ) { + return; + } + this.walkExpression(expression.right); + this.walkExpression(expression.left); + } else { + this.walkExpression(expression.right); + this.walkExpression( + /** @type {Exclude} */ + (expression.left) + ); + } + } + + /** + * @param {ConditionalExpression} expression conditional expression + */ + walkConditionalExpression(expression) { + const result = this.hooks.expressionConditionalOperator.call(expression); + if (result === undefined) { + this.walkExpression(expression.test); + this.walkExpression(expression.consequent); + + if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } else if (result) { + this.walkExpression(expression.consequent); + } else if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } + + /** + * @param {NewExpression} expression new expression + */ + walkNewExpression(expression) { + const result = this.callHooksForExpression( + this.hooks.new, + expression.callee, + expression + ); + if (result === true) return; + this.walkExpression(expression.callee); + if (expression.arguments) { + this.walkExpressions(expression.arguments); + } + } + + /** + * @param {YieldExpression} expression yield expression + */ + walkYieldExpression(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } + } + + /** + * @param {TemplateLiteral} expression template literal + */ + walkTemplateLiteral(expression) { + if (expression.expressions) { + this.walkExpressions(expression.expressions); + } + } + + /** + * @param {TaggedTemplateExpression} expression tagged template expression + */ + walkTaggedTemplateExpression(expression) { + if (expression.tag) { + this.scope.inTaggedTemplateTag = true; + this.walkExpression(expression.tag); + this.scope.inTaggedTemplateTag = false; + } + if (expression.quasi && expression.quasi.expressions) { + this.walkExpressions(expression.quasi.expressions); + } + } + + /** + * @param {ClassExpression} expression the class expression + */ + walkClassExpression(expression) { + this.walkClass(expression); + } + + /** + * @param {ChainExpression} expression expression + */ + walkChainExpression(expression) { + const result = this.hooks.optionalChaining.call(expression); + + if (result === undefined) { + if (expression.expression.type === "CallExpression") { + this.walkCallExpression(expression.expression); + } else { + this.walkMemberExpression(expression.expression); + } + } + } + + /** + * @private + * @param {FunctionExpression | ArrowFunctionExpression} functionExpression function expression + * @param {(Expression | SpreadElement)[]} options options + * @param {Expression | SpreadElement | null} currentThis current this + */ + _walkIIFE(functionExpression, options, currentThis) { + /** + * @param {Expression | SpreadElement} argOrThis arg or this + * @returns {string | VariableInfo | undefined} var info + */ + const getVarInfo = (argOrThis) => { + const renameIdentifier = this.getRenameIdentifier(argOrThis); + if ( + renameIdentifier && + this.callHooksForInfo( + this.hooks.canRename, + renameIdentifier, + /** @type {Expression} */ + (argOrThis) + ) && + !this.callHooksForInfo( + this.hooks.rename, + renameIdentifier, + /** @type {Expression} */ + (argOrThis) + ) + ) { + return typeof renameIdentifier === "string" + ? /** @type {string} */ (this.getVariableInfo(renameIdentifier)) + : renameIdentifier; + } + this.walkExpression(argOrThis); + }; + const { params, type } = functionExpression; + const arrow = type === "ArrowFunctionExpression"; + const renameThis = currentThis ? getVarInfo(currentThis) : null; + const varInfoForArgs = options.map(getVarInfo); + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false; + const scopeParams = + /** @type {(Identifier | string)[]} */ + (params.filter((identifier, idx) => !varInfoForArgs[idx])); + + // Add function name in scope for recursive calls + if ( + functionExpression.type === "FunctionExpression" && + functionExpression.id + ) { + scopeParams.push(functionExpression.id.name); + } + + this.inFunctionScope(true, scopeParams, () => { + if (renameThis && !arrow) { + this.setVariable("this", renameThis); + } + for (let i = 0; i < varInfoForArgs.length; i++) { + const varInfo = varInfoForArgs[i]; + if (!varInfo) continue; + if (!params[i] || params[i].type !== "Identifier") continue; + this.setVariable(/** @type {Identifier} */ (params[i]).name, varInfo); + } + if (functionExpression.body.type === "BlockStatement") { + this.detectMode(functionExpression.body.body); + const prev = this.prevStatement; + this.preWalkStatement(functionExpression.body); + this.prevStatement = prev; + this.walkStatement(functionExpression.body); + } else { + this.walkExpression(functionExpression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + + /** + * @param {ImportExpression} expression import expression + */ + walkImportExpression(expression) { + const result = this.hooks.importCall.call(expression); + if (result === true) return; + + this.walkExpression(expression.source); + } + + /** + * @param {CallExpression} expression expression + */ + walkCallExpression(expression) { + /** + * @param {FunctionExpression | ArrowFunctionExpression} fn function + * @returns {boolean} true when simple function + */ + const isSimpleFunction = (fn) => + fn.params.every((p) => p.type === "Identifier"); + if ( + expression.callee.type === "MemberExpression" && + expression.callee.object.type.endsWith("FunctionExpression") && + !expression.callee.computed && + /** @type {boolean} */ + ( + /** @type {Identifier} */ + (expression.callee.property).name === "call" || + /** @type {Identifier} */ + (expression.callee.property).name === "bind" + ) && + expression.arguments.length > 0 && + isSimpleFunction( + /** @type {FunctionExpression | ArrowFunctionExpression} */ + (expression.callee.object) + ) + ) { + // (function(…) { }.call/bind(?, …)) + this._walkIIFE( + /** @type {FunctionExpression | ArrowFunctionExpression} */ + (expression.callee.object), + expression.arguments.slice(1), + expression.arguments[0] + ); + } else if ( + expression.callee.type.endsWith("FunctionExpression") && + isSimpleFunction( + /** @type {FunctionExpression | ArrowFunctionExpression} */ + (expression.callee) + ) + ) { + // (function(…) { }(…)) + this._walkIIFE( + /** @type {FunctionExpression | ArrowFunctionExpression} */ + (expression.callee), + expression.arguments, + null + ); + } else { + if (expression.callee.type === "MemberExpression") { + const exprInfo = this.getMemberExpressionInfo( + expression.callee, + ALLOWED_MEMBER_TYPES_CALL_EXPRESSION + ); + if (exprInfo && exprInfo.type === "call") { + const result = this.callHooksForInfo( + this.hooks.callMemberChainOfCallMemberChain, + exprInfo.rootInfo, + expression, + exprInfo.getCalleeMembers(), + exprInfo.call, + exprInfo.getMembers(), + exprInfo.getMemberRanges() + ); + if (result === true) return; + } + } + const callee = this.evaluateExpression(expression.callee); + if (callee.isIdentifier()) { + const result1 = this.callHooksForInfo( + this.hooks.callMemberChain, + /** @type {NonNullable} */ + (callee.rootInfo), + expression, + /** @type {NonNullable} */ + (callee.getMembers)(), + callee.getMembersOptionals + ? callee.getMembersOptionals() + : /** @type {NonNullable} */ + (callee.getMembers)().map(() => false), + callee.getMemberRanges ? callee.getMemberRanges() : [] + ); + if (result1 === true) return; + const result2 = this.callHooksForInfo( + this.hooks.call, + /** @type {NonNullable} */ + (callee.identifier), + expression + ); + if (result2 === true) return; + } + + if (expression.callee) { + if (expression.callee.type === "MemberExpression") { + // because of call context we need to walk the call context as expression + this.walkExpression(expression.callee.object); + if (expression.callee.computed === true) { + this.walkExpression(expression.callee.property); + } + } else { + this.walkExpression(expression.callee); + } + } + if (expression.arguments) this.walkExpressions(expression.arguments); + } + } + + /** + * @param {MemberExpression} expression member expression + */ + walkMemberExpression(expression) { + const exprInfo = this.getMemberExpressionInfo( + expression, + ALLOWED_MEMBER_TYPES_ALL + ); + if (exprInfo) { + switch (exprInfo.type) { + case "expression": { + const result1 = this.callHooksForInfo( + this.hooks.expression, + exprInfo.name, + expression + ); + if (result1 === true) return; + const members = exprInfo.getMembers(); + const membersOptionals = exprInfo.getMembersOptionals(); + const memberRanges = exprInfo.getMemberRanges(); + const result2 = this.callHooksForInfo( + this.hooks.expressionMemberChain, + exprInfo.rootInfo, + expression, + members, + membersOptionals, + memberRanges + ); + if (result2 === true) return; + this.walkMemberExpressionWithExpressionName( + expression, + exprInfo.name, + exprInfo.rootInfo, + [...members], + () => + this.callHooksForInfo( + this.hooks.unhandledExpressionMemberChain, + exprInfo.rootInfo, + expression, + members + ) + ); + return; + } + case "call": { + const result = this.callHooksForInfo( + this.hooks.memberChainOfCallMemberChain, + exprInfo.rootInfo, + expression, + exprInfo.getCalleeMembers(), + exprInfo.call, + exprInfo.getMembers(), + exprInfo.getMemberRanges() + ); + if (result === true) return; + // Fast skip over the member chain as we already called memberChainOfCallMemberChain + // and call computed property are literals anyway + this.walkExpression(exprInfo.call); + return; + } + } + } + this.walkExpression(expression.object); + if (expression.computed === true) this.walkExpression(expression.property); + } + + /** + * @template R + * @param {MemberExpression} expression member expression + * @param {string} name name + * @param {string | VariableInfo} rootInfo root info + * @param {string[]} members members + * @param {() => R | undefined} onUnhandled on unhandled callback + */ + walkMemberExpressionWithExpressionName( + expression, + name, + rootInfo, + members, + onUnhandled + ) { + if (expression.object.type === "MemberExpression") { + // optimize the case where expression.object is a MemberExpression too. + // we can keep info here when calling walkMemberExpression directly + const property = + /** @type {Identifier} */ + (expression.property).name || + `${/** @type {Literal} */ (expression.property).value}`; + name = name.slice(0, -property.length - 1); + members.pop(); + const result = this.callHooksForInfo( + this.hooks.expression, + name, + expression.object + ); + if (result === true) return; + this.walkMemberExpressionWithExpressionName( + expression.object, + name, + rootInfo, + members, + onUnhandled + ); + } else if (!onUnhandled || !onUnhandled()) { + this.walkExpression(expression.object); + } + if (expression.computed === true) this.walkExpression(expression.property); + } + + /** + * @param {ThisExpression} expression this expression + */ + walkThisExpression(expression) { + this.callHooksForName(this.hooks.expression, "this", expression); + } + + /** + * @param {Identifier} expression identifier + */ + walkIdentifier(expression) { + this.callHooksForName(this.hooks.expression, expression.name, expression); + } + + /** + * @param {MetaProperty} metaProperty meta property + */ + walkMetaProperty(metaProperty) { + this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty); + } + + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {Expression | Super} expr expression + * @param {AsArray} args args for the hook + * @returns {R | undefined} result of hook + */ + callHooksForExpression(hookMap, expr, ...args) { + return this.callHooksForExpressionWithFallback( + hookMap, + expr, + undefined, + undefined, + ...args + ); + } + + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {Expression | Super} expr expression info + * @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => string[]) => R) | undefined} fallback callback when variable in not handled by hooks + * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined + * @param {AsArray} args args for the hook + * @returns {R | undefined} result of hook + */ + callHooksForExpressionWithFallback( + hookMap, + expr, + fallback, + defined, + ...args + ) { + const exprName = this.getMemberExpressionInfo( + expr, + ALLOWED_MEMBER_TYPES_EXPRESSION + ); + if (exprName !== undefined) { + const members = exprName.getMembers(); + return this.callHooksForInfoWithFallback( + hookMap, + members.length === 0 ? exprName.rootInfo : exprName.name, + fallback && + ((name) => fallback(name, exprName.rootInfo, exprName.getMembers)), + defined && (() => defined(exprName.name)), + ...args + ); + } + } + + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {string} name key in map + * @param {AsArray} args args for the hook + * @returns {R | undefined} result of hook + */ + callHooksForName(hookMap, name, ...args) { + return this.callHooksForNameWithFallback( + hookMap, + name, + undefined, + undefined, + ...args + ); + } + + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks that should be called + * @param {ExportedVariableInfo} info variable info + * @param {AsArray} args args for the hook + * @returns {R | undefined} result of hook + */ + callHooksForInfo(hookMap, info, ...args) { + return this.callHooksForInfoWithFallback( + hookMap, + info, + undefined, + undefined, + ...args + ); + } + + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {ExportedVariableInfo} info variable info + * @param {((name: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks + * @param {((result?: string) => TODO) | undefined} defined callback when variable is defined + * @param {AsArray} args args for the hook + * @returns {R | undefined} result of hook + */ + callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) { + let name; + if (typeof info === "string") { + name = info; + } else { + if (!(info instanceof VariableInfo)) { + if (defined !== undefined) { + return defined(); + } + return; + } + let tagInfo = info.tagInfo; + while (tagInfo !== undefined) { + const hook = hookMap.get(tagInfo.tag); + if (hook !== undefined) { + this.currentTagData = tagInfo.data; + const result = hook.call(...args); + this.currentTagData = undefined; + if (result !== undefined) return result; + } + tagInfo = tagInfo.next; + } + if (!info.isFree() && !info.isTagged()) { + if (defined !== undefined) { + return defined(); + } + return; + } + name = info.name; + } + const hook = hookMap.get(name); + if (hook !== undefined) { + const result = hook.call(...args); + if (result !== undefined) return result; + } + if (fallback !== undefined) { + return fallback(/** @type {string} */ (name)); + } + } + + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {string} name key in map + * @param {((value: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks + * @param {(() => R) | undefined} defined callback when variable is defined + * @param {AsArray} args args for the hook + * @returns {R | undefined} result of hook + */ + callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) { + return this.callHooksForInfoWithFallback( + hookMap, + this.getVariableInfo(name), + fallback, + defined, + ...args + ); + } + + /** + * @deprecated + * @param {(string | Pattern | Property)[]} params scope params + * @param {() => void} fn inner function + * @returns {void} + */ + inScope(params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + inTaggedTemplateTag: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + terminated: undefined, + definitions: oldScope.definitions.createChild() + }; + + this.undefineVariable("this"); + + this.enterPatterns(params, (ident) => { + this.defineVariable(ident); + }); + + fn(); + + this.scope = oldScope; + } + + /** + * @param {boolean} hasThis true, when this is defined + * @param {Identifier[]} params scope params + * @param {() => void} fn inner function + * @returns {void} + */ + inClassScope(hasThis, params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + inTaggedTemplateTag: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + terminated: undefined, + definitions: oldScope.definitions.createChild() + }; + + if (hasThis) { + this.undefineVariable("this"); + } + + this.enterPatterns(params, (ident) => { + this.defineVariable(ident); + }); + + fn(); + + this.scope = oldScope; + } + + /** + * @param {boolean} hasThis true, when this is defined + * @param {(Pattern | string)[]} params scope params + * @param {() => void} fn inner function + * @returns {void} + */ + inFunctionScope(hasThis, params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + inTaggedTemplateTag: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + terminated: undefined, + definitions: oldScope.definitions.createChild() + }; + + if (hasThis) { + this.undefineVariable("this"); + } + + this.enterPatterns(params, (ident) => { + this.defineVariable(ident); + }); + + fn(); + + this.scope = oldScope; + } + + /** + * @param {() => void} fn inner function + * @param {boolean} inExecutedPath executed state + * @returns {void} + */ + inBlockScope(fn, inExecutedPath = false) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: oldScope.inTry, + inShorthand: false, + inTaggedTemplateTag: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + terminated: oldScope.terminated, + definitions: oldScope.definitions.createChild() + }; + + fn(); + + const terminated = this.scope.terminated; + + if (inExecutedPath && terminated) { + oldScope.terminated = terminated; + } + + this.scope = oldScope; + } + + /** + * @param {Array} statements statements + */ + detectMode(statements) { + const isLiteral = + statements.length >= 1 && + statements[0].type === "ExpressionStatement" && + statements[0].expression.type === "Literal"; + if ( + isLiteral && + /** @type {Literal} */ + (/** @type {ExpressionStatement} */ (statements[0]).expression).value === + "use strict" + ) { + this.scope.isStrict = true; + } + if ( + isLiteral && + /** @type {Literal} */ + (/** @type {ExpressionStatement} */ (statements[0]).expression).value === + "use asm" + ) { + this.scope.isAsmJs = true; + } + } + + /** + * @param {(string | Pattern | Property)[]} patterns patterns + * @param {OnIdentString} onIdent on ident callback + */ + enterPatterns(patterns, onIdent) { + for (const pattern of patterns) { + if (typeof pattern !== "string") { + this.enterPattern(pattern, onIdent); + } else if (pattern) { + onIdent(pattern); + } + } + } + + /** + * @param {Pattern | Property} pattern pattern + * @param {OnIdent} onIdent on ident callback + */ + enterPattern(pattern, onIdent) { + if (!pattern) return; + switch (pattern.type) { + case "ArrayPattern": + this.enterArrayPattern(pattern, onIdent); + break; + case "AssignmentPattern": + this.enterAssignmentPattern(pattern, onIdent); + break; + case "Identifier": + this.enterIdentifier(pattern, onIdent); + break; + case "ObjectPattern": + this.enterObjectPattern(pattern, onIdent); + break; + case "RestElement": + this.enterRestElement(pattern, onIdent); + break; + case "Property": + if (pattern.shorthand && pattern.value.type === "Identifier") { + this.scope.inShorthand = pattern.value.name; + this.enterIdentifier(pattern.value, onIdent); + this.scope.inShorthand = false; + } else { + this.enterPattern(/** @type {Pattern} */ (pattern.value), onIdent); + } + break; + } + } + + /** + * @param {Identifier} pattern identifier pattern + * @param {OnIdent} onIdent callback + */ + enterIdentifier(pattern, onIdent) { + if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) { + onIdent(pattern.name, pattern); + } + } + + /** + * @param {ObjectPattern} pattern object pattern + * @param {OnIdent} onIdent callback + */ + enterObjectPattern(pattern, onIdent) { + for ( + let propIndex = 0, len = pattern.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = pattern.properties[propIndex]; + this.enterPattern(prop, onIdent); + } + } + + /** + * @param {ArrayPattern} pattern object pattern + * @param {OnIdent} onIdent callback + */ + enterArrayPattern(pattern, onIdent) { + for ( + let elementIndex = 0, len = pattern.elements.length; + elementIndex < len; + elementIndex++ + ) { + const element = pattern.elements[elementIndex]; + + if (element) { + this.enterPattern(element, onIdent); + } + } + } + + /** + * @param {RestElement} pattern object pattern + * @param {OnIdent} onIdent callback + */ + enterRestElement(pattern, onIdent) { + this.enterPattern(pattern.argument, onIdent); + } + + /** + * @param {AssignmentPattern} pattern object pattern + * @param {OnIdent} onIdent callback + */ + enterAssignmentPattern(pattern, onIdent) { + this.enterPattern(pattern.left, onIdent); + } + + /** + * @param {Expression | SpreadElement | PrivateIdentifier | Super} expression expression node + * @returns {BasicEvaluatedExpression} evaluation result + */ + evaluateExpression(expression) { + try { + const hook = this.hooks.evaluate.get(expression.type); + if (hook !== undefined) { + const result = hook.call(expression); + if (result !== undefined && result !== null) { + result.setExpression(expression); + return result; + } + } + } catch (err) { + // eslint-disable-next-line no-console + console.warn(err); + // ignore error + } + return new BasicEvaluatedExpression() + .setRange(/** @type {Range} */ (expression.range)) + .setExpression(expression); + } + + /** + * @param {Expression} expression expression + * @returns {string} parsed string + */ + parseString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + return ( + this.parseString(/** @type {Expression} */ (expression.left)) + + this.parseString(expression.right) + ); + } + break; + case "Literal": + return String(expression.value); + } + throw new Error( + `${expression.type} is not supported as parameter for require` + ); + } + + /** @typedef {{ range?: Range, value: string, code: boolean, conditional: false | CalculatedStringResult[] }} CalculatedStringResult */ + + /** + * @param {Expression} expression expression + * @returns {CalculatedStringResult} result + */ + parseCalculatedString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + const left = this.parseCalculatedString( + /** @type {Expression} */ + (expression.left) + ); + const right = this.parseCalculatedString(expression.right); + if (left.code) { + return { + range: left.range, + value: left.value, + code: true, + conditional: false + }; + } else if (right.code) { + return { + range: [ + /** @type {Range} */ + (left.range)[0], + right.range + ? right.range[1] + : /** @type {Range} */ (left.range)[1] + ], + value: left.value + right.value, + code: true, + conditional: false + }; + } + return { + range: [ + /** @type {Range} */ + (left.range)[0], + /** @type {Range} */ + (right.range)[1] + ], + value: left.value + right.value, + code: false, + conditional: false + }; + } + break; + case "ConditionalExpression": { + const consequent = this.parseCalculatedString(expression.consequent); + const alternate = this.parseCalculatedString(expression.alternate); + /** @type {CalculatedStringResult[]} */ + const items = []; + if (consequent.conditional) { + items.push(...consequent.conditional); + } else if (!consequent.code) { + items.push(consequent); + } else { + break; + } + if (alternate.conditional) { + items.push(...alternate.conditional); + } else if (!alternate.code) { + items.push(alternate); + } else { + break; + } + return { + range: undefined, + value: "", + code: true, + conditional: items + }; + } + case "Literal": + return { + range: expression.range, + value: String(expression.value), + code: false, + conditional: false + }; + } + return { + range: undefined, + value: "", + code: true, + conditional: false + }; + } + + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + let ast; + /** @type {import("acorn").Comment[]} */ + let comments; + const semicolons = new Set(); + if (source === null) { + throw new Error("source must not be null"); + } + if (Buffer.isBuffer(source)) { + source = source.toString("utf8"); + } + if (typeof source === "object") { + ast = /** @type {Program} */ (source); + comments = source.comments; + if (source.semicolons) { + // Forward semicolon information from the preparsed AST if present + // This ensures the output is consistent with that of a fresh AST + for (const pos of source.semicolons) { + semicolons.add(pos); + } + } + } else { + comments = []; + ast = JavascriptParser._parse(source, { + sourceType: this.sourceType, + onComment: comments, + onInsertedSemicolon: (pos) => semicolons.add(pos) + }); + } + + const oldScope = this.scope; + const oldState = this.state; + const oldComments = this.comments; + const oldSemicolons = this.semicolons; + const oldStatementPath = this.statementPath; + const oldPrevStatement = this.prevStatement; + this.scope = { + topLevelScope: true, + inTry: false, + inShorthand: false, + inTaggedTemplateTag: false, + isStrict: false, + isAsmJs: false, + terminated: undefined, + definitions: new StackedMap() + }; + this.state = /** @type {ParserState} */ (state); + this.comments = comments; + this.semicolons = semicolons; + this.statementPath = []; + this.prevStatement = undefined; + if (this.hooks.program.call(ast, comments) === undefined) { + this.destructuringAssignmentProperties = new WeakMap(); + this.detectMode(ast.body); + this.modulePreWalkStatements(ast.body); + this.preWalkStatements(ast.body); + this.prevStatement = undefined; + this.blockPreWalkStatements(ast.body); + this.prevStatement = undefined; + this.walkStatements(ast.body); + this.destructuringAssignmentProperties = undefined; + } + this.hooks.finish.call(ast, comments); + this.scope = oldScope; + this.state = oldState; + this.comments = oldComments; + this.semicolons = oldSemicolons; + this.statementPath = oldStatementPath; + this.prevStatement = oldPrevStatement; + return state; + } + + /** + * @param {string} source source code + * @returns {BasicEvaluatedExpression} evaluation result + */ + evaluate(source) { + const ast = JavascriptParser._parse(`(${source})`, { + sourceType: this.sourceType, + locations: false + }); + if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { + throw new Error("evaluate: Source is not a expression"); + } + return this.evaluateExpression(ast.body[0].expression); + } + + /** + * @param {Expression | Declaration | PrivateIdentifier | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | null | undefined} expr an expression + * @param {number} commentsStartPos source position from which annotation comments are checked + * @returns {boolean} true, when the expression is pure + */ + isPure(expr, commentsStartPos) { + if (!expr) return true; + const result = this.hooks.isPure + .for(expr.type) + .call(expr, commentsStartPos); + if (typeof result === "boolean") return result; + switch (expr.type) { + // TODO handle more cases + case "ClassDeclaration": + case "ClassExpression": { + if (expr.body.type !== "ClassBody") return false; + if ( + expr.superClass && + !this.isPure(expr.superClass, /** @type {Range} */ (expr.range)[0]) + ) { + return false; + } + const items = expr.body.body; + return items.every((item) => { + if (item.type === "StaticBlock") { + return false; + } + + if ( + item.computed && + item.key && + !this.isPure( + item.key, + /** @type {Range} */ + (item.range)[0] + ) + ) { + return false; + } + + if ( + item.static && + item.value && + !this.isPure( + item.value, + item.key + ? /** @type {Range} */ (item.key.range)[1] + : /** @type {Range} */ (item.range)[0] + ) + ) { + return false; + } + + if ( + expr.superClass && + item.type === "MethodDefinition" && + item.kind === "constructor" + ) { + return false; + } + + return true; + }); + } + + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "ThisExpression": + case "Literal": + case "TemplateLiteral": + case "Identifier": + case "PrivateIdentifier": + return true; + + case "VariableDeclaration": + return expr.declarations.every((decl) => + this.isPure(decl.init, /** @type {Range} */ (decl.range)[0]) + ); + + case "ConditionalExpression": + return ( + this.isPure(expr.test, commentsStartPos) && + this.isPure( + expr.consequent, + /** @type {Range} */ (expr.test.range)[1] + ) && + this.isPure( + expr.alternate, + /** @type {Range} */ (expr.consequent.range)[1] + ) + ); + + case "LogicalExpression": + return ( + this.isPure(expr.left, commentsStartPos) && + this.isPure(expr.right, /** @type {Range} */ (expr.left.range)[1]) + ); + + case "SequenceExpression": + return expr.expressions.every((expr) => { + const pureFlag = this.isPure(expr, commentsStartPos); + commentsStartPos = /** @type {Range} */ (expr.range)[1]; + return pureFlag; + }); + + case "CallExpression": { + const pureFlag = + /** @type {Range} */ (expr.range)[0] - commentsStartPos > 12 && + this.getComments([ + commentsStartPos, + /** @type {Range} */ (expr.range)[0] + ]).some( + (comment) => + comment.type === "Block" && + /^\s*(#|@)__PURE__\s*$/.test(comment.value) + ); + if (!pureFlag) return false; + commentsStartPos = /** @type {Range} */ (expr.callee.range)[1]; + return expr.arguments.every((arg) => { + if (arg.type === "SpreadElement") return false; + const pureFlag = this.isPure(arg, commentsStartPos); + commentsStartPos = /** @type {Range} */ (arg.range)[1]; + return pureFlag; + }); + } + } + const evaluated = this.evaluateExpression(expr); + return !evaluated.couldHaveSideEffects(); + } + + /** + * @param {Range} range range + * @returns {Comment[]} comments in the range + */ + getComments(range) { + const [rangeStart, rangeEnd] = range; + /** + * @param {Comment} comment comment + * @param {number} needle needle + * @returns {number} compared + */ + const compare = (comment, needle) => + /** @type {Range} */ (comment.range)[0] - needle; + const comments = /** @type {Comment[]} */ (this.comments); + let idx = binarySearchBounds.ge(comments, rangeStart, compare); + /** @type {Comment[]} */ + const commentsInRange = []; + while ( + comments[idx] && + /** @type {Range} */ (comments[idx].range)[1] <= rangeEnd + ) { + commentsInRange.push(comments[idx]); + idx++; + } + + return commentsInRange; + } + + /** + * @param {number} pos source code position + * @returns {boolean} true when a semicolon has been inserted before this position, false if not + */ + isAsiPosition(pos) { + const currentStatement = + /** @type {StatementPath} */ + (this.statementPath)[ + /** @type {StatementPath} */ + (this.statementPath).length - 1 + ]; + if (currentStatement === undefined) throw new Error("Not in statement"); + const range = /** @type {Range} */ (currentStatement.range); + + return ( + // Either asking directly for the end position of the current statement + (range[1] === pos && + /** @type {Set} */ (this.semicolons).has(pos)) || + // Or asking for the start position of the current statement, + // here we have to check multiple things + (range[0] === pos && + // is there a previous statement which might be relevant? + this.prevStatement !== undefined && + // is the end position of the previous statement an ASI position? + /** @type {Set} */ (this.semicolons).has( + /** @type {Range} */ (this.prevStatement.range)[1] + )) + ); + } + + /** + * @param {number} pos source code position + * @returns {void} + */ + setAsiPosition(pos) { + /** @type {Set} */ (this.semicolons).add(pos); + } + + /** + * @param {number} pos source code position + * @returns {void} + */ + unsetAsiPosition(pos) { + /** @type {Set} */ (this.semicolons).delete(pos); + } + + /** + * @param {Expression} expr expression + * @returns {boolean} true, when the expression is a statement level expression + */ + isStatementLevelExpression(expr) { + const currentStatement = + /** @type {StatementPath} */ + (this.statementPath)[ + /** @type {StatementPath} */ + (this.statementPath).length - 1 + ]; + return ( + expr === currentStatement || + (currentStatement.type === "ExpressionStatement" && + currentStatement.expression === expr) + ); + } + + /** + * @param {string} name name + * @param {Tag} tag tag info + * @returns {TagData | undefined} tag data + */ + getTagData(name, tag) { + const info = this.scope.definitions.get(name); + if (info instanceof VariableInfo) { + let tagInfo = info.tagInfo; + while (tagInfo !== undefined) { + if (tagInfo.tag === tag) return tagInfo.data; + tagInfo = tagInfo.next; + } + } + } + + /** + * @param {string} name name + * @param {Tag} tag tag info + * @param {TagData=} data data + * @param {VariableInfoFlagsType=} flags flags + */ + tagVariable(name, tag, data, flags = VariableInfoFlags.Tagged) { + const oldInfo = this.scope.definitions.get(name); + /** @type {VariableInfo} */ + let newInfo; + if (oldInfo === undefined) { + newInfo = new VariableInfo(this.scope, name, flags, { + tag, + data, + next: undefined + }); + } else if (oldInfo instanceof VariableInfo) { + newInfo = new VariableInfo( + oldInfo.declaredScope, + oldInfo.name, + /** @type {VariableInfoFlagsType} */ (oldInfo.flags | flags), + { + tag, + data, + next: oldInfo.tagInfo + } + ); + } else { + newInfo = new VariableInfo(oldInfo, name, flags, { + tag, + data, + next: undefined + }); + } + this.scope.definitions.set(name, newInfo); + } + + /** + * @param {string} name variable name + */ + defineVariable(name) { + const oldInfo = this.scope.definitions.get(name); + // Don't redefine variable in same scope to keep existing tags + if ( + oldInfo instanceof VariableInfo && + oldInfo.declaredScope === this.scope + ) { + return; + } + this.scope.definitions.set(name, this.scope); + } + + /** + * @param {string} name variable name + */ + undefineVariable(name) { + this.scope.definitions.delete(name); + } + + /** + * @param {string} name variable name + * @returns {boolean} true, when variable is defined + */ + isVariableDefined(name) { + const info = this.scope.definitions.get(name); + if (info === undefined) return false; + if (info instanceof VariableInfo) { + return !info.isFree(); + } + return true; + } + + /** + * @param {string} name variable name + * @returns {string | ExportedVariableInfo} info for this variable + */ + getVariableInfo(name) { + const value = this.scope.definitions.get(name); + if (value === undefined) { + return name; + } + return value; + } + + /** + * @param {string} name variable name + * @param {string | ExportedVariableInfo} variableInfo new info for this variable + * @returns {void} + */ + setVariable(name, variableInfo) { + if (typeof variableInfo === "string") { + if (variableInfo === name) { + this.scope.definitions.delete(name); + } else { + this.scope.definitions.set( + name, + new VariableInfo( + this.scope, + variableInfo, + VariableInfoFlags.Free, + undefined + ) + ); + } + } else { + this.scope.definitions.set(name, variableInfo); + } + } + + /** + * @param {TagInfo} tagInfo tag info + * @returns {VariableInfo} variable info + */ + evaluatedVariable(tagInfo) { + return new VariableInfo( + this.scope, + undefined, + VariableInfoFlags.Evaluated, + tagInfo + ); + } + + /** + * @param {Range} range range of the comment + * @returns {{ options: Record | null, errors: (Error & { comment: Comment })[] | null }} result + */ + parseCommentOptions(range) { + const comments = this.getComments(range); + if (comments.length === 0) { + return EMPTY_COMMENT_OPTIONS; + } + /** @type {Record } */ + const options = {}; + /** @type {(Error & { comment: Comment })[]} */ + const errors = []; + for (const comment of comments) { + const { value } = comment; + if (value && webpackCommentRegExp.test(value)) { + // try compile only if webpack options comment is present + try { + for (let [key, val] of Object.entries( + vm.runInContext( + `(function(){return {${value}};})()`, + this.magicCommentContext + ) + )) { + if (typeof val === "object" && val !== null) { + val = + val.constructor.name === "RegExp" + ? new RegExp(val) + : JSON.parse(JSON.stringify(val)); + } + options[key] = val; + } + } catch (err) { + const newErr = new Error(String(/** @type {Error} */ (err).message)); + newErr.stack = String(/** @type {Error} */ (err).stack); + Object.assign(newErr, { comment }); + errors.push(/** @type {(Error & { comment: Comment })} */ (newErr)); + } + } + } + return { options, errors }; + } + + /** + * @param {Expression | Super} expression a member expression + * @returns {{ members: string[], object: Expression | Super, membersOptionals: boolean[], memberRanges: Range[] }} member names (reverse order) and remaining object + */ + extractMemberExpressionChain(expression) { + /** @type {Node} */ + let expr = expression; + const members = []; + const membersOptionals = []; + const memberRanges = []; + while (expr.type === "MemberExpression") { + if (expr.computed) { + if (expr.property.type !== "Literal") break; + members.push(`${expr.property.value}`); // the literal + memberRanges.push(/** @type {Range} */ (expr.object.range)); // the range of the expression fragment before the literal + } else { + if (expr.property.type !== "Identifier") break; + members.push(expr.property.name); // the identifier + memberRanges.push(/** @type {Range} */ (expr.object.range)); // the range of the expression fragment before the identifier + } + membersOptionals.push(expr.optional); + expr = expr.object; + } + + return { + members, + membersOptionals, + memberRanges, + object: expr + }; + } + + /** + * @param {string} varName variable name + * @returns {{name: string, info: VariableInfo | string} | undefined} name of the free variable and variable info for that + */ + getFreeInfoFromVariable(varName) { + const info = this.getVariableInfo(varName); + let name; + if (info instanceof VariableInfo && info.name) { + if (!info.isFree()) return; + name = info.name; + } else if (typeof info !== "string") { + return; + } else { + name = info; + } + return { info, name }; + } + + /** + * @param {string} varName variable name + * @returns {{name: string, info: VariableInfo | string} | undefined} name of the free variable and variable info for that + */ + getNameInfoFromVariable(varName) { + const info = this.getVariableInfo(varName); + let name; + if (info instanceof VariableInfo && info.name) { + if (!info.isFree() && !info.isTagged()) return; + name = info.name; + } else if (typeof info !== "string") { + return; + } else { + name = info; + } + return { info, name }; + } + + /** @typedef {{ type: "call", call: CallExpression, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} CallExpressionInfo */ + /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[], getMembersOptionals: () => boolean[], getMemberRanges: () => Range[]}} ExpressionExpressionInfo */ + + /** + * @param {Expression | Super} expression a member expression + * @param {number} allowedTypes which types should be returned, presented in bit mask + * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info + */ + getMemberExpressionInfo(expression, allowedTypes) { + const { object, members, membersOptionals, memberRanges } = + this.extractMemberExpressionChain(expression); + switch (object.type) { + case "CallExpression": { + if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) return; + let callee = object.callee; + let rootMembers = EMPTY_ARRAY; + if (callee.type === "MemberExpression") { + ({ object: callee, members: rootMembers } = + this.extractMemberExpressionChain(callee)); + } + const rootName = getRootName(callee); + if (!rootName) return; + const result = this.getNameInfoFromVariable(rootName); + if (!result) return; + const { info: rootInfo, name: resolvedRoot } = result; + const calleeName = objectAndMembersToName(resolvedRoot, rootMembers); + return { + type: "call", + call: object, + calleeName, + rootInfo, + getCalleeMembers: memoize(() => rootMembers.reverse()), + name: objectAndMembersToName(`${calleeName}()`, members), + getMembers: memoize(() => members.reverse()), + getMembersOptionals: memoize(() => membersOptionals.reverse()), + getMemberRanges: memoize(() => memberRanges.reverse()) + }; + } + case "Identifier": + case "MetaProperty": + case "ThisExpression": { + if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) return; + const rootName = getRootName(object); + if (!rootName) return; + + const result = this.getNameInfoFromVariable(rootName); + if (!result) return; + const { info: rootInfo, name: resolvedRoot } = result; + return { + type: "expression", + name: objectAndMembersToName(resolvedRoot, members), + rootInfo, + getMembers: memoize(() => members.reverse()), + getMembersOptionals: memoize(() => membersOptionals.reverse()), + getMemberRanges: memoize(() => memberRanges.reverse()) + }; + } + } + } + + /** + * @param {Expression} expression an expression + * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]} | undefined} name info + */ + getNameForExpression(expression) { + return this.getMemberExpressionInfo( + expression, + ALLOWED_MEMBER_TYPES_EXPRESSION + ); + } + + /** + * @param {string} code source code + * @param {ParseOptions} options parsing options + * @returns {Program} parsed ast + */ + static _parse(code, options) { + const type = options ? options.sourceType : "module"; + /** @type {AcornOptions} */ + const parserOptions = { + ...defaultParserOptions, + allowReturnOutsideFunction: type === "script", + ...options, + sourceType: type === "auto" ? "module" : type + }; + + /** @type {import("acorn").Program | undefined} */ + let ast; + let error; + let threw = false; + try { + ast = parser.parse(code, parserOptions); + } catch (err) { + error = err; + threw = true; + } + + if (threw && type === "auto") { + parserOptions.sourceType = "script"; + if (!("allowReturnOutsideFunction" in options)) { + parserOptions.allowReturnOutsideFunction = true; + } + if (Array.isArray(parserOptions.onComment)) { + parserOptions.onComment.length = 0; + } + try { + ast = parser.parse(code, parserOptions); + threw = false; + } catch (_err) { + // we use the error from first parse try + // so nothing to do here + } + } + + if (threw) { + throw error; + } + + return /** @type {Program} */ (ast); + } + + /** + * @param {((BaseParser: typeof AcornParser) => typeof AcornParser)[]} plugins parser plugin + * @returns {typeof JavascriptParser} parser + */ + static extend(...plugins) { + parser = parser.extend(...plugins); + return JavascriptParser; + } +} + +module.exports = JavascriptParser; +module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL; +module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = + ALLOWED_MEMBER_TYPES_CALL_EXPRESSION; +module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION = + ALLOWED_MEMBER_TYPES_EXPRESSION; +module.exports.VariableInfo = VariableInfo; +module.exports.VariableInfoFlags = VariableInfoFlags; +module.exports.getImportAttributes = getImportAttributes; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptParserHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptParserHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..03628beabfb9a4de4a68a9e1e1e35e739bcb25f5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/JavascriptParserHelpers.js @@ -0,0 +1,129 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); +const ConstDependency = require("../dependencies/ConstDependency"); +const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); + +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").SourceLocation} SourceLocation */ +/** @typedef {import("./JavascriptParser")} JavascriptParser */ +/** @typedef {import("./JavascriptParser").Range} Range */ + +module.exports.approve = () => true; + +/** + * @param {boolean} value the boolean value + * @returns {(expression: Expression) => BasicEvaluatedExpression} plugin function + */ +module.exports.evaluateToBoolean = (value) => + function booleanExpression(expr) { + return new BasicEvaluatedExpression() + .setBoolean(value) + .setRange(/** @type {Range} */ (expr.range)); + }; + +/** + * @param {string} identifier identifier + * @param {string} rootInfo rootInfo + * @param {() => string[]} getMembers getMembers + * @param {boolean | null=} truthy is truthy, null if nullish + * @returns {(expression: Expression) => BasicEvaluatedExpression} callback + */ +module.exports.evaluateToIdentifier = ( + identifier, + rootInfo, + getMembers, + truthy +) => + function identifierExpression(expr) { + const evaluatedExpression = new BasicEvaluatedExpression() + .setIdentifier(identifier, rootInfo, getMembers) + .setSideEffects(false) + .setRange(/** @type {Range} */ (expr.range)); + switch (truthy) { + case true: + evaluatedExpression.setTruthy(); + break; + case null: + evaluatedExpression.setNullish(true); + break; + case false: + evaluatedExpression.setFalsy(); + break; + } + + return evaluatedExpression; + }; + +/** + * @param {number} value the number value + * @returns {(expression: Expression) => BasicEvaluatedExpression} plugin function + */ +module.exports.evaluateToNumber = (value) => + function stringExpression(expr) { + return new BasicEvaluatedExpression() + .setNumber(value) + .setRange(/** @type {Range} */ (expr.range)); + }; + +/** + * @param {string} value the string value + * @returns {(expression: Expression) => BasicEvaluatedExpression} plugin function + */ +module.exports.evaluateToString = (value) => + function stringExpression(expr) { + return new BasicEvaluatedExpression() + .setString(value) + .setRange(/** @type {Range} */ (expr.range)); + }; + +/** + * @param {JavascriptParser} parser the parser + * @param {string} message the message + * @returns {(expression: Expression) => boolean | undefined} callback to handle unsupported expression + */ +module.exports.expressionIsUnsupported = (parser, message) => + function unsupportedExpression(expr) { + const dep = new ConstDependency( + "(void 0)", + /** @type {Range} */ (expr.range), + null + ); + dep.loc = /** @type {SourceLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + if (!parser.state.module) return; + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + message, + /** @type {SourceLocation} */ (expr.loc) + ) + ); + return true; + }; + +module.exports.skipTraversal = () => true; + +/** + * @param {JavascriptParser} parser the parser + * @param {string} value the const value + * @param {(string[] | null)=} runtimeRequirements runtime requirements + * @returns {(expression: Expression) => true} plugin function + */ +module.exports.toConstantDependency = (parser, value, runtimeRequirements) => + function constDependency(expr) { + const dep = new ConstDependency( + value, + /** @type {Range} */ + (expr.range), + runtimeRequirements + ); + dep.loc = /** @type {SourceLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + return true; + }; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/StartupHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/StartupHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..94f1adf299beca40e6b2c0b1f6263c0b6fc54eec --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/javascript/StartupHelpers.js @@ -0,0 +1,180 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const { isSubset } = require("../util/SetHelpers"); +const { getAllChunks } = require("./ChunkHelpers"); + +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Chunk").ChunkId} ChunkId */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../ChunkGraph").EntryModuleWithChunkGroup} EntryModuleWithChunkGroup */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {(string|number)[]} EntryItem */ + +const EXPORT_PREFIX = `var ${RuntimeGlobals.exports} = `; + +/** @typedef {Set} Chunks */ +/** @typedef {ModuleId[]} ModuleIds */ + +/** + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate + * @param {EntryModuleWithChunkGroup[]} entries entries + * @param {Chunk} chunk chunk + * @param {boolean} passive true: passive startup with on chunks loaded + * @returns {string} runtime code + */ +module.exports.generateEntryStartup = ( + chunkGraph, + runtimeTemplate, + entries, + chunk, + passive +) => { + /** @type {string[]} */ + const runtime = [ + `var __webpack_exec__ = ${runtimeTemplate.returningFunction( + `${RuntimeGlobals.require}(${RuntimeGlobals.entryModuleId} = moduleId)`, + "moduleId" + )}` + ]; + + /** + * @param {ModuleId} id id + * @returns {string} fn to execute + */ + const runModule = (id) => `__webpack_exec__(${JSON.stringify(id)})`; + /** + * @param {Chunks} chunks chunks + * @param {ModuleIds} moduleIds module ids + * @param {boolean=} final true when final, otherwise false + */ + const outputCombination = (chunks, moduleIds, final) => { + if (chunks.size === 0) { + runtime.push( + `${final ? EXPORT_PREFIX : ""}(${moduleIds.map(runModule).join(", ")});` + ); + } else { + const fn = runtimeTemplate.returningFunction( + moduleIds.map(runModule).join(", ") + ); + runtime.push( + `${final && !passive ? EXPORT_PREFIX : ""}${ + passive + ? RuntimeGlobals.onChunksLoaded + : RuntimeGlobals.startupEntrypoint + }(0, ${JSON.stringify(Array.from(chunks, (c) => c.id))}, ${fn});` + ); + if (final && passive) { + runtime.push(`${EXPORT_PREFIX}${RuntimeGlobals.onChunksLoaded}();`); + } + } + }; + + /** @type {Chunks | undefined} */ + let currentChunks; + /** @type {ModuleIds | undefined} */ + let currentModuleIds; + + for (const [module, entrypoint] of entries) { + if (!chunkGraph.getModuleSourceTypes(module).has("javascript")) { + continue; + } + const runtimeChunk = + /** @type {Entrypoint} */ + (entrypoint).getRuntimeChunk(); + const moduleId = /** @type {ModuleId} */ (chunkGraph.getModuleId(module)); + const chunks = getAllChunks( + /** @type {Entrypoint} */ + (entrypoint), + chunk, + runtimeChunk + ); + if ( + currentChunks && + currentChunks.size === chunks.size && + isSubset(currentChunks, chunks) + ) { + /** @type {ModuleIds} */ + (currentModuleIds).push(moduleId); + } else { + if (currentChunks) { + outputCombination( + currentChunks, + /** @type {ModuleIds} */ (currentModuleIds) + ); + } + currentChunks = chunks; + currentModuleIds = [moduleId]; + } + } + + // output current modules with export prefix + if (currentChunks) { + outputCombination( + currentChunks, + /** @type {ModuleIds} */ + (currentModuleIds), + true + ); + } + runtime.push(""); + return Template.asString(runtime); +}; + +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {(chunk: Chunk, chunkGraph: ChunkGraph) => boolean} filterFn filter function + * @returns {Set} initially fulfilled chunk ids + */ +module.exports.getInitialChunkIds = (chunk, chunkGraph, filterFn) => { + const initialChunkIds = new Set(chunk.ids); + for (const c of chunk.getAllInitialChunks()) { + if (c === chunk || filterFn(c, chunkGraph)) continue; + for (const id of /** @type {ChunkId[]} */ (c.ids)) { + initialChunkIds.add(id); + } + } + return initialChunkIds; +}; + +/** + * @param {Hash} hash the hash to update + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {EntryModuleWithChunkGroup[]} entries entries + * @param {Chunk} chunk chunk + * @returns {void} + */ +module.exports.updateHashForEntryStartup = ( + hash, + chunkGraph, + entries, + chunk +) => { + for (const [module, entrypoint] of entries) { + const runtimeChunk = + /** @type {Entrypoint} */ + (entrypoint).getRuntimeChunk(); + const moduleId = chunkGraph.getModuleId(module); + hash.update(`${moduleId}`); + for (const c of getAllChunks( + /** @type {Entrypoint} */ (entrypoint), + chunk, + /** @type {Chunk} */ (runtimeChunk) + )) { + hash.update(`${c.id}`); + } + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonData.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonData.js new file mode 100644 index 0000000000000000000000000000000000000000..c46bdeb6355cfcc4fb1511efdd3d205e44a2584a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonData.js @@ -0,0 +1,74 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { register } = require("../util/serialization"); + +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */ + +class JsonData { + /** + * @param {Buffer | JsonValue} data JSON data + */ + constructor(data) { + /** @type {Buffer | undefined} */ + this._buffer = undefined; + /** @type {JsonValue | undefined} */ + this._data = undefined; + if (Buffer.isBuffer(data)) { + this._buffer = data; + } else { + this._data = data; + } + } + + /** + * @returns {JsonValue | undefined} Raw JSON data + */ + get() { + if (this._data === undefined && this._buffer !== undefined) { + this._data = JSON.parse(this._buffer.toString()); + } + return this._data; + } + + /** + * @param {Hash} hash hash to be updated + * @returns {void} the updated hash + */ + updateHash(hash) { + if (this._buffer === undefined && this._data !== undefined) { + this._buffer = Buffer.from(JSON.stringify(this._data)); + } + + if (this._buffer) hash.update(this._buffer); + } +} + +register(JsonData, "webpack/lib/json/JsonData", null, { + /** + * @param {JsonData} obj JSONData object + * @param {ObjectSerializerContext} context context + */ + serialize(obj, { write }) { + if (obj._buffer === undefined && obj._data !== undefined) { + obj._buffer = Buffer.from(JSON.stringify(obj._data)); + } + write(obj._buffer); + }, + /** + * @param {ObjectDeserializerContext} context context + * @returns {JsonData} deserialized JSON data + */ + deserialize({ read }) { + return new JsonData(read()); + } +}); + +module.exports = JsonData; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonGenerator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..b53201928f718caa2b4eb46cffed7ec293924cc9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonGenerator.js @@ -0,0 +1,233 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const ConcatenationScope = require("../ConcatenationScope"); +const { UsageState } = require("../ExportsInfo"); +const Generator = require("../Generator"); +const { JS_TYPES } = require("../ModuleSourceTypesConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").JsonGeneratorOptions} JsonGeneratorOptions */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./JsonData")} JsonData */ +/** @typedef {import("./JsonModulesPlugin").JsonArray} JsonArray */ +/** @typedef {import("./JsonModulesPlugin").JsonObject} JsonObject */ +/** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */ + +/** + * @param {JsonValue} data Raw JSON data + * @returns {undefined|string} stringified data + */ +const stringifySafe = (data) => { + const stringified = JSON.stringify(data); + if (!stringified) { + return; // Invalid JSON + } + + return stringified.replace(/\u2028|\u2029/g, (str) => + str === "\u2029" ? "\\u2029" : "\\u2028" + ); // invalid in JavaScript but valid JSON +}; + +/** + * @param {JsonObject | JsonArray} data Raw JSON data (always an object or array) + * @param {ExportsInfo} exportsInfo exports info + * @param {RuntimeSpec} runtime the runtime + * @returns {JsonObject | JsonArray} reduced data + */ +const createObjectForExportsInfo = (data, exportsInfo, runtime) => { + if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + return data; + } + const isArray = Array.isArray(data); + /** @type {JsonObject | JsonArray} */ + const reducedData = isArray ? [] : {}; + for (const key of Object.keys(data)) { + const exportInfo = exportsInfo.getReadOnlyExportInfo(key); + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) continue; + + // The real type is `JsonObject | JsonArray`, but typescript doesn't work `Object.keys(['string', 'other-string', 'etc'])` properly + const newData = /** @type {JsonObject} */ (data)[key]; + const value = + used === UsageState.OnlyPropertiesUsed && + exportInfo.exportsInfo && + typeof newData === "object" && + newData + ? createObjectForExportsInfo(newData, exportInfo.exportsInfo, runtime) + : newData; + + const name = /** @type {string} */ (exportInfo.getUsedName(key, runtime)); + /** @type {JsonObject} */ + (reducedData)[name] = value; + } + if (isArray) { + const arrayLengthWhenUsed = + exportsInfo.getReadOnlyExportInfo("length").getUsed(runtime) !== + UsageState.Unused + ? data.length + : undefined; + + let sizeObjectMinusArray = 0; + const reducedDataLength = + /** @type {JsonArray} */ + (reducedData).length; + for (let i = 0; i < reducedDataLength; i++) { + if (/** @type {JsonArray} */ (reducedData)[i] === undefined) { + sizeObjectMinusArray -= 2; + } else { + sizeObjectMinusArray += `${i}`.length + 3; + } + } + if (arrayLengthWhenUsed !== undefined) { + sizeObjectMinusArray += + `${arrayLengthWhenUsed}`.length + + 8 - + (arrayLengthWhenUsed - reducedDataLength) * 2; + } + if (sizeObjectMinusArray < 0) { + return Object.assign( + arrayLengthWhenUsed === undefined + ? {} + : { length: arrayLengthWhenUsed }, + reducedData + ); + } + /** @type {number} */ + const generatedLength = + arrayLengthWhenUsed !== undefined + ? Math.max(arrayLengthWhenUsed, reducedDataLength) + : reducedDataLength; + for (let i = 0; i < generatedLength; i++) { + if (/** @type {JsonArray} */ (reducedData)[i] === undefined) { + /** @type {JsonArray} */ + (reducedData)[i] = 0; + } + } + } + return reducedData; +}; + +class JsonGenerator extends Generator { + /** + * @param {JsonGeneratorOptions} options options + */ + constructor(options) { + super(); + this.options = options; + } + + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + return JS_TYPES; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + /** @type {JsonValue | undefined} */ + const data = + module.buildInfo && + module.buildInfo.jsonData && + module.buildInfo.jsonData.get(); + if (!data) return 0; + return /** @type {string} */ (stringifySafe(data)).length + 10; + } + + /** + * @param {NormalModule} module module for which the bailout reason should be determined + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(module, context) { + return undefined; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate( + module, + { + moduleGraph, + runtimeTemplate, + runtimeRequirements, + runtime, + concatenationScope + } + ) { + /** @type {JsonValue | undefined} */ + const data = + module.buildInfo && + module.buildInfo.jsonData && + module.buildInfo.jsonData.get(); + if (data === undefined) { + return new RawSource( + runtimeTemplate.missingModuleStatement({ + request: module.rawRequest + }) + ); + } + const exportsInfo = moduleGraph.getExportsInfo(module); + /** @type {JsonValue} */ + const finalJson = + typeof data === "object" && + data && + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused + ? createObjectForExportsInfo(data, exportsInfo, runtime) + : data; + // Use JSON because JSON.parse() is much faster than JavaScript evaluation + const jsonStr = /** @type {string} */ (stringifySafe(finalJson)); + const jsonExpr = + this.options.JSONParse && + jsonStr.length > 20 && + typeof finalJson === "object" + ? `/*#__PURE__*/JSON.parse('${jsonStr.replace(/[\\']/g, "\\$&")}')` + : jsonStr.replace(/"__proto__":/g, '["__proto__"]:'); + /** @type {string} */ + let content; + if (concatenationScope) { + content = `${runtimeTemplate.supportsConst() ? "const" : "var"} ${ + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + } = ${jsonExpr};`; + concatenationScope.registerNamespaceExport( + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + ); + } else { + runtimeRequirements.add(RuntimeGlobals.module); + content = `${module.moduleArgument}.exports = ${jsonExpr};`; + } + return new RawSource(content); + } + + /** + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generateError(error, module, generateContext) { + return new RawSource(`throw new Error(${JSON.stringify(error.message)});`); + } +} + +module.exports = JsonGenerator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..df97ca7b32d523b95df38901909a302d68dcb465 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonModulesPlugin.js @@ -0,0 +1,69 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { JSON_MODULE_TYPE } = require("../ModuleTypeConstants"); +const createSchemaValidation = require("../util/create-schema-validation"); +const JsonGenerator = require("./JsonGenerator"); +const JsonParser = require("./JsonParser"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../util/fs").JsonArray} JsonArray */ +/** @typedef {import("../util/fs").JsonObject} JsonObject */ +/** @typedef {import("../util/fs").JsonValue} JsonValue */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/json/JsonModulesPluginParser.check"), + () => require("../../schemas/plugins/json/JsonModulesPluginParser.json"), + { + name: "Json Modules Plugin", + baseDataPath: "parser" + } +); + +const validateGenerator = createSchemaValidation( + require("../../schemas/plugins/json/JsonModulesPluginGenerator.check"), + () => require("../../schemas/plugins/json/JsonModulesPluginGenerator.json"), + { + name: "Json Modules Plugin", + baseDataPath: "generator" + } +); + +const PLUGIN_NAME = "JsonModulesPlugin"; + +/** + * The JsonModulesPlugin is the entrypoint plugin for the json modules feature. + * It adds the json module type to the compiler and registers the json parser and generator. + */ +class JsonModulesPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.createParser + .for(JSON_MODULE_TYPE) + .tap(PLUGIN_NAME, (parserOptions) => { + validate(parserOptions); + return new JsonParser(parserOptions); + }); + normalModuleFactory.hooks.createGenerator + .for(JSON_MODULE_TYPE) + .tap(PLUGIN_NAME, (generatorOptions) => { + validateGenerator(generatorOptions); + return new JsonGenerator(generatorOptions); + }); + } + ); + } +} + +module.exports = JsonModulesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonParser.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonParser.js new file mode 100644 index 0000000000000000000000000000000000000000..983ed2896bd5c5d1e5d5aa489874bf6d7468c4ab --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/json/JsonParser.js @@ -0,0 +1,77 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Parser = require("../Parser"); +const JsonExportsDependency = require("../dependencies/JsonExportsDependency"); +const memoize = require("../util/memoize"); +const JsonData = require("./JsonData"); + +/** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +/** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */ + +const getParseJson = memoize(() => require("json-parse-even-better-errors")); + +class JsonParser extends Parser { + /** + * @param {JsonModulesPluginParserOptions} options parser options + */ + constructor(options) { + super(); + this.options = options || {}; + } + + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (Buffer.isBuffer(source)) { + source = source.toString("utf8"); + } + + /** @type {NonNullable} */ + const parseFn = + typeof this.options.parse === "function" + ? this.options.parse + : getParseJson(); + /** @type {Buffer | JsonValue | undefined} */ + let data; + try { + data = + typeof source === "object" + ? source + : parseFn(source[0] === "\uFEFF" ? source.slice(1) : source); + } catch (err) { + throw new Error( + `Cannot parse JSON: ${/** @type {Error} */ (err).message}` + ); + } + const jsonData = new JsonData(/** @type {Buffer | JsonValue} */ (data)); + const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo); + buildInfo.jsonData = jsonData; + buildInfo.strict = true; + const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta); + buildMeta.exportsType = "default"; + buildMeta.defaultObject = + typeof data === "object" ? "redirect-warn" : false; + state.module.addDependency( + new JsonExportsDependency( + jsonData, + /** @type {number} */ + (this.options.exportsDepth) + ) + ); + return state; + } +} + +module.exports = JsonParser; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/AbstractLibraryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/AbstractLibraryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b6a0090684d85e95583b5eefc95387e1c76c4090 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/AbstractLibraryPlugin.js @@ -0,0 +1,336 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").ModuleRenderContext} ModuleRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ + +const COMMON_LIBRARY_NAME_MESSAGE = + "Common configuration options that specific library names are 'output.library[.name]', 'entry.xyz.library[.name]', 'ModuleFederationPlugin.name' and 'ModuleFederationPlugin.library[.name]'."; + +/** + * @template T + * @typedef {object} LibraryContext + * @property {Compilation} compilation + * @property {ChunkGraph} chunkGraph + * @property {T} options + */ + +/** + * @typedef {object} AbstractLibraryPluginOptions + * @property {string} pluginName name of the plugin + * @property {LibraryType} type used library type + */ + +/** + * @template T + */ +class AbstractLibraryPlugin { + /** + * @param {AbstractLibraryPluginOptions} options options + */ + constructor({ pluginName, type }) { + this._pluginName = pluginName; + this._type = type; + this._parseCache = new WeakMap(); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _pluginName } = this; + compiler.hooks.thisCompilation.tap(_pluginName, (compilation) => { + compilation.hooks.finishModules.tap( + { name: _pluginName, stage: 10 }, + () => { + for (const [ + name, + { + dependencies: deps, + options: { library } + } + ] of compilation.entries) { + const options = this._parseOptionsCached( + library !== undefined + ? library + : compilation.outputOptions.library + ); + if (options !== false) { + const dep = deps[deps.length - 1]; + if (dep) { + const module = compilation.moduleGraph.getModule(dep); + if (module) { + this.finishEntryModule(module, name, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + } + } + } + } + } + ); + + /** + * @param {Chunk} chunk chunk + * @returns {T | false} options for the chunk + */ + const getOptionsForChunk = (chunk) => { + if (compilation.chunkGraph.getNumberOfEntryModules(chunk) === 0) { + return false; + } + const options = chunk.getEntryOptions(); + const library = options && options.library; + return this._parseOptionsCached( + library !== undefined ? library : compilation.outputOptions.library + ); + }; + + if ( + this.render !== AbstractLibraryPlugin.prototype.render || + this.runtimeRequirements !== + AbstractLibraryPlugin.prototype.runtimeRequirements + ) { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + _pluginName, + (chunk, set, { chunkGraph }) => { + const options = getOptionsForChunk(chunk); + if (options !== false) { + this.runtimeRequirements(chunk, set, { + options, + compilation, + chunkGraph + }); + } + } + ); + } + + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + + if (this.render !== AbstractLibraryPlugin.prototype.render) { + hooks.render.tap(_pluginName, (source, renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return source; + return this.render(source, renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + }); + } + + if ( + this.embedInRuntimeBailout !== + AbstractLibraryPlugin.prototype.embedInRuntimeBailout + ) { + hooks.embedInRuntimeBailout.tap( + _pluginName, + (module, renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return; + return this.embedInRuntimeBailout(module, renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + } + ); + } + + if ( + this.strictRuntimeBailout !== + AbstractLibraryPlugin.prototype.strictRuntimeBailout + ) { + hooks.strictRuntimeBailout.tap(_pluginName, (renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return; + return this.strictRuntimeBailout(renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + }); + } + + if ( + this.renderModuleContent !== + AbstractLibraryPlugin.prototype.renderModuleContent + ) { + hooks.renderModuleContent.tap( + _pluginName, + (source, module, renderContext) => + this.renderModuleContent(source, module, renderContext, { + compilation, + chunkGraph: compilation.chunkGraph + }) + ); + } + + if ( + this.renderStartup !== AbstractLibraryPlugin.prototype.renderStartup + ) { + hooks.renderStartup.tap( + _pluginName, + (source, module, renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return source; + return this.renderStartup(source, module, renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + } + ); + } + + hooks.chunkHash.tap(_pluginName, (chunk, hash, context) => { + const options = getOptionsForChunk(chunk); + if (options === false) return; + this.chunkHash(chunk, hash, context, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + }); + }); + } + + /** + * @param {LibraryOptions=} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + _parseOptionsCached(library) { + if (!library) return false; + if (library.type !== this._type) return false; + const cacheEntry = this._parseCache.get(library); + if (cacheEntry !== undefined) return cacheEntry; + const result = this.parseOptions(library); + this._parseCache.set(library, result); + return result; + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const AbstractMethodError = require("../AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /** + * @param {Module} module the exporting entry module + * @param {string} entryName the name of the entrypoint + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + finishEntryModule(module, entryName, libraryContext) {} + + /** + * @param {Module} module the exporting entry module + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + embedInRuntimeBailout(module, renderContext, libraryContext) { + return undefined; + } + + /** + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + strictRuntimeBailout(renderContext, libraryContext) { + return undefined; + } + + /** + * @param {Chunk} chunk the chunk + * @param {Set} set runtime requirements + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + runtimeRequirements(chunk, set, libraryContext) { + if (this.render !== AbstractLibraryPlugin.prototype.render) { + set.add(RuntimeGlobals.returnExportsFromRuntime); + } + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, renderContext, libraryContext) { + return source; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup(source, module, renderContext, libraryContext) { + return source; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {ModuleRenderContext} renderContext render context + * @param {Omit, 'options'>} libraryContext context + * @returns {Source} source with library export + */ + renderModuleContent(source, module, renderContext, libraryContext) { + return source; + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, libraryContext) { + const options = this._parseOptionsCached( + libraryContext.compilation.outputOptions.library + ); + hash.update(this._pluginName); + hash.update(JSON.stringify(options)); + } +} + +AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE = COMMON_LIBRARY_NAME_MESSAGE; + +module.exports = AbstractLibraryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/AmdLibraryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/AmdLibraryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..e8afbfe8cc4e1333e35bcfef1651da72f8750773 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/AmdLibraryPlugin.js @@ -0,0 +1,178 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const ExternalModule = require("../ExternalModule"); +const Template = require("../Template"); +const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {object} AmdLibraryPluginOptions + * @property {LibraryType} type + * @property {boolean=} requireAsWrapper + */ + +/** + * @typedef {object} AmdLibraryPluginParsed + * @property {string} name + * @property {string} amdContainer + */ + +/** + * @typedef {AmdLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class AmdLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {AmdLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "AmdLibraryPlugin", + type: options.type + }); + this.requireAsWrapper = options.requireAsWrapper; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name, amdContainer } = library; + if (this.requireAsWrapper) { + if (name) { + throw new Error( + `AMD library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + } else if (name && typeof name !== "string") { + throw new Error( + `AMD library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + const _name = /** @type {string} */ (name); + const _amdContainer = /** @type {string} */ (amdContainer); + return { name: _name, amdContainer: _amdContainer }; + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render( + source, + { chunkGraph, chunk, runtimeTemplate }, + { options, compilation } + ) { + const modern = runtimeTemplate.supportsArrowFunction(); + const modules = chunkGraph + .getChunkModules(chunk) + .filter( + (m) => + m instanceof ExternalModule && + (m.externalType === "amd" || m.externalType === "amd-require") + ); + const externals = /** @type {ExternalModule[]} */ (modules); + const externalsDepsArray = JSON.stringify( + externals.map((m) => + typeof m.request === "object" && !Array.isArray(m.request) + ? m.request.amd + : m.request + ) + ); + const externalsArguments = externals + .map( + (m) => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${chunkGraph.getModuleId(m)}` + )}__` + ) + .join(", "); + + const iife = runtimeTemplate.isIIFE(); + const fnStart = + (modern + ? `(${externalsArguments}) => {` + : `function(${externalsArguments}) {`) + + (iife || !chunk.hasRuntime() ? " return " : "\n"); + const fnEnd = iife ? ";\n}" : "\n}"; + + let amdContainerPrefix = ""; + if (options.amdContainer) { + amdContainerPrefix = `${options.amdContainer}.`; + } + + if (this.requireAsWrapper) { + return new ConcatSource( + `${amdContainerPrefix}require(${externalsDepsArray}, ${fnStart}`, + source, + `${fnEnd});` + ); + } else if (options.name) { + const name = compilation.getPath(options.name, { + chunk + }); + + return new ConcatSource( + `${amdContainerPrefix}define(${JSON.stringify( + name + )}, ${externalsDepsArray}, ${fnStart}`, + source, + `${fnEnd});` + ); + } else if (externalsArguments) { + return new ConcatSource( + `${amdContainerPrefix}define(${externalsDepsArray}, ${fnStart}`, + source, + `${fnEnd});` + ); + } + return new ConcatSource( + `${amdContainerPrefix}define(${fnStart}`, + source, + `${fnEnd});` + ); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("AmdLibraryPlugin"); + if (this.requireAsWrapper) { + hash.update("requireAsWrapper"); + } else if (options.name) { + hash.update("named"); + const name = compilation.getPath(options.name, { + chunk + }); + hash.update(name); + } else if (options.amdContainer) { + hash.update("amdContainer"); + hash.update(options.amdContainer); + } + } +} + +module.exports = AmdLibraryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/AssignLibraryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/AssignLibraryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..afe8557842468097305252cd254d02420bdb9b9e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/AssignLibraryPlugin.js @@ -0,0 +1,430 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const { UsageState } = require("../ExportsInfo"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const propertyAccess = require("../util/propertyAccess"); +const { getEntryRuntime } = require("../util/runtime"); +const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +const KEYWORD_REGEX = + /^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/; +const IDENTIFIER_REGEX = + /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu; + +/** + * Validates the library name by checking for keywords and valid characters + * @param {string} name name to be validated + * @returns {boolean} true, when valid + */ +const isNameValid = (name) => + !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name); + +/** + * @param {string[]} accessor variable plus properties + * @param {number} existingLength items of accessor that are existing already + * @param {boolean=} initLast if the last property should also be initialized to an object + * @returns {string} code to access the accessor while initializing + */ +const accessWithInit = (accessor, existingLength, initLast = false) => { + // This generates for [a, b, c, d]: + // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d + const base = accessor[0]; + if (accessor.length === 1 && !initLast) return base; + let current = + existingLength > 0 + ? base + : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`; + + // i is the current position in accessor that has been printed + let i = 1; + + // all properties printed so far (excluding base) + /** @type {string[] | undefined} */ + let propsSoFar; + + // if there is existingLength, print all properties until this position as property access + if (existingLength > i) { + propsSoFar = accessor.slice(1, existingLength); + i = existingLength; + current += propertyAccess(propsSoFar); + } else { + propsSoFar = []; + } + + // all remaining properties (except the last one when initLast is not set) + // should be printed as initializer + const initUntil = initLast ? accessor.length : accessor.length - 1; + for (; i < initUntil; i++) { + const prop = accessor[i]; + propsSoFar.push(prop); + current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess( + propsSoFar + )} || {})`; + } + + // print the last property as property access if not yet printed + if (i < accessor.length) { + current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`; + } + + return current; +}; + +/** + * @typedef {object} AssignLibraryPluginOptions + * @property {LibraryType} type + * @property {string[] | "global"} prefix name prefix + * @property {string | false} declare declare name as variable + * @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name + * @property {"copy"|"assign"=} named behavior for named library name + */ + +/** + * @typedef {object} AssignLibraryPluginParsed + * @property {string | string[]} name + * @property {string | string[] | undefined} export + */ + +/** + * @typedef {AssignLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class AssignLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {AssignLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "AssignLibraryPlugin", + type: options.type + }); + this.prefix = options.prefix; + this.declare = options.declare; + this.unnamed = options.unnamed; + this.named = options.named || "assign"; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (this.unnamed === "error") { + if (typeof name !== "string" && !Array.isArray(name)) { + throw new Error( + `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + } else if (name && typeof name !== "string" && !Array.isArray(name)) { + throw new Error( + `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + const _name = /** @type {string | string[]} */ (name); + return { + name: _name, + export: library.export + }; + } + + /** + * @param {Module} module the exporting entry module + * @param {string} entryName the name of the entrypoint + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + finishEntryModule( + module, + entryName, + { options, compilation, compilation: { moduleGraph } } + ) { + const runtime = getEntryRuntime(compilation, entryName); + if (options.export) { + const exportsInfo = moduleGraph.getExportInfo( + module, + Array.isArray(options.export) ? options.export[0] : options.export + ); + exportsInfo.setUsed(UsageState.Used, runtime); + exportsInfo.canMangleUse = false; + } else { + const exportsInfo = moduleGraph.getExportsInfo(module); + exportsInfo.setUsedInUnknownWay(runtime); + } + moduleGraph.addExtraReason(module, "used as library export"); + } + + /** + * @param {Compilation} compilation the compilation + * @returns {string[]} the prefix + */ + _getPrefix(compilation) { + return this.prefix === "global" + ? [compilation.runtimeTemplate.globalObject] + : this.prefix; + } + + /** + * @param {AssignLibraryPluginParsed} options the library options + * @param {Chunk} chunk the chunk + * @param {Compilation} compilation the compilation + * @returns {Array} the resolved full name + */ + _getResolvedFullName(options, chunk, compilation) { + const prefix = this._getPrefix(compilation); + const fullName = options.name + ? [ + ...prefix, + ...(Array.isArray(options.name) ? options.name : [options.name]) + ] + : prefix; + return fullName.map((n) => + compilation.getPath(n, { + chunk + }) + ); + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, { chunk }, { options, compilation }) { + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + if (this.declare) { + const base = fullNameResolved[0]; + if (!isNameValid(base)) { + throw new Error( + `Library name base (${base}) must be a valid identifier when using a var declaring library type. Either use a valid identifier (e. g. ${Template.toIdentifier( + base + )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${ + AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE + }` + ); + } + source = new ConcatSource(`${this.declare} ${base};\n`, source); + } + return source; + } + + /** + * @param {Module} module the exporting entry module + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + embedInRuntimeBailout( + module, + { chunk, codeGenerationResults }, + { options, compilation } + ) { + const { data } = codeGenerationResults.get(module, chunk.runtime); + const topLevelDeclarations = + (data && data.get("topLevelDeclarations")) || + (module.buildInfo && module.buildInfo.topLevelDeclarations); + if (!topLevelDeclarations) { + return "it doesn't tell about top level declarations."; + } + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + const base = fullNameResolved[0]; + if (topLevelDeclarations.has(base)) { + return `it declares '${base}' on top-level, which conflicts with the current library output.`; + } + } + + /** + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + strictRuntimeBailout({ chunk }, { options, compilation }) { + if ( + this.declare || + this.prefix === "global" || + this.prefix.length > 0 || + !options.name + ) { + return; + } + return "a global variable is assign and maybe created"; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup( + source, + module, + { moduleGraph, chunk }, + { options, compilation } + ) { + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + const staticExports = this.unnamed === "static"; + const exportAccess = options.export + ? propertyAccess( + Array.isArray(options.export) ? options.export : [options.export] + ) + : ""; + const result = new ConcatSource(source); + if (staticExports) { + const exportsInfo = moduleGraph.getExportsInfo(module); + const exportTarget = accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + true + ); + + /** @type {string[]} */ + const provided = []; + for (const exportInfo of exportsInfo.orderedExports) { + if (!exportInfo.provided) continue; + const nameAccess = propertyAccess([exportInfo.name]); + result.add( + `${exportTarget}${nameAccess} = ${RuntimeGlobals.exports}${exportAccess}${nameAccess};\n` + ); + provided.push(exportInfo.name); + } + + const webpackExportTarget = accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + true + ); + /** @type {string} */ + let exports = RuntimeGlobals.exports; + if (exportAccess) { + result.add( + `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n` + ); + + exports = "__webpack_exports_export__"; + } + result.add(`for(var __webpack_i__ in ${exports}) {\n`); + const hasProvided = provided.length > 0; + if (hasProvided) { + result.add( + ` if (${JSON.stringify(provided)}.indexOf(__webpack_i__) === -1) {\n` + ); + } + result.add( + ` ${ + hasProvided ? " " : "" + }${webpackExportTarget}[__webpack_i__] = ${exports}[__webpack_i__];\n` + ); + if (hasProvided) { + result.add(" }\n"); + } + result.add("}\n"); + result.add( + `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n` + ); + } else if (options.name ? this.named === "copy" : this.unnamed === "copy") { + result.add( + `var __webpack_export_target__ = ${accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + true + )};\n` + ); + /** @type {string} */ + let exports = RuntimeGlobals.exports; + if (exportAccess) { + result.add( + `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n` + ); + + exports = "__webpack_exports_export__"; + } + result.add( + `for(var __webpack_i__ in ${exports}) __webpack_export_target__[__webpack_i__] = ${exports}[__webpack_i__];\n` + ); + result.add( + `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n` + ); + } else { + result.add( + `${accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + false + )} = ${RuntimeGlobals.exports}${exportAccess};\n` + ); + } + return result; + } + + /** + * @param {Chunk} chunk the chunk + * @param {Set} set runtime requirements + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + runtimeRequirements(chunk, set, libraryContext) { + set.add(RuntimeGlobals.exports); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("AssignLibraryPlugin"); + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + if (options.name ? this.named === "copy" : this.unnamed === "copy") { + hash.update("copy"); + } + if (this.declare) { + hash.update(this.declare); + } + hash.update(fullNameResolved.join(".")); + if (options.export) { + hash.update(`${options.export}`); + } + } +} + +module.exports = AssignLibraryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/EnableLibraryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/EnableLibraryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..a21d6a5ae47cd8dd5352cb5d872fa52d42c03b04 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/EnableLibraryPlugin.js @@ -0,0 +1,309 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Compiler")} Compiler */ + +/** @type {WeakMap>} */ +const enabledTypes = new WeakMap(); + +/** + * @typedef {object} EnableLibraryPluginOptions + * @property {() => void=} additionalApply function that runs when applying the current plugin. + */ + +/** + * @param {Compiler} compiler the compiler instance + * @returns {Set} enabled types + */ +const getEnabledTypes = (compiler) => { + let set = enabledTypes.get(compiler); + if (set === undefined) { + set = new Set(); + enabledTypes.set(compiler, set); + } + return set; +}; + +class EnableLibraryPlugin { + /** + * @param {LibraryType} type library type that should be available + * @param {EnableLibraryPluginOptions} options options of EnableLibraryPlugin + */ + constructor(type, options = {}) { + /** @type {LibraryType} */ + this.type = type; + /** @type {EnableLibraryPluginOptions} */ + this.options = options; + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {LibraryType} type type of library + * @returns {void} + */ + static setEnabled(compiler, type) { + getEnabledTypes(compiler).add(type); + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {LibraryType} type type of library + * @returns {void} + */ + static checkEnabled(compiler, type) { + if (!getEnabledTypes(compiler).has(type)) { + throw new Error( + `Library type "${type}" is not enabled. ` + + "EnableLibraryPlugin need to be used to enable this type of library. " + + 'This usually happens through the "output.enabledLibraryTypes" option. ' + + 'If you are using a function as entry which sets "library", you need to add all potential library types to "output.enabledLibraryTypes". ' + + `These types are enabled: ${[...getEnabledTypes(compiler)].join(", ")}` + ); + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { type, options } = this; + + // Only enable once + const enabled = getEnabledTypes(compiler); + if (enabled.has(type)) return; + enabled.add(type); + + if (typeof options.additionalApply === "function") { + options.additionalApply(); + } + + if (typeof type === "string") { + const enableExportProperty = () => { + const ExportPropertyTemplatePlugin = require("./ExportPropertyLibraryPlugin"); + + new ExportPropertyTemplatePlugin({ + type, + nsObjectUsed: !["module", "modern-module"].includes(type), + runtimeExportsUsed: !["module", "modern-module"].includes(type), + renderStartupUsed: !["module", "modern-module"].includes(type) + }).apply(compiler); + }; + switch (type) { + case "var": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: [], + declare: "var", + unnamed: "error" + }).apply(compiler); + break; + } + case "assign-properties": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: [], + declare: false, + unnamed: "error", + named: "copy" + }).apply(compiler); + break; + } + case "assign": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: [], + declare: false, + unnamed: "error" + }).apply(compiler); + break; + } + case "this": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: ["this"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "window": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: ["window"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "self": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: ["self"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "global": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: "global", + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "commonjs": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: ["exports"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "commonjs-static": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: ["exports"], + declare: false, + unnamed: "static" + }).apply(compiler); + break; + } + case "commonjs2": + case "commonjs-module": { + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = require("./AssignLibraryPlugin"); + + new AssignLibraryPlugin({ + type, + prefix: ["module", "exports"], + declare: false, + unnamed: "assign" + }).apply(compiler); + break; + } + case "amd": + case "amd-require": { + enableExportProperty(); + + const AmdLibraryPlugin = require("./AmdLibraryPlugin"); + + new AmdLibraryPlugin({ + type, + requireAsWrapper: type === "amd-require" + }).apply(compiler); + break; + } + case "umd": + case "umd2": { + if (compiler.options.output.iife === false) { + compiler.options.output.iife = true; + + class WarnFalseIifeUmdPlugin { + /** + * @param {Compiler} compiler the compiler instance + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "WarnFalseIifeUmdPlugin", + (compilation) => { + const FalseIIFEUmdWarning = require("../FalseIIFEUmdWarning"); + + compilation.warnings.push(new FalseIIFEUmdWarning()); + } + ); + } + } + + new WarnFalseIifeUmdPlugin().apply(compiler); + } + enableExportProperty(); + + const UmdLibraryPlugin = require("./UmdLibraryPlugin"); + + new UmdLibraryPlugin({ + type, + optionalAmdExternalAsGlobal: type === "umd2" + }).apply(compiler); + break; + } + case "system": { + enableExportProperty(); + + const SystemLibraryPlugin = require("./SystemLibraryPlugin"); + + new SystemLibraryPlugin({ + type + }).apply(compiler); + break; + } + case "jsonp": { + enableExportProperty(); + + const JsonpLibraryPlugin = require("./JsonpLibraryPlugin"); + + new JsonpLibraryPlugin({ + type + }).apply(compiler); + break; + } + case "module": + case "modern-module": { + enableExportProperty(); + + const ModuleLibraryPlugin = require("./ModuleLibraryPlugin"); + + new ModuleLibraryPlugin({ + type + }).apply(compiler); + break; + } + default: + throw new Error(`Unsupported library type ${type}. +Plugins which provide custom library types must call EnableLibraryPlugin.setEnabled(compiler, type) to disable this error.`); + } + } else { + // TODO support plugin instances here + // apply them to the compiler + } + } +} + +module.exports = EnableLibraryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/ExportPropertyLibraryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/ExportPropertyLibraryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..8825bc0896760caceffa5fedae6e1e261b73c8f7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/ExportPropertyLibraryPlugin.js @@ -0,0 +1,125 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const { UsageState } = require("../ExportsInfo"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const propertyAccess = require("../util/propertyAccess"); +const { getEntryRuntime } = require("../util/runtime"); +const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {object} ExportPropertyLibraryPluginParsed + * @property {string | string[]} export + */ + +/** + * @typedef {object} ExportPropertyLibraryPluginOptions + * @property {LibraryType} type + * @property {boolean} nsObjectUsed the namespace object is used + * @property {boolean} runtimeExportsUsed runtime exports are used + * @property {boolean} renderStartupUsed render startup is used + */ +/** + * @typedef {ExportPropertyLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {ExportPropertyLibraryPluginOptions} options options + */ + constructor({ type, nsObjectUsed, runtimeExportsUsed, renderStartupUsed }) { + super({ + pluginName: "ExportPropertyLibraryPlugin", + type + }); + this.nsObjectUsed = nsObjectUsed; + this.runtimeExportsUsed = runtimeExportsUsed; + this.renderStartupUsed = renderStartupUsed; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + return { + export: /** @type {string | string[]} */ (library.export) + }; + } + + /** + * @param {Module} module the exporting entry module + * @param {string} entryName the name of the entrypoint + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + finishEntryModule( + module, + entryName, + { options, compilation, compilation: { moduleGraph } } + ) { + const runtime = getEntryRuntime(compilation, entryName); + if (options.export) { + const exportsInfo = moduleGraph.getExportInfo( + module, + Array.isArray(options.export) ? options.export[0] : options.export + ); + exportsInfo.setUsed(UsageState.Used, runtime); + exportsInfo.canMangleUse = false; + } else { + const exportsInfo = moduleGraph.getExportsInfo(module); + if (this.nsObjectUsed) { + exportsInfo.setUsedInUnknownWay(runtime); + } else { + exportsInfo.setAllKnownExportsUsed(runtime); + } + } + moduleGraph.addExtraReason(module, "used as library export"); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Set} set runtime requirements + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + runtimeRequirements(chunk, set, libraryContext) { + if (this.runtimeExportsUsed) { + set.add(RuntimeGlobals.exports); + } + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup(source, module, renderContext, { options }) { + if (!this.renderStartupUsed) return source; + if (!options.export) return source; + const postfix = `${RuntimeGlobals.exports} = ${ + RuntimeGlobals.exports + }${propertyAccess( + Array.isArray(options.export) ? options.export : [options.export] + )};\n`; + return new ConcatSource(source, postfix); + } +} + +module.exports = ExportPropertyLibraryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/JsonpLibraryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/JsonpLibraryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9757874232de5ba4527378b6e739700f02507b22 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/JsonpLibraryPlugin.js @@ -0,0 +1,89 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {object} JsonpLibraryPluginOptions + * @property {LibraryType} type + */ + +/** + * @typedef {object} JsonpLibraryPluginParsed + * @property {string} name + */ + +/** + * @typedef {JsonpLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class JsonpLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {JsonpLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "JsonpLibraryPlugin", + type: options.type + }); + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (typeof name !== "string") { + throw new Error( + `Jsonp library name must be a simple string. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + const _name = /** @type {string} */ (name); + return { + name: _name + }; + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, { chunk }, { options, compilation }) { + const name = compilation.getPath(options.name, { + chunk + }); + return new ConcatSource(`${name}(`, source, ")"); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("JsonpLibraryPlugin"); + hash.update(compilation.getPath(options.name, { chunk })); + } +} + +module.exports = JsonpLibraryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/ModuleLibraryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/ModuleLibraryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..01e5de7a57807f28729c3a474b2919f92bb23064 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/ModuleLibraryPlugin.js @@ -0,0 +1,258 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const CommonJsSelfReferenceDependency = require("../dependencies/CommonJsSelfReferenceDependency"); +const ConcatenatedModule = require("../optimize/ConcatenatedModule"); +const propertyAccess = require("../util/propertyAccess"); +const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").ModuleRenderContext} ModuleRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ + +/** + * @template T + * @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext + */ + +/** + * @typedef {object} ModuleLibraryPluginOptions + * @property {LibraryType} type + */ + +/** + * @typedef {object} ModuleLibraryPluginParsed + * @property {string} name + * @property {string | string[]=} export + */ + +const PLUGIN_NAME = "ModuleLibraryPlugin"; + +/** + * @typedef {ModuleLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class ModuleLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {ModuleLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "ModuleLibraryPlugin", + type: options.type + }); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + super.apply(compiler); + + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const { onDemandExportsGeneration } = + ConcatenatedModule.getCompilationHooks(compilation); + onDemandExportsGeneration.tap(PLUGIN_NAME, (_module) => true); + }); + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (name) { + throw new Error( + `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + const _name = /** @type {string} */ (name); + return { + name: _name, + export: library.export + }; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup( + source, + module, + { moduleGraph, chunk, codeGenerationResults, inlined, inlinedInIIFE }, + { options, compilation } + ) { + const result = new ConcatSource(source); + + if (!module.buildMeta || !module.buildMeta.exportsType) { + for (const dependency of module.dependencies) { + if (dependency instanceof CommonJsSelfReferenceDependency) { + result.add(`export { ${RuntimeGlobals.exports} as default }`); + break; + } + } + return result; + } + + const exportsInfo = options.export + ? [ + moduleGraph.getExportInfo( + module, + Array.isArray(options.export) ? options.export[0] : options.export + ) + ] + : moduleGraph.getExportsInfo(module).orderedExports; + const definitions = + inlined && !inlinedInIIFE + ? (module.buildMeta && + /** @type {GenerationMeta} */ module.buildMeta.exportsFinalName) || + {} + : {}; + /** @type {string[]} */ + const shortHandedExports = []; + /** @type {[string, string][]} */ + const exports = []; + const isAsync = moduleGraph.isAsync(module); + + if (isAsync) { + result.add( + `${RuntimeGlobals.exports} = await ${RuntimeGlobals.exports};\n` + ); + } + + const varType = compilation.outputOptions.environment.const + ? "const" + : "var"; + + for (const exportInfo of exportsInfo) { + if (!exportInfo.provided) continue; + + let shouldContinue = false; + + const reexport = exportInfo.findTarget(moduleGraph, (_m) => true); + + if (reexport) { + const exp = moduleGraph.getExportsInfo(reexport.module); + + for (const reexportInfo of exp.orderedExports) { + if ( + reexportInfo.provided === false && + reexportInfo.name !== "default" && + reexportInfo.name === /** @type {string[]} */ (reexport.export)[0] + ) { + shouldContinue = true; + } + } + } + + if (shouldContinue) continue; + + const originalName = exportInfo.name; + const usedName = + /** @type {string} */ + (exportInfo.getUsedName(originalName, chunk.runtime)); + /** @type {string | undefined} */ + const definition = definitions[usedName]; + const finalName = + definition || + `${RuntimeGlobals.exports}${Template.toIdentifier(originalName)}`; + + if (!definition) { + result.add( + `${varType} ${finalName} = ${RuntimeGlobals.exports}${propertyAccess([ + usedName + ])};\n` + ); + } + + if ( + finalName && + (finalName.includes(".") || + finalName.includes("[") || + finalName.includes("(")) + ) { + if (exportInfo.isReexport()) { + const { data } = codeGenerationResults.get(module, chunk.runtime); + const topLevelDeclarations = + (data && data.get("topLevelDeclarations")) || + (module.buildInfo && module.buildInfo.topLevelDeclarations); + + if (topLevelDeclarations && topLevelDeclarations.has(originalName)) { + const name = `${RuntimeGlobals.exports}${Template.toIdentifier(originalName)}`; + result.add(`${varType} ${name} = ${finalName};\n`); + shortHandedExports.push(`${name} as ${originalName}`); + } else { + exports.push([originalName, finalName]); + } + } else { + exports.push([originalName, finalName]); + } + } else { + shortHandedExports.push( + definition && finalName === originalName + ? finalName + : `${finalName} as ${originalName}` + ); + } + } + + if (shortHandedExports.length > 0) { + result.add(`export { ${shortHandedExports.join(", ")} };\n`); + } + + for (const [exportName, final] of exports) { + result.add(`export ${varType} ${exportName} = ${final};\n`); + } + + return result; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {ModuleRenderContext} renderContext render context + * @param {Omit, 'options'>} libraryContext context + * @returns {Source} source with library export + */ + renderModuleContent( + source, + module, + { factory, inlinedInIIFE }, + libraryContext + ) { + // Re-add `factoryExportsBinding` to the source + // when the module is rendered as a factory or treated as an inlined (startup) module but wrapped in an IIFE + if ( + (inlinedInIIFE || factory) && + module.buildMeta && + module.buildMeta.factoryExportsBinding + ) { + return new ConcatSource(module.buildMeta.factoryExportsBinding, source); + } + return source; + } +} + +module.exports = ModuleLibraryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/SystemLibraryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/SystemLibraryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7f06287c25b05bd92261b8612871c79fc5c2ce5c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/SystemLibraryPlugin.js @@ -0,0 +1,237 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Joel Denning @joeldenning +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const { UsageState } = require("../ExportsInfo"); +const ExternalModule = require("../ExternalModule"); +const Template = require("../Template"); +const propertyAccess = require("../util/propertyAccess"); +const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {object} SystemLibraryPluginOptions + * @property {LibraryType} type + */ + +/** + * @typedef {object} SystemLibraryPluginParsed + * @property {string} name + */ + +/** + * @typedef {SystemLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class SystemLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {SystemLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "SystemLibraryPlugin", + type: options.type + }); + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (name && typeof name !== "string") { + throw new Error( + `System.js library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + const _name = /** @type {string} */ (name); + return { + name: _name + }; + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, { chunkGraph, moduleGraph, chunk }, { options, compilation }) { + const modules = chunkGraph + .getChunkModules(chunk) + .filter( + (m) => m instanceof ExternalModule && m.externalType === "system" + ); + const externals = /** @type {ExternalModule[]} */ (modules); + + // The name this bundle should be registered as with System + const name = options.name + ? `${JSON.stringify(compilation.getPath(options.name, { chunk }))}, ` + : ""; + + // The array of dependencies that are external to webpack and will be provided by System + const systemDependencies = JSON.stringify( + externals.map((m) => + typeof m.request === "object" && !Array.isArray(m.request) + ? m.request.amd + : m.request + ) + ); + + // The name of the variable provided by System for exporting + const dynamicExport = "__WEBPACK_DYNAMIC_EXPORT__"; + + // An array of the internal variable names for the webpack externals + const externalWebpackNames = externals.map( + (m) => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${chunkGraph.getModuleId(m)}` + )}__` + ); + + // Declaring variables for the internal variable names for the webpack externals + const externalVarDeclarations = externalWebpackNames + .map((name) => `var ${name} = {};`) + .join("\n"); + + // Define __esModule flag on all internal variables and helpers + /** @type {string[]} */ + const externalVarInitialization = []; + + // The system.register format requires an array of setter functions for externals. + const setters = + externalWebpackNames.length === 0 + ? "" + : Template.asString([ + "setters: [", + Template.indent( + externals + .map((module, i) => { + const external = externalWebpackNames[i]; + const exportsInfo = moduleGraph.getExportsInfo(module); + const otherUnused = + exportsInfo.otherExportsInfo.getUsed(chunk.runtime) === + UsageState.Unused; + const instructions = []; + const handledNames = []; + for (const exportInfo of exportsInfo.orderedExports) { + const used = exportInfo.getUsedName( + undefined, + chunk.runtime + ); + if (used) { + if (otherUnused || used !== exportInfo.name) { + instructions.push( + `${external}${propertyAccess([ + used + ])} = module${propertyAccess([exportInfo.name])};` + ); + handledNames.push(exportInfo.name); + } + } else { + handledNames.push(exportInfo.name); + } + } + if (!otherUnused) { + if ( + !Array.isArray(module.request) || + module.request.length === 1 + ) { + externalVarInitialization.push( + `Object.defineProperty(${external}, "__esModule", { value: true });` + ); + } + if (handledNames.length > 0) { + const name = `${external}handledNames`; + externalVarInitialization.push( + `var ${name} = ${JSON.stringify(handledNames)};` + ); + instructions.push( + Template.asString([ + "Object.keys(module).forEach(function(key) {", + Template.indent([ + `if(${name}.indexOf(key) >= 0)`, + Template.indent(`${external}[key] = module[key];`) + ]), + "});" + ]) + ); + } else { + instructions.push( + Template.asString([ + "Object.keys(module).forEach(function(key) {", + Template.indent([`${external}[key] = module[key];`]), + "});" + ]) + ); + } + } + if (instructions.length === 0) return "function() {}"; + return Template.asString([ + "function(module) {", + Template.indent(instructions), + "}" + ]); + }) + .join(",\n") + ), + "]," + ]); + + return new ConcatSource( + Template.asString([ + `System.register(${name}${systemDependencies}, function(${dynamicExport}, __system_context__) {`, + Template.indent([ + externalVarDeclarations, + Template.asString(externalVarInitialization), + "return {", + Template.indent([ + setters, + "execute: function() {", + Template.indent(`${dynamicExport}(`) + ]) + ]), + "" + ]), + source, + Template.asString([ + "", + Template.indent([ + Template.indent([Template.indent([");"]), "}"]), + "};" + ]), + "})" + ]) + ); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("SystemLibraryPlugin"); + if (options.name) { + hash.update(compilation.getPath(options.name, { chunk })); + } + } +} + +module.exports = SystemLibraryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/UmdLibraryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/UmdLibraryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..2d33f0f165d97ba6d8c4e32f17c668b3d97fb1eb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/library/UmdLibraryPlugin.js @@ -0,0 +1,360 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource, OriginalSource } = require("webpack-sources"); +const ExternalModule = require("../ExternalModule"); +const Template = require("../Template"); +const AbstractLibraryPlugin = require("./AbstractLibraryPlugin"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdCommentObject} LibraryCustomUmdCommentObject */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../ExternalModule").RequestRecord} RequestRecord */ +/** @typedef {import("../util/Hash")} Hash */ +/** + * @template T + * @typedef {import("./AbstractLibraryPlugin").LibraryContext} + * LibraryContext + */ + +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = (accessor) => + accessor.map((a) => `[${JSON.stringify(a)}]`).join(""); + +/** + * @param {string|undefined} base the path prefix + * @param {string|string[]} accessor the accessor + * @param {string=} joinWith the element separator + * @returns {string} the path + */ +const accessorAccess = (base, accessor, joinWith = ", ") => { + const accessors = Array.isArray(accessor) ? accessor : [accessor]; + return accessors + .map((_, idx) => { + const a = base + ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) + : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); + if (idx === accessors.length - 1) return a; + if (idx === 0 && base === undefined) { + return `${a} = typeof ${a} === "object" ? ${a} : {}`; + } + return `${a} = ${a} || {}`; + }) + .join(joinWith); +}; + +/** @typedef {string | string[] | LibraryCustomUmdObject} UmdLibraryPluginName */ + +/** + * @typedef {object} UmdLibraryPluginOptions + * @property {LibraryType} type + * @property {boolean=} optionalAmdExternalAsGlobal + */ + +/** + * @typedef {object} UmdLibraryPluginParsed + * @property {string | string[] | undefined} name + * @property {LibraryCustomUmdObject} names + * @property {string | LibraryCustomUmdCommentObject | undefined} auxiliaryComment + * @property {boolean | undefined} namedDefine + */ + +/** + * @typedef {UmdLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class UmdLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {UmdLibraryPluginOptions} options the plugin option + */ + constructor(options) { + super({ + pluginName: "UmdLibraryPlugin", + type: options.type + }); + + this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + /** @type {LibraryName | undefined} */ + let name; + /** @type {LibraryCustomUmdObject} */ + let names; + if (typeof library.name === "object" && !Array.isArray(library.name)) { + name = library.name.root || library.name.amd || library.name.commonjs; + names = library.name; + } else { + name = library.name; + const singleName = Array.isArray(name) ? name[0] : name; + names = { + commonjs: singleName, + root: library.name, + amd: singleName + }; + } + return { + name, + names, + auxiliaryComment: library.auxiliaryComment, + namedDefine: library.umdNamedDefine + }; + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render( + source, + { chunkGraph, runtimeTemplate, chunk, moduleGraph }, + { options, compilation } + ) { + const modules = chunkGraph + .getChunkModules(chunk) + .filter( + (m) => + m instanceof ExternalModule && + (m.externalType === "umd" || m.externalType === "umd2") + ); + let externals = /** @type {ExternalModule[]} */ (modules); + /** @type {ExternalModule[]} */ + const optionalExternals = []; + /** @type {ExternalModule[]} */ + let requiredExternals = []; + if (this.optionalAmdExternalAsGlobal) { + for (const m of externals) { + if (m.isOptional(moduleGraph)) { + optionalExternals.push(m); + } else { + requiredExternals.push(m); + } + } + externals = [...requiredExternals, ...optionalExternals]; + } else { + requiredExternals = externals; + } + + /** + * @param {string} str the string to replace + * @returns {string} the replaced keys + */ + const replaceKeys = (str) => + compilation.getPath(str, { + chunk + }); + + /** + * @param {ExternalModule[]} modules external modules + * @returns {string} result + */ + const externalsDepsArray = (modules) => + `[${replaceKeys( + modules + .map((m) => + JSON.stringify( + typeof m.request === "object" + ? /** @type {RequestRecord} */ + (m.request).amd + : m.request + ) + ) + .join(", ") + )}]`; + + /** + * @param {ExternalModule[]} modules external modules + * @returns {string} result + */ + const externalsRootArray = (modules) => + replaceKeys( + modules + .map((m) => { + let request = m.request; + if (typeof request === "object") { + request = + /** @type {RequestRecord} */ + (request).root; + } + return `root${accessorToObjectAccess( + /** @type {string[]} */ + ([...(Array.isArray(request) ? request : [request])]) + )}`; + }) + .join(", ") + ); + + /** + * @param {string} type the type + * @returns {string} external require array + */ + const externalsRequireArray = (type) => + replaceKeys( + externals + .map((m) => { + let expr; + let request = m.request; + if (typeof request === "object") { + request = + /** @type {RequestRecord} */ + (request)[type]; + } + if (request === undefined) { + throw new Error( + `Missing external configuration for type:${type}` + ); + } + expr = Array.isArray(request) + ? `require(${JSON.stringify( + request[0] + )})${accessorToObjectAccess(request.slice(1))}` + : `require(${JSON.stringify(request)})`; + if (m.isOptional(moduleGraph)) { + expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; + } + return expr; + }) + .join(", ") + ); + + /** + * @param {ExternalModule[]} modules external modules + * @returns {string} arguments + */ + const externalsArguments = (modules) => + modules + .map( + (m) => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${chunkGraph.getModuleId(m)}` + )}__` + ) + .join(", "); + + /** + * @param {string| string[]} library library name + * @returns {string} stringified library name + */ + const libraryName = (library) => + JSON.stringify( + replaceKeys( + /** @type {string} */ + ( + /** @type {string[]} */ + ([...(Array.isArray(library) ? library : [library])]).pop() + ) + ) + ); + + let amdFactory; + if (optionalExternals.length > 0) { + const wrapperArguments = externalsArguments(requiredExternals); + const factoryArguments = + requiredExternals.length > 0 + ? `${externalsArguments(requiredExternals)}, ${externalsRootArray( + optionalExternals + )}` + : externalsRootArray(optionalExternals); + amdFactory = + `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + + ` return factory(${factoryArguments});\n` + + " }"; + } else { + amdFactory = "factory"; + } + + const { auxiliaryComment, namedDefine, names } = options; + + /** + * @param {keyof LibraryCustomUmdCommentObject} type type + * @returns {string} comment + */ + const getAuxiliaryComment = (type) => { + if (auxiliaryComment) { + if (typeof auxiliaryComment === "string") { + return `\t//${auxiliaryComment}\n`; + } + if (auxiliaryComment[type]) return `\t//${auxiliaryComment[type]}\n`; + } + return ""; + }; + + return new ConcatSource( + new OriginalSource( + `(function webpackUniversalModuleDefinition(root, factory) {\n${getAuxiliaryComment( + "commonjs2" + )} if(typeof exports === 'object' && typeof module === 'object')\n` + + ` module.exports = factory(${externalsRequireArray( + "commonjs2" + )});\n${getAuxiliaryComment( + "amd" + )} else if(typeof define === 'function' && define.amd)\n${ + requiredExternals.length > 0 + ? names.amd && namedDefine === true + ? ` define(${libraryName(names.amd)}, ${externalsDepsArray( + requiredExternals + )}, ${amdFactory});\n` + : ` define(${externalsDepsArray(requiredExternals)}, ${ + amdFactory + });\n` + : names.amd && namedDefine === true + ? ` define(${libraryName(names.amd)}, [], ${amdFactory});\n` + : ` define([], ${amdFactory});\n` + }${ + names.root || names.commonjs + ? `${getAuxiliaryComment( + "commonjs" + )} else if(typeof exports === 'object')\n` + + ` exports[${libraryName( + /** @type {string | string[]} */ + (names.commonjs || names.root) + )}] = factory(${externalsRequireArray( + "commonjs" + )});\n${getAuxiliaryComment("root")} else\n` + + ` ${replaceKeys( + accessorAccess( + "root", + /** @type {string | string[]} */ + (names.root || names.commonjs) + ) + )} = factory(${externalsRootArray(externals)});\n` + : ` else {\n${ + externals.length > 0 + ? ` var a = typeof exports === 'object' ? factory(${externalsRequireArray( + "commonjs" + )}) : factory(${externalsRootArray(externals)});\n` + : " var a = factory();\n" + } for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n` + + " }\n" + }})(${runtimeTemplate.outputOptions.globalObject}, ${ + runtimeTemplate.supportsArrowFunction() + ? `(${externalsArguments(externals)}) =>` + : `function(${externalsArguments(externals)})` + } {\nreturn `, + "webpack/universalModuleDefinition" + ), + source, + ";\n})" + ); + } +} + +module.exports = UmdLibraryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/Logger.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/Logger.js new file mode 100644 index 0000000000000000000000000000000000000000..d785e0c0008f108647c2fa32b72e898bf501ea58 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/Logger.js @@ -0,0 +1,216 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const LogType = Object.freeze({ + error: /** @type {"error"} */ ("error"), // message, c style arguments + warn: /** @type {"warn"} */ ("warn"), // message, c style arguments + info: /** @type {"info"} */ ("info"), // message, c style arguments + log: /** @type {"log"} */ ("log"), // message, c style arguments + debug: /** @type {"debug"} */ ("debug"), // message, c style arguments + + trace: /** @type {"trace"} */ ("trace"), // no arguments + + group: /** @type {"group"} */ ("group"), // [label] + groupCollapsed: /** @type {"groupCollapsed"} */ ("groupCollapsed"), // [label] + groupEnd: /** @type {"groupEnd"} */ ("groupEnd"), // [label] + + profile: /** @type {"profile"} */ ("profile"), // [profileName] + profileEnd: /** @type {"profileEnd"} */ ("profileEnd"), // [profileName] + + time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds] + + clear: /** @type {"clear"} */ ("clear"), // no arguments + status: /** @type {"status"} */ ("status") // message, arguments +}); + +module.exports.LogType = LogType; + +/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */ + +const LOG_SYMBOL = Symbol("webpack logger raw log method"); +const TIMERS_SYMBOL = Symbol("webpack logger times"); +const TIMERS_AGGREGATES_SYMBOL = Symbol("webpack logger aggregated times"); + +class WebpackLogger { + /** + * @param {(type: LogTypeEnum, args?: EXPECTED_ANY[]) => void} log log function + * @param {(name: string | (() => string)) => WebpackLogger} getChildLogger function to create child logger + */ + constructor(log, getChildLogger) { + this[LOG_SYMBOL] = log; + this.getChildLogger = getChildLogger; + } + + /** + * @param {...EXPECTED_ANY} args args + */ + error(...args) { + this[LOG_SYMBOL](LogType.error, args); + } + + /** + * @param {...EXPECTED_ANY} args args + */ + warn(...args) { + this[LOG_SYMBOL](LogType.warn, args); + } + + /** + * @param {...EXPECTED_ANY} args args + */ + info(...args) { + this[LOG_SYMBOL](LogType.info, args); + } + + /** + * @param {...EXPECTED_ANY} args args + */ + log(...args) { + this[LOG_SYMBOL](LogType.log, args); + } + + /** + * @param {...EXPECTED_ANY} args args + */ + debug(...args) { + this[LOG_SYMBOL](LogType.debug, args); + } + + /** + * @param {EXPECTED_ANY} assertion assertion + * @param {...EXPECTED_ANY} args args + */ + assert(assertion, ...args) { + if (!assertion) { + this[LOG_SYMBOL](LogType.error, args); + } + } + + trace() { + this[LOG_SYMBOL](LogType.trace, ["Trace"]); + } + + clear() { + this[LOG_SYMBOL](LogType.clear); + } + + /** + * @param {...EXPECTED_ANY} args args + */ + status(...args) { + this[LOG_SYMBOL](LogType.status, args); + } + + /** + * @param {...EXPECTED_ANY} args args + */ + group(...args) { + this[LOG_SYMBOL](LogType.group, args); + } + + /** + * @param {...EXPECTED_ANY} args args + */ + groupCollapsed(...args) { + this[LOG_SYMBOL](LogType.groupCollapsed, args); + } + + groupEnd() { + this[LOG_SYMBOL](LogType.groupEnd); + } + + /** + * @param {string=} label label + */ + profile(label) { + this[LOG_SYMBOL](LogType.profile, [label]); + } + + /** + * @param {string=} label label + */ + profileEnd(label) { + this[LOG_SYMBOL](LogType.profileEnd, [label]); + } + + /** + * @param {string} label label + */ + time(label) { + /** @type {Map} */ + this[TIMERS_SYMBOL] = this[TIMERS_SYMBOL] || new Map(); + this[TIMERS_SYMBOL].set(label, process.hrtime()); + } + + /** + * @param {string=} label label + */ + timeLog(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error(`No such label '${label}' for WebpackLogger.timeLog()`); + } + const time = process.hrtime(prev); + this[LOG_SYMBOL](LogType.time, [label, ...time]); + } + + /** + * @param {string=} label label + */ + timeEnd(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error(`No such label '${label}' for WebpackLogger.timeEnd()`); + } + const time = process.hrtime(prev); + /** @type {Map} */ + (this[TIMERS_SYMBOL]).delete(label); + this[LOG_SYMBOL](LogType.time, [label, ...time]); + } + + /** + * @param {string=} label label + */ + timeAggregate(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error( + `No such label '${label}' for WebpackLogger.timeAggregate()` + ); + } + const time = process.hrtime(prev); + /** @type {Map} */ + (this[TIMERS_SYMBOL]).delete(label); + /** @type {Map} */ + this[TIMERS_AGGREGATES_SYMBOL] = + this[TIMERS_AGGREGATES_SYMBOL] || new Map(); + const current = this[TIMERS_AGGREGATES_SYMBOL].get(label); + if (current !== undefined) { + if (time[1] + current[1] > 1e9) { + time[0] += current[0] + 1; + time[1] = time[1] - 1e9 + current[1]; + } else { + time[0] += current[0]; + time[1] += current[1]; + } + } + this[TIMERS_AGGREGATES_SYMBOL].set(label, time); + } + + /** + * @param {string=} label label + */ + timeAggregateEnd(label) { + if (this[TIMERS_AGGREGATES_SYMBOL] === undefined) return; + const time = this[TIMERS_AGGREGATES_SYMBOL].get(label); + if (time === undefined) return; + this[TIMERS_AGGREGATES_SYMBOL].delete(label); + this[LOG_SYMBOL](LogType.time, [label, ...time]); + } +} + +module.exports.Logger = WebpackLogger; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/createConsoleLogger.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/createConsoleLogger.js new file mode 100644 index 0000000000000000000000000000000000000000..072ce19aed894cf1ebae17f6453d341a8a7d287d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/createConsoleLogger.js @@ -0,0 +1,212 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { LogType } = require("./Logger"); + +/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ +/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ +/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ + +/** @typedef {(item: string) => boolean} FilterFunction */ +/** @typedef {(value: string, type: LogTypeEnum, args?: EXPECTED_ANY[]) => void} LoggingFunction */ + +/** + * @typedef {object} LoggerConsole + * @property {() => void} clear + * @property {() => void} trace + * @property {(...args: EXPECTED_ANY[]) => void} info + * @property {(...args: EXPECTED_ANY[]) => void} log + * @property {(...args: EXPECTED_ANY[]) => void} warn + * @property {(...args: EXPECTED_ANY[]) => void} error + * @property {(...args: EXPECTED_ANY[]) => void=} debug + * @property {(...args: EXPECTED_ANY[]) => void=} group + * @property {(...args: EXPECTED_ANY[]) => void=} groupCollapsed + * @property {(...args: EXPECTED_ANY[]) => void=} groupEnd + * @property {(...args: EXPECTED_ANY[]) => void=} status + * @property {(...args: EXPECTED_ANY[]) => void=} profile + * @property {(...args: EXPECTED_ANY[]) => void=} profileEnd + * @property {(...args: EXPECTED_ANY[]) => void=} logTime + */ + +/** + * @typedef {object} LoggerOptions + * @property {false|true|"none"|"error"|"warn"|"info"|"log"|"verbose"} level loglevel + * @property {FilterTypes|boolean} debug filter for debug logging + * @property {LoggerConsole} console the console to log to + */ + +/** + * @param {FilterItemTypes} item an input item + * @returns {FilterFunction | undefined} filter function + */ +const filterToFunction = (item) => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace(/[-[\]{}()*+?.\\^$|]/g, "\\$&")}([\\\\/]|$|!|\\?)` + ); + return (ident) => regExp.test(ident); + } + if (item && typeof item === "object" && typeof item.test === "function") { + return (ident) => item.test(ident); + } + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; + } +}; + +/** + * @enum {number} + */ +const LogLevel = { + none: 6, + false: 6, + error: 5, + warn: 4, + info: 3, + log: 2, + true: 2, + verbose: 1 +}; + +/** + * @param {LoggerOptions} options options object + * @returns {LoggingFunction} logging function + */ +module.exports = ({ level = "info", debug = false, console }) => { + const debugFilters = + /** @type {FilterFunction[]} */ + ( + typeof debug === "boolean" + ? [() => debug] + : /** @type {FilterItemTypes[]} */ ([ + ...(Array.isArray(debug) ? debug : [debug]) + ]).map(filterToFunction) + ); + const loglevel = LogLevel[`${level}`] || 0; + + /** + * @param {string} name name of the logger + * @param {LogTypeEnum} type type of the log entry + * @param {EXPECTED_ANY[]=} args arguments of the log entry + * @returns {void} + */ + const logger = (name, type, args) => { + const labeledArgs = () => { + if (Array.isArray(args)) { + if (args.length > 0 && typeof args[0] === "string") { + return [`[${name}] ${args[0]}`, ...args.slice(1)]; + } + return [`[${name}]`, ...args]; + } + return []; + }; + const debug = debugFilters.some((f) => f(name)); + switch (type) { + case LogType.debug: + if (!debug) return; + if (typeof console.debug === "function") { + console.debug(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + case LogType.log: + if (!debug && loglevel > LogLevel.log) return; + console.log(...labeledArgs()); + break; + case LogType.info: + if (!debug && loglevel > LogLevel.info) return; + console.info(...labeledArgs()); + break; + case LogType.warn: + if (!debug && loglevel > LogLevel.warn) return; + console.warn(...labeledArgs()); + break; + case LogType.error: + if (!debug && loglevel > LogLevel.error) return; + console.error(...labeledArgs()); + break; + case LogType.trace: + if (!debug) return; + console.trace(); + break; + case LogType.groupCollapsed: + if (!debug && loglevel > LogLevel.log) return; + if (!debug && loglevel > LogLevel.verbose) { + if (typeof console.groupCollapsed === "function") { + console.groupCollapsed(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + } + // falls through + case LogType.group: + if (!debug && loglevel > LogLevel.log) return; + if (typeof console.group === "function") { + console.group(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + case LogType.groupEnd: + if (!debug && loglevel > LogLevel.log) return; + if (typeof console.groupEnd === "function") { + console.groupEnd(); + } + break; + case LogType.time: { + if (!debug && loglevel > LogLevel.log) return; + const [label, start, end] = + /** @type {[string, number, number]} */ + (args); + const ms = start * 1000 + end / 1000000; + const msg = `[${name}] ${label}: ${ms} ms`; + if (typeof console.logTime === "function") { + console.logTime(msg); + } else { + console.log(msg); + } + break; + } + case LogType.profile: + if (typeof console.profile === "function") { + console.profile(...labeledArgs()); + } + break; + case LogType.profileEnd: + if (typeof console.profileEnd === "function") { + console.profileEnd(...labeledArgs()); + } + break; + case LogType.clear: + if (!debug && loglevel > LogLevel.log) return; + if (typeof console.clear === "function") { + console.clear(); + } + break; + case LogType.status: + if (!debug && loglevel > LogLevel.info) return; + if (typeof console.status === "function") { + if (!args || args.length === 0) { + console.status(); + } else { + console.status(...labeledArgs()); + } + } else if (args && args.length !== 0) { + console.info(...labeledArgs()); + } + break; + default: + throw new Error(`Unexpected LogType ${type}`); + } + }; + return logger; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/runtime.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..a153064d66b42c7f2d894dbfa3b302afdfb74a43 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/runtime.js @@ -0,0 +1,45 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { SyncBailHook } = require("tapable"); +const { Logger } = require("./Logger"); +const createConsoleLogger = require("./createConsoleLogger"); + +/** @type {createConsoleLogger.LoggerOptions} */ +const currentDefaultLoggerOptions = { + level: "info", + debug: false, + console +}; +let currentDefaultLogger = createConsoleLogger(currentDefaultLoggerOptions); + +/** + * @param {createConsoleLogger.LoggerOptions} options new options, merge with old options + * @returns {void} + */ +module.exports.configureDefaultLogger = (options) => { + Object.assign(currentDefaultLoggerOptions, options); + currentDefaultLogger = createConsoleLogger(currentDefaultLoggerOptions); +}; + +/** + * @param {string} name name of the logger + * @returns {Logger} a logger + */ +module.exports.getLogger = (name) => + new Logger( + (type, args) => { + if (module.exports.hooks.log.call(name, type, args) === undefined) { + currentDefaultLogger(name, type, args); + } + }, + (childName) => module.exports.getLogger(`${name}/${childName}`) + ); + +module.exports.hooks = { + log: new SyncBailHook(["origin", "type", "args"]) +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/truncateArgs.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/truncateArgs.js new file mode 100644 index 0000000000000000000000000000000000000000..800f8d85b455ce3ba7eaf7db175e3946970dc2fe --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/logging/truncateArgs.js @@ -0,0 +1,83 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @param {Array} array array of numbers + * @returns {number} sum of all numbers in array + */ +const arraySum = (array) => { + let sum = 0; + for (const item of array) sum += item; + return sum; +}; + +/** + * @param {EXPECTED_ANY[]} args items to be truncated + * @param {number} maxLength maximum length of args including spaces between + * @returns {string[]} truncated args + */ +const truncateArgs = (args, maxLength) => { + const lengths = args.map((a) => `${a}`.length); + const availableLength = maxLength - lengths.length + 1; + + if (availableLength > 0 && args.length === 1) { + if (availableLength >= args[0].length) { + return args; + } else if (availableLength > 3) { + return [`...${args[0].slice(-availableLength + 3)}`]; + } + return [args[0].slice(-availableLength)]; + } + + // Check if there is space for at least 4 chars per arg + if (availableLength < arraySum(lengths.map((i) => Math.min(i, 6)))) { + // remove args + if (args.length > 1) return truncateArgs(args.slice(0, -1), maxLength); + return []; + } + + let currentLength = arraySum(lengths); + + // Check if all fits into maxLength + if (currentLength <= availableLength) return args; + + // Try to remove chars from the longest items until it fits + while (currentLength > availableLength) { + const maxLength = Math.max(...lengths); + const shorterItems = lengths.filter((l) => l !== maxLength); + const nextToMaxLength = + shorterItems.length > 0 ? Math.max(...shorterItems) : 0; + const maxReduce = maxLength - nextToMaxLength; + let maxItems = lengths.length - shorterItems.length; + let overrun = currentLength - availableLength; + for (let i = 0; i < lengths.length; i++) { + if (lengths[i] === maxLength) { + const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce); + lengths[i] -= reduce; + currentLength -= reduce; + overrun -= reduce; + maxItems--; + } + } + } + + // Return args reduced to length in lengths + return args.map((a, i) => { + const str = `${a}`; + const length = lengths[i]; + if (str.length === length) { + return str; + } else if (length > 5) { + return `...${str.slice(-length + 3)}`; + } else if (length > 0) { + return str.slice(-length); + } + return ""; + }); +}; + +module.exports = truncateArgs; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/CommonJsChunkLoadingPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/CommonJsChunkLoadingPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f039772d9e0d50cc3290695deaf5ef9a296d8029 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/CommonJsChunkLoadingPlugin.js @@ -0,0 +1,117 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const StartupChunkDependenciesPlugin = require("../runtime/StartupChunkDependenciesPlugin"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {object} CommonJsChunkLoadingPluginOptions + * @property {boolean=} asyncChunkLoading enable async chunk loading + */ + +const PLUGIN_NAME = "CommonJsChunkLoadingPlugin"; + +class CommonJsChunkLoadingPlugin { + /** + * @param {CommonJsChunkLoadingPluginOptions=} options options + */ + constructor(options = {}) { + this._asyncChunkLoading = options.asyncChunkLoading; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const ChunkLoadingRuntimeModule = this._asyncChunkLoading + ? require("./ReadFileChunkLoadingRuntimeModule") + : require("./RequireChunkLoadingRuntimeModule"); + const chunkLoadingValue = this._asyncChunkLoading + ? "async-node" + : "require"; + new StartupChunkDependenciesPlugin({ + chunkLoading: chunkLoadingValue, + asyncChunkLoading: this._asyncChunkLoading + }).apply(compiler); + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + /** + * @param {Chunk} chunk chunk + * @returns {boolean} true, if wasm loading is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === chunkLoadingValue; + }; + const onceForChunkSet = new WeakSet(); + /** + * @param {Chunk} chunk chunk + * @param {Set} set runtime requirements + */ + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule(chunk, new ChunkLoadingRuntimeModule(set)); + }; + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.externalInstallChunk) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap(PLUGIN_NAME, handler); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getChunkScriptFilename); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getUpdateManifestFilename); + }); + }); + } +} + +module.exports = CommonJsChunkLoadingPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeEnvironmentPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeEnvironmentPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..96e90debf3342844145a2a09854e30f13cec5bfc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeEnvironmentPlugin.js @@ -0,0 +1,72 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const CachedInputFileSystem = require("enhanced-resolve").CachedInputFileSystem; +const fs = require("graceful-fs"); +const createConsoleLogger = require("../logging/createConsoleLogger"); +const NodeWatchFileSystem = require("./NodeWatchFileSystem"); +const nodeConsole = require("./nodeConsole"); + +/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + +/** + * @typedef {object} NodeEnvironmentPluginOptions + * @property {InfrastructureLogging} infrastructureLogging infrastructure logging options + */ + +const PLUGIN_NAME = "NodeEnvironmentPlugin"; + +class NodeEnvironmentPlugin { + /** + * @param {NodeEnvironmentPluginOptions} options options + */ + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { infrastructureLogging } = this.options; + compiler.infrastructureLogger = createConsoleLogger({ + level: infrastructureLogging.level || "info", + debug: infrastructureLogging.debug || false, + console: + infrastructureLogging.console || + nodeConsole({ + colors: infrastructureLogging.colors, + appendOnly: infrastructureLogging.appendOnly, + stream: + /** @type {NodeJS.WritableStream} */ + (infrastructureLogging.stream) + }) + }); + compiler.inputFileSystem = new CachedInputFileSystem(fs, 60000); + const inputFileSystem = + /** @type {InputFileSystem} */ + (compiler.inputFileSystem); + compiler.outputFileSystem = fs; + compiler.intermediateFileSystem = fs; + compiler.watchFileSystem = new NodeWatchFileSystem(inputFileSystem); + compiler.hooks.beforeRun.tap(PLUGIN_NAME, (compiler) => { + if ( + compiler.inputFileSystem === inputFileSystem && + inputFileSystem.purge + ) { + compiler.fsStartTime = Date.now(); + inputFileSystem.purge(); + } + }); + } +} + +module.exports = NodeEnvironmentPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeSourcePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeSourcePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..fca1fc9caafcdae95f56738f227bac32a8d43856 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeSourcePlugin.js @@ -0,0 +1,19 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../Compiler")} Compiler */ + +class NodeSourcePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) {} +} + +module.exports = NodeSourcePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeTargetPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeTargetPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..1cc01810daa99cae394c4a54498e4c9bb96a7876 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeTargetPlugin.js @@ -0,0 +1,85 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ExternalsPlugin = require("../ExternalsPlugin"); + +/** @typedef {import("../Compiler")} Compiler */ + +const builtins = [ + "assert", + "assert/strict", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "diagnostics_channel", + "dns", + "dns/promises", + "domain", + "events", + "fs", + "fs/promises", + "http", + "http2", + "https", + "inspector", + "inspector/promises", + "module", + "net", + "os", + "path", + "path/posix", + "path/win32", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "readline/promises", + "repl", + "stream", + "stream/consumers", + "stream/promises", + "stream/web", + "string_decoder", + "sys", + "timers", + "timers/promises", + "tls", + "trace_events", + "tty", + "url", + "util", + "util/types", + "v8", + "vm", + "wasi", + "worker_threads", + "zlib", + /^node:/, + + // cspell:word pnpapi + // Yarn PnP adds pnpapi as "builtin" + "pnpapi" +]; + +class NodeTargetPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + new ExternalsPlugin("node-commonjs", builtins).apply(compiler); + } +} + +module.exports = NodeTargetPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeTemplatePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeTemplatePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..03877443abc9a767a70e13912cb8386670d357e3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeTemplatePlugin.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const CommonJsChunkFormatPlugin = require("../javascript/CommonJsChunkFormatPlugin"); +const EnableChunkLoadingPlugin = require("../javascript/EnableChunkLoadingPlugin"); + +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {object} NodeTemplatePluginOptions + * @property {boolean=} asyncChunkLoading enable async chunk loading + */ + +class NodeTemplatePlugin { + /** + * @param {NodeTemplatePluginOptions=} options options object + */ + constructor(options = {}) { + this._options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const chunkLoading = this._options.asyncChunkLoading + ? "async-node" + : "require"; + compiler.options.output.chunkLoading = chunkLoading; + new CommonJsChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin(chunkLoading).apply(compiler); + } +} + +module.exports = NodeTemplatePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeWatchFileSystem.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeWatchFileSystem.js new file mode 100644 index 0000000000000000000000000000000000000000..091864a2b94b5c0713df6148fa2211a68aa9dbc8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/NodeWatchFileSystem.js @@ -0,0 +1,192 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const Watchpack = require("watchpack"); + +/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("../util/fs").WatchMethod} WatchMethod */ + +class NodeWatchFileSystem { + /** + * @param {InputFileSystem} inputFileSystem input filesystem + */ + constructor(inputFileSystem) { + this.inputFileSystem = inputFileSystem; + this.watcherOptions = { + aggregateTimeout: 0 + }; + /** @type {Watchpack | null} */ + this.watcher = new Watchpack(this.watcherOptions); + } + + /** @type {WatchMethod} */ + watch( + files, + directories, + missing, + startTime, + options, + callback, + callbackUndelayed + ) { + if (!files || typeof files[Symbol.iterator] !== "function") { + throw new Error("Invalid arguments: 'files'"); + } + if (!directories || typeof directories[Symbol.iterator] !== "function") { + throw new Error("Invalid arguments: 'directories'"); + } + if (!missing || typeof missing[Symbol.iterator] !== "function") { + throw new Error("Invalid arguments: 'missing'"); + } + if (typeof callback !== "function") { + throw new Error("Invalid arguments: 'callback'"); + } + if (typeof startTime !== "number" && startTime) { + throw new Error("Invalid arguments: 'startTime'"); + } + if (typeof options !== "object") { + throw new Error("Invalid arguments: 'options'"); + } + if (typeof callbackUndelayed !== "function" && callbackUndelayed) { + throw new Error("Invalid arguments: 'callbackUndelayed'"); + } + const oldWatcher = this.watcher; + this.watcher = new Watchpack(options); + + if (callbackUndelayed) { + this.watcher.once("change", callbackUndelayed); + } + + const fetchTimeInfo = () => { + const fileTimeInfoEntries = new Map(); + const contextTimeInfoEntries = new Map(); + if (this.watcher) { + this.watcher.collectTimeInfoEntries( + fileTimeInfoEntries, + contextTimeInfoEntries + ); + } + return { fileTimeInfoEntries, contextTimeInfoEntries }; + }; + this.watcher.once( + "aggregated", + /** + * @param {Set} changes changes + * @param {Set} removals removals + */ + (changes, removals) => { + // pause emitting events (avoids clearing aggregated changes and removals on timeout) + /** @type {Watchpack} */ + (this.watcher).pause(); + + const fs = this.inputFileSystem; + if (fs && fs.purge) { + for (const item of changes) { + fs.purge(item); + } + for (const item of removals) { + fs.purge(item); + } + } + const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); + callback( + null, + fileTimeInfoEntries, + contextTimeInfoEntries, + changes, + removals + ); + } + ); + + this.watcher.watch({ files, directories, missing, startTime }); + + if (oldWatcher) { + oldWatcher.close(); + } + return { + close: () => { + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + }, + pause: () => { + if (this.watcher) { + this.watcher.pause(); + } + }, + getAggregatedRemovals: util.deprecate( + () => { + const items = this.watcher && this.watcher.aggregatedRemovals; + const fs = this.inputFileSystem; + if (items && fs && fs.purge) { + for (const item of items) { + fs.purge(item); + } + } + return items; + }, + "Watcher.getAggregatedRemovals is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_GET_AGGREGATED_REMOVALS" + ), + getAggregatedChanges: util.deprecate( + () => { + const items = this.watcher && this.watcher.aggregatedChanges; + const fs = this.inputFileSystem; + if (items && fs && fs.purge) { + for (const item of items) { + fs.purge(item); + } + } + return items; + }, + "Watcher.getAggregatedChanges is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_GET_AGGREGATED_CHANGES" + ), + getFileTimeInfoEntries: util.deprecate( + () => fetchTimeInfo().fileTimeInfoEntries, + "Watcher.getFileTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_FILE_TIME_INFO_ENTRIES" + ), + getContextTimeInfoEntries: util.deprecate( + () => fetchTimeInfo().contextTimeInfoEntries, + "Watcher.getContextTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_CONTEXT_TIME_INFO_ENTRIES" + ), + getInfo: () => { + const removals = this.watcher && this.watcher.aggregatedRemovals; + const changes = this.watcher && this.watcher.aggregatedChanges; + const fs = this.inputFileSystem; + if (fs && fs.purge) { + if (removals) { + for (const item of removals) { + fs.purge(item); + } + } + if (changes) { + for (const item of changes) { + fs.purge(item); + } + } + } + const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); + return { + changes, + removals, + fileTimeInfoEntries, + contextTimeInfoEntries + }; + } + }; + } +} + +module.exports = NodeWatchFileSystem; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/ReadFileChunkLoadingRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/ReadFileChunkLoadingRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..dcf763d67fffb5e9a1780781b58d84598cdb4167 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/ReadFileChunkLoadingRuntimeModule.js @@ -0,0 +1,285 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const { + generateJavascriptHMR +} = require("../hmr/JavascriptHotModuleReplacementHelper"); +const { + chunkHasJs, + getChunkFilenameTemplate +} = require("../javascript/JavascriptModulesPlugin"); +const { getInitialChunkIds } = require("../javascript/StartupHelpers"); +const compileBooleanMatcher = require("../util/compileBooleanMatcher"); +const { getUndoPath } = require("../util/identifier"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ + +class ReadFileChunkLoadingRuntimeModule extends RuntimeModule { + /** + * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super("readFile chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @private + * @param {Chunk} chunk chunk + * @param {string} rootOutputDir root output directory + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @returns {string} generated code + */ + _generateBaseUri(chunk, rootOutputDir, runtimeTemplate) { + const options = chunk.getEntryOptions(); + if (options && options.baseUri) { + return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`; + } + + return `${RuntimeGlobals.baseURI} = require(${runtimeTemplate.renderNodePrefixForCoreModule("url")}).pathToFileURL(${ + rootOutputDir + ? `__dirname + ${JSON.stringify(`/${rootOutputDir}`)}` + : "__filename" + });`; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const { runtimeTemplate } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); + const withExternalInstallChunk = this.runtimeRequirements.has( + RuntimeGlobals.externalInstallChunk + ); + const withOnChunkLoad = this.runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withLoading = this.runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withHmr = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const outputName = compilation.getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + /** @type {string} */ (compilation.outputOptions.path), + false + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_readFileVm` + : undefined; + + return Template.asString([ + withBaseURI + ? this._generateBaseUri(chunk, rootOutputDir, runtimeTemplate) + : "// no baseURI", + "", + "// object to store loaded chunks", + '// "0" means "already loaded", Promise means loading', + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), + "};", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.readFileVm = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId] === 0", + "chunkId" + )};` + : "// no on chunks loaded", + "", + withLoading || withExternalInstallChunk + ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ + "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ]), + "}" + ]), + "}", + `if(runtime) runtime(${RuntimeGlobals.require});`, + "for(var i = 0; i < chunkIds.length; i++) {", + Template.indent([ + "if(installedChunks[chunkIds[i]]) {", + Template.indent(["installedChunks[chunkIds[i]][0]();"]), + "}", + "installedChunks[chunkIds[i]] = 0;" + ]), + "}", + withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" + ])};` + : "// no chunk install function needed", + "", + withLoading + ? Template.asString([ + "// ReadFile + VM.run chunk loading for javascript", + `${fn}.readFileVm = function(chunkId, promises) {`, + hasJsMatcher !== false + ? Template.indent([ + "", + "var installedChunkData = installedChunks[chunkId];", + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + '// array of [resolve, reject, promise] means "currently loading"', + "if(installedChunkData) {", + Template.indent(["promises.push(installedChunkData[2]);"]), + "} else {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + "// load the chunk and return promise to it", + "var promise = new Promise(function(resolve, reject) {", + Template.indent([ + "installedChunkData = installedChunks[chunkId] = [resolve, reject];", + `var filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify( + rootOutputDir + )} + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId));`, + `require(${runtimeTemplate.renderNodePrefixForCoreModule("fs")}).readFile(filename, 'utf-8', function(err, content) {`, + Template.indent([ + "if(err) return reject(err);", + "var chunk = {};", + `require(${runtimeTemplate.renderNodePrefixForCoreModule("vm")}).runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)` + + `(chunk, require, require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).dirname(filename), filename);`, + "installChunk(chunk);" + ]), + "});" + ]), + "});", + "promises.push(installedChunkData[2] = promise);" + ]), + hasJsMatcher === true + ? "}" + : "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ]) + : Template.indent(["installedChunks[chunkId] = 0;"]), + "};" + ]) + : "// no chunk loading", + "", + withExternalInstallChunk + ? Template.asString([ + `module.exports = ${RuntimeGlobals.require};`, + `${RuntimeGlobals.externalInstallChunk} = installChunk;` + ]) + : "// no external install chunk", + "", + withHmr + ? Template.asString([ + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + "return new Promise(function(resolve, reject) {", + Template.indent([ + `var filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify( + rootOutputDir + )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`, + `require(${runtimeTemplate.renderNodePrefixForCoreModule("fs")}).readFile(filename, 'utf-8', function(err, content) {`, + Template.indent([ + "if(err) return reject(err);", + "var update = {};", + `require(${runtimeTemplate.renderNodePrefixForCoreModule("vm")}).runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)` + + `(update, require, require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).dirname(filename), filename);`, + "var updatedModules = update.modules;", + "var runtime = update.runtime;", + "for(var moduleId in updatedModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, + Template.indent([ + "currentUpdate[moduleId] = updatedModules[moduleId];", + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);", + "resolve();" + ]), + "});" + ]), + "});" + ]), + "}", + "", + generateJavascriptHMR("readFileVm") + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${RuntimeGlobals.hmrDownloadManifest} = function() {`, + Template.indent([ + "return new Promise(function(resolve, reject) {", + Template.indent([ + `var filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify( + rootOutputDir + )} + ${RuntimeGlobals.getUpdateManifestFilename}());`, + `require(${runtimeTemplate.renderNodePrefixForCoreModule("fs")}).readFile(filename, 'utf-8', function(err, content) {`, + Template.indent([ + "if(err) {", + Template.indent([ + 'if(err.code === "ENOENT") return resolve();', + "return reject(err);" + ]), + "}", + "try { resolve(JSON.parse(content)); }", + "catch(e) { reject(e); }" + ]), + "});" + ]), + "});" + ]), + "}" + ]) + : "// no HMR manifest" + ]); + } +} + +module.exports = ReadFileChunkLoadingRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/ReadFileCompileAsyncWasmPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/ReadFileCompileAsyncWasmPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..bf8f273d813adfb7223bfcb082888379e4be9ab7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/ReadFileCompileAsyncWasmPlugin.js @@ -0,0 +1,122 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const AsyncWasmLoadingRuntimeModule = require("../wasm-async/AsyncWasmLoadingRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {object} ReadFileCompileAsyncWasmPluginOptions + * @property {boolean=} import use import? + */ + +const PLUGIN_NAME = "ReadFileCompileAsyncWasmPlugin"; + +class ReadFileCompileAsyncWasmPlugin { + /** + * @param {ReadFileCompileAsyncWasmPluginOptions=} options options object + */ + constructor({ import: useImport = false } = {}) { + this._import = useImport; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + /** + * @param {Chunk} chunk chunk + * @returns {boolean} true, if wasm loading is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "async-node"; + }; + + /** + * @type {(path: string) => string} callback to generate code to load the wasm file + */ + const generateLoadBinaryCode = this._import + ? (path) => + Template.asString([ + "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {", + Template.indent([ + `readFile(new URL(${path}, ${compilation.outputOptions.importMetaName}.url), (err, buffer) => {`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "}))" + ]) + : (path) => + Template.asString([ + "new Promise(function (resolve, reject) {", + Template.indent([ + "try {", + Template.indent([ + `var { readFile } = require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("fs")});`, + `var { join } = require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("path")});`, + "", + `readFile(join(__dirname, ${path}), function(err, buffer){`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "} catch (err) { reject(err); }" + ]), + "})" + ]); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.instantiateWasm) + .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + (m) => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC + ) + ) { + return; + } + compilation.addRuntimeModule( + chunk, + new AsyncWasmLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: false + }) + ); + }); + }); + } +} + +module.exports = ReadFileCompileAsyncWasmPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/ReadFileCompileWasmPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/ReadFileCompileWasmPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..bbc1f4dd7def1358993861e089b15a8023a02770 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/ReadFileCompileWasmPlugin.js @@ -0,0 +1,128 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { WEBASSEMBLY_MODULE_TYPE_SYNC } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const WasmChunkLoadingRuntimeModule = require("../wasm-sync/WasmChunkLoadingRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {object} ReadFileCompileWasmPluginOptions + * @property {boolean=} mangleImports mangle imports + * @property {boolean=} import use import? + */ + +// TODO webpack 6 remove + +const PLUGIN_NAME = "ReadFileCompileWasmPlugin"; + +class ReadFileCompileWasmPlugin { + /** + * @param {ReadFileCompileWasmPluginOptions=} options options object + */ + constructor(options = {}) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + /** + * @param {Chunk} chunk chunk + * @returns {boolean} true, when wasm loading is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "async-node"; + }; + + /** + * @type {(path: string) => string} callback to generate code to load the wasm file + */ + const generateLoadBinaryCode = this.options.import + ? (path) => + Template.asString([ + "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {", + Template.indent([ + `readFile(new URL(${path}, ${compilation.outputOptions.importMetaName}.url), (err, buffer) => {`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "}))" + ]) + : (path) => + Template.asString([ + "new Promise(function (resolve, reject) {", + Template.indent([ + `var { readFile } = require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("fs")});`, + `var { join } = require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("path")});`, + "", + "try {", + Template.indent([ + `readFile(join(__dirname, ${path}), function(err, buffer){`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "} catch (err) { reject(err); }" + ]), + "})" + ]); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + (m) => m.type === WEBASSEMBLY_MODULE_TYPE_SYNC + ) + ) { + return; + } + set.add(RuntimeGlobals.moduleCache); + compilation.addRuntimeModule( + chunk, + new WasmChunkLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: false, + mangleImports: this.options.mangleImports, + runtimeRequirements: set + }) + ); + }); + }); + } +} + +module.exports = ReadFileCompileWasmPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/RequireChunkLoadingRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/RequireChunkLoadingRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..c3f9748191efdc2f651382b7688c14129c613321 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/RequireChunkLoadingRuntimeModule.js @@ -0,0 +1,235 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const { + generateJavascriptHMR +} = require("../hmr/JavascriptHotModuleReplacementHelper"); +const { + chunkHasJs, + getChunkFilenameTemplate +} = require("../javascript/JavascriptModulesPlugin"); +const { getInitialChunkIds } = require("../javascript/StartupHelpers"); +const compileBooleanMatcher = require("../util/compileBooleanMatcher"); +const { getUndoPath } = require("../util/identifier"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ + +class RequireChunkLoadingRuntimeModule extends RuntimeModule { + /** + * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super("require chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @private + * @param {Chunk} chunk chunk + * @param {string} rootOutputDir root output directory + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @returns {string} generated code + */ + _generateBaseUri(chunk, rootOutputDir, runtimeTemplate) { + const options = chunk.getEntryOptions(); + if (options && options.baseUri) { + return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`; + } + + return `${RuntimeGlobals.baseURI} = require(${runtimeTemplate.renderNodePrefixForCoreModule("url")}).pathToFileURL(${ + rootOutputDir !== "./" + ? `__dirname + ${JSON.stringify(`/${rootOutputDir}`)}` + : "__filename" + });`; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const { runtimeTemplate } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); + const withExternalInstallChunk = this.runtimeRequirements.has( + RuntimeGlobals.externalInstallChunk + ); + const withOnChunkLoad = this.runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withLoading = this.runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withHmr = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const outputName = compilation.getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + /** @type {string} */ (compilation.outputOptions.path), + true + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_require` + : undefined; + + return Template.asString([ + withBaseURI + ? this._generateBaseUri(chunk, rootOutputDir, runtimeTemplate) + : "// no baseURI", + "", + "// object to store loaded chunks", + '// "1" means "loaded", otherwise not loaded yet', + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 1`).join( + ",\n" + ) + ), + "};", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.require = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId]", + "chunkId" + )};` + : "// no on chunks loaded", + "", + withLoading || withExternalInstallChunk + ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ + "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ]), + "}" + ]), + "}", + `if(runtime) runtime(${RuntimeGlobals.require});`, + "for(var i = 0; i < chunkIds.length; i++)", + Template.indent("installedChunks[chunkIds[i]] = 1;"), + withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" + ])};` + : "// no chunk install function needed", + "", + withLoading + ? Template.asString([ + "// require() chunk loading for javascript", + `${fn}.require = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? [ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + // The require function loads and runs a chunk. When the chunk is being run, + // it can call __webpack_require__.C to directly complete installed. + `var installedChunk = require(${JSON.stringify( + rootOutputDir + )} + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId));`, + "if (!installedChunks[chunkId]) {", + Template.indent(["installChunk(installedChunk);"]), + "}" + ]), + "} else installedChunks[chunkId] = 1;", + "" + ]), + "}" + ] + : "installedChunks[chunkId] = 1;" + )};` + ]) + : "// no chunk loading", + "", + withExternalInstallChunk + ? Template.asString([ + `module.exports = ${RuntimeGlobals.require};`, + `${RuntimeGlobals.externalInstallChunk} = installChunk;` + ]) + : "// no external install chunk", + "", + withHmr + ? Template.asString([ + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + `var update = require(${JSON.stringify(rootOutputDir)} + ${ + RuntimeGlobals.getChunkUpdateScriptFilename + }(chunkId));`, + "var updatedModules = update.modules;", + "var runtime = update.runtime;", + "for(var moduleId in updatedModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, + Template.indent([ + "currentUpdate[moduleId] = updatedModules[moduleId];", + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);" + ]), + "}", + "", + generateJavascriptHMR("require") + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${RuntimeGlobals.hmrDownloadManifest} = function() {`, + Template.indent([ + "return Promise.resolve().then(function() {", + Template.indent([ + `return require(${JSON.stringify(rootOutputDir)} + ${ + RuntimeGlobals.getUpdateManifestFilename + }());` + ]), + "})['catch'](function(err) { if(err.code !== 'MODULE_NOT_FOUND') throw err; });" + ]), + "}" + ]) + : "// no HMR manifest" + ]); + } +} + +module.exports = RequireChunkLoadingRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/nodeConsole.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/nodeConsole.js new file mode 100644 index 0000000000000000000000000000000000000000..2ba080ca46cc5f28b6f6e6137071481921998b74 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/node/nodeConsole.js @@ -0,0 +1,168 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const truncateArgs = require("../logging/truncateArgs"); + +/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ +/** @typedef {import("../logging/createConsoleLogger").LoggerConsole} LoggerConsole */ + +/* eslint-disable no-console */ + +/** + * @param {object} options options + * @param {boolean=} options.colors colors + * @param {boolean=} options.appendOnly append only + * @param {NonNullable} options.stream stream + * @returns {LoggerConsole} logger function + */ +module.exports = ({ colors, appendOnly, stream }) => { + /** @type {string[] | undefined} */ + let currentStatusMessage; + let hasStatusMessage = false; + let currentIndent = ""; + let currentCollapsed = 0; + + /** + * @param {string} str string + * @param {string} prefix prefix + * @param {string} colorPrefix color prefix + * @param {string} colorSuffix color suffix + * @returns {string} indented string + */ + const indent = (str, prefix, colorPrefix, colorSuffix) => { + if (str === "") return str; + prefix = currentIndent + prefix; + if (colors) { + return ( + prefix + + colorPrefix + + str.replace(/\n/g, `${colorSuffix}\n${prefix}${colorPrefix}`) + + colorSuffix + ); + } + + return prefix + str.replace(/\n/g, `\n${prefix}`); + }; + + const clearStatusMessage = () => { + if (hasStatusMessage) { + stream.write("\u001B[2K\r"); + hasStatusMessage = false; + } + }; + + const writeStatusMessage = () => { + if (!currentStatusMessage) return; + const l = stream.columns || 40; + const args = truncateArgs(currentStatusMessage, l - 1); + const str = args.join(" "); + const coloredStr = `\u001B[1m${str}\u001B[39m\u001B[22m`; + stream.write(`\u001B[2K\r${coloredStr}`); + hasStatusMessage = true; + }; + + /** + * @param {string} prefix prefix + * @param {string} colorPrefix color prefix + * @param {string} colorSuffix color suffix + * @returns {(...args: EXPECTED_ANY[]) => void} function to write with colors + */ + const writeColored = + (prefix, colorPrefix, colorSuffix) => + (...args) => { + if (currentCollapsed > 0) return; + clearStatusMessage(); + const str = indent( + util.format(...args), + prefix, + colorPrefix, + colorSuffix + ); + stream.write(`${str}\n`); + writeStatusMessage(); + }; + + const writeGroupMessage = writeColored( + "<-> ", + "\u001B[1m\u001B[36m", + "\u001B[39m\u001B[22m" + ); + + const writeGroupCollapsedMessage = writeColored( + "<+> ", + "\u001B[1m\u001B[36m", + "\u001B[39m\u001B[22m" + ); + + return { + log: writeColored(" ", "\u001B[1m", "\u001B[22m"), + debug: writeColored(" ", "", ""), + trace: writeColored(" ", "", ""), + info: writeColored(" ", "\u001B[1m\u001B[32m", "\u001B[39m\u001B[22m"), + warn: writeColored(" ", "\u001B[1m\u001B[33m", "\u001B[39m\u001B[22m"), + error: writeColored(" ", "\u001B[1m\u001B[31m", "\u001B[39m\u001B[22m"), + logTime: writeColored( + " ", + "\u001B[1m\u001B[35m", + "\u001B[39m\u001B[22m" + ), + group: (...args) => { + writeGroupMessage(...args); + if (currentCollapsed > 0) { + currentCollapsed++; + } else { + currentIndent += " "; + } + }, + groupCollapsed: (...args) => { + writeGroupCollapsedMessage(...args); + currentCollapsed++; + }, + groupEnd: () => { + if (currentCollapsed > 0) { + currentCollapsed--; + } else if (currentIndent.length >= 2) { + currentIndent = currentIndent.slice(0, -2); + } + }, + profile: console.profile && ((name) => console.profile(name)), + profileEnd: console.profileEnd && ((name) => console.profileEnd(name)), + clear: + /** @type {() => void} */ + ( + !appendOnly && + console.clear && + (() => { + clearStatusMessage(); + console.clear(); + writeStatusMessage(); + }) + ), + status: appendOnly + ? writeColored(" ", "", "") + : (name, ...args) => { + args = args.filter(Boolean); + if (name === undefined && args.length === 0) { + clearStatusMessage(); + currentStatusMessage = undefined; + } else if ( + typeof name === "string" && + name.startsWith("[webpack.Progress] ") + ) { + currentStatusMessage = [name.slice(19), ...args]; + writeStatusMessage(); + } else if (name === "[webpack.Progress]") { + currentStatusMessage = [...args]; + writeStatusMessage(); + } else { + currentStatusMessage = [name, ...args]; + writeStatusMessage(); + } + } + }; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/AggressiveMergingPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/AggressiveMergingPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f2b7698e217e8981440482ae512390af22873d24 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/AggressiveMergingPlugin.js @@ -0,0 +1,97 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { STAGE_ADVANCED } = require("../OptimizationStages"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {object} AggressiveMergingPluginOptions + * @property {number=} minSizeReduce minimal size reduction to trigger merging + */ + +const PLUGIN_NAME = "AggressiveMergingPlugin"; + +class AggressiveMergingPlugin { + /** + * @param {AggressiveMergingPluginOptions=} options options object + */ + constructor(options) { + if ( + (options !== undefined && typeof options !== "object") || + Array.isArray(options) + ) { + throw new Error( + "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" + ); + } + this.options = options || {}; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + const minSizeReduce = options.minSizeReduce || 1.5; + + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: STAGE_ADVANCED + }, + (chunks) => { + const chunkGraph = compilation.chunkGraph; + /** @type {{a: Chunk, b: Chunk, improvement: number}[]} */ + const combinations = []; + for (const a of chunks) { + if (a.canBeInitial()) continue; + for (const b of chunks) { + if (b.canBeInitial()) continue; + if (b === a) break; + if (!chunkGraph.canChunksBeIntegrated(a, b)) { + continue; + } + const aSize = chunkGraph.getChunkSize(b, { + chunkOverhead: 0 + }); + const bSize = chunkGraph.getChunkSize(a, { + chunkOverhead: 0 + }); + const abSize = chunkGraph.getIntegratedChunksSize(b, a, { + chunkOverhead: 0 + }); + const improvement = (aSize + bSize) / abSize; + combinations.push({ + a, + b, + improvement + }); + } + } + + combinations.sort((a, b) => b.improvement - a.improvement); + + const pair = combinations[0]; + + if (!pair) return; + if (pair.improvement < minSizeReduce) return; + + chunkGraph.integrateChunks(pair.b, pair.a); + compilation.chunks.delete(pair.a); + return true; + } + ); + }); + } +} + +module.exports = AggressiveMergingPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/AggressiveSplittingPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/AggressiveSplittingPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..fa99181a2ec545ed1d79217ba376a26a7249d8fe --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/AggressiveSplittingPlugin.js @@ -0,0 +1,341 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { STAGE_ADVANCED } = require("../OptimizationStages"); +const { intersect } = require("../util/SetHelpers"); +const { + compareChunks, + compareModulesByIdentifier +} = require("../util/comparators"); +const createSchemaValidation = require("../util/create-schema-validation"); +const identifierUtils = require("../util/identifier"); + +/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.check"), + () => + require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.json"), + { + name: "Aggressive Splitting Plugin", + baseDataPath: "options" + } +); + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} oldChunk the old chunk + * @param {Chunk} newChunk the new chunk + * @returns {(module: Module) => void} function to move module between chunks + */ +const moveModuleBetween = (chunkGraph, oldChunk, newChunk) => (module) => { + chunkGraph.disconnectChunkAndModule(oldChunk, module); + chunkGraph.connectChunkAndModule(newChunk, module); +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} chunk the chunk + * @returns {(module: Module) => boolean} filter for entry module + */ +const isNotAEntryModule = (chunkGraph, chunk) => (module) => + !chunkGraph.isEntryModuleInChunk(module, chunk); + +/** @typedef {{ id?: NonNullable, hash?: NonNullable, modules: Module[], size: number }} SplitData */ + +/** @type {WeakSet} */ +const recordedChunks = new WeakSet(); + +const PLUGIN_NAME = "AggressiveSplittingPlugin"; + +class AggressiveSplittingPlugin { + /** + * @param {AggressiveSplittingPluginOptions=} options options object + */ + constructor(options = {}) { + validate(options); + + this.options = options; + if (typeof this.options.minSize !== "number") { + this.options.minSize = 30 * 1024; + } + if (typeof this.options.maxSize !== "number") { + this.options.maxSize = 50 * 1024; + } + if (typeof this.options.chunkOverhead !== "number") { + this.options.chunkOverhead = 0; + } + if (typeof this.options.entryChunkMultiplicator !== "number") { + this.options.entryChunkMultiplicator = 1; + } + } + + /** + * @param {Chunk} chunk the chunk to test + * @returns {boolean} true if the chunk was recorded + */ + static wasChunkRecorded(chunk) { + return recordedChunks.has(chunk); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + let needAdditionalSeal = false; + /** @type {SplitData[]} */ + let newSplits; + /** @type {Set} */ + let fromAggressiveSplittingSet; + /** @type {Map} */ + let chunkSplitDataMap; + compilation.hooks.optimize.tap(PLUGIN_NAME, () => { + newSplits = []; + fromAggressiveSplittingSet = new Set(); + chunkSplitDataMap = new Map(); + }); + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: STAGE_ADVANCED + }, + (chunks) => { + const chunkGraph = compilation.chunkGraph; + // Precompute stuff + const nameToModuleMap = new Map(); + const moduleToNameMap = new Map(); + const makePathsRelative = + identifierUtils.makePathsRelative.bindContextCache( + compiler.context, + compiler.root + ); + for (const m of compilation.modules) { + const name = makePathsRelative(m.identifier()); + nameToModuleMap.set(name, m); + moduleToNameMap.set(m, name); + } + + // Check used chunk ids + const usedIds = new Set(); + for (const chunk of chunks) { + usedIds.add(chunk.id); + } + + const recordedSplits = + (compilation.records && compilation.records.aggressiveSplits) || []; + const usedSplits = newSplits + ? [...recordedSplits, ...newSplits] + : recordedSplits; + + const minSize = /** @type {number} */ (this.options.minSize); + const maxSize = /** @type {number} */ (this.options.maxSize); + + /** + * @param {SplitData} splitData split data + * @returns {boolean} true when applied, otherwise false + */ + const applySplit = (splitData) => { + // Cannot split if id is already taken + if (splitData.id !== undefined && usedIds.has(splitData.id)) { + return false; + } + + // Get module objects from names + const selectedModules = splitData.modules.map((name) => + nameToModuleMap.get(name) + ); + + // Does the modules exist at all? + if (!selectedModules.every(Boolean)) return false; + + // Check if size matches (faster than waiting for hash) + let size = 0; + for (const m of selectedModules) size += m.size(); + if (size !== splitData.size) return false; + + // get chunks with all modules + const selectedChunks = intersect( + selectedModules.map( + (m) => new Set(chunkGraph.getModuleChunksIterable(m)) + ) + ); + + // No relevant chunks found + if (selectedChunks.size === 0) return false; + + // The found chunk is already the split or similar + if ( + selectedChunks.size === 1 && + chunkGraph.getNumberOfChunkModules([...selectedChunks][0]) === + selectedModules.length + ) { + const chunk = [...selectedChunks][0]; + if (fromAggressiveSplittingSet.has(chunk)) return false; + fromAggressiveSplittingSet.add(chunk); + chunkSplitDataMap.set(chunk, splitData); + return true; + } + + // split the chunk into two parts + const newChunk = compilation.addChunk(); + newChunk.chunkReason = "aggressive splitted"; + for (const chunk of selectedChunks) { + for (const module of selectedModules) { + moveModuleBetween(chunkGraph, chunk, newChunk)(module); + } + chunk.split(newChunk); + chunk.name = null; + } + fromAggressiveSplittingSet.add(newChunk); + chunkSplitDataMap.set(newChunk, splitData); + + if (splitData.id !== null && splitData.id !== undefined) { + newChunk.id = splitData.id; + newChunk.ids = [splitData.id]; + } + return true; + }; + + // try to restore to recorded splitting + let changed = false; + for (let j = 0; j < usedSplits.length; j++) { + const splitData = usedSplits[j]; + if (applySplit(splitData)) changed = true; + } + + // for any chunk which isn't splitted yet, split it and create a new entry + // start with the biggest chunk + const cmpFn = compareChunks(chunkGraph); + const sortedChunks = [...chunks].sort((a, b) => { + const diff1 = + chunkGraph.getChunkModulesSize(b) - + chunkGraph.getChunkModulesSize(a); + if (diff1) return diff1; + const diff2 = + chunkGraph.getNumberOfChunkModules(a) - + chunkGraph.getNumberOfChunkModules(b); + if (diff2) return diff2; + return cmpFn(a, b); + }); + for (const chunk of sortedChunks) { + if (fromAggressiveSplittingSet.has(chunk)) continue; + const size = chunkGraph.getChunkModulesSize(chunk); + if ( + size > maxSize && + chunkGraph.getNumberOfChunkModules(chunk) > 1 + ) { + const modules = chunkGraph + .getOrderedChunkModules(chunk, compareModulesByIdentifier) + .filter(isNotAEntryModule(chunkGraph, chunk)); + const selectedModules = []; + let selectedModulesSize = 0; + for (let k = 0; k < modules.length; k++) { + const module = modules[k]; + const newSize = selectedModulesSize + module.size(); + if (newSize > maxSize && selectedModulesSize >= minSize) { + break; + } + selectedModulesSize = newSize; + selectedModules.push(module); + } + if (selectedModules.length === 0) continue; + /** @type {SplitData} */ + const splitData = { + modules: selectedModules + .map((m) => moduleToNameMap.get(m)) + .sort(), + size: selectedModulesSize + }; + + if (applySplit(splitData)) { + newSplits = [...(newSplits || []), splitData]; + changed = true; + } + } + } + if (changed) return true; + } + ); + compilation.hooks.recordHash.tap(PLUGIN_NAME, (records) => { + // 4. save made splittings to records + const allSplits = new Set(); + /** @type {Set} */ + const invalidSplits = new Set(); + + // Check if some splittings are invalid + // We remove invalid splittings and try again + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if ( + splitData !== undefined && + splitData.hash && + chunk.hash !== splitData.hash + ) { + // Split was successful, but hash doesn't equal + // We can throw away the split since it's useless now + invalidSplits.add(splitData); + } + } + + if (invalidSplits.size > 0) { + records.aggressiveSplits = + /** @type {SplitData[]} */ + (records.aggressiveSplits).filter( + (splitData) => !invalidSplits.has(splitData) + ); + needAdditionalSeal = true; + } else { + // set hash and id values on all (new) splittings + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + splitData.hash = + /** @type {NonNullable} */ + (chunk.hash); + splitData.id = + /** @type {NonNullable} */ + (chunk.id); + allSplits.add(splitData); + // set flag for stats + recordedChunks.add(chunk); + } + } + + // Also add all unused historical splits (after the used ones) + // They can still be used in some future compilation + const recordedSplits = + compilation.records && compilation.records.aggressiveSplits; + if (recordedSplits) { + for (const splitData of recordedSplits) { + if (!invalidSplits.has(splitData)) allSplits.add(splitData); + } + } + + // record all splits + records.aggressiveSplits = [...allSplits]; + + needAdditionalSeal = false; + } + }); + compilation.hooks.needAdditionalSeal.tap(PLUGIN_NAME, () => { + if (needAdditionalSeal) { + needAdditionalSeal = false; + return true; + } + }); + }); + } +} + +module.exports = AggressiveSplittingPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/ConcatenatedModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/ConcatenatedModule.js new file mode 100644 index 0000000000000000000000000000000000000000..74b9b18a96f34ba9bbf62a3f6da625d74d3e2177 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/ConcatenatedModule.js @@ -0,0 +1,2190 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const eslintScope = require("eslint-scope"); +const Referencer = require("eslint-scope/lib/referencer"); +const { SyncBailHook } = require("tapable"); +const { + CachedSource, + ConcatSource, + ReplaceSource +} = require("webpack-sources"); +const ConcatenationScope = require("../ConcatenationScope"); +const { UsageState } = require("../ExportsInfo"); +const Module = require("../Module"); +const { JS_TYPES } = require("../ModuleSourceTypesConstants"); +const { JAVASCRIPT_MODULE_TYPE_ESM } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const { DEFAULTS } = require("../config/defaults"); +const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); +const HarmonyImportSideEffectDependency = require("../dependencies/HarmonyImportSideEffectDependency"); +const JavascriptParser = require("../javascript/JavascriptParser"); +const { + getMakeDeferredNamespaceModeFromExportsType, + getOptimizedDeferredModule +} = require("../runtime/MakeDeferredNamespaceObjectRuntime"); +const { equals } = require("../util/ArrayHelpers"); +const LazySet = require("../util/LazySet"); +const { concatComparators } = require("../util/comparators"); +const { + RESERVED_NAMES, + addScopeSymbols, + findNewName, + getAllReferences, + getPathInAst, + getUsedNamesInScopeInfo +} = require("../util/concatenate"); +const createHash = require("../util/createHash"); +const { makePathsRelative } = require("../util/identifier"); +const makeSerializable = require("../util/makeSerializable"); +const propertyAccess = require("../util/propertyAccess"); +const { propertyName } = require("../util/propertyName"); +const { + filterRuntime, + intersectRuntime, + mergeRuntimeCondition, + mergeRuntimeConditionNonFalse, + runtimeConditionToString, + subtractRuntimeCondition +} = require("../util/runtime"); + +/** @typedef {import("eslint-scope").Reference} Reference */ +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("../ExternalModule")} ExternalModule */ +/** @typedef {import("../Module").BuildCallback} BuildCallback */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ +/** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../ModuleParseError")} ModuleParseError */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("../javascript/JavascriptParser").Program} Program */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {typeof import("../util/Hash")} HashConstructor */ +/** @typedef {import("../util/concatenate").ScopeInfo} ScopeInfo */ +/** @typedef {import("../util/concatenate").UsedNames} UsedNames */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** + * @template T + * @typedef {import("../InitFragment")} InitFragment + */ + +/** + * @template T + * @typedef {import("../util/comparators").Comparator} Comparator + */ + +// fix eslint-scope to support class properties correctly +// cspell:word Referencer +const ReferencerClass = /** @type {EXPECTED_ANY} */ (Referencer); +if (!ReferencerClass.prototype.PropertyDefinition) { + ReferencerClass.prototype.PropertyDefinition = + ReferencerClass.prototype.Property; +} + +/** + * @typedef {object} ReexportInfo + * @property {Module} module + * @property {string[]} export + */ + +/** @typedef {RawBinding | SymbolBinding} Binding */ + +/** + * @typedef {object} RawBinding + * @property {ModuleInfo} info + * @property {string} rawName + * @property {string=} comment + * @property {string[]} ids + * @property {string[]} exportName + */ + +/** + * @typedef {object} SymbolBinding + * @property {ConcatenatedModuleInfo} info + * @property {string} name + * @property {string=} comment + * @property {string[]} ids + * @property {string[]} exportName + */ + +/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */ +/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo | ReferenceToModuleInfo } ModuleInfoOrReference */ + +/** + * @typedef {object} ConcatenatedModuleInfo + * @property {"concatenated"} type + * @property {Module} module + * @property {number} index + * @property {Program | undefined} ast + * @property {Source | undefined} internalSource + * @property {ReplaceSource | undefined} source + * @property {InitFragment[]=} chunkInitFragments + * @property {ReadOnlyRuntimeRequirements | undefined} runtimeRequirements + * @property {Scope | undefined} globalScope + * @property {Scope | undefined} moduleScope + * @property {Map} internalNames + * @property {Map | undefined} exportMap + * @property {Map | undefined} rawExportMap + * @property {string=} namespaceExportSymbol + * @property {string | undefined} namespaceObjectName + * @property {ConcatenationScope | undefined} concatenationScope + * @property {boolean} interopNamespaceObjectUsed "default-with-named" namespace + * @property {string | undefined} interopNamespaceObjectName "default-with-named" namespace + * @property {boolean} interopNamespaceObject2Used "default-only" namespace + * @property {string | undefined} interopNamespaceObject2Name "default-only" namespace + * @property {boolean} interopDefaultAccessUsed runtime namespace object that detects "__esModule" + * @property {string | undefined} interopDefaultAccessName runtime namespace object that detects "__esModule" + */ + +/** + * @typedef {object} ExternalModuleInfo + * @property {"external"} type + * @property {Module} module + * @property {RuntimeSpec | boolean} runtimeCondition + * @property {number} index + * @property {string | undefined} name module.exports / harmony namespace object + * @property {string | undefined} deferredName deferred module.exports / harmony namespace object + * @property {boolean} deferred the module is deferred at least once + * @property {boolean} deferredNamespaceObjectUsed deferred namespace object that being used in a not-analyzable way so it must be materialized + * @property {string | undefined} deferredNamespaceObjectName deferred namespace object that being used in a not-analyzable way so it must be materialized + * @property {boolean} interopNamespaceObjectUsed "default-with-named" namespace + * @property {string | undefined} interopNamespaceObjectName "default-with-named" namespace + * @property {boolean} interopNamespaceObject2Used "default-only" namespace + * @property {string | undefined} interopNamespaceObject2Name "default-only" namespace + * @property {boolean} interopDefaultAccessUsed runtime namespace object that detects "__esModule" + * @property {string | undefined} interopDefaultAccessName runtime namespace object that detects "__esModule" + */ + +/** + * @typedef {object} ReferenceToModuleInfo + * @property {"reference"} type + * @property {RuntimeSpec | boolean} runtimeCondition + * @property {ModuleInfo} target + */ + +/** + * @template T + * @param {string} property property + * @param {function(T[keyof T], T[keyof T]): 0 | 1 | -1} comparator comparator + * @returns {Comparator} comparator + */ + +const createComparator = (property, comparator) => (a, b) => + comparator( + a[/** @type {keyof T} */ (property)], + b[/** @type {keyof T} */ (property)] + ); + +/** + * @param {number} a a + * @param {number} b b + * @returns {0 | 1 | -1} result + */ +const compareNumbers = (a, b) => { + if (Number.isNaN(a)) { + if (!Number.isNaN(b)) { + return 1; + } + } else { + if (Number.isNaN(b)) { + return -1; + } + if (a !== b) { + return a < b ? -1 : 1; + } + } + return 0; +}; +const bySourceOrder = createComparator("sourceOrder", compareNumbers); +const byRangeStart = createComparator("rangeStart", compareNumbers); +const moveDeferToLast = ( + /** @type {{ defer?: boolean }} */ a, + /** @type {{ defer?: boolean }} */ b +) => { + if (a.defer === b.defer) return 0; + if (a.defer) return 1; + return -1; +}; + +/** + * @param {Iterable} iterable iterable object + * @returns {string} joined iterable object + */ +const joinIterableWithComma = (iterable) => { + // This is more performant than Array.from().join(", ") + // as it doesn't create an array + let str = ""; + let first = true; + for (const item of iterable) { + if (first) { + first = false; + } else { + str += ", "; + } + str += item; + } + return str; +}; + +/** + * @typedef {object} ConcatenationEntry + * @property {"concatenated" | "external"} type + * @property {Module} module + * @property {RuntimeSpec | boolean} runtimeCondition + */ + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ModuleInfo} info module info + * @param {string[]} exportName exportName + * @param {Map} moduleToInfoMap moduleToInfoMap + * @param {RuntimeSpec} runtime for which runtime + * @param {RequestShortener} requestShortener the request shortener + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated + * @param {boolean} asCall asCall + * @param {boolean} depDeferred the dependency is deferred + * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule + * @param {boolean | undefined} asiSafe asiSafe + * @param {Set} alreadyVisited alreadyVisited + * @returns {Binding} the final variable + */ +const getFinalBinding = ( + moduleGraph, + info, + exportName, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + depDeferred, + strictHarmonyModule, + asiSafe, + alreadyVisited = new Set() +) => { + const exportsType = info.module.getExportsType( + moduleGraph, + strictHarmonyModule + ); + const deferred = + depDeferred && + info.type === "external" && + info.deferred && + !moduleGraph.isAsync(info.module); + if (exportName.length === 0) { + switch (exportsType) { + case "default-only": + if (deferred) info.deferredNamespaceObjectUsed = true; + else info.interopNamespaceObject2Used = true; + return { + info, + rawName: /** @type {string} */ ( + deferred + ? info.deferredNamespaceObjectName + : info.interopNamespaceObject2Name + ), + ids: exportName, + exportName + }; + case "default-with-named": + if (deferred) info.deferredNamespaceObjectUsed = true; + else info.interopNamespaceObjectUsed = true; + return { + info, + rawName: /** @type {string} */ ( + deferred + ? info.deferredNamespaceObjectName + : info.interopNamespaceObjectName + ), + ids: exportName, + exportName + }; + case "namespace": + case "dynamic": + break; + default: + throw new Error(`Unexpected exportsType ${exportsType}`); + } + } else { + switch (exportsType) { + case "namespace": + break; + case "default-with-named": + switch (exportName[0]) { + case "default": + exportName = exportName.slice(1); + break; + case "__esModule": + return { + info, + rawName: "/* __esModule */true", + ids: exportName.slice(1), + exportName + }; + } + break; + case "default-only": { + const exportId = exportName[0]; + if (exportId === "__esModule") { + return { + info, + rawName: "/* __esModule */true", + ids: exportName.slice(1), + exportName + }; + } + exportName = exportName.slice(1); + if (exportId !== "default") { + return { + info, + rawName: + "/* non-default import from default-exporting module */undefined", + ids: exportName, + exportName + }; + } + break; + } + case "dynamic": + switch (exportName[0]) { + case "default": { + exportName = exportName.slice(1); + if (deferred) { + return { + info, + rawName: `${info.deferredName}.a`, + ids: exportName, + exportName + }; + } + info.interopDefaultAccessUsed = true; + const defaultExport = asCall + ? `${info.interopDefaultAccessName}()` + : asiSafe + ? `(${info.interopDefaultAccessName}())` + : asiSafe === false + ? `;(${info.interopDefaultAccessName}())` + : `${info.interopDefaultAccessName}.a`; + return { + info, + rawName: defaultExport, + ids: exportName, + exportName + }; + } + case "__esModule": + return { + info, + rawName: "/* __esModule */true", + ids: exportName.slice(1), + exportName + }; + } + break; + default: + throw new Error(`Unexpected exportsType ${exportsType}`); + } + } + if (exportName.length === 0) { + switch (info.type) { + case "concatenated": + neededNamespaceObjects.add(info); + return { + info, + rawName: + /** @type {NonNullable} */ + (info.namespaceObjectName), + ids: exportName, + exportName + }; + case "external": + if (deferred) { + info.deferredNamespaceObjectUsed = true; + return { + info, + rawName: /** @type {string} */ (info.deferredNamespaceObjectName), + ids: exportName, + exportName + }; + } + return { + info, + rawName: + /** @type {NonNullable} */ + (info.name), + ids: exportName, + exportName + }; + } + } + const exportsInfo = moduleGraph.getExportsInfo(info.module); + const exportInfo = exportsInfo.getExportInfo(exportName[0]); + if (alreadyVisited.has(exportInfo)) { + return { + info, + rawName: "/* circular reexport */ Object(function x() { x() }())", + ids: [], + exportName + }; + } + alreadyVisited.add(exportInfo); + switch (info.type) { + case "concatenated": { + const exportId = exportName[0]; + if (exportInfo.provided === false) { + // It's not provided, but it could be on the prototype + neededNamespaceObjects.add(info); + return { + info, + rawName: /** @type {string} */ (info.namespaceObjectName), + ids: exportName, + exportName + }; + } + const directExport = info.exportMap && info.exportMap.get(exportId); + if (directExport) { + const usedName = /** @type {string[]} */ ( + exportsInfo.getUsedName(exportName, runtime) + ); + if (!usedName) { + return { + info, + rawName: "/* unused export */ undefined", + ids: exportName.slice(1), + exportName + }; + } + return { + info, + name: directExport, + ids: usedName.slice(1), + exportName + }; + } + const rawExport = info.rawExportMap && info.rawExportMap.get(exportId); + if (rawExport) { + return { + info, + rawName: rawExport, + ids: exportName.slice(1), + exportName + }; + } + const reexport = exportInfo.findTarget(moduleGraph, (module) => + moduleToInfoMap.has(module) + ); + if (reexport === false) { + throw new Error( + `Target module of reexport from '${info.module.readableIdentifier( + requestShortener + )}' is not part of the concatenation (export '${exportId}')\nModules in the concatenation:\n${Array.from( + moduleToInfoMap, + ([m, info]) => + ` * ${info.type} ${m.readableIdentifier(requestShortener)}` + ).join("\n")}` + ); + } + if (reexport) { + const refInfo = moduleToInfoMap.get(reexport.module); + return getFinalBinding( + moduleGraph, + /** @type {ModuleInfo} */ (refInfo), + reexport.export + ? [...reexport.export, ...exportName.slice(1)] + : exportName.slice(1), + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + reexport.deferred, + /** @type {BuildMeta} */ + (info.module.buildMeta).strictHarmonyModule, + asiSafe, + alreadyVisited + ); + } + if (info.namespaceExportSymbol) { + const usedName = /** @type {string[]} */ ( + exportsInfo.getUsedName(exportName, runtime) + ); + return { + info, + rawName: /** @type {string} */ (info.namespaceObjectName), + ids: usedName, + exportName + }; + } + throw new Error( + `Cannot get final name for export '${exportName.join( + "." + )}' of ${info.module.readableIdentifier(requestShortener)}` + ); + } + + case "external": { + const used = /** @type {string[]} */ ( + exportsInfo.getUsedName(exportName, runtime) + ); + if (!used) { + return { + info, + rawName: "/* unused export */ undefined", + ids: exportName.slice(1), + exportName + }; + } + const comment = equals(used, exportName) + ? "" + : Template.toNormalComment(`${exportName.join(".")}`); + return { + info, + rawName: + (deferred ? info.deferredName : info.name) + + (deferred ? ".a" : "") + + comment, + ids: used, + exportName + }; + } + } +}; + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ModuleInfo} info module info + * @param {string[]} exportName exportName + * @param {Map} moduleToInfoMap moduleToInfoMap + * @param {RuntimeSpec} runtime for which runtime + * @param {RequestShortener} requestShortener the request shortener + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated + * @param {boolean} asCall asCall + * @param {boolean} depDeferred the dependency is deferred + * @param {boolean | undefined} callContext callContext + * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule + * @param {boolean | undefined} asiSafe asiSafe + * @returns {string} the final name + */ +const getFinalName = ( + moduleGraph, + info, + exportName, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + depDeferred, + callContext, + strictHarmonyModule, + asiSafe +) => { + const binding = getFinalBinding( + moduleGraph, + info, + exportName, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + depDeferred, + strictHarmonyModule, + asiSafe + ); + { + const { ids, comment } = binding; + let reference; + let isPropertyAccess; + if ("rawName" in binding) { + reference = `${binding.rawName}${comment || ""}${propertyAccess(ids)}`; + isPropertyAccess = ids.length > 0; + } else { + const { info, name: exportId } = binding; + const name = info.internalNames.get(exportId); + if (!name) { + throw new Error( + `The export "${exportId}" in "${info.module.readableIdentifier( + requestShortener + )}" has no internal name (existing names: ${ + Array.from( + info.internalNames, + ([name, symbol]) => `${name}: ${symbol}` + ).join(", ") || "none" + })` + ); + } + reference = `${name}${comment || ""}${propertyAccess(ids)}`; + isPropertyAccess = ids.length > 1; + } + if (isPropertyAccess && asCall && callContext === false) { + return asiSafe + ? `(0,${reference})` + : asiSafe === false + ? `;(0,${reference})` + : `/*#__PURE__*/Object(${reference})`; + } + return reference; + } +}; + +/** + * @typedef {object} ConcatenateModuleHooks + * @property {SyncBailHook<[ConcatenatedModule], boolean>} onDemandExportsGeneration + * @property {SyncBailHook<[Partial, ConcatenatedModuleInfo], boolean | void>} concatenatedModuleInfo + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class ConcatenatedModule extends Module { + /** + * @param {Module} rootModule the root module of the concatenation + * @param {Set} modules all modules in the concatenation (including the root module) + * @param {RuntimeSpec} runtime the runtime + * @param {Compilation} compilation the compilation + * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching + * @param {string | HashConstructor=} hashFunction hash function to use + * @returns {ConcatenatedModule} the module + */ + static create( + rootModule, + modules, + runtime, + compilation, + associatedObjectForCache, + hashFunction = DEFAULTS.HASH_FUNCTION + ) { + const identifier = ConcatenatedModule._createIdentifier( + rootModule, + modules, + associatedObjectForCache, + hashFunction + ); + return new ConcatenatedModule({ + identifier, + rootModule, + modules, + runtime, + compilation + }); + } + + /** + * @param {Compilation} compilation the compilation + * @returns {ConcatenateModuleHooks} the attached hooks + */ + static getCompilationHooks(compilation) { + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + onDemandExportsGeneration: new SyncBailHook(["module"]), + concatenatedModuleInfo: new SyncBailHook([ + "updatedInfo", + "concatenatedModuleInfo" + ]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** + * @param {object} options options + * @param {string} options.identifier the identifier of the module + * @param {Module} options.rootModule the root module of the concatenation + * @param {RuntimeSpec} options.runtime the selected runtime + * @param {Set} options.modules all concatenated modules + * @param {Compilation} options.compilation the compilation + */ + constructor({ identifier, rootModule, modules, runtime, compilation }) { + super(JAVASCRIPT_MODULE_TYPE_ESM, null, rootModule && rootModule.layer); + + // Info from Factory + /** @type {string} */ + this._identifier = identifier; + /** @type {Module} */ + this.rootModule = rootModule; + /** @type {Set} */ + this._modules = modules; + this._runtime = runtime; + this.factoryMeta = rootModule && rootModule.factoryMeta; + /** @type {Compilation | undefined} */ + this.compilation = compilation; + } + + /** + * Assuming this module is in the cache. Update the (cached) module with + * the fresh module from the factory. Usually updates internal references + * and properties. + * @param {Module} module fresh module + * @returns {void} + */ + updateCacheModule(module) { + throw new Error("Must not be called"); + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return JS_TYPES; + } + + get modules() { + return [...this._modules]; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this._identifier; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `${this.rootModule.readableIdentifier( + requestShortener + )} + ${this._modules.size - 1} modules`; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return this.rootModule.libIdent(options); + } + + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + return this.rootModule.nameForCondition(); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + */ + getSideEffectsConnectionState(moduleGraph) { + return this.rootModule.getSideEffectsConnectionState(moduleGraph); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + const { rootModule } = this; + const { moduleArgument, exportsArgument } = + /** @type {BuildInfo} */ + (rootModule.buildInfo); + this.buildInfo = { + strict: true, + cacheable: true, + moduleArgument, + exportsArgument, + /** @type {LazySet} */ + fileDependencies: new LazySet(), + /** @type {LazySet} */ + contextDependencies: new LazySet(), + /** @type {LazySet} */ + missingDependencies: new LazySet(), + /** @type {Set} */ + topLevelDeclarations: new Set(), + assets: undefined + }; + this.buildMeta = rootModule.buildMeta; + this.clearDependenciesAndBlocks(); + this.clearWarningsAndErrors(); + + for (const m of this._modules) { + // populate cacheable + if (!(/** @type {BuildInfo} */ (m.buildInfo).cacheable)) { + /** @type {BuildInfo} */ + (this.buildInfo).cacheable = false; + } + + // populate dependencies + for (const d of m.dependencies.filter( + (dep) => + !(dep instanceof HarmonyImportDependency) || + !this._modules.has( + /** @type {Module} */ + (compilation.moduleGraph.getModule(dep)) + ) + )) { + this.dependencies.push(d); + } + // populate blocks + for (const d of m.blocks) { + this.blocks.push(d); + } + + // populate warnings + const warnings = m.getWarnings(); + if (warnings !== undefined) { + for (const warning of warnings) { + this.addWarning(warning); + } + } + + // populate errors + const errors = m.getErrors(); + if (errors !== undefined) { + for (const error of errors) { + this.addError(error); + } + } + + const { assets, assetsInfo, topLevelDeclarations } = + /** @type {BuildInfo} */ (m.buildInfo); + + const buildInfo = /** @type {BuildInfo} */ (this.buildInfo); + + // populate topLevelDeclarations + if (topLevelDeclarations) { + const topLevelDeclarations = buildInfo.topLevelDeclarations; + if (topLevelDeclarations !== undefined) { + for (const decl of topLevelDeclarations) { + topLevelDeclarations.add(decl); + } + } + } else { + buildInfo.topLevelDeclarations = undefined; + } + + // populate assets + if (assets) { + if (buildInfo.assets === undefined) { + buildInfo.assets = Object.create(null); + } + Object.assign( + /** @type {NonNullable} */ + (buildInfo.assets), + assets + ); + } + if (assetsInfo) { + if (buildInfo.assetsInfo === undefined) { + buildInfo.assetsInfo = new Map(); + } + for (const [key, value] of assetsInfo) { + buildInfo.assetsInfo.set(key, value); + } + } + } + callback(); + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + // Guess size from embedded modules + let size = 0; + for (const module of this._modules) { + size += module.size(type); + } + return size; + } + + /** + * @private + * @param {Module} rootModule the root of the concatenation + * @param {Set} modulesSet a set of modules which should be concatenated + * @param {RuntimeSpec} runtime for this runtime + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConcatenationEntry[]} concatenation list + */ + _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) { + /** @type {ConcatenationEntry[]} */ + const list = []; + /** @type {Map} */ + const existingEntries = new Map(); + const deferEnabled = + /** @type {Compilation} */ + (this.compilation).options.experiments.deferImport; + + /** + * @param {Module} module a module + * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order + */ + const getConcatenatedImports = (module) => { + const connections = [...moduleGraph.getOutgoingConnections(module)]; + if (module === rootModule) { + for (const c of moduleGraph.getOutgoingConnections(this)) { + connections.push(c); + } + } + /** + * @type {Array<{ connection: ModuleGraphConnection, sourceOrder: number, rangeStart: number, defer?: boolean }>} + */ + const references = connections + .filter((connection) => { + if (!(connection.dependency instanceof HarmonyImportDependency)) { + return false; + } + return ( + connection && + connection.resolvedOriginModule === module && + connection.module && + connection.isTargetActive(runtime) + ); + }) + .map((connection) => { + const dep = /** @type {HarmonyImportDependency} */ ( + connection.dependency + ); + return { + connection, + sourceOrder: dep.sourceOrder, + rangeStart: dep.range && dep.range[0], + defer: dep.defer + }; + }); + /** + * bySourceOrder + * @example + * import a from "a"; // sourceOrder=1 + * import b from "b"; // sourceOrder=2 + * + * byRangeStart + * @example + * import {a, b} from "a"; // sourceOrder=1 + * a.a(); // first range + * b.b(); // second range + * + * If the import is deferred, we always move it to the last. + * If there is no reexport, we have the same source. + * If there is reexport, but module has side effects, this will lead to reexport module only. + * If there is side-effects-free reexport, we can get simple deterministic result with range start comparison. + */ + references.sort(concatComparators(bySourceOrder, byRangeStart)); + if (deferEnabled) { + // do not combine those two sorts. defer is not the same as source or range which has a comparable number, defer is only moving them. + references.sort(moveDeferToLast); + } + /** @type {Map} */ + const referencesMap = new Map(); + for (const { connection } of references) { + const runtimeCondition = filterRuntime(runtime, (r) => + connection.isTargetActive(r) + ); + if (runtimeCondition === false) continue; + const module = connection.module; + const entry = referencesMap.get(module); + if (entry === undefined) { + referencesMap.set(module, { connection, runtimeCondition }); + continue; + } + entry.runtimeCondition = mergeRuntimeConditionNonFalse( + entry.runtimeCondition, + runtimeCondition, + runtime + ); + } + return referencesMap.values(); + }; + + /** + * @param {ModuleGraphConnection} connection graph connection + * @param {RuntimeSpec | true} runtimeCondition runtime condition + * @returns {void} + */ + const enterModule = (connection, runtimeCondition) => { + const module = connection.module; + if (!module) return; + const existingEntry = existingEntries.get(module); + if (existingEntry === true) { + return; + } + if (modulesSet.has(module)) { + existingEntries.set(module, true); + if (runtimeCondition !== true) { + throw new Error( + `Cannot runtime-conditional concatenate a module (${module.identifier()} in ${this.rootModule.identifier()}, ${runtimeConditionToString( + runtimeCondition + )}). This should not happen.` + ); + } + const imports = getConcatenatedImports(module); + for (const { connection, runtimeCondition } of imports) { + enterModule(connection, runtimeCondition); + } + list.push({ + type: "concatenated", + module: connection.module, + runtimeCondition + }); + } else { + if (existingEntry !== undefined) { + const reducedRuntimeCondition = subtractRuntimeCondition( + runtimeCondition, + existingEntry, + runtime + ); + if (reducedRuntimeCondition === false) return; + runtimeCondition = reducedRuntimeCondition; + existingEntries.set( + connection.module, + mergeRuntimeConditionNonFalse( + existingEntry, + runtimeCondition, + runtime + ) + ); + } else { + existingEntries.set(connection.module, runtimeCondition); + } + if (list.length > 0) { + const lastItem = list[list.length - 1]; + if ( + lastItem.type === "external" && + lastItem.module === connection.module + ) { + lastItem.runtimeCondition = mergeRuntimeCondition( + lastItem.runtimeCondition, + runtimeCondition, + runtime + ); + return; + } + } + list.push({ + type: "external", + get module() { + // We need to use a getter here, because the module in the dependency + // could be replaced by some other process (i. e. also replaced with a + // concatenated module) + return connection.module; + }, + runtimeCondition + }); + } + }; + + existingEntries.set(rootModule, true); + const imports = getConcatenatedImports(rootModule); + for (const { connection, runtimeCondition } of imports) { + enterModule(connection, runtimeCondition); + } + list.push({ + type: "concatenated", + module: rootModule, + runtimeCondition: true + }); + + return list; + } + + /** + * @param {Module} rootModule the root module of the concatenation + * @param {Set} modules all modules in the concatenation (including the root module) + * @param {AssociatedObjectForCache=} associatedObjectForCache object for caching + * @param {string | HashConstructor=} hashFunction hash function to use + * @returns {string} the identifier + */ + static _createIdentifier( + rootModule, + modules, + associatedObjectForCache, + hashFunction = DEFAULTS.HASH_FUNCTION + ) { + const cachedMakePathsRelative = makePathsRelative.bindContextCache( + /** @type {string} */ (rootModule.context), + associatedObjectForCache + ); + const identifiers = []; + for (const module of modules) { + identifiers.push(cachedMakePathsRelative(module.identifier())); + } + identifiers.sort(); + const hash = createHash(hashFunction); + hash.update(identifiers.join(" ")); + return `${rootModule.identifier()}|${hash.digest("hex")}`; + } + + /** + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to + */ + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) { + for (const module of this._modules) { + module.addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ); + } + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime: generationRuntime, + codeGenerationResults + }) { + const { concatenatedModuleInfo } = ConcatenatedModule.getCompilationHooks( + /** @type {Compilation} */ (this.compilation) + ); + + /** @type {RuntimeRequirements} */ + const runtimeRequirements = new Set(); + const runtime = intersectRuntime(generationRuntime, this._runtime); + + const requestShortener = runtimeTemplate.requestShortener; + // Meta info for each module + const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo( + moduleGraph, + runtime + ); + + // Set with modules that need a generated namespace object + /** @type {Set} */ + const neededNamespaceObjects = new Set(); + + // List of all used names to avoid conflicts + const allUsedNames = new Set(RESERVED_NAMES); + + // Generate source code and analyse scopes + // Prepare a ReplaceSource for the final source + for (const info of moduleToInfoMap.values()) { + this._analyseModule( + moduleToInfoMap, + info, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + /** @type {CodeGenerationResults} */ + (codeGenerationResults), + allUsedNames + ); + } + + // Updated Top level declarations are created by renaming + /** @type {Set} */ + const topLevelDeclarations = new Set(); + + // List of additional names in scope for module references + /** @type {Map} */ + const usedNamesInScopeInfo = new Map(); + + // Set of already checked scopes + const ignoredScopes = new Set(); + + // get all global names + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + // ignore symbols from moduleScope + if (info.moduleScope) { + ignoredScopes.add(info.moduleScope); + } + + // The super class expression in class scopes behaves weird + // We get ranges of all super class expressions to make + // renaming to work correctly + const superClassCache = new WeakMap(); + /** + * @param {Scope} scope scope + * @returns {{ range: Range, variables: Variable[] }[]} result + */ + const getSuperClassExpressions = (scope) => { + const cacheEntry = superClassCache.get(scope); + if (cacheEntry !== undefined) return cacheEntry; + const superClassExpressions = []; + for (const childScope of scope.childScopes) { + if (childScope.type !== "class") continue; + const block = childScope.block; + if ( + (block.type === "ClassDeclaration" || + block.type === "ClassExpression") && + block.superClass + ) { + superClassExpressions.push({ + range: /** @type {Range} */ (block.superClass.range), + variables: childScope.variables + }); + } + } + superClassCache.set(scope, superClassExpressions); + return superClassExpressions; + }; + + // add global symbols + if (info.globalScope) { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + if (ConcatenationScope.isModuleReference(name)) { + const match = ConcatenationScope.matchModuleReference(name); + if (!match) continue; + const referencedInfo = modulesWithInfo[match.index]; + if (referencedInfo.type === "reference") { + throw new Error("Module reference can't point to a reference"); + } + const binding = getFinalBinding( + moduleGraph, + referencedInfo, + match.ids, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + false, + match.deferredImport, + /** @type {BuildMeta} */ + (info.module.buildMeta).strictHarmonyModule, + true + ); + if (!binding.ids) continue; + const { usedNames, alreadyCheckedScopes } = + getUsedNamesInScopeInfo( + usedNamesInScopeInfo, + binding.info.module.identifier(), + "name" in binding ? binding.name : "" + ); + for (const expr of getSuperClassExpressions(reference.from)) { + if ( + expr.range[0] <= + /** @type {Range} */ (reference.identifier.range)[0] && + expr.range[1] >= + /** @type {Range} */ (reference.identifier.range)[1] + ) { + for (const variable of expr.variables) { + usedNames.add(variable.name); + } + } + } + addScopeSymbols( + reference.from, + usedNames, + alreadyCheckedScopes, + ignoredScopes + ); + } else { + allUsedNames.add(name); + } + } + } + } + } + + /** + * @param {string} name the name to find a new name for + * @param {ConcatenatedModuleInfo} info the info of the module + * @param {Reference[]} references the references to the name + * @returns {string|undefined} the new name or undefined if the name is not found + */ + const _findNewName = (name, info, references) => { + const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo( + usedNamesInScopeInfo, + info.module.identifier(), + name + ); + if (allUsedNames.has(name) || usedNames.has(name)) { + for (const ref of references) { + addScopeSymbols( + ref.from, + usedNames, + alreadyCheckedScopes, + ignoredScopes + ); + } + const newName = findNewName( + name, + allUsedNames, + usedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(newName); + info.internalNames.set(name, newName); + topLevelDeclarations.add(newName); + return newName; + } + }; + + /** + * @param {string} name the name to find a new name for + * @param {ConcatenatedModuleInfo} info the info of the module + * @param {Reference[]} references the references to the name + * @returns {string|undefined} the new name or undefined if the name is not found + */ + const _findNewNameForSpecifier = (name, info, references) => { + const { usedNames: moduleUsedNames, alreadyCheckedScopes } = + getUsedNamesInScopeInfo( + usedNamesInScopeInfo, + info.module.identifier(), + name + ); + const referencesUsedNames = new Set(); + for (const ref of references) { + addScopeSymbols( + ref.from, + referencesUsedNames, + alreadyCheckedScopes, + ignoredScopes + ); + } + if (moduleUsedNames.has(name) || referencesUsedNames.has(name)) { + const newName = findNewName( + name, + allUsedNames, + new Set([...moduleUsedNames, ...referencesUsedNames]), + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(newName); + topLevelDeclarations.add(newName); + return newName; + } + }; + + // generate names for symbols + for (const info of moduleToInfoMap.values()) { + const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo( + usedNamesInScopeInfo, + info.module.identifier(), + "" + ); + switch (info.type) { + case "concatenated": { + const variables = /** @type {Scope} */ (info.moduleScope).variables; + for (const variable of variables) { + const name = variable.name; + const references = getAllReferences(variable); + const newName = _findNewName(name, info, references); + if (newName) { + const source = /** @type {ReplaceSource} */ (info.source); + const allIdentifiers = new Set([ + ...references.map((r) => r.identifier), + ...variable.identifiers + ]); + for (const identifier of allIdentifiers) { + const r = /** @type {Range} */ (identifier.range); + const path = getPathInAst( + /** @type {NonNullable} */ + (info.ast), + identifier + ); + if (path && path.length > 1) { + const maybeProperty = + path[1].type === "AssignmentPattern" && + path[1].left === path[0] + ? path[2] + : path[1]; + if ( + maybeProperty.type === "Property" && + maybeProperty.shorthand + ) { + source.insert(r[1], `: ${newName}`); + continue; + } + } + source.replace(r[0], r[1] - 1, newName); + } + } else { + allUsedNames.add(name); + info.internalNames.set(name, name); + topLevelDeclarations.add(name); + } + } + let namespaceObjectName; + if (info.namespaceExportSymbol) { + namespaceObjectName = info.internalNames.get( + info.namespaceExportSymbol + ); + } else { + namespaceObjectName = findNewName( + "namespaceObject", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(namespaceObjectName); + } + info.namespaceObjectName = + /** @type {string} */ + (namespaceObjectName); + topLevelDeclarations.add( + /** @type {string} */ + (namespaceObjectName) + ); + break; + } + case "external": { + const externalName = findNewName( + "", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalName); + info.name = externalName; + topLevelDeclarations.add(externalName); + + if (info.deferred) { + const externalName = findNewName( + "deferred", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalName); + info.deferredName = externalName; + topLevelDeclarations.add(externalName); + + const externalNameInterop = findNewName( + "deferredNamespaceObject", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.deferredNamespaceObjectName = externalNameInterop; + topLevelDeclarations.add(externalNameInterop); + } + break; + } + } + const buildMeta = /** @type {BuildMeta} */ (info.module.buildMeta); + if (buildMeta.exportsType !== "namespace") { + const externalNameInterop = findNewName( + "namespaceObject", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopNamespaceObjectName = externalNameInterop; + topLevelDeclarations.add(externalNameInterop); + } + if ( + buildMeta.exportsType === "default" && + buildMeta.defaultObject !== "redirect" && + info.interopNamespaceObject2Used + ) { + const externalNameInterop = findNewName( + "namespaceObject2", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopNamespaceObject2Name = externalNameInterop; + topLevelDeclarations.add(externalNameInterop); + } + if (buildMeta.exportsType === "dynamic" || !buildMeta.exportsType) { + const externalNameInterop = findNewName( + "default", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopDefaultAccessName = externalNameInterop; + topLevelDeclarations.add(externalNameInterop); + } + } + + // Find and replace references to modules + for (const info of moduleToInfoMap.values()) { + if (info.type === "concatenated") { + const globalScope = /** @type {Scope} */ (info.globalScope); + // group references by name + const referencesByName = new Map(); + for (const reference of globalScope.through) { + const name = reference.identifier.name; + if (!referencesByName.has(name)) { + referencesByName.set(name, []); + } + referencesByName.get(name).push(reference); + } + for (const [name, references] of referencesByName) { + const match = ConcatenationScope.matchModuleReference(name); + if (match) { + const referencedInfo = modulesWithInfo[match.index]; + if (referencedInfo.type === "reference") { + throw new Error("Module reference can't point to a reference"); + } + const concatenationScope = /** @type {ConcatenatedModuleInfo} */ ( + referencedInfo + ).concatenationScope; + const exportId = match.ids[0]; + const specifier = + concatenationScope && concatenationScope.getRawExport(exportId); + if (specifier) { + const newName = _findNewNameForSpecifier( + specifier, + info, + references + ); + const initFragmentChanged = + newName && + concatenatedModuleInfo.call( + { + rawExportMap: new Map([ + [exportId, /** @type {string} */ (newName)] + ]) + }, + /** @type {ConcatenatedModuleInfo} */ (referencedInfo) + ); + if (initFragmentChanged) { + concatenationScope.setRawExportMap(exportId, newName); + } + } + const finalName = getFinalName( + moduleGraph, + referencedInfo, + match.ids, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + match.call, + match.deferredImport, + !match.directImport, + /** @type {BuildMeta} */ + (info.module.buildMeta).strictHarmonyModule, + match.asiSafe + ); + + for (const reference of references) { + const r = /** @type {Range} */ (reference.identifier.range); + const source = /** @type {ReplaceSource} */ (info.source); + // range is extended by 2 chars to cover the appended "._" + source.replace(r[0], r[1] + 1, finalName); + } + } + } + } + } + + // Map with all root exposed used exports + /** @type {Map string>} */ + const exportsMap = new Map(); + + // Set with all root exposed unused exports + /** @type {Set} */ + const unusedExports = new Set(); + + const rootInfo = + /** @type {ConcatenatedModuleInfo} */ + (moduleToInfoMap.get(this.rootModule)); + const strictHarmonyModule = + /** @type {BuildMeta} */ + (rootInfo.module.buildMeta).strictHarmonyModule; + const exportsInfo = moduleGraph.getExportsInfo(rootInfo.module); + /** @type {Record} */ + const exportsFinalName = {}; + for (const exportInfo of exportsInfo.orderedExports) { + const name = exportInfo.name; + if (exportInfo.provided === false) continue; + const used = exportInfo.getUsedName(undefined, runtime); + if (!used) { + unusedExports.add(name); + continue; + } + exportsMap.set(used, (requestShortener) => { + try { + const finalName = getFinalName( + moduleGraph, + rootInfo, + [name], + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + false, + false, + false, + strictHarmonyModule, + true + ); + exportsFinalName[used] = finalName; + return `/* ${ + exportInfo.isReexport() ? "reexport" : "binding" + } */ ${finalName}`; + } catch (err) { + /** @type {Error} */ + (err).message += + `\nwhile generating the root export '${name}' (used name: '${used}')`; + throw err; + } + }); + } + + const result = new ConcatSource(); + + // add harmony compatibility flag (must be first because of possible circular dependencies) + let shouldAddHarmonyFlag = false; + if ( + moduleGraph.getExportsInfo(this).otherExportsInfo.getUsed(runtime) !== + UsageState.Unused + ) { + shouldAddHarmonyFlag = true; + } + + // define exports + if (exportsMap.size > 0) { + const definitions = []; + for (const [key, value] of exportsMap) { + definitions.push( + `\n ${propertyName(key)}: ${runtimeTemplate.returningFunction( + value(requestShortener) + )}` + ); + } + + const { onDemandExportsGeneration } = + ConcatenatedModule.getCompilationHooks( + /** @type {Compilation} */ + (this.compilation) + ); + + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + + if (shouldAddHarmonyFlag) { + result.add("// ESM COMPAT FLAG\n"); + result.add( + runtimeTemplate.defineEsModuleFlagStatement({ + exportsArgument: this.exportsArgument, + runtimeRequirements + }) + ); + } + + if (onDemandExportsGeneration.call(this)) { + /** @type {BuildMeta} */ (this.buildMeta).factoryExportsBinding = + "\n// EXPORTS\n" + + `${RuntimeGlobals.definePropertyGetters}(${ + this.exportsArgument + }, {${definitions.join(",")}\n});\n`; + /** @type {BuildMeta} */ (this.buildMeta).exportsFinalName = + exportsFinalName; + } else { + result.add("\n// EXPORTS\n"); + result.add( + `${RuntimeGlobals.definePropertyGetters}(${ + this.exportsArgument + }, {${definitions.join(",")}\n});\n` + ); + } + } + + // list unused exports + if (unusedExports.size > 0) { + result.add( + `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n` + ); + } + + // generate namespace objects + const namespaceObjectSources = new Map(); + for (const info of neededNamespaceObjects) { + if (info.namespaceExportSymbol) continue; + const nsObj = []; + const exportsInfo = moduleGraph.getExportsInfo(info.module); + for (const exportInfo of exportsInfo.orderedExports) { + if (exportInfo.provided === false) continue; + const usedName = exportInfo.getUsedName(undefined, runtime); + if (usedName) { + const finalName = getFinalName( + moduleGraph, + info, + [exportInfo.name], + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + false, + false, + undefined, + /** @type {BuildMeta} */ + (info.module.buildMeta).strictHarmonyModule, + true + ); + nsObj.push( + `\n ${propertyName(usedName)}: ${runtimeTemplate.returningFunction( + finalName + )}` + ); + } + } + const name = info.namespaceObjectName; + const defineGetters = + nsObj.length > 0 + ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join( + "," + )}\n});\n` + : ""; + if (nsObj.length > 0) { + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + } + namespaceObjectSources.set( + info, + ` +// NAMESPACE OBJECT: ${info.module.readableIdentifier(requestShortener)} +var ${name} = {}; +${RuntimeGlobals.makeNamespaceObject}(${name}); +${defineGetters}` + ); + runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); + } + + // define required namespace objects (must be before evaluation modules) + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + const source = namespaceObjectSources.get(info); + if (!source) continue; + result.add(source); + } + } + + /** @type {InitFragment[]} */ + const chunkInitFragments = []; + const deferEnabled = + /** @type {Compilation} */ + (this.compilation).options.experiments.deferImport; + + // evaluate modules in order + for (const rawInfo of modulesWithInfo) { + let name; + let isConditional = false; + const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo; + switch (info.type) { + case "concatenated": { + result.add( + `\n;// ${info.module.readableIdentifier(requestShortener)}\n` + ); + // If a module is deferred in other places, but used as non-deferred here, + // the module itself will be emitted as mod_deferred (in the case "external"), + // we need to emit an extra import declaration to evaluate it in order. + if (deferEnabled) { + for (const dep of info.module.dependencies) { + if ( + !dep.defer && + dep instanceof HarmonyImportSideEffectDependency + ) { + const referredModule = moduleGraph.getModule(dep); + if (!referredModule) continue; + if (moduleGraph.isDeferred(referredModule)) { + const deferredModuleInfo = /** @type {ExternalModuleInfo} */ ( + modulesWithInfo.find( + (i) => + i.type === "external" && i.module === referredModule + ) + ); + if (!deferredModuleInfo) continue; + result.add( + `\n// non-deferred import to a deferred module (${referredModule.readableIdentifier(requestShortener)})\nvar ${deferredModuleInfo.name} = ${deferredModuleInfo.deferredName}.a;` + ); + } + } + } + } + result.add(/** @type {ReplaceSource} */ (info.source)); + if (info.chunkInitFragments) { + for (const f of info.chunkInitFragments) chunkInitFragments.push(f); + } + if (info.runtimeRequirements) { + for (const r of info.runtimeRequirements) { + runtimeRequirements.add(r); + } + } + name = info.namespaceObjectName; + break; + } + case "external": { + result.add( + `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + runtimeRequirements.add(RuntimeGlobals.require); + const { runtimeCondition } = + /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */ + (rawInfo); + const condition = runtimeTemplate.runtimeConditionExpression({ + chunkGraph, + runtimeCondition, + runtime, + runtimeRequirements + }); + if (condition !== "true") { + isConditional = true; + result.add(`if (${condition}) {\n`); + } + const moduleId = JSON.stringify(chunkGraph.getModuleId(info.module)); + if (info.deferred) { + const loader = getOptimizedDeferredModule( + runtimeTemplate, + info.module.getExportsType( + moduleGraph, + /** @type {BuildMeta} */ + (this.rootModule.buildMeta).strictHarmonyModule + ), + moduleId, + // an async module will opt-out of the concat module optimization. + [] + ); + result.add(`var ${info.deferredName} = ${loader};`); + name = info.deferredName; + } else { + result.add(`var ${info.name} = __webpack_require__(${moduleId});`); + name = info.name; + } + break; + } + default: + // @ts-expect-error never is expected here + throw new Error(`Unsupported concatenation entry type ${info.type}`); + } + if (info.type === "external" && info.deferredNamespaceObjectUsed) { + runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject); + result.add( + `\nvar ${info.deferredNamespaceObjectName} = /*#__PURE__*/${ + RuntimeGlobals.makeDeferredNamespaceObject + }(${JSON.stringify( + chunkGraph.getModuleId(info.module) + )}, ${getMakeDeferredNamespaceModeFromExportsType( + info.module.getExportsType(moduleGraph, strictHarmonyModule) + )});` + ); + } + if (info.interopNamespaceObjectUsed) { + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + result.add( + `\nvar ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2);` + ); + } + if (info.interopNamespaceObject2Used) { + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + result.add( + `\nvar ${info.interopNamespaceObject2Name} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name});` + ); + } + if (info.interopDefaultAccessUsed) { + runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); + result.add( + `\nvar ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${name});` + ); + } + if (isConditional) { + result.add("\n}"); + } + } + + const data = new Map(); + if (chunkInitFragments.length > 0) { + data.set("chunkInitFragments", chunkInitFragments); + } + data.set("topLevelDeclarations", topLevelDeclarations); + + /** @type {CodeGenerationResult} */ + const resultEntry = { + sources: new Map([["javascript", new CachedSource(result)]]), + data, + runtimeRequirements + }; + + return resultEntry; + } + + /** + * @param {Map} modulesMap modulesMap + * @param {ModuleInfo} info info + * @param {DependencyTemplates} dependencyTemplates dependencyTemplates + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {RuntimeSpec} runtime runtime + * @param {CodeGenerationResults} codeGenerationResults codeGenerationResults + * @param {Set} usedNames used names + */ + _analyseModule( + modulesMap, + info, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + codeGenerationResults, + usedNames + ) { + if (info.type === "concatenated") { + const m = info.module; + try { + // Create a concatenation scope to track and capture information + const concatenationScope = new ConcatenationScope( + modulesMap, + info, + usedNames + ); + + // TODO cache codeGeneration results + const codeGenResult = m.codeGeneration({ + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + concatenationScope, + codeGenerationResults, + sourceTypes: JS_TYPES + }); + const source = + /** @type {Source} */ + (codeGenResult.sources.get("javascript")); + const data = codeGenResult.data; + const chunkInitFragments = data && data.get("chunkInitFragments"); + const code = source.source().toString(); + let ast; + try { + ast = JavascriptParser._parse(code, { + sourceType: "module" + }); + } catch (_err) { + const err = + /** @type {Error & { loc?: { line: number, column: number } }} */ + (_err); + if ( + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + const lineNumber = err.loc.line; + const lines = code.split("\n"); + err.message += `\n| ${lines + .slice(Math.max(0, lineNumber - 3), lineNumber + 2) + .join("\n| ")}`; + } + throw err; + } + const scopeManager = eslintScope.analyze(ast, { + ecmaVersion: 6, + sourceType: "module", + optimistic: true, + ignoreEval: true, + impliedStrict: true + }); + const globalScope = /** @type {Scope} */ (scopeManager.acquire(ast)); + const moduleScope = globalScope.childScopes[0]; + const resultSource = new ReplaceSource(source); + info.runtimeRequirements = + /** @type {ReadOnlyRuntimeRequirements} */ + (codeGenResult.runtimeRequirements); + info.ast = ast; + info.internalSource = source; + info.source = resultSource; + info.chunkInitFragments = chunkInitFragments; + info.globalScope = globalScope; + info.moduleScope = moduleScope; + info.concatenationScope = concatenationScope; + } catch (err) { + /** @type {Error} */ + (err).message += + `\nwhile analyzing module ${m.identifier()} for concatenation`; + throw err; + } + } + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @returns {[ModuleInfoOrReference[], Map]} module info items + */ + _getModulesWithInfo(moduleGraph, runtime) { + const orderedConcatenationList = this._createConcatenationList( + this.rootModule, + this._modules, + runtime, + moduleGraph + ); + /** @type {Map} */ + const map = new Map(); + const list = orderedConcatenationList.map((info, index) => { + let item = map.get(info.module); + if (item === undefined) { + switch (info.type) { + case "concatenated": + item = { + type: "concatenated", + module: info.module, + index, + ast: undefined, + internalSource: undefined, + runtimeRequirements: undefined, + source: undefined, + globalScope: undefined, + moduleScope: undefined, + internalNames: new Map(), + exportMap: undefined, + rawExportMap: undefined, + namespaceExportSymbol: undefined, + namespaceObjectName: undefined, + interopNamespaceObjectUsed: false, + interopNamespaceObjectName: undefined, + interopNamespaceObject2Used: false, + interopNamespaceObject2Name: undefined, + interopDefaultAccessUsed: false, + interopDefaultAccessName: undefined, + concatenationScope: undefined + }; + break; + case "external": + item = { + type: "external", + module: info.module, + runtimeCondition: info.runtimeCondition, + index, + name: undefined, + deferredName: undefined, + interopNamespaceObjectUsed: false, + interopNamespaceObjectName: undefined, + interopNamespaceObject2Used: false, + interopNamespaceObject2Name: undefined, + interopDefaultAccessUsed: false, + interopDefaultAccessName: undefined, + deferred: moduleGraph.isDeferred(info.module), + deferredNamespaceObjectName: undefined, + deferredNamespaceObjectUsed: false + }; + break; + default: + throw new Error( + `Unsupported concatenation entry type ${info.type}` + ); + } + map.set( + /** @type {ModuleInfo} */ (item).module, + /** @type {ModuleInfo} */ (item) + ); + return /** @type {ModuleInfo} */ (item); + } + /** @type {ReferenceToModuleInfo} */ + const ref = { + type: "reference", + runtimeCondition: info.runtimeCondition, + target: item + }; + return ref; + }); + return [list, map]; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const { chunkGraph, runtime } = context; + for (const info of this._createConcatenationList( + this.rootModule, + this._modules, + intersectRuntime(runtime, this._runtime), + chunkGraph.moduleGraph + )) { + switch (info.type) { + case "concatenated": + info.module.updateHash(hash, context); + break; + case "external": + hash.update(`${chunkGraph.getModuleId(info.module)}`); + // TODO runtimeCondition + break; + } + } + super.updateHash(hash, context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {ConcatenatedModule} ConcatenatedModule + */ + static deserialize(context) { + const obj = new ConcatenatedModule({ + identifier: /** @type {EXPECTED_ANY} */ (undefined), + rootModule: /** @type {EXPECTED_ANY} */ (undefined), + modules: /** @type {EXPECTED_ANY} */ (undefined), + runtime: undefined, + compilation: /** @type {EXPECTED_ANY} */ (undefined) + }); + obj.deserialize(context); + return obj; + } +} + +makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule"); + +module.exports = ConcatenatedModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/EnsureChunkConditionsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/EnsureChunkConditionsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d6210f1879883f27275b868bc38bd7cec4a3e181 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/EnsureChunkConditionsPlugin.js @@ -0,0 +1,88 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { STAGE_BASIC } = require("../OptimizationStages"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "EnsureChunkConditionsPlugin"; + +class EnsureChunkConditionsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + /** + * @param {Iterable} chunks the chunks + */ + const handler = (chunks) => { + const chunkGraph = compilation.chunkGraph; + // These sets are hoisted here to save memory + // They are cleared at the end of every loop + /** @type {Set} */ + const sourceChunks = new Set(); + /** @type {Set} */ + const chunkGroups = new Set(); + for (const module of compilation.modules) { + if (!module.hasChunkCondition()) continue; + for (const chunk of chunkGraph.getModuleChunksIterable(module)) { + if (!module.chunkCondition(chunk, compilation)) { + sourceChunks.add(chunk); + for (const group of chunk.groupsIterable) { + chunkGroups.add(group); + } + } + } + if (sourceChunks.size === 0) continue; + /** @type {Set} */ + const targetChunks = new Set(); + chunkGroupLoop: for (const chunkGroup of chunkGroups) { + // Can module be placed in a chunk of this group? + for (const chunk of chunkGroup.chunks) { + if (module.chunkCondition(chunk, compilation)) { + targetChunks.add(chunk); + continue chunkGroupLoop; + } + } + // We reached the entrypoint: fail + if (chunkGroup.isInitial()) { + throw new Error( + `Cannot fulfil chunk condition of ${module.identifier()}` + ); + } + // Try placing in all parents + for (const group of chunkGroup.parentsIterable) { + chunkGroups.add(group); + } + } + for (const sourceChunk of sourceChunks) { + chunkGraph.disconnectChunkAndModule(sourceChunk, module); + } + for (const targetChunk of targetChunks) { + chunkGraph.connectChunkAndModule(targetChunk, module); + } + sourceChunks.clear(); + chunkGroups.clear(); + } + }; + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: STAGE_BASIC + }, + handler + ); + }); + } +} + +module.exports = EnsureChunkConditionsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/FlagIncludedChunksPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/FlagIncludedChunksPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..78e74d47feac555af09e25f1902e65e5c19efed3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/FlagIncludedChunksPlugin.js @@ -0,0 +1,127 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { compareIds } = require("../util/comparators"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Chunk").ChunkId} ChunkId */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +const PLUGIN_NAME = "FlagIncludedChunksPlugin"; + +class FlagIncludedChunksPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.optimizeChunkIds.tap(PLUGIN_NAME, (chunks) => { + const chunkGraph = compilation.chunkGraph; + + // prepare two bit integers for each module + // 2^31 is the max number represented as SMI in v8 + // we want the bits distributed this way: + // the bit 2^31 is pretty rar and only one module should get it + // so it has a probability of 1 / modulesCount + // the first bit (2^0) is the easiest and every module could get it + // if it doesn't get a better bit + // from bit 2^n to 2^(n+1) there is a probability of p + // so 1 / modulesCount == p^31 + // <=> p = sqrt31(1 / modulesCount) + // so we use a modulo of 1 / sqrt31(1 / modulesCount) + /** @type {WeakMap} */ + const moduleBits = new WeakMap(); + const modulesCount = compilation.modules.size; + + // precalculate the modulo values for each bit + const modulo = 1 / (1 / modulesCount) ** (1 / 31); + const modulos = Array.from({ length: 31 }, (x, i) => (modulo ** i) | 0); + + // iterate all modules to generate bit values + let i = 0; + for (const module of compilation.modules) { + let bit = 30; + while (i % modulos[bit] !== 0) { + bit--; + } + moduleBits.set(module, 1 << bit); + i++; + } + + // iterate all chunks to generate bitmaps + /** @type {WeakMap} */ + const chunkModulesHash = new WeakMap(); + for (const chunk of chunks) { + let hash = 0; + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + hash |= /** @type {number} */ (moduleBits.get(module)); + } + chunkModulesHash.set(chunk, hash); + } + + for (const chunkA of chunks) { + const chunkAHash = + /** @type {number} */ + (chunkModulesHash.get(chunkA)); + const chunkAModulesCount = chunkGraph.getNumberOfChunkModules(chunkA); + if (chunkAModulesCount === 0) continue; + let bestModule; + for (const module of chunkGraph.getChunkModulesIterable(chunkA)) { + if ( + bestModule === undefined || + chunkGraph.getNumberOfModuleChunks(bestModule) > + chunkGraph.getNumberOfModuleChunks(module) + ) { + bestModule = module; + } + } + loopB: for (const chunkB of chunkGraph.getModuleChunksIterable( + /** @type {Module} */ (bestModule) + )) { + // as we iterate the same iterables twice + // skip if we find ourselves + if (chunkA === chunkB) continue; + + const chunkBModulesCount = + chunkGraph.getNumberOfChunkModules(chunkB); + + // ids for empty chunks are not included + if (chunkBModulesCount === 0) continue; + + // instead of swapping A and B just bail + // as we loop twice the current A will be B and B then A + if (chunkAModulesCount > chunkBModulesCount) continue; + + // is chunkA in chunkB? + + // we do a cheap check for the hash value + const chunkBHash = + /** @type {number} */ + (chunkModulesHash.get(chunkB)); + if ((chunkBHash & chunkAHash) !== chunkAHash) continue; + + // compare all modules + for (const m of chunkGraph.getChunkModulesIterable(chunkA)) { + if (!chunkGraph.isModuleInChunk(m, chunkB)) continue loopB; + } + + /** @type {ChunkId[]} */ + (chunkB.ids).push(/** @type {ChunkId} */ (chunkA.id)); + // https://github.com/webpack/webpack/issues/18837 + /** @type {ChunkId[]} */ + (chunkB.ids).sort(compareIds); + } + } + }); + }); + } +} + +module.exports = FlagIncludedChunksPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/InnerGraph.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/InnerGraph.js new file mode 100644 index 0000000000000000000000000000000000000000..ee37d3dc84834bf3e8e9c67414fd4e4ecaa23ef7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/InnerGraph.js @@ -0,0 +1,360 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + +"use strict"; + +const { UsageState } = require("../ExportsInfo"); +const JavascriptParser = require("../javascript/JavascriptParser"); + +/** @typedef {import("estree").Node} AnyNode */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** @typedef {Map | true | undefined>} InnerGraph */ +/** @typedef {(value: boolean | Set | undefined) => void} UsageCallback */ + +/** + * @typedef {object} StateObject + * @property {InnerGraph} innerGraph + * @property {TopLevelSymbol=} currentTopLevelSymbol + * @property {Map>} usageCallbackMap + */ + +/** @typedef {false|StateObject} State */ + +class TopLevelSymbol { + /** + * @param {string} name name of the variable + */ + constructor(name) { + this.name = name; + } +} + +module.exports.TopLevelSymbol = TopLevelSymbol; + +/** @type {WeakMap} */ +const parserStateMap = new WeakMap(); +const topLevelSymbolTag = Symbol("top level symbol"); + +/** + * @param {ParserState} parserState parser state + * @returns {State | undefined} state + */ +function getState(parserState) { + return parserStateMap.get(parserState); +} + +/** + * @param {ParserState} state parser state + * @param {TopLevelSymbol | null} symbol the symbol, or null for all symbols + * @param {string | TopLevelSymbol | true} usage usage data + * @returns {void} + */ +module.exports.addUsage = (state, symbol, usage) => { + const innerGraphState = getState(state); + + if (innerGraphState) { + const { innerGraph } = innerGraphState; + const info = innerGraph.get(symbol); + if (usage === true) { + innerGraph.set(symbol, true); + } else if (info === undefined) { + innerGraph.set(symbol, new Set([usage])); + } else if (info !== true) { + info.add(usage); + } + } +}; + +/** + * @param {JavascriptParser} parser the parser + * @param {string} name name of variable + * @param {string | TopLevelSymbol | true} usage usage data + * @returns {void} + */ +module.exports.addVariableUsage = (parser, name, usage) => { + const symbol = + /** @type {TopLevelSymbol} */ ( + parser.getTagData(name, topLevelSymbolTag) + ) || module.exports.tagTopLevelSymbol(parser, name); + if (symbol) { + module.exports.addUsage(parser.state, symbol, usage); + } +}; + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +module.exports.bailout = (parserState) => { + parserStateMap.set(parserState, false); +}; + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +module.exports.enable = (parserState) => { + const state = parserStateMap.get(parserState); + if (state === false) { + return; + } + parserStateMap.set(parserState, { + innerGraph: new Map(), + currentTopLevelSymbol: undefined, + usageCallbackMap: new Map() + }); +}; + +/** + * @param {Dependency} dependency the dependency + * @param {Set | boolean | undefined} usedByExports usedByExports info + * @param {ModuleGraph} moduleGraph moduleGraph + * @returns {null | false | GetConditionFn} function to determine if the connection is active + */ +module.exports.getDependencyUsedByExportsCondition = ( + dependency, + usedByExports, + moduleGraph +) => { + if (usedByExports === false) return false; + if (usedByExports !== true && usedByExports !== undefined) { + const selfModule = + /** @type {Module} */ + (moduleGraph.getParentModule(dependency)); + const exportsInfo = moduleGraph.getExportsInfo(selfModule); + return (connections, runtime) => { + for (const exportName of usedByExports) { + if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) { + return true; + } + } + return false; + }; + } + return null; +}; + +/** + * @param {ParserState} state parser state + * @returns {TopLevelSymbol|void} usage data + */ +module.exports.getTopLevelSymbol = (state) => { + const innerGraphState = getState(state); + + if (innerGraphState) { + return innerGraphState.currentTopLevelSymbol; + } +}; + +/** + * @param {ParserState} state parser state + * @returns {void} + */ +module.exports.inferDependencyUsage = (state) => { + const innerGraphState = getState(state); + + if (!innerGraphState) { + return; + } + + const { innerGraph, usageCallbackMap } = innerGraphState; + const processed = new Map(); + // flatten graph to terminal nodes (string, undefined or true) + const nonTerminal = new Set(innerGraph.keys()); + while (nonTerminal.size > 0) { + for (const key of nonTerminal) { + /** @type {Set | true} */ + let newSet = new Set(); + let isTerminal = true; + const value = innerGraph.get(key); + let alreadyProcessed = processed.get(key); + if (alreadyProcessed === undefined) { + alreadyProcessed = new Set(); + processed.set(key, alreadyProcessed); + } + if (value !== true && value !== undefined) { + for (const item of value) { + alreadyProcessed.add(item); + } + for (const item of value) { + if (typeof item === "string") { + newSet.add(item); + } else { + const itemValue = innerGraph.get(item); + if (itemValue === true) { + newSet = true; + break; + } + if (itemValue !== undefined) { + for (const i of itemValue) { + if (i === key) continue; + if (alreadyProcessed.has(i)) continue; + newSet.add(i); + if (typeof i !== "string") { + isTerminal = false; + } + } + } + } + } + if (newSet === true) { + innerGraph.set(key, true); + } else if (newSet.size === 0) { + innerGraph.set(key, undefined); + } else { + innerGraph.set(key, newSet); + } + } + if (isTerminal) { + nonTerminal.delete(key); + + // For the global key, merge with all other keys + if (key === null) { + const globalValue = innerGraph.get(null); + if (globalValue) { + for (const [key, value] of innerGraph) { + if (key !== null && value !== true) { + if (globalValue === true) { + innerGraph.set(key, true); + } else { + const newSet = new Set(value); + for (const item of globalValue) { + newSet.add(item); + } + innerGraph.set(key, newSet); + } + } + } + } + } + } + } + } + + /** @type {Map>} */ + for (const [symbol, callbacks] of usageCallbackMap) { + const usage = /** @type {true | Set | undefined} */ ( + innerGraph.get(symbol) + ); + for (const callback of callbacks) { + callback(usage === undefined ? false : usage); + } + } +}; + +/** + * @param {Dependency} dependency the dependency + * @param {Set | boolean} usedByExports usedByExports info + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {RuntimeSpec} runtime runtime + * @returns {boolean} false, when unused. Otherwise true + */ +module.exports.isDependencyUsedByExports = ( + dependency, + usedByExports, + moduleGraph, + runtime +) => { + if (usedByExports === false) return false; + if (usedByExports !== true && usedByExports !== undefined) { + const selfModule = + /** @type {Module} */ + (moduleGraph.getParentModule(dependency)); + const exportsInfo = moduleGraph.getExportsInfo(selfModule); + let used = false; + for (const exportName of usedByExports) { + if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) { + used = true; + } + } + if (!used) return false; + } + return true; +}; + +/** + * @param {ParserState} parserState parser state + * @returns {boolean} true, when enabled + */ +module.exports.isEnabled = (parserState) => { + const state = parserStateMap.get(parserState); + return Boolean(state); +}; + +/** + * @param {ParserState} state parser state + * @param {UsageCallback} onUsageCallback on usage callback + */ +module.exports.onUsage = (state, onUsageCallback) => { + const innerGraphState = getState(state); + + if (innerGraphState) { + const { usageCallbackMap, currentTopLevelSymbol } = innerGraphState; + if (currentTopLevelSymbol) { + let callbacks = usageCallbackMap.get(currentTopLevelSymbol); + + if (callbacks === undefined) { + callbacks = new Set(); + usageCallbackMap.set(currentTopLevelSymbol, callbacks); + } + + callbacks.add(onUsageCallback); + } else { + onUsageCallback(true); + } + } else { + onUsageCallback(undefined); + } +}; + +/** + * @param {ParserState} state parser state + * @param {TopLevelSymbol | undefined} symbol the symbol + */ +module.exports.setTopLevelSymbol = (state, symbol) => { + const innerGraphState = getState(state); + + if (innerGraphState) { + innerGraphState.currentTopLevelSymbol = symbol; + } +}; + +/** + * @param {JavascriptParser} parser parser + * @param {string} name name of variable + * @returns {TopLevelSymbol | undefined} symbol + */ +module.exports.tagTopLevelSymbol = (parser, name) => { + const innerGraphState = getState(parser.state); + if (!innerGraphState) return; + + parser.defineVariable(name); + + const existingTag = /** @type {TopLevelSymbol} */ ( + parser.getTagData(name, topLevelSymbolTag) + ); + if (existingTag) { + return existingTag; + } + + const fn = new TopLevelSymbol(name); + parser.tagVariable( + name, + topLevelSymbolTag, + fn, + JavascriptParser.VariableInfoFlags.Normal + ); + return fn; +}; + +module.exports.topLevelSymbolTag = topLevelSymbolTag; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/InnerGraphPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/InnerGraphPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..aee400627c003816b18d19c656872330435bd1ab --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/InnerGraphPlugin.js @@ -0,0 +1,458 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("../ModuleTypeConstants"); +const PureExpressionDependency = require("../dependencies/PureExpressionDependency"); +const InnerGraph = require("./InnerGraph"); + +/** @typedef {import("estree").ClassDeclaration} ClassDeclaration */ +/** @typedef {import("estree").ClassExpression} ClassExpression */ +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").MaybeNamedClassDeclaration} MaybeNamedClassDeclaration */ +/** @typedef {import("estree").MaybeNamedFunctionDeclaration} MaybeNamedFunctionDeclaration */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").VariableDeclarator} VariableDeclarator */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("./InnerGraph").InnerGraph} InnerGraph */ +/** @typedef {import("./InnerGraph").TopLevelSymbol} TopLevelSymbol */ + +const { topLevelSymbolTag } = InnerGraph; + +const PLUGIN_NAME = "InnerGraphPlugin"; + +class InnerGraphPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + const logger = compilation.getLogger("webpack.InnerGraphPlugin"); + + compilation.dependencyTemplates.set( + PureExpressionDependency, + new PureExpressionDependency.Template() + ); + + /** + * @param {JavascriptParser} parser the parser + * @param {JavascriptParserOptions} parserOptions options + * @returns {void} + */ + const handler = (parser, parserOptions) => { + /** + * @param {Expression} sup sup + */ + const onUsageSuper = (sup) => { + InnerGraph.onUsage(parser.state, (usedByExports) => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + /** @type {Range} */ + (sup.range) + ); + dep.loc = /** @type {DependencyLocation} */ (sup.loc); + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + }; + + parser.hooks.program.tap(PLUGIN_NAME, () => { + InnerGraph.enable(parser.state); + }); + + parser.hooks.finish.tap(PLUGIN_NAME, () => { + if (!InnerGraph.isEnabled(parser.state)) return; + + logger.time("infer dependency usage"); + InnerGraph.inferDependencyUsage(parser.state); + logger.timeAggregate("infer dependency usage"); + }); + + // During prewalking the following datastructures are filled with + // nodes that have a TopLevelSymbol assigned and + // variables are tagged with the assigned TopLevelSymbol + + // We differ 3 types of nodes: + // 1. full statements (export default, function declaration) + // 2. classes (class declaration, class expression) + // 3. variable declarators (const x = ...) + + /** @type {WeakMap} */ + const statementWithTopLevelSymbol = new WeakMap(); + /** @type {WeakMap} */ + const statementPurePart = new WeakMap(); + + /** @type {WeakMap} */ + const classWithTopLevelSymbol = new WeakMap(); + + /** @type {WeakMap} */ + const declWithTopLevelSymbol = new WeakMap(); + /** @type {WeakSet} */ + const pureDeclarators = new WeakSet(); + + // The following hooks are used during prewalking: + + parser.hooks.preStatement.tap(PLUGIN_NAME, (statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + + if ( + parser.scope.topLevelScope === true && + statement.type === "FunctionDeclaration" + ) { + const name = statement.id ? statement.id.name : "*default*"; + const fn = + /** @type {TopLevelSymbol} */ + (InnerGraph.tagTopLevelSymbol(parser, name)); + statementWithTopLevelSymbol.set(statement, fn); + return true; + } + }); + + parser.hooks.blockPreStatement.tap(PLUGIN_NAME, (statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + + if (parser.scope.topLevelScope === true) { + if ( + statement.type === "ClassDeclaration" && + parser.isPure( + statement, + /** @type {Range} */ (statement.range)[0] + ) + ) { + const name = statement.id ? statement.id.name : "*default*"; + const fn = /** @type {TopLevelSymbol} */ ( + InnerGraph.tagTopLevelSymbol(parser, name) + ); + classWithTopLevelSymbol.set(statement, fn); + return true; + } + if (statement.type === "ExportDefaultDeclaration") { + const name = "*default*"; + const fn = + /** @type {TopLevelSymbol} */ + (InnerGraph.tagTopLevelSymbol(parser, name)); + const decl = statement.declaration; + if ( + (decl.type === "ClassExpression" || + decl.type === "ClassDeclaration") && + parser.isPure( + /** @type {ClassExpression | ClassDeclaration} */ + (decl), + /** @type {Range} */ + (decl.range)[0] + ) + ) { + classWithTopLevelSymbol.set( + /** @type {ClassExpression | ClassDeclaration} */ + (decl), + fn + ); + } else if ( + parser.isPure( + /** @type {Expression} */ + (decl), + /** @type {Range} */ + (statement.range)[0] + ) + ) { + statementWithTopLevelSymbol.set(statement, fn); + if ( + !decl.type.endsWith("FunctionExpression") && + !decl.type.endsWith("Declaration") && + decl.type !== "Literal" + ) { + statementPurePart.set( + statement, + /** @type {Expression} */ + (decl) + ); + } + } + } + } + }); + + parser.hooks.preDeclarator.tap(PLUGIN_NAME, (decl, _statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if ( + parser.scope.topLevelScope === true && + decl.init && + decl.id.type === "Identifier" + ) { + const name = decl.id.name; + if ( + decl.init.type === "ClassExpression" && + parser.isPure( + decl.init, + /** @type {Range} */ (decl.id.range)[1] + ) + ) { + const fn = + /** @type {TopLevelSymbol} */ + (InnerGraph.tagTopLevelSymbol(parser, name)); + classWithTopLevelSymbol.set(decl.init, fn); + } else if ( + parser.isPure( + decl.init, + /** @type {Range} */ (decl.id.range)[1] + ) + ) { + const fn = + /** @type {TopLevelSymbol} */ + (InnerGraph.tagTopLevelSymbol(parser, name)); + declWithTopLevelSymbol.set(decl, fn); + if ( + !decl.init.type.endsWith("FunctionExpression") && + decl.init.type !== "Literal" + ) { + pureDeclarators.add(decl); + } + } + } + }); + + // During real walking we set the TopLevelSymbol state to the assigned + // TopLevelSymbol by using the fill datastructures. + + // In addition to tracking TopLevelSymbols, we sometimes need to + // add a PureExpressionDependency. This is needed to skip execution + // of pure expressions, even when they are not dropped due to + // minimizing. Otherwise symbols used there might not exist anymore + // as they are removed as unused by this optimization + + // When we find a reference to a TopLevelSymbol, we register a + // TopLevelSymbol dependency from TopLevelSymbol in state to the + // referenced TopLevelSymbol. This way we get a graph of all + // TopLevelSymbols. + + // The following hooks are called during walking: + + parser.hooks.statement.tap(PLUGIN_NAME, (statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + InnerGraph.setTopLevelSymbol(parser.state, undefined); + + const fn = statementWithTopLevelSymbol.get(statement); + if (fn) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + const purePart = statementPurePart.get(statement); + if (purePart) { + InnerGraph.onUsage(parser.state, (usedByExports) => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + /** @type {Range} */ (purePart.range) + ); + dep.loc = + /** @type {DependencyLocation} */ + (statement.loc); + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + } + } + } + }); + + parser.hooks.classExtendsExpression.tap( + PLUGIN_NAME, + (expr, statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + const fn = classWithTopLevelSymbol.get(statement); + if ( + fn && + parser.isPure( + expr, + statement.id + ? /** @type {Range} */ (statement.id.range)[1] + : /** @type {Range} */ (statement.range)[0] + ) + ) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + onUsageSuper(expr); + } + } + } + ); + + parser.hooks.classBodyElement.tap( + PLUGIN_NAME, + (element, classDefinition) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + const fn = classWithTopLevelSymbol.get(classDefinition); + if (fn) { + InnerGraph.setTopLevelSymbol(parser.state, undefined); + } + } + } + ); + + parser.hooks.classBodyValue.tap( + PLUGIN_NAME, + (expression, element, classDefinition) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + const fn = classWithTopLevelSymbol.get(classDefinition); + if (fn) { + if ( + !element.static || + parser.isPure( + expression, + element.key + ? /** @type {Range} */ (element.key.range)[1] + : /** @type {Range} */ (element.range)[0] + ) + ) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + if (element.type !== "MethodDefinition" && element.static) { + InnerGraph.onUsage(parser.state, (usedByExports) => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + /** @type {Range} */ (expression.range) + ); + dep.loc = + /** @type {DependencyLocation} */ + (expression.loc); + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + } + } else { + InnerGraph.setTopLevelSymbol(parser.state, undefined); + } + } + } + } + ); + + parser.hooks.declarator.tap(PLUGIN_NAME, (decl, _statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + const fn = declWithTopLevelSymbol.get(decl); + + if (fn) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + if (pureDeclarators.has(decl)) { + if ( + /** @type {ClassExpression} */ + (decl.init).type === "ClassExpression" + ) { + if (decl.init.superClass) { + onUsageSuper(decl.init.superClass); + } + } else { + InnerGraph.onUsage(parser.state, (usedByExports) => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + /** @type {Range} */ ( + /** @type {ClassExpression} */ + (decl.init).range + ) + ); + dep.loc = /** @type {DependencyLocation} */ (decl.loc); + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + } + } + parser.walkExpression( + /** @type {NonNullable} */ ( + decl.init + ) + ); + InnerGraph.setTopLevelSymbol(parser.state, undefined); + return true; + } else if ( + decl.id.type === "Identifier" && + decl.init && + decl.init.type === "ClassExpression" && + classWithTopLevelSymbol.has(decl.init) + ) { + parser.walkExpression(decl.init); + InnerGraph.setTopLevelSymbol(parser.state, undefined); + return true; + } + }); + + parser.hooks.expression + .for(topLevelSymbolTag) + .tap(PLUGIN_NAME, () => { + const topLevelSymbol = /** @type {TopLevelSymbol} */ ( + parser.currentTagData + ); + const currentTopLevelSymbol = InnerGraph.getTopLevelSymbol( + parser.state + ); + InnerGraph.addUsage( + parser.state, + topLevelSymbol, + currentTopLevelSymbol || true + ); + }); + parser.hooks.assign + .for(topLevelSymbolTag) + .tap(PLUGIN_NAME, (expr) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (expr.operator === "=") return true; + }); + }; + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_AUTO) + .tap(PLUGIN_NAME, handler); + normalModuleFactory.hooks.parser + .for(JAVASCRIPT_MODULE_TYPE_ESM) + .tap(PLUGIN_NAME, handler); + + compilation.hooks.finishModules.tap(PLUGIN_NAME, () => { + logger.timeAggregateEnd("infer dependency usage"); + }); + } + ); + } +} + +module.exports = InnerGraphPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/LimitChunkCountPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/LimitChunkCountPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..74ed24815e92742cdb54612184a9b2b40fd4eb08 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/LimitChunkCountPlugin.js @@ -0,0 +1,301 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { STAGE_ADVANCED } = require("../OptimizationStages"); +const LazyBucketSortedSet = require("../util/LazyBucketSortedSet"); +const { compareChunks } = require("../util/comparators"); +const createSchemaValidation = require("../util/create-schema-validation"); + +/** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/optimize/LimitChunkCountPlugin.check"), + () => require("../../schemas/plugins/optimize/LimitChunkCountPlugin.json"), + { + name: "Limit Chunk Count Plugin", + baseDataPath: "options" + } +); + +/** + * @typedef {object} ChunkCombination + * @property {boolean} deleted this is set to true when combination was removed + * @property {number} sizeDiff + * @property {number} integratedSize + * @property {Chunk} a + * @property {Chunk} b + * @property {number} aIdx + * @property {number} bIdx + * @property {number} aSize + * @property {number} bSize + */ + +/** + * @template K, V + * @param {Map>} map map + * @param {K} key key + * @param {V} value value + */ +const addToSetMap = (map, key, value) => { + const set = map.get(key); + if (set === undefined) { + map.set(key, new Set([value])); + } else { + set.add(value); + } +}; + +const PLUGIN_NAME = "LimitChunkCountPlugin"; + +class LimitChunkCountPlugin { + /** + * @param {LimitChunkCountPluginOptions=} options options object + */ + constructor(options) { + validate(options); + this.options = /** @type {LimitChunkCountPluginOptions} */ (options); + } + + /** + * @param {Compiler} compiler the webpack compiler + * @returns {void} + */ + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: STAGE_ADVANCED + }, + (chunks) => { + const chunkGraph = compilation.chunkGraph; + const maxChunks = options.maxChunks; + if (!maxChunks) return; + if (maxChunks < 1) return; + if (compilation.chunks.size <= maxChunks) return; + + let remainingChunksToMerge = compilation.chunks.size - maxChunks; + + // order chunks in a deterministic way + const compareChunksWithGraph = compareChunks(chunkGraph); + /** @type {Chunk[]} */ + const orderedChunks = [...chunks].sort(compareChunksWithGraph); + + // create a lazy sorted data structure to keep all combinations + // this is large. Size = chunks * (chunks - 1) / 2 + // It uses a multi layer bucket sort plus normal sort in the last layer + // It's also lazy so only accessed buckets are sorted + /** @type {LazyBucketSortedSet} */ + const combinations = new LazyBucketSortedSet( + // Layer 1: ordered by largest size benefit + (c) => c.sizeDiff, + (a, b) => b - a, + + // Layer 2: ordered by smallest combined size + /** + * @param {ChunkCombination} c combination + * @returns {number} integrated size + */ + (c) => c.integratedSize, + /** + * @param {number} a a + * @param {number} b b + * @returns {number} result + */ + (a, b) => a - b, + + // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic) + /** + * @param {ChunkCombination} c combination + * @returns {number} position difference + */ + (c) => c.bIdx - c.aIdx, + /** + * @param {number} a a + * @param {number} b b + * @returns {number} result + */ + (a, b) => a - b, + + // Layer 4: ordered by position in orderedChunk (-> to be deterministic) + /** + * @param {ChunkCombination} a a + * @param {ChunkCombination} b b + * @returns {number} result + */ + (a, b) => a.bIdx - b.bIdx + ); + + // we keep a mapping from chunk to all combinations + // but this mapping is not kept up-to-date with deletions + // so `deleted` flag need to be considered when iterating this + /** @type {Map>} */ + const combinationsByChunk = new Map(); + + for (const [bIdx, b] of orderedChunks.entries()) { + // create combination pairs with size and integrated size + for (let aIdx = 0; aIdx < bIdx; aIdx++) { + const a = orderedChunks[aIdx]; + // filter pairs that can not be integrated! + if (!chunkGraph.canChunksBeIntegrated(a, b)) continue; + + const integratedSize = chunkGraph.getIntegratedChunksSize( + a, + b, + options + ); + + const aSize = chunkGraph.getChunkSize(a, options); + const bSize = chunkGraph.getChunkSize(b, options); + /** @type {ChunkCombination} */ + const c = { + deleted: false, + sizeDiff: aSize + bSize - integratedSize, + integratedSize, + a, + b, + aIdx, + bIdx, + aSize, + bSize + }; + combinations.add(c); + addToSetMap(combinationsByChunk, a, c); + addToSetMap(combinationsByChunk, b, c); + } + } + + // list of modified chunks during this run + // combinations affected by this change are skipped to allow + // further optimizations + /** @type {Set} */ + const modifiedChunks = new Set(); + + let changed = false; + loop: while (true) { + const combination = combinations.popFirst(); + if (combination === undefined) break; + + combination.deleted = true; + const { a, b, integratedSize } = combination; + + // skip over pair when + // one of the already merged chunks is a parent of one of the chunks + if (modifiedChunks.size > 0) { + const queue = new Set(a.groupsIterable); + for (const group of b.groupsIterable) { + queue.add(group); + } + for (const group of queue) { + for (const mChunk of modifiedChunks) { + if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) { + // This is a potential pair which needs recalculation + // We can't do that now, but it merge before following pairs + // so we leave space for it, and consider chunks as modified + // just for the worse case + remainingChunksToMerge--; + if (remainingChunksToMerge <= 0) break loop; + modifiedChunks.add(a); + modifiedChunks.add(b); + continue loop; + } + } + for (const parent of group.parentsIterable) { + queue.add(parent); + } + } + } + + // merge the chunks + if (chunkGraph.canChunksBeIntegrated(a, b)) { + chunkGraph.integrateChunks(a, b); + compilation.chunks.delete(b); + + // flag chunk a as modified as further optimization are possible for all children here + modifiedChunks.add(a); + + changed = true; + remainingChunksToMerge--; + if (remainingChunksToMerge <= 0) break; + + // Update all affected combinations + // delete all combination with the removed chunk + // we will use combinations with the kept chunk instead + for (const combination of /** @type {Set} */ ( + combinationsByChunk.get(a) + )) { + if (combination.deleted) continue; + combination.deleted = true; + combinations.delete(combination); + } + + // Update combinations with the kept chunk with new sizes + for (const combination of /** @type {Set} */ ( + combinationsByChunk.get(b) + )) { + if (combination.deleted) continue; + if (combination.a === b) { + if (!chunkGraph.canChunksBeIntegrated(a, combination.b)) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + // Update size + const newIntegratedSize = chunkGraph.getIntegratedChunksSize( + a, + combination.b, + options + ); + const finishUpdate = combinations.startUpdate(combination); + combination.a = a; + combination.integratedSize = newIntegratedSize; + combination.aSize = integratedSize; + combination.sizeDiff = + combination.bSize + integratedSize - newIntegratedSize; + finishUpdate(); + } else if (combination.b === b) { + if (!chunkGraph.canChunksBeIntegrated(combination.a, a)) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + // Update size + const newIntegratedSize = chunkGraph.getIntegratedChunksSize( + combination.a, + a, + options + ); + + const finishUpdate = combinations.startUpdate(combination); + combination.b = a; + combination.integratedSize = newIntegratedSize; + combination.bSize = integratedSize; + combination.sizeDiff = + integratedSize + combination.aSize - newIntegratedSize; + finishUpdate(); + } + } + combinationsByChunk.set( + a, + /** @type {Set} */ ( + combinationsByChunk.get(b) + ) + ); + combinationsByChunk.delete(b); + } + } + if (changed) return true; + } + ); + }); + } +} + +module.exports = LimitChunkCountPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MangleExportsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MangleExportsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..39383da8f75fff3a5d57ebb4dcaa3fd6e519c209 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MangleExportsPlugin.js @@ -0,0 +1,182 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { UsageState } = require("../ExportsInfo"); +const { + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS, + NUMBER_OF_IDENTIFIER_START_CHARS, + numberToIdentifier +} = require("../Template"); +const { assignDeterministicIds } = require("../ids/IdHelpers"); +const { compareSelect, compareStringsNumeric } = require("../util/comparators"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ + +/** + * @param {ExportsInfo} exportsInfo exports info + * @returns {boolean} mangle is possible + */ +const canMangle = (exportsInfo) => { + if (exportsInfo.otherExportsInfo.getUsed(undefined) !== UsageState.Unused) { + return false; + } + let hasSomethingToMangle = false; + for (const exportInfo of exportsInfo.exports) { + if (exportInfo.canMangle === true) { + hasSomethingToMangle = true; + } + } + return hasSomethingToMangle; +}; + +// Sort by name +const comparator = compareSelect((e) => e.name, compareStringsNumeric); +/** + * @param {boolean} deterministic use deterministic names + * @param {ExportsInfo} exportsInfo exports info + * @param {boolean | undefined} isNamespace is namespace object + * @returns {void} + */ +const mangleExportsInfo = (deterministic, exportsInfo, isNamespace) => { + if (!canMangle(exportsInfo)) return; + const usedNames = new Set(); + /** @type {ExportInfo[]} */ + const mangleableExports = []; + + // Avoid to renamed exports that are not provided when + // 1. it's not a namespace export: non-provided exports can be found in prototype chain + // 2. there are other provided exports and deterministic mode is chosen: + // non-provided exports would break the determinism + let avoidMangleNonProvided = !isNamespace; + if (!avoidMangleNonProvided && deterministic) { + for (const exportInfo of exportsInfo.ownedExports) { + if (exportInfo.provided !== false) { + avoidMangleNonProvided = true; + break; + } + } + } + for (const exportInfo of exportsInfo.ownedExports) { + const name = exportInfo.name; + if (!exportInfo.hasUsedName()) { + if ( + // Can the export be mangled? + exportInfo.canMangle !== true || + // Never rename 1 char exports + (name.length === 1 && /^[a-zA-Z0-9_$]/.test(name)) || + // Don't rename 2 char exports in deterministic mode + (deterministic && + name.length === 2 && + /^[a-zA-Z_$][a-zA-Z0-9_$]|^[1-9][0-9]/.test(name)) || + // Don't rename exports that are not provided + (avoidMangleNonProvided && exportInfo.provided !== true) + ) { + exportInfo.setUsedName(name); + usedNames.add(name); + } else { + mangleableExports.push(exportInfo); + } + } + if (exportInfo.exportsInfoOwned) { + const used = exportInfo.getUsed(undefined); + if ( + used === UsageState.OnlyPropertiesUsed || + used === UsageState.Unused + ) { + mangleExportsInfo( + deterministic, + /** @type {ExportsInfo} */ (exportInfo.exportsInfo), + false + ); + } + } + } + if (deterministic) { + assignDeterministicIds( + mangleableExports, + (e) => e.name, + comparator, + (e, id) => { + const name = numberToIdentifier(id); + const size = usedNames.size; + usedNames.add(name); + if (size === usedNames.size) return false; + e.setUsedName(name); + return true; + }, + [ + NUMBER_OF_IDENTIFIER_START_CHARS, + NUMBER_OF_IDENTIFIER_START_CHARS * + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS + ], + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS, + usedNames.size + ); + } else { + const usedExports = []; + const unusedExports = []; + for (const exportInfo of mangleableExports) { + if (exportInfo.getUsed(undefined) === UsageState.Unused) { + unusedExports.push(exportInfo); + } else { + usedExports.push(exportInfo); + } + } + usedExports.sort(comparator); + unusedExports.sort(comparator); + let i = 0; + for (const list of [usedExports, unusedExports]) { + for (const exportInfo of list) { + let name; + do { + name = numberToIdentifier(i++); + } while (usedNames.has(name)); + exportInfo.setUsedName(name); + } + } + } +}; + +const PLUGIN_NAME = "MangleExportsPlugin"; + +class MangleExportsPlugin { + /** + * @param {boolean} deterministic use deterministic names + */ + constructor(deterministic) { + this._deterministic = deterministic; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _deterministic: deterministic } = this; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.optimizeCodeGeneration.tap(PLUGIN_NAME, (modules) => { + if (compilation.moduleMemCaches) { + throw new Error( + "optimization.mangleExports can't be used with cacheUnaffected as export mangling is a global effect" + ); + } + for (const module of modules) { + const isNamespace = + module.buildMeta && module.buildMeta.exportsType === "namespace"; + const exportsInfo = moduleGraph.getExportsInfo(module); + mangleExportsInfo(deterministic, exportsInfo, isNamespace); + } + }); + }); + } +} + +module.exports = MangleExportsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MergeDuplicateChunksPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MergeDuplicateChunksPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f0adc666cc4811ae5b519291739a651392061ec6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MergeDuplicateChunksPlugin.js @@ -0,0 +1,134 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { STAGE_BASIC } = require("../OptimizationStages"); +const createSchemaValidation = require("../util/create-schema-validation"); +const { runtimeEqual } = require("../util/runtime"); + +/** @typedef {import("../../declarations/plugins/optimize/MergeDuplicateChunksPlugin").MergeDuplicateChunksPluginOptions} MergeDuplicateChunksPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/optimize/MergeDuplicateChunksPlugin.check"), + () => + require("../../schemas/plugins/optimize/MergeDuplicateChunksPlugin.json"), + { + name: "Merge Duplicate Chunks Plugin", + baseDataPath: "options" + } +); + +const PLUGIN_NAME = "MergeDuplicateChunksPlugin"; + +class MergeDuplicateChunksPlugin { + /** + * @param {MergeDuplicateChunksPluginOptions} options options object + */ + constructor(options = { stage: STAGE_BASIC }) { + validate(options); + this.options = options; + } + + /** + * @param {Compiler} compiler the compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: this.options.stage + }, + (chunks) => { + const { chunkGraph, moduleGraph } = compilation; + + // remember already tested chunks for performance + const notDuplicates = new Set(); + + // for each chunk + for (const chunk of chunks) { + // track a Set of all chunk that could be duplicates + let possibleDuplicates; + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (possibleDuplicates === undefined) { + // when possibleDuplicates is not yet set, + // create a new Set from chunks of the current module + // including only chunks with the same number of modules + for (const dup of chunkGraph.getModuleChunksIterable(module)) { + if ( + dup !== chunk && + chunkGraph.getNumberOfChunkModules(chunk) === + chunkGraph.getNumberOfChunkModules(dup) && + !notDuplicates.has(dup) + ) { + // delay allocating the new Set until here, reduce memory pressure + if (possibleDuplicates === undefined) { + possibleDuplicates = new Set(); + } + possibleDuplicates.add(dup); + } + } + // when no chunk is possible we can break here + if (possibleDuplicates === undefined) break; + } else { + // validate existing possible duplicates + for (const dup of possibleDuplicates) { + // remove possible duplicate when module is not contained + if (!chunkGraph.isModuleInChunk(module, dup)) { + possibleDuplicates.delete(dup); + } + } + // when all chunks has been removed we can break here + if (possibleDuplicates.size === 0) break; + } + } + + // when we found duplicates + if ( + possibleDuplicates !== undefined && + possibleDuplicates.size > 0 + ) { + outer: for (const otherChunk of possibleDuplicates) { + if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) continue; + if (chunkGraph.getNumberOfEntryModules(otherChunk) > 0) { + continue; + } + if (!runtimeEqual(chunk.runtime, otherChunk.runtime)) { + for (const module of chunkGraph.getChunkModulesIterable( + chunk + )) { + const exportsInfo = moduleGraph.getExportsInfo(module); + if ( + !exportsInfo.isEquallyUsed( + chunk.runtime, + otherChunk.runtime + ) + ) { + continue outer; + } + } + } + // merge them + if (chunkGraph.canChunksBeIntegrated(chunk, otherChunk)) { + chunkGraph.integrateChunks(chunk, otherChunk); + compilation.chunks.delete(otherChunk); + } + } + } + + // don't check already processed chunks twice + notDuplicates.add(chunk); + } + } + ); + }); + } +} + +module.exports = MergeDuplicateChunksPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MinChunkSizePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MinChunkSizePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d00f7a6c91573bed9ea38213b54771706d7aba50 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MinChunkSizePlugin.js @@ -0,0 +1,118 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { STAGE_ADVANCED } = require("../OptimizationStages"); +const createSchemaValidation = require("../util/create-schema-validation"); + +/** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/optimize/MinChunkSizePlugin.check"), + () => require("../../schemas/plugins/optimize/MinChunkSizePlugin.json"), + { + name: "Min Chunk Size Plugin", + baseDataPath: "options" + } +); + +const PLUGIN_NAME = "MinChunkSizePlugin"; + +class MinChunkSizePlugin { + /** + * @param {MinChunkSizePluginOptions} options options object + */ + constructor(options) { + validate(options); + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + const minChunkSize = options.minChunkSize; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: STAGE_ADVANCED + }, + (chunks) => { + const chunkGraph = compilation.chunkGraph; + const equalOptions = { + chunkOverhead: 1, + entryChunkMultiplicator: 1 + }; + + const chunkSizesMap = new Map(); + /** @type {[Chunk, Chunk][]} */ + const combinations = []; + /** @type {Chunk[]} */ + const smallChunks = []; + const visitedChunks = []; + for (const a of chunks) { + // check if one of the chunks sizes is smaller than the minChunkSize + // and filter pairs that can NOT be integrated! + if (chunkGraph.getChunkSize(a, equalOptions) < minChunkSize) { + smallChunks.push(a); + for (const b of visitedChunks) { + if (chunkGraph.canChunksBeIntegrated(b, a)) { + combinations.push([b, a]); + } + } + } else { + for (const b of smallChunks) { + if (chunkGraph.canChunksBeIntegrated(b, a)) { + combinations.push([b, a]); + } + } + } + chunkSizesMap.set(a, chunkGraph.getChunkSize(a, options)); + visitedChunks.push(a); + } + + const sortedSizeFilteredExtendedPairCombinations = combinations + .map((pair) => { + // extend combination pairs with size and integrated size + const a = chunkSizesMap.get(pair[0]); + const b = chunkSizesMap.get(pair[1]); + const ab = chunkGraph.getIntegratedChunksSize( + pair[0], + pair[1], + options + ); + /** @type {[number, number, Chunk, Chunk]} */ + const extendedPair = [a + b - ab, ab, pair[0], pair[1]]; + return extendedPair; + }) + .sort((a, b) => { + // sadly javascript does an in place sort here + // sort by size + const diff = b[0] - a[0]; + if (diff !== 0) return diff; + return a[1] - b[1]; + }); + + if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; + + const pair = sortedSizeFilteredExtendedPairCombinations[0]; + + chunkGraph.integrateChunks(pair[2], pair[3]); + compilation.chunks.delete(pair[3]); + return true; + } + ); + }); + } +} + +module.exports = MinChunkSizePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MinMaxSizeWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MinMaxSizeWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..2cc845eb9f0e921d5938175a29e6aea0dfab76b1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/MinMaxSizeWarning.js @@ -0,0 +1,35 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const SizeFormatHelpers = require("../SizeFormatHelpers"); +const WebpackError = require("../WebpackError"); + +class MinMaxSizeWarning extends WebpackError { + /** + * @param {string[] | undefined} keys keys + * @param {number} minSize minimum size + * @param {number} maxSize maximum size + */ + constructor(keys, minSize, maxSize) { + let keysMessage = "Fallback cache group"; + if (keys) { + keysMessage = + keys.length > 1 + ? `Cache groups ${keys.sort().join(", ")}` + : `Cache group ${keys[0]}`; + } + super( + "SplitChunksPlugin\n" + + `${keysMessage}\n` + + `Configured minSize (${SizeFormatHelpers.formatSize(minSize)}) is ` + + `bigger than maxSize (${SizeFormatHelpers.formatSize(maxSize)}).\n` + + "This seem to be a invalid optimization.splitChunks configuration." + ); + } +} + +module.exports = MinMaxSizeWarning; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/ModuleConcatenationPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/ModuleConcatenationPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..8d9618df01b50c4288118cf99c3d69991da91924 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/ModuleConcatenationPlugin.js @@ -0,0 +1,953 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const asyncLib = require("neo-async"); +const ChunkGraph = require("../ChunkGraph"); +const ModuleGraph = require("../ModuleGraph"); +const { JS_TYPE } = require("../ModuleSourceTypesConstants"); +const { STAGE_DEFAULT } = require("../OptimizationStages"); +const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); +const { compareModulesByIdentifier } = require("../util/comparators"); +const { + filterRuntime, + intersectRuntime, + mergeRuntime, + mergeRuntimeOwned, + runtimeToString +} = require("../util/runtime"); +const ConcatenatedModule = require("./ConcatenatedModule"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @typedef {object} Statistics + * @property {number} cached + * @property {number} alreadyInConfig + * @property {number} invalidModule + * @property {number} incorrectChunks + * @property {number} incorrectDependency + * @property {number} incorrectModuleDependency + * @property {number} incorrectChunksOfImporter + * @property {number} incorrectRuntimeCondition + * @property {number} importerFailed + * @property {number} added + */ + +/** + * @param {string} msg message + * @returns {string} formatted message + */ +const formatBailoutReason = (msg) => `ModuleConcatenation bailout: ${msg}`; + +const PLUGIN_NAME = "ModuleConcatenationPlugin"; + +class ModuleConcatenationPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _backCompat: backCompat } = compiler; + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + if (compilation.moduleMemCaches) { + throw new Error( + "optimization.concatenateModules can't be used with cacheUnaffected as module concatenation is a global effect" + ); + } + const moduleGraph = compilation.moduleGraph; + /** @type {Map string)>} */ + const bailoutReasonMap = new Map(); + + /** + * @param {Module} module the module + * @param {string | ((requestShortener: RequestShortener) => string)} reason the reason + */ + const setBailoutReason = (module, reason) => { + setInnerBailoutReason(module, reason); + moduleGraph + .getOptimizationBailout(module) + .push( + typeof reason === "function" + ? (rs) => formatBailoutReason(reason(rs)) + : formatBailoutReason(reason) + ); + }; + + /** + * @param {Module} module the module + * @param {string | ((requestShortener: RequestShortener) => string)} reason the reason + */ + const setInnerBailoutReason = (module, reason) => { + bailoutReasonMap.set(module, reason); + }; + + /** + * @param {Module} module the module + * @param {RequestShortener} requestShortener the request shortener + * @returns {string | ((requestShortener: RequestShortener) => string) | undefined} the reason + */ + const getInnerBailoutReason = (module, requestShortener) => { + const reason = bailoutReasonMap.get(module); + if (typeof reason === "function") return reason(requestShortener); + return reason; + }; + + /** + * @param {Module} module the module + * @param {Module | ((requestShortener: RequestShortener) => string)} problem the problem + * @returns {(requestShortener: RequestShortener) => string} the reason + */ + const formatBailoutWarning = (module, problem) => (requestShortener) => { + if (typeof problem === "function") { + return formatBailoutReason( + `Cannot concat with ${module.readableIdentifier( + requestShortener + )}: ${problem(requestShortener)}` + ); + } + const reason = getInnerBailoutReason(module, requestShortener); + const reasonWithPrefix = reason ? `: ${reason}` : ""; + if (module === problem) { + return formatBailoutReason( + `Cannot concat with ${module.readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } + return formatBailoutReason( + `Cannot concat with ${module.readableIdentifier( + requestShortener + )} because of ${problem.readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + }; + + compilation.hooks.optimizeChunkModules.tapAsync( + { + name: PLUGIN_NAME, + stage: STAGE_DEFAULT + }, + (allChunks, modules, callback) => { + const logger = compilation.getLogger( + "webpack.ModuleConcatenationPlugin" + ); + const { chunkGraph, moduleGraph } = compilation; + const relevantModules = []; + const possibleInners = new Set(); + const context = { + chunkGraph, + moduleGraph + }; + const deferEnabled = compilation.options.experiments.deferImport; + logger.time("select relevant modules"); + for (const module of modules) { + let canBeRoot = true; + let canBeInner = true; + + const bailoutReason = module.getConcatenationBailoutReason(context); + if (bailoutReason) { + setBailoutReason(module, bailoutReason); + continue; + } + + // Must not be an async module + if (moduleGraph.isAsync(module)) { + setBailoutReason(module, "Module is async"); + continue; + } + + // Must be in strict mode + if (!(/** @type {BuildInfo} */ (module.buildInfo).strict)) { + setBailoutReason(module, "Module is not in strict mode"); + continue; + } + + // Module must be in any chunk (we don't want to do useless work) + if (chunkGraph.getNumberOfModuleChunks(module) === 0) { + setBailoutReason(module, "Module is not in any chunk"); + continue; + } + + // Exports must be known (and not dynamic) + const exportsInfo = moduleGraph.getExportsInfo(module); + const relevantExports = exportsInfo.getRelevantExports(undefined); + const unknownReexports = relevantExports.filter( + (exportInfo) => + exportInfo.isReexport() && !exportInfo.getTarget(moduleGraph) + ); + if (unknownReexports.length > 0) { + setBailoutReason( + module, + `Reexports in this module do not have a static target (${Array.from( + unknownReexports, + (exportInfo) => + `${ + exportInfo.name || "other exports" + }: ${exportInfo.getUsedInfo()}` + ).join(", ")})` + ); + continue; + } + + // Root modules must have a static list of exports + const unknownProvidedExports = relevantExports.filter( + (exportInfo) => exportInfo.provided !== true + ); + if (unknownProvidedExports.length > 0) { + setBailoutReason( + module, + `List of module exports is dynamic (${Array.from( + unknownProvidedExports, + (exportInfo) => + `${ + exportInfo.name || "other exports" + }: ${exportInfo.getProvidedInfo()} and ${exportInfo.getUsedInfo()}` + ).join(", ")})` + ); + canBeRoot = false; + } + + // Module must not be an entry point + if (chunkGraph.isEntryModule(module)) { + setInnerBailoutReason(module, "Module is an entry point"); + canBeInner = false; + } + + if (deferEnabled && moduleGraph.isDeferred(module)) { + setInnerBailoutReason(module, "Module is deferred"); + canBeInner = false; + } + + if (canBeRoot) relevantModules.push(module); + if (canBeInner) possibleInners.add(module); + } + logger.timeEnd("select relevant modules"); + logger.debug( + `${relevantModules.length} potential root modules, ${possibleInners.size} potential inner modules` + ); + // sort by depth + // modules with lower depth are more likely suited as roots + // this improves performance, because modules already selected as inner are skipped + logger.time("sort relevant modules"); + relevantModules.sort( + (a, b) => + /** @type {number} */ (moduleGraph.getDepth(a)) - + /** @type {number} */ (moduleGraph.getDepth(b)) + ); + logger.timeEnd("sort relevant modules"); + + /** @type {Statistics} */ + const stats = { + cached: 0, + alreadyInConfig: 0, + invalidModule: 0, + incorrectChunks: 0, + incorrectDependency: 0, + incorrectModuleDependency: 0, + incorrectChunksOfImporter: 0, + incorrectRuntimeCondition: 0, + importerFailed: 0, + added: 0 + }; + let statsCandidates = 0; + let statsSizeSum = 0; + let statsEmptyConfigurations = 0; + + logger.time("find modules to concatenate"); + const concatConfigurations = []; + const usedAsInner = new Set(); + for (const currentRoot of relevantModules) { + // when used by another configuration as inner: + // the other configuration is better and we can skip this one + // TODO reconsider that when it's only used in a different runtime + if (usedAsInner.has(currentRoot)) continue; + + let chunkRuntime; + for (const r of chunkGraph.getModuleRuntimes(currentRoot)) { + chunkRuntime = mergeRuntimeOwned(chunkRuntime, r); + } + const exportsInfo = moduleGraph.getExportsInfo(currentRoot); + const filteredRuntime = filterRuntime(chunkRuntime, (r) => + exportsInfo.isModuleUsed(r) + ); + const activeRuntime = + filteredRuntime === true + ? chunkRuntime + : filteredRuntime === false + ? undefined + : filteredRuntime; + + // create a configuration with the root + const currentConfiguration = new ConcatConfiguration( + currentRoot, + activeRuntime + ); + + // cache failures to add modules + const failureCache = new Map(); + + // potential optional import candidates + /** @type {Set} */ + const candidates = new Set(); + + // try to add all imports + for (const imp of this._getImports( + compilation, + currentRoot, + activeRuntime + )) { + candidates.add(imp); + } + + for (const imp of candidates) { + const impCandidates = new Set(); + const problem = this._tryToAdd( + compilation, + currentConfiguration, + imp, + chunkRuntime, + activeRuntime, + possibleInners, + impCandidates, + failureCache, + chunkGraph, + true, + stats + ); + if (problem) { + failureCache.set(imp, problem); + currentConfiguration.addWarning(imp, problem); + } else { + for (const c of impCandidates) { + candidates.add(c); + } + } + } + statsCandidates += candidates.size; + if (!currentConfiguration.isEmpty()) { + const modules = currentConfiguration.getModules(); + statsSizeSum += modules.size; + concatConfigurations.push(currentConfiguration); + for (const module of modules) { + if (module !== currentConfiguration.rootModule) { + usedAsInner.add(module); + } + } + } else { + statsEmptyConfigurations++; + const optimizationBailouts = + moduleGraph.getOptimizationBailout(currentRoot); + for (const warning of currentConfiguration.getWarningsSorted()) { + optimizationBailouts.push( + formatBailoutWarning(warning[0], warning[1]) + ); + } + } + } + logger.timeEnd("find modules to concatenate"); + logger.debug( + `${ + concatConfigurations.length + } successful concat configurations (avg size: ${ + statsSizeSum / concatConfigurations.length + }), ${statsEmptyConfigurations} bailed out completely` + ); + logger.debug( + `${statsCandidates} candidates were considered for adding (${stats.cached} cached failure, ${stats.alreadyInConfig} already in config, ${stats.invalidModule} invalid module, ${stats.incorrectChunks} incorrect chunks, ${stats.incorrectDependency} incorrect dependency, ${stats.incorrectChunksOfImporter} incorrect chunks of importer, ${stats.incorrectModuleDependency} incorrect module dependency, ${stats.incorrectRuntimeCondition} incorrect runtime condition, ${stats.importerFailed} importer failed, ${stats.added} added)` + ); + // HACK: Sort configurations by length and start with the longest one + // to get the biggest groups possible. Used modules are marked with usedModules + // TODO: Allow to reuse existing configuration while trying to add dependencies. + // This would improve performance. O(n^2) -> O(n) + logger.time("sort concat configurations"); + concatConfigurations.sort((a, b) => b.modules.size - a.modules.size); + logger.timeEnd("sort concat configurations"); + const usedModules = new Set(); + + logger.time("create concatenated modules"); + asyncLib.each( + concatConfigurations, + (concatConfiguration, callback) => { + const rootModule = concatConfiguration.rootModule; + + // Avoid overlapping configurations + // TODO: remove this when todo above is fixed + if (usedModules.has(rootModule)) return callback(); + const modules = concatConfiguration.getModules(); + for (const m of modules) { + usedModules.add(m); + } + + // Create a new ConcatenatedModule + ConcatenatedModule.getCompilationHooks(compilation); + const newModule = ConcatenatedModule.create( + rootModule, + modules, + concatConfiguration.runtime, + compilation, + compiler.root, + compilation.outputOptions.hashFunction + ); + + const build = () => { + newModule.build( + compiler.options, + compilation, + /** @type {EXPECTED_ANY} */ + (null), + /** @type {EXPECTED_ANY} */ + (null), + (err) => { + if (err) { + if (!err.module) { + err.module = newModule; + } + return callback(err); + } + integrate(); + } + ); + }; + + const integrate = () => { + if (backCompat) { + ChunkGraph.setChunkGraphForModule(newModule, chunkGraph); + ModuleGraph.setModuleGraphForModule(newModule, moduleGraph); + } + + for (const warning of concatConfiguration.getWarningsSorted()) { + moduleGraph + .getOptimizationBailout(newModule) + .push(formatBailoutWarning(warning[0], warning[1])); + } + moduleGraph.cloneModuleAttributes(rootModule, newModule); + for (const m of modules) { + // add to builtModules when one of the included modules was built + if (compilation.builtModules.has(m)) { + compilation.builtModules.add(newModule); + } + if (m !== rootModule) { + // attach external references to the concatenated module too + moduleGraph.copyOutgoingModuleConnections( + m, + newModule, + (c) => + c.originModule === m && + !( + c.dependency instanceof HarmonyImportDependency && + modules.has(c.module) + ) + ); + // remove module from chunk + for (const chunk of chunkGraph.getModuleChunksIterable( + rootModule + )) { + const sourceTypes = chunkGraph.getChunkModuleSourceTypes( + chunk, + m + ); + if (sourceTypes.size === 1) { + chunkGraph.disconnectChunkAndModule(chunk, m); + } else { + const newSourceTypes = new Set(sourceTypes); + newSourceTypes.delete(JS_TYPE); + chunkGraph.setChunkModuleSourceTypes( + chunk, + m, + newSourceTypes + ); + } + } + } + } + compilation.modules.delete(rootModule); + ChunkGraph.clearChunkGraphForModule(rootModule); + ModuleGraph.clearModuleGraphForModule(rootModule); + + // remove module from chunk + chunkGraph.replaceModule(rootModule, newModule); + // replace module references with the concatenated module + moduleGraph.moveModuleConnections( + rootModule, + newModule, + (c) => { + const otherModule = + c.module === rootModule ? c.originModule : c.module; + const innerConnection = + c.dependency instanceof HarmonyImportDependency && + modules.has(/** @type {Module} */ (otherModule)); + return !innerConnection; + } + ); + // add concatenated module to the compilation + compilation.modules.add(newModule); + + callback(); + }; + + build(); + }, + (err) => { + logger.timeEnd("create concatenated modules"); + process.nextTick(callback.bind(null, err)); + } + ); + } + ); + }); + } + + /** + * @param {Compilation} compilation the compilation + * @param {Module} module the module to be added + * @param {RuntimeSpec} runtime the runtime scope + * @returns {Set} the imported modules + */ + _getImports(compilation, module, runtime) { + const moduleGraph = compilation.moduleGraph; + const set = new Set(); + for (const dep of module.dependencies) { + // Get reference info only for harmony Dependencies + if (!(dep instanceof HarmonyImportDependency)) continue; + + const connection = moduleGraph.getConnection(dep); + // Reference is valid and has a module + if ( + !connection || + !connection.module || + !connection.isTargetActive(runtime) + ) { + continue; + } + + const importedNames = compilation.getDependencyReferencedExports( + dep, + undefined + ); + + if ( + importedNames.every((i) => + Array.isArray(i) ? i.length > 0 : i.name.length > 0 + ) || + Array.isArray(moduleGraph.getProvidedExports(module)) + ) { + set.add(connection.module); + } + } + return set; + } + + /** + * @param {Compilation} compilation webpack compilation + * @param {ConcatConfiguration} config concat configuration (will be modified when added) + * @param {Module} module the module to be added + * @param {RuntimeSpec} runtime the runtime scope of the generated code + * @param {RuntimeSpec} activeRuntime the runtime scope of the root module + * @param {Set} possibleModules modules that are candidates + * @param {Set} candidates list of potential candidates (will be added to) + * @param {Map string)>} failureCache cache for problematic modules to be more performant + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {boolean} avoidMutateOnFailure avoid mutating the config when adding fails + * @param {Statistics} statistics gathering metrics + * @returns {null | Module | ((requestShortener: RequestShortener) => string)} the problematic module + */ + _tryToAdd( + compilation, + config, + module, + runtime, + activeRuntime, + possibleModules, + candidates, + failureCache, + chunkGraph, + avoidMutateOnFailure, + statistics + ) { + const cacheEntry = failureCache.get(module); + if (cacheEntry) { + statistics.cached++; + return cacheEntry; + } + + // Already added? + if (config.has(module)) { + statistics.alreadyInConfig++; + return null; + } + + // Not possible to add? + if (!possibleModules.has(module)) { + statistics.invalidModule++; + failureCache.set(module, module); // cache failures for performance + return module; + } + + // Module must be in the correct chunks + const missingChunks = [ + ...chunkGraph.getModuleChunksIterable(config.rootModule) + ].filter((chunk) => !chunkGraph.isModuleInChunk(module, chunk)); + if (missingChunks.length > 0) { + /** + * @param {RequestShortener} requestShortener request shortener + * @returns {string} problem description + */ + const problem = (requestShortener) => { + const missingChunksList = [ + ...new Set( + missingChunks.map((chunk) => chunk.name || "unnamed chunk(s)") + ) + ].sort(); + const chunks = [ + ...new Set( + [...chunkGraph.getModuleChunksIterable(module)].map( + (chunk) => chunk.name || "unnamed chunk(s)" + ) + ) + ].sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is not in the same chunk(s) (expected in chunk(s) ${missingChunksList.join( + ", " + )}, module is in chunk(s) ${chunks.join(", ")})`; + }; + statistics.incorrectChunks++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + + const moduleGraph = compilation.moduleGraph; + + const incomingConnections = + moduleGraph.getIncomingConnectionsByOriginModule(module); + + const incomingConnectionsFromNonModules = + incomingConnections.get(null) || incomingConnections.get(undefined); + if (incomingConnectionsFromNonModules) { + const activeNonModulesConnections = + incomingConnectionsFromNonModules.filter((connection) => + // We are not interested in inactive connections + // or connections without dependency + connection.isActive(runtime) + ); + if (activeNonModulesConnections.length > 0) { + /** + * @param {RequestShortener} requestShortener request shortener + * @returns {string} problem description + */ + const problem = (requestShortener) => { + const importingExplanations = new Set( + activeNonModulesConnections + .map((c) => c.explanation) + .filter(Boolean) + ); + const explanations = [...importingExplanations].sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is referenced ${ + explanations.length > 0 + ? `by: ${explanations.join(", ")}` + : "in an unsupported way" + }`; + }; + statistics.incorrectDependency++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } + + /** @type {Map} */ + const incomingConnectionsFromModules = new Map(); + for (const [originModule, connections] of incomingConnections) { + if (originModule) { + // Ignore connection from orphan modules + if (chunkGraph.getNumberOfModuleChunks(originModule) === 0) continue; + + // We don't care for connections from other runtimes + let originRuntime; + for (const r of chunkGraph.getModuleRuntimes(originModule)) { + originRuntime = mergeRuntimeOwned(originRuntime, r); + } + + if (!intersectRuntime(runtime, originRuntime)) continue; + + // We are not interested in inactive connections + const activeConnections = connections.filter((connection) => + connection.isActive(runtime) + ); + if (activeConnections.length > 0) { + incomingConnectionsFromModules.set(originModule, activeConnections); + } + } + } + + const incomingModules = [...incomingConnectionsFromModules.keys()]; + + // Module must be in the same chunks like the referencing module + const otherChunkModules = incomingModules.filter((originModule) => { + for (const chunk of chunkGraph.getModuleChunksIterable( + config.rootModule + )) { + if (!chunkGraph.isModuleInChunk(originModule, chunk)) { + return true; + } + } + return false; + }); + if (otherChunkModules.length > 0) { + /** + * @param {RequestShortener} requestShortener request shortener + * @returns {string} problem description + */ + const problem = (requestShortener) => { + const names = otherChunkModules + .map((m) => m.readableIdentifier(requestShortener)) + .sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is referenced from different chunks by these modules: ${names.join( + ", " + )}`; + }; + statistics.incorrectChunksOfImporter++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + + /** @type {Map} */ + const nonHarmonyConnections = new Map(); + for (const [originModule, connections] of incomingConnectionsFromModules) { + const selected = connections.filter( + (connection) => + !connection.dependency || + !(connection.dependency instanceof HarmonyImportDependency) + ); + if (selected.length > 0) { + nonHarmonyConnections.set(originModule, connections); + } + } + if (nonHarmonyConnections.size > 0) { + /** + * @param {RequestShortener} requestShortener request shortener + * @returns {string} problem description + */ + const problem = (requestShortener) => { + const names = [...nonHarmonyConnections] + .map( + ([originModule, connections]) => + `${originModule.readableIdentifier( + requestShortener + )} (referenced with ${[ + ...new Set( + connections + .map((c) => c.dependency && c.dependency.type) + .filter(Boolean) + ) + ] + .sort() + .join(", ")})` + ) + .sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is referenced from these modules with unsupported syntax: ${names.join( + ", " + )}`; + }; + statistics.incorrectModuleDependency++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + + if (runtime !== undefined && typeof runtime !== "string") { + // Module must be consistently referenced in the same runtimes + /** @type {{ originModule: Module, runtimeCondition: RuntimeSpec }[]} */ + const otherRuntimeConnections = []; + outer: for (const [ + originModule, + connections + ] of incomingConnectionsFromModules) { + /** @type {false | RuntimeSpec} */ + let currentRuntimeCondition = false; + for (const connection of connections) { + const runtimeCondition = filterRuntime(runtime, (runtime) => + connection.isTargetActive(runtime) + ); + if (runtimeCondition === false) continue; + if (runtimeCondition === true) continue outer; + currentRuntimeCondition = + currentRuntimeCondition !== false + ? mergeRuntime(currentRuntimeCondition, runtimeCondition) + : runtimeCondition; + } + if (currentRuntimeCondition !== false) { + otherRuntimeConnections.push({ + originModule, + runtimeCondition: currentRuntimeCondition + }); + } + } + if (otherRuntimeConnections.length > 0) { + /** + * @param {RequestShortener} requestShortener request shortener + * @returns {string} problem description + */ + const problem = (requestShortener) => + `Module ${module.readableIdentifier( + requestShortener + )} is runtime-dependent referenced by these modules: ${Array.from( + otherRuntimeConnections, + ({ originModule, runtimeCondition }) => + `${originModule.readableIdentifier( + requestShortener + )} (expected runtime ${runtimeToString( + runtime + )}, module is only referenced in ${runtimeToString( + /** @type {RuntimeSpec} */ (runtimeCondition) + )})` + ).join(", ")}`; + statistics.incorrectRuntimeCondition++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } + + let backup; + if (avoidMutateOnFailure) { + backup = config.snapshot(); + } + + // Add the module + config.add(module); + + incomingModules.sort(compareModulesByIdentifier); + + // Every module which depends on the added module must be in the configuration too. + for (const originModule of incomingModules) { + const problem = this._tryToAdd( + compilation, + config, + originModule, + runtime, + activeRuntime, + possibleModules, + candidates, + failureCache, + chunkGraph, + false, + statistics + ); + if (problem) { + if (backup !== undefined) config.rollback(backup); + statistics.importerFailed++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } + + // Add imports to possible candidates list + for (const imp of this._getImports(compilation, module, runtime)) { + candidates.add(imp); + } + statistics.added++; + return null; + } +} + +/** @typedef {Module | ((requestShortener: RequestShortener) => string)} Problem */ + +class ConcatConfiguration { + /** + * @param {Module} rootModule the root module + * @param {RuntimeSpec} runtime the runtime + */ + constructor(rootModule, runtime) { + this.rootModule = rootModule; + this.runtime = runtime; + /** @type {Set} */ + this.modules = new Set(); + this.modules.add(rootModule); + /** @type {Map} */ + this.warnings = new Map(); + } + + /** + * @param {Module} module the module + */ + add(module) { + this.modules.add(module); + } + + /** + * @param {Module} module the module + * @returns {boolean} true, when the module is in the module set + */ + has(module) { + return this.modules.has(module); + } + + isEmpty() { + return this.modules.size === 1; + } + + /** + * @param {Module} module the module + * @param {Problem} problem the problem + */ + addWarning(module, problem) { + this.warnings.set(module, problem); + } + + /** + * @returns {Map} warnings + */ + getWarningsSorted() { + return new Map( + [...this.warnings].sort((a, b) => { + const ai = a[0].identifier(); + const bi = b[0].identifier(); + if (ai < bi) return -1; + if (ai > bi) return 1; + return 0; + }) + ); + } + + /** + * @returns {Set} modules as set + */ + getModules() { + return this.modules; + } + + snapshot() { + return this.modules.size; + } + + /** + * @param {number} snapshot snapshot + */ + rollback(snapshot) { + const modules = this.modules; + for (const m of modules) { + if (snapshot === 0) { + modules.delete(m); + } else { + snapshot--; + } + } + } +} + +module.exports = ModuleConcatenationPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RealContentHashPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RealContentHashPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..8f03316eecefdaa08ef667c8eeeafc3ca55f19b6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RealContentHashPlugin.js @@ -0,0 +1,476 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { SyncBailHook } = require("tapable"); +const { CachedSource, CompatSource, RawSource } = require("webpack-sources"); +const Compilation = require("../Compilation"); +const WebpackError = require("../WebpackError"); +const { compareSelect, compareStrings } = require("../util/comparators"); +const createHash = require("../util/createHash"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {typeof import("../util/Hash")} Hash */ + +const EMPTY_SET = new Set(); + +/** + * @template T + * @param {T | T[]} itemOrItems item or items + * @param {Set} list list + */ +const addToList = (itemOrItems, list) => { + if (Array.isArray(itemOrItems)) { + for (const item of itemOrItems) { + list.add(item); + } + } else if (itemOrItems) { + list.add(itemOrItems); + } +}; + +/** + * @template T + * @param {T[]} input list + * @param {(item: T) => Buffer} fn map function + * @returns {Buffer[]} buffers without duplicates + */ +const mapAndDeduplicateBuffers = (input, fn) => { + // Buffer.equals compares size first so this should be efficient enough + // If it becomes a performance problem we can use a map and group by size + // instead of looping over all assets. + const result = []; + outer: for (const value of input) { + const buf = fn(value); + for (const other of result) { + if (buf.equals(other)) continue outer; + } + result.push(buf); + } + return result; +}; + +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quoteMeta = (str) => str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); + +const cachedSourceMap = new WeakMap(); + +/** + * @param {Source} source source + * @returns {CachedSource} cached source + */ +const toCachedSource = (source) => { + if (source instanceof CachedSource) { + return source; + } + const entry = cachedSourceMap.get(source); + if (entry !== undefined) return entry; + const newSource = new CachedSource(CompatSource.from(source)); + cachedSourceMap.set(source, newSource); + return newSource; +}; + +/** @typedef {Set} OwnHashes */ +/** @typedef {Set} ReferencedHashes */ +/** @typedef {Set} Hashes */ + +/** + * @typedef {object} AssetInfoForRealContentHash + * @property {string} name + * @property {AssetInfo} info + * @property {Source} source + * @property {RawSource | undefined} newSource + * @property {RawSource | undefined} newSourceWithoutOwn + * @property {string} content + * @property {OwnHashes | undefined} ownHashes + * @property {Promise | undefined} contentComputePromise + * @property {Promise | undefined} contentComputeWithoutOwnPromise + * @property {ReferencedHashes | undefined} referencedHashes + * @property {Hashes} hashes + */ + +/** + * @typedef {object} CompilationHooks + * @property {SyncBailHook<[Buffer[], string], string | void>} updateHash + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +/** + * @typedef {object} RealContentHashPluginOptions + * @property {string | Hash} hashFunction the hash function to use + * @property {string=} hashDigest the hash digest to use + */ + +const PLUGIN_NAME = "RealContentHashPlugin"; + +class RealContentHashPlugin { + /** + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} the attached hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + updateHash: new SyncBailHook(["content", "oldHash"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** + * @param {RealContentHashPluginOptions} options options + */ + constructor({ hashFunction, hashDigest }) { + this._hashFunction = hashFunction; + this._hashDigest = hashDigest; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const cacheAnalyse = compilation.getCache( + "RealContentHashPlugin|analyse" + ); + const cacheGenerate = compilation.getCache( + "RealContentHashPlugin|generate" + ); + const hooks = RealContentHashPlugin.getCompilationHooks(compilation); + compilation.hooks.processAssets.tapPromise( + { + name: PLUGIN_NAME, + stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH + }, + async () => { + const assets = compilation.getAssets(); + /** @type {AssetInfoForRealContentHash[]} */ + const assetsWithInfo = []; + /** @type {Map} */ + const hashToAssets = new Map(); + for (const { source, info, name } of assets) { + const cachedSource = toCachedSource(source); + const content = /** @type {string} */ (cachedSource.source()); + /** @type {Hashes} */ + const hashes = new Set(); + addToList(info.contenthash, hashes); + /** @type {AssetInfoForRealContentHash} */ + const data = { + name, + info, + source: cachedSource, + newSource: undefined, + newSourceWithoutOwn: undefined, + content, + ownHashes: undefined, + contentComputePromise: undefined, + contentComputeWithoutOwnPromise: undefined, + referencedHashes: undefined, + hashes + }; + assetsWithInfo.push(data); + for (const hash of hashes) { + const list = hashToAssets.get(hash); + if (list === undefined) { + hashToAssets.set(hash, [data]); + } else { + list.push(data); + } + } + } + if (hashToAssets.size === 0) return; + const hashRegExp = new RegExp( + Array.from(hashToAssets.keys(), quoteMeta).join("|"), + "g" + ); + await Promise.all( + assetsWithInfo.map(async (asset) => { + const { name, source, content, hashes } = asset; + if (Buffer.isBuffer(content)) { + asset.referencedHashes = EMPTY_SET; + asset.ownHashes = EMPTY_SET; + return; + } + const etag = cacheAnalyse.mergeEtags( + cacheAnalyse.getLazyHashedEtag(source), + [...hashes].join("|") + ); + [asset.referencedHashes, asset.ownHashes] = + await cacheAnalyse.providePromise(name, etag, () => { + const referencedHashes = new Set(); + const ownHashes = new Set(); + const inContent = content.match(hashRegExp); + if (inContent) { + for (const hash of inContent) { + if (hashes.has(hash)) { + ownHashes.add(hash); + continue; + } + referencedHashes.add(hash); + } + } + return [referencedHashes, ownHashes]; + }); + }) + ); + /** + * @param {string} hash the hash + * @returns {undefined | ReferencedHashes} the referenced hashes + */ + const getDependencies = (hash) => { + const assets = hashToAssets.get(hash); + if (!assets) { + const referencingAssets = assetsWithInfo.filter((asset) => + /** @type {ReferencedHashes} */ (asset.referencedHashes).has( + hash + ) + ); + const err = new WebpackError(`RealContentHashPlugin +Some kind of unexpected caching problem occurred. +An asset was cached with a reference to another asset (${hash}) that's not in the compilation anymore. +Either the asset was incorrectly cached, or the referenced asset should also be restored from cache. +Referenced by: +${referencingAssets + .map((a) => { + const match = new RegExp(`.{0,20}${quoteMeta(hash)}.{0,20}`).exec( + a.content + ); + return ` - ${a.name}: ...${match ? match[0] : "???"}...`; + }) + .join("\n")}`); + compilation.errors.push(err); + return; + } + const hashes = new Set(); + for (const { referencedHashes, ownHashes } of assets) { + if (!(/** @type {OwnHashes} */ (ownHashes).has(hash))) { + for (const hash of /** @type {OwnHashes} */ (ownHashes)) { + hashes.add(hash); + } + } + for (const hash of /** @type {ReferencedHashes} */ ( + referencedHashes + )) { + hashes.add(hash); + } + } + return hashes; + }; + /** + * @param {string} hash the hash + * @returns {string} the hash info + */ + const hashInfo = (hash) => { + const assets = hashToAssets.get(hash); + return `${hash} (${Array.from( + /** @type {AssetInfoForRealContentHash[]} */ (assets), + (a) => a.name + )})`; + }; + /** @type {Set} */ + const hashesInOrder = new Set(); + for (const hash of hashToAssets.keys()) { + /** + * @param {string} hash the hash + * @param {Set} stack stack of hashes + */ + const add = (hash, stack) => { + const deps = getDependencies(hash); + if (!deps) return; + stack.add(hash); + for (const dep of deps) { + if (hashesInOrder.has(dep)) continue; + if (stack.has(dep)) { + throw new Error( + `Circular hash dependency ${Array.from( + stack, + hashInfo + ).join(" -> ")} -> ${hashInfo(dep)}` + ); + } + add(dep, stack); + } + hashesInOrder.add(hash); + stack.delete(hash); + }; + if (hashesInOrder.has(hash)) continue; + add(hash, new Set()); + } + /** @type {Map} */ + const hashToNewHash = new Map(); + /** + * @param {AssetInfoForRealContentHash} asset asset info + * @returns {Etag} etag + */ + const getEtag = (asset) => + cacheGenerate.mergeEtags( + cacheGenerate.getLazyHashedEtag(asset.source), + Array.from( + /** @type {ReferencedHashes} */ (asset.referencedHashes), + (hash) => hashToNewHash.get(hash) + ).join("|") + ); + /** + * @param {AssetInfoForRealContentHash} asset asset info + * @returns {Promise} + */ + const computeNewContent = (asset) => { + if (asset.contentComputePromise) return asset.contentComputePromise; + return (asset.contentComputePromise = (async () => { + if ( + /** @type {OwnHashes} */ (asset.ownHashes).size > 0 || + [ + .../** @type {ReferencedHashes} */ (asset.referencedHashes) + ].some((hash) => hashToNewHash.get(hash) !== hash) + ) { + const identifier = asset.name; + const etag = getEtag(asset); + asset.newSource = await cacheGenerate.providePromise( + identifier, + etag, + () => { + const newContent = asset.content.replace( + hashRegExp, + (hash) => /** @type {string} */ (hashToNewHash.get(hash)) + ); + return new RawSource(newContent); + } + ); + } + })()); + }; + /** + * @param {AssetInfoForRealContentHash} asset asset info + * @returns {Promise} + */ + const computeNewContentWithoutOwn = (asset) => { + if (asset.contentComputeWithoutOwnPromise) { + return asset.contentComputeWithoutOwnPromise; + } + return (asset.contentComputeWithoutOwnPromise = (async () => { + if ( + /** @type {OwnHashes} */ (asset.ownHashes).size > 0 || + [ + .../** @type {ReferencedHashes} */ (asset.referencedHashes) + ].some((hash) => hashToNewHash.get(hash) !== hash) + ) { + const identifier = `${asset.name}|without-own`; + const etag = getEtag(asset); + asset.newSourceWithoutOwn = await cacheGenerate.providePromise( + identifier, + etag, + () => { + const newContent = asset.content.replace( + hashRegExp, + (hash) => { + if ( + /** @type {OwnHashes} */ + (asset.ownHashes).has(hash) + ) { + return ""; + } + return /** @type {string} */ (hashToNewHash.get(hash)); + } + ); + return new RawSource(newContent); + } + ); + } + })()); + }; + const comparator = compareSelect((a) => a.name, compareStrings); + for (const oldHash of hashesInOrder) { + const assets = + /** @type {AssetInfoForRealContentHash[]} */ + (hashToAssets.get(oldHash)); + assets.sort(comparator); + await Promise.all( + assets.map((asset) => + /** @type {OwnHashes} */ (asset.ownHashes).has(oldHash) + ? computeNewContentWithoutOwn(asset) + : computeNewContent(asset) + ) + ); + const assetsContent = mapAndDeduplicateBuffers(assets, (asset) => { + if (/** @type {OwnHashes} */ (asset.ownHashes).has(oldHash)) { + return asset.newSourceWithoutOwn + ? asset.newSourceWithoutOwn.buffer() + : asset.source.buffer(); + } + return asset.newSource + ? asset.newSource.buffer() + : asset.source.buffer(); + }); + let newHash = hooks.updateHash.call(assetsContent, oldHash); + if (!newHash) { + const hash = createHash(this._hashFunction); + if (compilation.outputOptions.hashSalt) { + hash.update(compilation.outputOptions.hashSalt); + } + for (const content of assetsContent) { + hash.update(content); + } + const digest = hash.digest(this._hashDigest); + newHash = /** @type {string} */ (digest.slice(0, oldHash.length)); + } + hashToNewHash.set(oldHash, newHash); + } + await Promise.all( + assetsWithInfo.map(async (asset) => { + await computeNewContent(asset); + const newName = asset.name.replace( + hashRegExp, + (hash) => /** @type {string} */ (hashToNewHash.get(hash)) + ); + + const infoUpdate = {}; + const hash = /** @type {string} */ (asset.info.contenthash); + infoUpdate.contenthash = Array.isArray(hash) + ? hash.map( + (hash) => /** @type {string} */ (hashToNewHash.get(hash)) + ) + : /** @type {string} */ (hashToNewHash.get(hash)); + + if (asset.newSource !== undefined) { + compilation.updateAsset( + asset.name, + asset.newSource, + infoUpdate + ); + } else { + compilation.updateAsset(asset.name, asset.source, infoUpdate); + } + + if (asset.name !== newName) { + compilation.renameAsset(asset.name, newName); + } + }) + ); + } + ); + }); + } +} + +module.exports = RealContentHashPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RemoveEmptyChunksPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RemoveEmptyChunksPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d6986acdb4b6c78600b52a42d898c9c448281fcf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RemoveEmptyChunksPlugin.js @@ -0,0 +1,60 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { STAGE_ADVANCED, STAGE_BASIC } = require("../OptimizationStages"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "RemoveEmptyChunksPlugin"; + +class RemoveEmptyChunksPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + /** + * @param {Iterable} chunks the chunks array + * @returns {void} + */ + const handler = (chunks) => { + const chunkGraph = compilation.chunkGraph; + for (const chunk of chunks) { + if ( + chunkGraph.getNumberOfChunkModules(chunk) === 0 && + !chunk.hasRuntime() && + chunkGraph.getNumberOfEntryModules(chunk) === 0 + ) { + compilation.chunkGraph.disconnectChunk(chunk); + compilation.chunks.delete(chunk); + } + } + }; + + // TODO do it once + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: STAGE_BASIC + }, + handler + ); + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: STAGE_ADVANCED + }, + handler + ); + }); + } +} + +module.exports = RemoveEmptyChunksPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RemoveParentModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RemoveParentModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..28b1e6921ab6f0d5c743180bb202b679f75fa037 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RemoveParentModulesPlugin.js @@ -0,0 +1,207 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { STAGE_BASIC } = require("../OptimizationStages"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +/** + * Intersects multiple masks represented as bigints + * @param {bigint[]} masks The module masks to intersect + * @returns {bigint} The intersection of all masks + */ +function intersectMasks(masks) { + let result = masks[0]; + for (let i = masks.length - 1; i >= 1; i--) { + result &= masks[i]; + } + return result; +} + +const ZERO_BIGINT = BigInt(0); +const ONE_BIGINT = BigInt(1); +const THIRTY_TWO_BIGINT = BigInt(32); + +/** + * Parses the module mask and returns the modules represented by it + * @param {bigint} mask the module mask + * @param {Module[]} ordinalModules the modules in the order they were added to the mask (LSB is index 0) + * @returns {Generator} the modules represented by the mask + */ +function* getModulesFromMask(mask, ordinalModules) { + let offset = 31; + while (mask !== ZERO_BIGINT) { + // Consider the last 32 bits, since that's what Math.clz32 can handle + let last32 = Number(BigInt.asUintN(32, mask)); + while (last32 > 0) { + const last = Math.clz32(last32); + // The number of trailing zeros is the number trimmed off the input mask + 31 - the number of leading zeros + // The 32 is baked into the initial value of offset + const moduleIndex = offset - last; + // The number of trailing zeros is the index into the array generated by getOrCreateModuleMask + const module = ordinalModules[moduleIndex]; + yield module; + // Remove the matched module from the mask + // Since we can only count leading zeros, not trailing, we can't just downshift the mask + last32 &= ~(1 << (31 - last)); + } + + // Remove the processed chunk from the mask + mask >>= THIRTY_TWO_BIGINT; + offset += 32; + } +} + +const PLUGIN_NAME = "RemoveParentModulesPlugin"; + +class RemoveParentModulesPlugin { + /** + * @param {Compiler} compiler the compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + /** + * @param {Iterable} chunks the chunks + * @param {ChunkGroup[]} chunkGroups the chunk groups + */ + const handler = (chunks, chunkGroups) => { + const chunkGraph = compilation.chunkGraph; + const queue = new Set(); + const availableModulesMap = new WeakMap(); + + let nextModuleMask = ONE_BIGINT; + const maskByModule = new WeakMap(); + /** @type {Module[]} */ + const ordinalModules = []; + + /** + * Gets or creates a unique mask for a module + * @param {Module} mod the module to get the mask for + * @returns {bigint} the module mask to uniquely identify the module + */ + const getOrCreateModuleMask = (mod) => { + let id = maskByModule.get(mod); + if (id === undefined) { + id = nextModuleMask; + ordinalModules.push(mod); + maskByModule.set(mod, id); + nextModuleMask <<= ONE_BIGINT; + } + return id; + }; + + // Initialize masks by chunk and by chunk group for quicker comparisons + const chunkMasks = new WeakMap(); + for (const chunk of chunks) { + let mask = ZERO_BIGINT; + for (const m of chunkGraph.getChunkModulesIterable(chunk)) { + const id = getOrCreateModuleMask(m); + mask |= id; + } + chunkMasks.set(chunk, mask); + } + + const chunkGroupMasks = new WeakMap(); + for (const chunkGroup of chunkGroups) { + let mask = ZERO_BIGINT; + for (const chunk of chunkGroup.chunks) { + const chunkMask = chunkMasks.get(chunk); + if (chunkMask !== undefined) { + mask |= chunkMask; + } + } + chunkGroupMasks.set(chunkGroup, mask); + } + + for (const chunkGroup of compilation.entrypoints.values()) { + // initialize available modules for chunks without parents + availableModulesMap.set(chunkGroup, ZERO_BIGINT); + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + for (const chunkGroup of compilation.asyncEntrypoints) { + // initialize available modules for chunks without parents + availableModulesMap.set(chunkGroup, ZERO_BIGINT); + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + + for (const chunkGroup of queue) { + let availableModulesMask = availableModulesMap.get(chunkGroup); + let changed = false; + for (const parent of chunkGroup.parentsIterable) { + const availableModulesInParent = availableModulesMap.get(parent); + if (availableModulesInParent !== undefined) { + const parentMask = + availableModulesInParent | chunkGroupMasks.get(parent); + // If we know the available modules in parent: process these + if (availableModulesMask === undefined) { + // if we have not own info yet: create new entry + availableModulesMask = parentMask; + changed = true; + } else { + const newMask = availableModulesMask & parentMask; + if (newMask !== availableModulesMask) { + changed = true; + availableModulesMask = newMask; + } + } + } + } + + if (changed) { + availableModulesMap.set(chunkGroup, availableModulesMask); + // if something changed: enqueue our children + for (const child of chunkGroup.childrenIterable) { + // Push the child to the end of the queue + queue.delete(child); + queue.add(child); + } + } + } + + // now we have available modules for every chunk + for (const chunk of chunks) { + const chunkMask = chunkMasks.get(chunk); + if (chunkMask === undefined) continue; // No info about this chunk + + const availableModulesSets = Array.from( + chunk.groupsIterable, + (chunkGroup) => availableModulesMap.get(chunkGroup) + ); + if (availableModulesSets.includes(undefined)) continue; // No info about this chunk group + + const availableModulesMask = intersectMasks(availableModulesSets); + const toRemoveMask = chunkMask & availableModulesMask; + if (toRemoveMask !== ZERO_BIGINT) { + for (const module of getModulesFromMask( + toRemoveMask, + ordinalModules + )) { + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } + } + }; + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: STAGE_BASIC + }, + handler + ); + }); + } +} + +module.exports = RemoveParentModulesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RuntimeChunkPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RuntimeChunkPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..061a0fb6c684c71e336209656c3b1436aa41a9dd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/RuntimeChunkPlugin.js @@ -0,0 +1,55 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../Compilation").EntryData} EntryData */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint")} Entrypoint */ + +const PLUGIN_NAME = "RuntimeChunkPlugin"; + +/** @typedef {(entrypoint: { name: string }) => string} RuntimeChunkFunction */ + +class RuntimeChunkPlugin { + /** + * @param {{ name?: RuntimeChunkFunction }=} options options + */ + constructor(options) { + this.options = { + /** @type {RuntimeChunkFunction} */ + name: (entrypoint) => `runtime~${entrypoint.name}`, + ...options + }; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.addEntry.tap(PLUGIN_NAME, (_, { name: entryName }) => { + if (entryName === undefined) return; + const data = + /** @type {EntryData} */ + (compilation.entries.get(entryName)); + if (data.options.runtime === undefined && !data.options.dependOn) { + // Determine runtime chunk name + let name = + /** @type {string | RuntimeChunkFunction} */ + (this.options.name); + if (typeof name === "function") { + name = name({ name: entryName }); + } + data.options.runtime = name; + } + }); + }); + } +} + +module.exports = RuntimeChunkPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/SideEffectsFlagPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/SideEffectsFlagPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f66eaadda1d1c2184ddec5e00a999991c43922a6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/SideEffectsFlagPlugin.js @@ -0,0 +1,420 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const glob2regexp = require("glob-to-regexp"); +const { + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_DYNAMIC, + JAVASCRIPT_MODULE_TYPE_ESM +} = require("../ModuleTypeConstants"); +const { STAGE_DEFAULT } = require("../OptimizationStages"); +const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency"); +const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency"); +const formatLocation = require("../formatLocation"); + +/** @typedef {import("estree").MaybeNamedClassDeclaration} MaybeNamedClassDeclaration */ +/** @typedef {import("estree").MaybeNamedFunctionDeclaration} MaybeNamedFunctionDeclaration */ +/** @typedef {import("estree").ModuleDeclaration} ModuleDeclaration */ +/** @typedef {import("estree").Statement} Statement */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../NormalModuleFactory").ModuleSettings} ModuleSettings */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +/** + * @typedef {object} ExportInModule + * @property {Module} module the module + * @property {string} exportName the name of the export + * @property {boolean} checked if the export is conditional + */ + +/** + * @typedef {object} ReexportInfo + * @property {Map} static + * @property {Map>} dynamic + */ + +/** @typedef {Map} CacheItem */ + +/** @type {WeakMap} */ +const globToRegexpCache = new WeakMap(); + +/** + * @param {string} glob the pattern + * @param {Map} cache the glob to RegExp cache + * @returns {RegExp} a regular expression + */ +const globToRegexp = (glob, cache) => { + const cacheEntry = cache.get(glob); + if (cacheEntry !== undefined) return cacheEntry; + if (!glob.includes("/")) { + glob = `**/${glob}`; + } + const baseRegexp = glob2regexp(glob, { globstar: true, extended: true }); + const regexpSource = baseRegexp.source; + const regexp = new RegExp(`^(\\./)?${regexpSource.slice(1)}`); + cache.set(glob, regexp); + return regexp; +}; + +const PLUGIN_NAME = "SideEffectsFlagPlugin"; + +class SideEffectsFlagPlugin { + /** + * @param {boolean} analyseSource analyse source code for side effects + */ + constructor(analyseSource = true) { + this._analyseSource = analyseSource; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + let cache = globToRegexpCache.get(compiler.root); + if (cache === undefined) { + cache = new Map(); + globToRegexpCache.set(compiler.root, cache); + } + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + const moduleGraph = compilation.moduleGraph; + normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module, data) => { + const resolveData = data.resourceResolveData; + if ( + resolveData && + resolveData.descriptionFileData && + resolveData.relativePath + ) { + const sideEffects = resolveData.descriptionFileData.sideEffects; + if (sideEffects !== undefined) { + if (module.factoryMeta === undefined) { + module.factoryMeta = {}; + } + const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects( + resolveData.relativePath, + /** @type {string | boolean | string[] | undefined} */ ( + sideEffects + ), + /** @type {CacheItem} */ (cache) + ); + module.factoryMeta.sideEffectFree = !hasSideEffects; + } + } + + return module; + }); + normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module, data) => { + const settings = /** @type {ModuleSettings} */ (data.settings); + if (typeof settings.sideEffects === "boolean") { + if (module.factoryMeta === undefined) { + module.factoryMeta = {}; + } + module.factoryMeta.sideEffectFree = !settings.sideEffects; + } + return module; + }); + if (this._analyseSource) { + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const parserHandler = (parser) => { + /** @type {undefined | Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */ + let sideEffectsStatement; + parser.hooks.program.tap(PLUGIN_NAME, () => { + sideEffectsStatement = undefined; + }); + parser.hooks.statement.tap( + { name: PLUGIN_NAME, stage: -100 }, + (statement) => { + if (sideEffectsStatement) return; + if (parser.scope.topLevelScope !== true) return; + switch (statement.type) { + case "ExpressionStatement": + if ( + !parser.isPure( + statement.expression, + /** @type {Range} */ + (statement.range)[0] + ) + ) { + sideEffectsStatement = statement; + } + break; + case "IfStatement": + case "WhileStatement": + case "DoWhileStatement": + if ( + !parser.isPure( + statement.test, + /** @type {Range} */ + (statement.range)[0] + ) + ) { + sideEffectsStatement = statement; + } + // statement hook will be called for child statements too + break; + case "ForStatement": + if ( + !parser.isPure( + statement.init, + /** @type {Range} */ (statement.range)[0] + ) || + !parser.isPure( + statement.test, + statement.init + ? /** @type {Range} */ (statement.init.range)[1] + : /** @type {Range} */ (statement.range)[0] + ) || + !parser.isPure( + statement.update, + statement.test + ? /** @type {Range} */ (statement.test.range)[1] + : statement.init + ? /** @type {Range} */ (statement.init.range)[1] + : /** @type {Range} */ (statement.range)[0] + ) + ) { + sideEffectsStatement = statement; + } + // statement hook will be called for child statements too + break; + case "SwitchStatement": + if ( + !parser.isPure( + statement.discriminant, + /** @type {Range} */ + (statement.range)[0] + ) + ) { + sideEffectsStatement = statement; + } + // statement hook will be called for child statements too + break; + case "VariableDeclaration": + case "ClassDeclaration": + case "FunctionDeclaration": + if ( + !parser.isPure( + statement, + /** @type {Range} */ (statement.range)[0] + ) + ) { + sideEffectsStatement = statement; + } + break; + case "ExportNamedDeclaration": + case "ExportDefaultDeclaration": + if ( + !parser.isPure( + statement.declaration, + /** @type {Range} */ + (statement.range)[0] + ) + ) { + sideEffectsStatement = statement; + } + break; + case "LabeledStatement": + case "BlockStatement": + // statement hook will be called for child statements too + break; + case "EmptyStatement": + break; + case "ExportAllDeclaration": + case "ImportDeclaration": + // imports will be handled by the dependencies + break; + default: + sideEffectsStatement = statement; + break; + } + } + ); + parser.hooks.finish.tap(PLUGIN_NAME, () => { + if (sideEffectsStatement === undefined) { + /** @type {BuildMeta} */ + (parser.state.module.buildMeta).sideEffectFree = true; + } else { + const { loc, type } = sideEffectsStatement; + moduleGraph + .getOptimizationBailout(parser.state.module) + .push( + () => + `Statement (${type}) with side effects in source code at ${formatLocation( + /** @type {DependencyLocation} */ (loc) + )}` + ); + } + }); + }; + for (const key of [ + JAVASCRIPT_MODULE_TYPE_AUTO, + JAVASCRIPT_MODULE_TYPE_ESM, + JAVASCRIPT_MODULE_TYPE_DYNAMIC + ]) { + normalModuleFactory.hooks.parser + .for(key) + .tap(PLUGIN_NAME, parserHandler); + } + } + compilation.hooks.optimizeDependencies.tap( + { + name: PLUGIN_NAME, + stage: STAGE_DEFAULT + }, + (modules) => { + const logger = compilation.getLogger( + "webpack.SideEffectsFlagPlugin" + ); + + logger.time("update dependencies"); + + const optimizedModules = new Set(); + + /** + * @param {Module} module module + */ + const optimizeIncomingConnections = (module) => { + if (optimizedModules.has(module)) return; + optimizedModules.add(module); + if (module.getSideEffectsConnectionState(moduleGraph) === false) { + const exportsInfo = moduleGraph.getExportsInfo(module); + for (const connection of moduleGraph.getIncomingConnections( + module + )) { + const dep = connection.dependency; + let isReexport; + if ( + (isReexport = + dep instanceof + HarmonyExportImportedSpecifierDependency) || + (dep instanceof HarmonyImportSpecifierDependency && + !dep.namespaceObjectAsContext) + ) { + if (connection.originModule !== null) { + optimizeIncomingConnections(connection.originModule); + } + // TODO improve for export * + if (isReexport && dep.name) { + const exportInfo = moduleGraph.getExportInfo( + /** @type {Module} */ (connection.originModule), + dep.name + ); + exportInfo.moveTarget( + moduleGraph, + ({ module }) => + module.getSideEffectsConnectionState(moduleGraph) === + false, + ({ + module: newModule, + export: exportName, + connection: targetConnection + }) => { + moduleGraph.updateModule(dep, newModule); + moduleGraph.updateParent( + dep, + targetConnection, + /** @type {Module} */ (connection.originModule) + ); + moduleGraph.addExplanation( + dep, + "(skipped side-effect-free modules)" + ); + const ids = dep.getIds(moduleGraph); + dep.setIds( + moduleGraph, + exportName + ? [...exportName, ...ids.slice(1)] + : ids.slice(1) + ); + return /** @type {ModuleGraphConnection} */ ( + moduleGraph.getConnection(dep) + ); + } + ); + continue; + } + // TODO improve for nested imports + const ids = dep.getIds(moduleGraph); + if (ids.length > 0) { + const exportInfo = exportsInfo.getExportInfo(ids[0]); + const target = exportInfo.getTarget( + moduleGraph, + ({ module }) => + module.getSideEffectsConnectionState(moduleGraph) === + false + ); + if (!target) continue; + + moduleGraph.updateModule(dep, target.module); + moduleGraph.updateParent( + dep, + /** @type {ModuleGraphConnection} */ ( + target.connection + ), + /** @type {Module} */ (connection.originModule) + ); + moduleGraph.addExplanation( + dep, + "(skipped side-effect-free modules)" + ); + dep.setIds( + moduleGraph, + target.export + ? [...target.export, ...ids.slice(1)] + : ids.slice(1) + ); + } + } + } + } + }; + + for (const module of modules) { + optimizeIncomingConnections(module); + } + logger.timeEnd("update dependencies"); + } + ); + } + ); + } + + /** + * @param {string} moduleName the module name + * @param {undefined | boolean | string | string[]} flagValue the flag value + * @param {Map} cache cache for glob to regexp + * @returns {boolean | undefined} true, when the module has side effects, undefined or false when not + */ + static moduleHasSideEffects(moduleName, flagValue, cache) { + switch (typeof flagValue) { + case "undefined": + return true; + case "boolean": + return flagValue; + case "string": + return globToRegexp(flagValue, cache).test(moduleName); + case "object": + return flagValue.some((glob) => + SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob, cache) + ); + } + } +} + +module.exports = SideEffectsFlagPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/SplitChunksPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/SplitChunksPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..747f2dada4d8cf6d66e16f5de8e3d3af46718312 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/optimize/SplitChunksPlugin.js @@ -0,0 +1,1798 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Chunk = require("../Chunk"); +const { STAGE_ADVANCED } = require("../OptimizationStages"); +const WebpackError = require("../WebpackError"); +const { requestToId } = require("../ids/IdHelpers"); +const { isSubset } = require("../util/SetHelpers"); +const SortableSet = require("../util/SortableSet"); +const { + compareIterables, + compareModulesByIdentifier +} = require("../util/comparators"); +const createHash = require("../util/createHash"); +const deterministicGrouping = require("../util/deterministicGrouping"); +const { makePathsRelative } = require("../util/identifier"); +const memoize = require("../util/memoize"); +const MinMaxSizeWarning = require("./MinMaxSizeWarning"); + +/** @typedef {import("../../declarations/WebpackOptions").HashFunction} HashFunction */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksCacheGroup} OptimizationSplitChunksCacheGroup */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksGetCacheGroups} OptimizationSplitChunksGetCacheGroups */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksSizes} OptimizationSplitChunksSizes */ +/** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("../Chunk").ChunkName} ChunkName */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ +/** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ + +/** @typedef {Record} SplitChunksSizes */ + +/** + * @callback ChunkFilterFunction + * @param {Chunk} chunk + * @returns {boolean | undefined} + */ + +/** + * @callback CombineSizeFunction + * @param {number} a + * @param {number} b + * @returns {number} + */ + +/** + * @typedef {object} CacheGroupSource + * @property {string} key + * @property {number=} priority + * @property {GetName=} getName + * @property {ChunkFilterFunction=} chunksFilter + * @property {boolean=} enforce + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} minSizeReduction + * @property {SplitChunksSizes} minRemainingSize + * @property {SplitChunksSizes} enforceSizeThreshold + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {number=} minChunks + * @property {number=} maxAsyncRequests + * @property {number=} maxInitialRequests + * @property {TemplatePath=} filename + * @property {string=} idHint + * @property {string=} automaticNameDelimiter + * @property {boolean=} reuseExistingChunk + * @property {boolean=} usedExports + */ + +/** + * @typedef {object} CacheGroup + * @property {string} key + * @property {number} priority + * @property {GetName=} getName + * @property {ChunkFilterFunction} chunksFilter + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} minSizeReduction + * @property {SplitChunksSizes} minRemainingSize + * @property {SplitChunksSizes} enforceSizeThreshold + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {number} minChunks + * @property {number} maxAsyncRequests + * @property {number} maxInitialRequests + * @property {TemplatePath=} filename + * @property {string} idHint + * @property {string} automaticNameDelimiter + * @property {boolean} reuseExistingChunk + * @property {boolean} usedExports + * @property {boolean} _validateSize + * @property {boolean} _validateRemainingSize + * @property {SplitChunksSizes} _minSizeForMaxSize + * @property {boolean} _conditionalEnforce + */ + +/** + * @typedef {object} FallbackCacheGroup + * @property {ChunkFilterFunction} chunksFilter + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {string} automaticNameDelimiter + */ + +/** + * @typedef {object} CacheGroupsContext + * @property {ModuleGraph} moduleGraph + * @property {ChunkGraph} chunkGraph + */ + +/** + * @callback GetCacheGroups + * @param {Module} module + * @param {CacheGroupsContext} context + * @returns {CacheGroupSource[] | null} + */ + +/** + * @callback GetName + * @param {Module} module + * @param {Chunk[]} chunks + * @param {string} key + * @returns {string=} + */ + +/** + * @typedef {object} SplitChunksOptions + * @property {ChunkFilterFunction} chunksFilter + * @property {string[]} defaultSizeTypes + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} minSizeReduction + * @property {SplitChunksSizes} minRemainingSize + * @property {SplitChunksSizes} enforceSizeThreshold + * @property {SplitChunksSizes} maxInitialSize + * @property {SplitChunksSizes} maxAsyncSize + * @property {number} minChunks + * @property {number} maxAsyncRequests + * @property {number} maxInitialRequests + * @property {boolean} hidePathInfo + * @property {TemplatePath=} filename + * @property {string} automaticNameDelimiter + * @property {GetCacheGroups} getCacheGroups + * @property {GetName} getName + * @property {boolean} usedExports + * @property {FallbackCacheGroup} fallbackCacheGroup + */ + +/** + * @typedef {object} ChunksInfoItem + * @property {SortableSet} modules + * @property {CacheGroup} cacheGroup + * @property {number} cacheGroupIndex + * @property {string=} name + * @property {Record} sizes + * @property {Set} chunks + * @property {Set} reusableChunks + * @property {Set} chunksKeys + */ + +/** @type {GetName} */ +const defaultGetName = () => undefined; + +const deterministicGroupingForModules = + /** @type {(options: DeterministicGroupingOptionsForModule) => DeterministicGroupingGroupedItemsForModule[]} */ + (deterministicGrouping); + +/** @type {WeakMap} */ +const getKeyCache = new WeakMap(); + +/** + * @param {string} name a filename to hash + * @param {OutputOptions} outputOptions hash function used + * @returns {string} hashed filename + */ +const hashFilename = (name, outputOptions) => { + const digest = + /** @type {string} */ + ( + createHash(/** @type {HashFunction} */ (outputOptions.hashFunction)) + .update(name) + .digest(outputOptions.hashDigest) + ); + return digest.slice(0, 8); +}; + +/** + * @param {Chunk} chunk the chunk + * @returns {number} the number of requests + */ +const getRequests = (chunk) => { + let requests = 0; + for (const chunkGroup of chunk.groupsIterable) { + requests = Math.max(requests, chunkGroup.chunks.length); + } + return requests; +}; + +/** + * @template {object} T + * @template {object} R + * @param {T} obj obj an object + * @param {function(T[keyof T], keyof T): T[keyof T]} fn fn + * @returns {T} result + */ +const mapObject = (obj, fn) => { + const newObj = Object.create(null); + for (const key of Object.keys(obj)) { + newObj[key] = fn( + obj[/** @type {keyof T} */ (key)], + /** @type {keyof T} */ + (key) + ); + } + return newObj; +}; + +/** + * @template T + * @param {Set} a set + * @param {Set} b other set + * @returns {boolean} true if at least one item of a is in b + */ +const isOverlap = (a, b) => { + for (const item of a) { + if (b.has(item)) return true; + } + return false; +}; + +const compareModuleIterables = compareIterables(compareModulesByIdentifier); + +/** + * @param {ChunksInfoItem} a item + * @param {ChunksInfoItem} b item + * @returns {number} compare result + */ +const compareEntries = (a, b) => { + // 1. by priority + const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority; + if (diffPriority) return diffPriority; + // 2. by number of chunks + const diffCount = a.chunks.size - b.chunks.size; + if (diffCount) return diffCount; + // 3. by size reduction + const aSizeReduce = totalSize(a.sizes) * (a.chunks.size - 1); + const bSizeReduce = totalSize(b.sizes) * (b.chunks.size - 1); + const diffSizeReduce = aSizeReduce - bSizeReduce; + if (diffSizeReduce) return diffSizeReduce; + // 4. by cache group index + const indexDiff = b.cacheGroupIndex - a.cacheGroupIndex; + if (indexDiff) return indexDiff; + // 5. by number of modules (to be able to compare by identifier) + const modulesA = a.modules; + const modulesB = b.modules; + const diff = modulesA.size - modulesB.size; + if (diff) return diff; + // 6. by module identifiers + modulesA.sort(); + modulesB.sort(); + return compareModuleIterables(modulesA, modulesB); +}; + +/** + * @param {Chunk} chunk the chunk + * @returns {boolean} true, if the chunk is an entry chunk + */ +const INITIAL_CHUNK_FILTER = (chunk) => chunk.canBeInitial(); +/** + * @param {Chunk} chunk the chunk + * @returns {boolean} true, if the chunk is an async chunk + */ +const ASYNC_CHUNK_FILTER = (chunk) => !chunk.canBeInitial(); +/** + * @param {Chunk} _chunk the chunk + * @returns {boolean} always true + */ +const ALL_CHUNK_FILTER = (_chunk) => true; + +/** + * @param {OptimizationSplitChunksSizes | undefined} value the sizes + * @param {string[]} defaultSizeTypes the default size types + * @returns {SplitChunksSizes} normalized representation + */ +const normalizeSizes = (value, defaultSizeTypes) => { + if (typeof value === "number") { + /** @type {Record} */ + const o = {}; + for (const sizeType of defaultSizeTypes) o[sizeType] = value; + return o; + } else if (typeof value === "object" && value !== null) { + return { ...value }; + } + return {}; +}; + +/** + * @param {...(SplitChunksSizes | undefined)} sizes the sizes + * @returns {SplitChunksSizes} the merged sizes + */ +const mergeSizes = (...sizes) => { + /** @type {SplitChunksSizes} */ + let merged = {}; + for (let i = sizes.length - 1; i >= 0; i--) { + merged = Object.assign(merged, sizes[i]); + } + return merged; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @returns {boolean} true, if there are sizes > 0 + */ +const hasNonZeroSizes = (sizes) => { + for (const key of Object.keys(sizes)) { + if (sizes[key] > 0) return true; + } + return false; +}; + +/** + * @param {SplitChunksSizes} a first sizes + * @param {SplitChunksSizes} b second sizes + * @param {CombineSizeFunction} combine a function to combine sizes + * @returns {SplitChunksSizes} the combine sizes + */ +const combineSizes = (a, b, combine) => { + const aKeys = new Set(Object.keys(a)); + const bKeys = new Set(Object.keys(b)); + /** @type {SplitChunksSizes} */ + const result = {}; + for (const key of aKeys) { + result[key] = bKeys.has(key) ? combine(a[key], b[key]) : a[key]; + } + for (const key of bKeys) { + if (!aKeys.has(key)) { + result[key] = b[key]; + } + } + return result; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @param {SplitChunksSizes} minSize the min sizes + * @returns {boolean} true if there are sizes and all existing sizes are at least `minSize` + */ +const checkMinSize = (sizes, minSize) => { + for (const key of Object.keys(minSize)) { + const size = sizes[key]; + if (size === undefined || size === 0) continue; + if (size < minSize[key]) return false; + } + return true; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @param {SplitChunksSizes} minSizeReduction the min sizes + * @param {number} chunkCount number of chunks + * @returns {boolean} true if there are sizes and all existing sizes are at least `minSizeReduction` + */ +const checkMinSizeReduction = (sizes, minSizeReduction, chunkCount) => { + for (const key of Object.keys(minSizeReduction)) { + const size = sizes[key]; + if (size === undefined || size === 0) continue; + if (size * chunkCount < minSizeReduction[key]) return false; + } + return true; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @param {SplitChunksSizes} minSize the min sizes + * @returns {undefined | string[]} list of size types that are below min size + */ +const getViolatingMinSizes = (sizes, minSize) => { + let list; + for (const key of Object.keys(minSize)) { + const size = sizes[key]; + if (size === undefined || size === 0) continue; + if (size < minSize[key]) { + if (list === undefined) list = [key]; + else list.push(key); + } + } + return list; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @returns {number} the total size + */ +const totalSize = (sizes) => { + let size = 0; + for (const key of Object.keys(sizes)) { + size += sizes[key]; + } + return size; +}; + +/** + * @param {OptimizationSplitChunksCacheGroup["name"]} name the chunk name + * @returns {GetName | undefined} a function to get the name of the chunk + */ +const normalizeName = (name) => { + if (typeof name === "string") { + return () => name; + } + if (typeof name === "function") { + return /** @type {GetName} */ (name); + } +}; + +/** + * @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option + * @returns {ChunkFilterFunction | undefined} the chunk filter function + */ +const normalizeChunksFilter = (chunks) => { + if (chunks === "initial") { + return INITIAL_CHUNK_FILTER; + } + if (chunks === "async") { + return ASYNC_CHUNK_FILTER; + } + if (chunks === "all") { + return ALL_CHUNK_FILTER; + } + if (chunks instanceof RegExp) { + return (chunk) => (chunk.name ? chunks.test(chunk.name) : false); + } + if (typeof chunks === "function") { + return chunks; + } +}; + +/** + * @param {undefined | GetCacheGroups | Record} cacheGroups the cache group options + * @param {string[]} defaultSizeTypes the default size types + * @returns {GetCacheGroups} a function to get the cache groups + */ +const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => { + if (typeof cacheGroups === "function") { + return cacheGroups; + } + if (typeof cacheGroups === "object" && cacheGroups !== null) { + /** @type {((module: Module, context: CacheGroupsContext, results: CacheGroupSource[]) => void)[]} */ + const handlers = []; + for (const key of Object.keys(cacheGroups)) { + const option = cacheGroups[key]; + if (option === false) { + continue; + } + if (typeof option === "string" || option instanceof RegExp) { + const source = createCacheGroupSource({}, key, defaultSizeTypes); + handlers.push((module, context, results) => { + if (checkTest(option, module, context)) { + results.push(source); + } + }); + } else if (typeof option === "function") { + const cache = new WeakMap(); + handlers.push((module, context, results) => { + const result = option(module); + if (result) { + const groups = Array.isArray(result) ? result : [result]; + for (const group of groups) { + const cachedSource = cache.get(group); + if (cachedSource !== undefined) { + results.push(cachedSource); + } else { + const source = createCacheGroupSource( + group, + key, + defaultSizeTypes + ); + cache.set(group, source); + results.push(source); + } + } + } + }); + } else { + const source = createCacheGroupSource(option, key, defaultSizeTypes); + handlers.push((module, context, results) => { + if ( + checkTest(option.test, module, context) && + checkModuleType(option.type, module) && + checkModuleLayer(option.layer, module) + ) { + results.push(source); + } + }); + } + } + /** + * @param {Module} module the current module + * @param {CacheGroupsContext} context the current context + * @returns {CacheGroupSource[]} the matching cache groups + */ + const fn = (module, context) => { + /** @type {CacheGroupSource[]} */ + const results = []; + for (const fn of handlers) { + fn(module, context, results); + } + return results; + }; + return fn; + } + return () => null; +}; + +/** + * @param {OptimizationSplitChunksCacheGroup["test"]} test test option + * @param {Module} module the module + * @param {CacheGroupsContext} context context object + * @returns {boolean} true, if the module should be selected + */ +const checkTest = (test, module, context) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module, context); + } + if (typeof test === "boolean") return test; + if (typeof test === "string") { + const name = module.nameForCondition(); + return name ? name.startsWith(test) : false; + } + if (test instanceof RegExp) { + const name = module.nameForCondition(); + return name ? test.test(name) : false; + } + return false; +}; + +/** + * @param {OptimizationSplitChunksCacheGroup["type"]} test type option + * @param {Module} module the module + * @returns {boolean} true, if the module should be selected + */ +const checkModuleType = (test, module) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module.type); + } + if (typeof test === "string") { + const type = module.type; + return test === type; + } + if (test instanceof RegExp) { + const type = module.type; + return test.test(type); + } + return false; +}; + +/** + * @param {OptimizationSplitChunksCacheGroup["layer"]} test type option + * @param {Module} module the module + * @returns {boolean} true, if the module should be selected + */ +const checkModuleLayer = (test, module) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module.layer); + } + if (typeof test === "string") { + const layer = module.layer; + return test === "" ? !layer : layer ? layer.startsWith(test) : false; + } + if (test instanceof RegExp) { + const layer = module.layer; + return layer ? test.test(layer) : false; + } + return false; +}; + +/** + * @param {OptimizationSplitChunksCacheGroup} options the group options + * @param {string} key key of cache group + * @param {string[]} defaultSizeTypes the default size types + * @returns {CacheGroupSource} the normalized cached group + */ +const createCacheGroupSource = (options, key, defaultSizeTypes) => { + const minSize = normalizeSizes(options.minSize, defaultSizeTypes); + const minSizeReduction = normalizeSizes( + options.minSizeReduction, + defaultSizeTypes + ); + const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); + return { + key, + priority: options.priority, + getName: normalizeName(options.name), + chunksFilter: normalizeChunksFilter(options.chunks), + enforce: options.enforce, + minSize, + minSizeReduction, + minRemainingSize: mergeSizes( + normalizeSizes(options.minRemainingSize, defaultSizeTypes), + minSize + ), + enforceSizeThreshold: normalizeSizes( + options.enforceSizeThreshold, + defaultSizeTypes + ), + maxAsyncSize: mergeSizes( + normalizeSizes(options.maxAsyncSize, defaultSizeTypes), + maxSize + ), + maxInitialSize: mergeSizes( + normalizeSizes(options.maxInitialSize, defaultSizeTypes), + maxSize + ), + minChunks: options.minChunks, + maxAsyncRequests: options.maxAsyncRequests, + maxInitialRequests: options.maxInitialRequests, + filename: options.filename, + idHint: options.idHint, + automaticNameDelimiter: options.automaticNameDelimiter, + reuseExistingChunk: options.reuseExistingChunk, + usedExports: options.usedExports + }; +}; + +const PLUGIN_NAME = "SplitChunksPlugin"; + +module.exports = class SplitChunksPlugin { + /** + * @param {OptimizationSplitChunksOptions=} options plugin options + */ + constructor(options = {}) { + const defaultSizeTypes = options.defaultSizeTypes || [ + "javascript", + "unknown" + ]; + const fallbackCacheGroup = options.fallbackCacheGroup || {}; + const minSize = normalizeSizes(options.minSize, defaultSizeTypes); + const minSizeReduction = normalizeSizes( + options.minSizeReduction, + defaultSizeTypes + ); + const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); + + /** @type {SplitChunksOptions} */ + this.options = { + chunksFilter: + /** @type {ChunkFilterFunction} */ + (normalizeChunksFilter(options.chunks || "all")), + defaultSizeTypes, + minSize, + minSizeReduction, + minRemainingSize: mergeSizes( + normalizeSizes(options.minRemainingSize, defaultSizeTypes), + minSize + ), + enforceSizeThreshold: normalizeSizes( + options.enforceSizeThreshold, + defaultSizeTypes + ), + maxAsyncSize: mergeSizes( + normalizeSizes(options.maxAsyncSize, defaultSizeTypes), + maxSize + ), + maxInitialSize: mergeSizes( + normalizeSizes(options.maxInitialSize, defaultSizeTypes), + maxSize + ), + minChunks: options.minChunks || 1, + maxAsyncRequests: options.maxAsyncRequests || 1, + maxInitialRequests: options.maxInitialRequests || 1, + hidePathInfo: options.hidePathInfo || false, + filename: options.filename || undefined, + getCacheGroups: normalizeCacheGroups( + options.cacheGroups, + defaultSizeTypes + ), + getName: options.name + ? /** @type {GetName} */ (normalizeName(options.name)) + : defaultGetName, + automaticNameDelimiter: options.automaticNameDelimiter || "-", + usedExports: options.usedExports || false, + fallbackCacheGroup: { + chunksFilter: + /** @type {ChunkFilterFunction} */ + ( + normalizeChunksFilter( + fallbackCacheGroup.chunks || options.chunks || "all" + ) + ), + minSize: mergeSizes( + normalizeSizes(fallbackCacheGroup.minSize, defaultSizeTypes), + minSize + ), + maxAsyncSize: mergeSizes( + normalizeSizes(fallbackCacheGroup.maxAsyncSize, defaultSizeTypes), + normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), + normalizeSizes(options.maxAsyncSize, defaultSizeTypes), + normalizeSizes(options.maxSize, defaultSizeTypes) + ), + maxInitialSize: mergeSizes( + normalizeSizes(fallbackCacheGroup.maxInitialSize, defaultSizeTypes), + normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), + normalizeSizes(options.maxInitialSize, defaultSizeTypes), + normalizeSizes(options.maxSize, defaultSizeTypes) + ), + automaticNameDelimiter: + fallbackCacheGroup.automaticNameDelimiter || + options.automaticNameDelimiter || + "~" + } + }; + + /** @type {WeakMap} */ + this._cacheGroupCache = new WeakMap(); + } + + /** + * @param {CacheGroupSource} cacheGroupSource source + * @returns {CacheGroup} the cache group (cached) + */ + _getCacheGroup(cacheGroupSource) { + const cacheEntry = this._cacheGroupCache.get(cacheGroupSource); + if (cacheEntry !== undefined) return cacheEntry; + const minSize = mergeSizes( + cacheGroupSource.minSize, + cacheGroupSource.enforce ? undefined : this.options.minSize + ); + const minSizeReduction = mergeSizes( + cacheGroupSource.minSizeReduction, + cacheGroupSource.enforce ? undefined : this.options.minSizeReduction + ); + const minRemainingSize = mergeSizes( + cacheGroupSource.minRemainingSize, + cacheGroupSource.enforce ? undefined : this.options.minRemainingSize + ); + const enforceSizeThreshold = mergeSizes( + cacheGroupSource.enforceSizeThreshold, + cacheGroupSource.enforce ? undefined : this.options.enforceSizeThreshold + ); + /** @type {CacheGroup} */ + const cacheGroup = { + key: cacheGroupSource.key, + priority: cacheGroupSource.priority || 0, + chunksFilter: cacheGroupSource.chunksFilter || this.options.chunksFilter, + minSize, + minSizeReduction, + minRemainingSize, + enforceSizeThreshold, + maxAsyncSize: mergeSizes( + cacheGroupSource.maxAsyncSize, + cacheGroupSource.enforce ? undefined : this.options.maxAsyncSize + ), + maxInitialSize: mergeSizes( + cacheGroupSource.maxInitialSize, + cacheGroupSource.enforce ? undefined : this.options.maxInitialSize + ), + minChunks: + cacheGroupSource.minChunks !== undefined + ? cacheGroupSource.minChunks + : cacheGroupSource.enforce + ? 1 + : this.options.minChunks, + maxAsyncRequests: + cacheGroupSource.maxAsyncRequests !== undefined + ? cacheGroupSource.maxAsyncRequests + : cacheGroupSource.enforce + ? Infinity + : this.options.maxAsyncRequests, + maxInitialRequests: + cacheGroupSource.maxInitialRequests !== undefined + ? cacheGroupSource.maxInitialRequests + : cacheGroupSource.enforce + ? Infinity + : this.options.maxInitialRequests, + getName: + cacheGroupSource.getName !== undefined + ? cacheGroupSource.getName + : this.options.getName, + usedExports: + cacheGroupSource.usedExports !== undefined + ? cacheGroupSource.usedExports + : this.options.usedExports, + filename: + cacheGroupSource.filename !== undefined + ? cacheGroupSource.filename + : this.options.filename, + automaticNameDelimiter: + cacheGroupSource.automaticNameDelimiter !== undefined + ? cacheGroupSource.automaticNameDelimiter + : this.options.automaticNameDelimiter, + idHint: + cacheGroupSource.idHint !== undefined + ? cacheGroupSource.idHint + : cacheGroupSource.key, + reuseExistingChunk: cacheGroupSource.reuseExistingChunk || false, + _validateSize: hasNonZeroSizes(minSize), + _validateRemainingSize: hasNonZeroSizes(minRemainingSize), + _minSizeForMaxSize: mergeSizes( + cacheGroupSource.minSize, + this.options.minSize + ), + _conditionalEnforce: hasNonZeroSizes(enforceSizeThreshold) + }; + this._cacheGroupCache.set(cacheGroupSource, cacheGroup); + return cacheGroup; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const cachedMakePathsRelative = makePathsRelative.bindContextCache( + compiler.context, + compiler.root + ); + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const logger = compilation.getLogger(`webpack.${PLUGIN_NAME}`); + let alreadyOptimized = false; + compilation.hooks.unseal.tap(PLUGIN_NAME, () => { + alreadyOptimized = false; + }); + compilation.hooks.optimizeChunks.tap( + { + name: PLUGIN_NAME, + stage: STAGE_ADVANCED + }, + (chunks) => { + if (alreadyOptimized) return; + alreadyOptimized = true; + logger.time("prepare"); + const chunkGraph = compilation.chunkGraph; + const moduleGraph = compilation.moduleGraph; + // Give each selected chunk an index (to create strings from chunks) + /** @type {Map} */ + const chunkIndexMap = new Map(); + const ZERO = BigInt("0"); + const ONE = BigInt("1"); + const START = ONE << BigInt("31"); + let index = START; + for (const chunk of chunks) { + chunkIndexMap.set( + chunk, + index | BigInt((Math.random() * 0x7fffffff) | 0) + ); + index <<= ONE; + } + /** + * @param {Iterable} chunks list of chunks + * @returns {bigint | Chunk} key of the chunks + */ + const getKey = (chunks) => { + const iterator = chunks[Symbol.iterator](); + let result = iterator.next(); + if (result.done) return ZERO; + const first = result.value; + result = iterator.next(); + if (result.done) return first; + let key = + /** @type {bigint} */ (chunkIndexMap.get(first)) | + /** @type {bigint} */ (chunkIndexMap.get(result.value)); + while (!(result = iterator.next()).done) { + const raw = chunkIndexMap.get(result.value); + key ^= /** @type {bigint} */ (raw); + } + return key; + }; + /** + * @param {bigint | Chunk} key key of the chunks + * @returns {string} stringified key + */ + const keyToString = (key) => { + if (typeof key === "bigint") return key.toString(16); + return /** @type {bigint} */ (chunkIndexMap.get(key)).toString(16); + }; + + const getChunkSetsInGraph = memoize(() => { + /** @type {Map>} */ + const chunkSetsInGraph = new Map(); + /** @type {Set} */ + const singleChunkSets = new Set(); + for (const module of compilation.modules) { + const chunks = chunkGraph.getModuleChunksIterable(module); + const chunksKey = getKey(chunks); + if (typeof chunksKey === "bigint") { + if (!chunkSetsInGraph.has(chunksKey)) { + chunkSetsInGraph.set(chunksKey, new Set(chunks)); + } + } else { + singleChunkSets.add(chunksKey); + } + } + return { chunkSetsInGraph, singleChunkSets }; + }); + + /** + * @param {Module} module the module + * @returns {Iterable} groups of chunks with equal exports + */ + const groupChunksByExports = (module) => { + const exportsInfo = moduleGraph.getExportsInfo(module); + const groupedByUsedExports = new Map(); + for (const chunk of chunkGraph.getModuleChunksIterable(module)) { + const key = exportsInfo.getUsageKey(chunk.runtime); + const list = groupedByUsedExports.get(key); + if (list !== undefined) { + list.push(chunk); + } else { + groupedByUsedExports.set(key, [chunk]); + } + } + return groupedByUsedExports.values(); + }; + + /** @type {Map>} */ + const groupedByExportsMap = new Map(); + + const getExportsChunkSetsInGraph = memoize(() => { + /** @type {Map>} */ + const chunkSetsInGraph = new Map(); + /** @type {Set} */ + const singleChunkSets = new Set(); + for (const module of compilation.modules) { + const groupedChunks = [...groupChunksByExports(module)]; + groupedByExportsMap.set(module, groupedChunks); + for (const chunks of groupedChunks) { + if (chunks.length === 1) { + singleChunkSets.add(chunks[0]); + } else { + const chunksKey = getKey(chunks); + if (!chunkSetsInGraph.has(chunksKey)) { + chunkSetsInGraph.set(chunksKey, new Set(chunks)); + } + } + } + } + return { chunkSetsInGraph, singleChunkSets }; + }); + + // group these set of chunks by count + // to allow to check less sets via isSubset + // (only smaller sets can be subset) + /** + * @param {IterableIterator>} chunkSets set of sets of chunks + * @returns {Map>>} map of sets of chunks by count + */ + const groupChunkSetsByCount = (chunkSets) => { + /** @type {Map>>} */ + const chunkSetsByCount = new Map(); + for (const chunksSet of chunkSets) { + const count = chunksSet.size; + let array = chunkSetsByCount.get(count); + if (array === undefined) { + array = []; + chunkSetsByCount.set(count, array); + } + array.push(chunksSet); + } + return chunkSetsByCount; + }; + const getChunkSetsByCount = memoize(() => + groupChunkSetsByCount( + getChunkSetsInGraph().chunkSetsInGraph.values() + ) + ); + const getExportsChunkSetsByCount = memoize(() => + groupChunkSetsByCount( + getExportsChunkSetsInGraph().chunkSetsInGraph.values() + ) + ); + + // Create a list of possible combinations + /** + * @param {Map>} chunkSets chunk sets + * @param {Set} singleChunkSets single chunks sets + * @param {Map[]>} chunkSetsByCount chunk sets by count + * @returns {(key: bigint | Chunk) => (Set | Chunk)[]} combinations + */ + const createGetCombinations = ( + chunkSets, + singleChunkSets, + chunkSetsByCount + ) => { + /** @type {Map | Chunk)[]>} */ + const combinationsCache = new Map(); + + return (key) => { + const cacheEntry = combinationsCache.get(key); + if (cacheEntry !== undefined) return cacheEntry; + if (key instanceof Chunk) { + const result = [key]; + combinationsCache.set(key, result); + return result; + } + const chunksSet = + /** @type {Set} */ + (chunkSets.get(key)); + /** @type {(Set | Chunk)[]} */ + const array = [chunksSet]; + for (const [count, setArray] of chunkSetsByCount) { + // "equal" is not needed because they would have been merge in the first step + if (count < chunksSet.size) { + for (const set of setArray) { + if (isSubset(chunksSet, set)) { + array.push(set); + } + } + } + } + for (const chunk of singleChunkSets) { + if (chunksSet.has(chunk)) { + array.push(chunk); + } + } + combinationsCache.set(key, array); + return array; + }; + }; + + const getCombinationsFactory = memoize(() => { + const { chunkSetsInGraph, singleChunkSets } = getChunkSetsInGraph(); + return createGetCombinations( + chunkSetsInGraph, + singleChunkSets, + getChunkSetsByCount() + ); + }); + + /** + * @param {bigint | Chunk} key key + * @returns {(Set | Chunk)[]} combinations by key + */ + const getCombinations = (key) => getCombinationsFactory()(key); + + const getExportsCombinationsFactory = memoize(() => { + const { chunkSetsInGraph, singleChunkSets } = + getExportsChunkSetsInGraph(); + return createGetCombinations( + chunkSetsInGraph, + singleChunkSets, + getExportsChunkSetsByCount() + ); + }); + /** + * @param {bigint | Chunk} key key + * @returns {(Set | Chunk)[]} exports combinations by key + */ + const getExportsCombinations = (key) => + getExportsCombinationsFactory()(key); + + /** + * @typedef {object} SelectedChunksResult + * @property {Chunk[]} chunks the list of chunks + * @property {bigint | Chunk} key a key of the list + */ + + /** @type {WeakMap | Chunk, WeakMap>} */ + const selectedChunksCacheByChunksSet = new WeakMap(); + + /** + * get list and key by applying the filter function to the list + * It is cached for performance reasons + * @param {Set | Chunk} chunks list of chunks + * @param {ChunkFilterFunction} chunkFilter filter function for chunks + * @returns {SelectedChunksResult} list and key + */ + const getSelectedChunks = (chunks, chunkFilter) => { + let entry = selectedChunksCacheByChunksSet.get(chunks); + if (entry === undefined) { + entry = new WeakMap(); + selectedChunksCacheByChunksSet.set(chunks, entry); + } + let entry2 = + /** @type {SelectedChunksResult} */ + (entry.get(chunkFilter)); + if (entry2 === undefined) { + /** @type {Chunk[]} */ + const selectedChunks = []; + if (chunks instanceof Chunk) { + if (chunkFilter(chunks)) selectedChunks.push(chunks); + } else { + for (const chunk of chunks) { + if (chunkFilter(chunk)) selectedChunks.push(chunk); + } + } + entry2 = { + chunks: selectedChunks, + key: getKey(selectedChunks) + }; + entry.set(chunkFilter, entry2); + } + return entry2; + }; + + /** @type {Map} */ + const alreadyValidatedParents = new Map(); + /** @type {Set} */ + const alreadyReportedErrors = new Set(); + + // Map a list of chunks to a list of modules + // For the key the chunk "index" is used, the value is a SortableSet of modules + /** @type {Map} */ + const chunksInfoMap = new Map(); + + /** + * @param {CacheGroup} cacheGroup the current cache group + * @param {number} cacheGroupIndex the index of the cache group of ordering + * @param {Chunk[]} selectedChunks chunks selected for this module + * @param {bigint | Chunk} selectedChunksKey a key of selectedChunks + * @param {Module} module the current module + * @returns {void} + */ + const addModuleToChunksInfoMap = ( + cacheGroup, + cacheGroupIndex, + selectedChunks, + selectedChunksKey, + module + ) => { + // Break if minimum number of chunks is not reached + if (selectedChunks.length < cacheGroup.minChunks) return; + // Determine name for split chunk + + const name = + /** @type {GetName} */ + (cacheGroup.getName)(module, selectedChunks, cacheGroup.key); + // Check if the name is ok + const existingChunk = name && compilation.namedChunks.get(name); + if (existingChunk) { + const parentValidationKey = `${name}|${ + typeof selectedChunksKey === "bigint" + ? selectedChunksKey + : selectedChunksKey.debugId + }`; + const valid = alreadyValidatedParents.get(parentValidationKey); + if (valid === false) return; + if (valid === undefined) { + // Module can only be moved into the existing chunk if the existing chunk + // is a parent of all selected chunks + let isInAllParents = true; + /** @type {Set} */ + const queue = new Set(); + for (const chunk of selectedChunks) { + for (const group of chunk.groupsIterable) { + queue.add(group); + } + } + for (const group of queue) { + if (existingChunk.isInGroup(group)) continue; + let hasParent = false; + for (const parent of group.parentsIterable) { + hasParent = true; + queue.add(parent); + } + if (!hasParent) { + isInAllParents = false; + } + } + const valid = isInAllParents; + alreadyValidatedParents.set(parentValidationKey, valid); + if (!valid) { + if (!alreadyReportedErrors.has(name)) { + alreadyReportedErrors.add(name); + compilation.errors.push( + new WebpackError( + `${PLUGIN_NAME}\n` + + `Cache group "${cacheGroup.key}" conflicts with existing chunk.\n` + + `Both have the same name "${name}" and existing chunk is not a parent of the selected modules.\n` + + "Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependOn).\n" + + 'HINT: You can omit "name" to automatically create a name.\n' + + "BREAKING CHANGE: webpack < 5 used to allow to use an entrypoint as splitChunk. " + + "This is no longer allowed when the entrypoint is not a parent of the selected modules.\n" + + "Remove this entrypoint and add modules to cache group's 'test' instead. " + + "If you need modules to be evaluated on startup, add them to the existing entrypoints (make them arrays). " + + "See migration guide of more info." + ) + ); + } + return; + } + } + } + // Create key for maps + // When it has a name we use the name as key + // Otherwise we create the key from chunks and cache group key + // This automatically merges equal names + const key = + cacheGroup.key + + (name + ? ` name:${name}` + : ` chunks:${keyToString(selectedChunksKey)}`); + // Add module to maps + let info = chunksInfoMap.get(key); + if (info === undefined) { + chunksInfoMap.set( + key, + (info = { + modules: new SortableSet( + undefined, + compareModulesByIdentifier + ), + cacheGroup, + cacheGroupIndex, + name, + sizes: {}, + chunks: new Set(), + reusableChunks: new Set(), + chunksKeys: new Set() + }) + ); + } + const oldSize = info.modules.size; + info.modules.add(module); + if (info.modules.size !== oldSize) { + for (const type of module.getSourceTypes()) { + info.sizes[type] = (info.sizes[type] || 0) + module.size(type); + } + } + const oldChunksKeysSize = info.chunksKeys.size; + info.chunksKeys.add(selectedChunksKey); + if (oldChunksKeysSize !== info.chunksKeys.size) { + for (const chunk of selectedChunks) { + info.chunks.add(chunk); + } + } + }; + + const context = { + moduleGraph, + chunkGraph + }; + + logger.timeEnd("prepare"); + + logger.time("modules"); + + // Walk through all modules + for (const module of compilation.modules) { + // Get cache group + const cacheGroups = this.options.getCacheGroups(module, context); + if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { + continue; + } + + // Prepare some values (usedExports = false) + const getCombs = memoize(() => { + const chunks = chunkGraph.getModuleChunksIterable(module); + const chunksKey = getKey(chunks); + return getCombinations(chunksKey); + }); + + // Prepare some values (usedExports = true) + const getCombsByUsedExports = memoize(() => { + // fill the groupedByExportsMap + getExportsChunkSetsInGraph(); + /** @type {Set | Chunk>} */ + const set = new Set(); + const groupedByUsedExports = + /** @type {Iterable} */ + (groupedByExportsMap.get(module)); + for (const chunks of groupedByUsedExports) { + const chunksKey = getKey(chunks); + for (const comb of getExportsCombinations(chunksKey)) { + set.add(comb); + } + } + return set; + }); + + let cacheGroupIndex = 0; + for (const cacheGroupSource of cacheGroups) { + const cacheGroup = this._getCacheGroup(cacheGroupSource); + + const combs = cacheGroup.usedExports + ? getCombsByUsedExports() + : getCombs(); + // For all combination of chunk selection + for (const chunkCombination of combs) { + // Break if minimum number of chunks is not reached + const count = + chunkCombination instanceof Chunk ? 1 : chunkCombination.size; + if (count < cacheGroup.minChunks) continue; + // Select chunks by configuration + const { chunks: selectedChunks, key: selectedChunksKey } = + getSelectedChunks( + chunkCombination, + /** @type {ChunkFilterFunction} */ + (cacheGroup.chunksFilter) + ); + + addModuleToChunksInfoMap( + cacheGroup, + cacheGroupIndex, + selectedChunks, + selectedChunksKey, + module + ); + } + cacheGroupIndex++; + } + } + + logger.timeEnd("modules"); + + logger.time("queue"); + + /** + * @param {ChunksInfoItem} info entry + * @param {string[]} sourceTypes source types to be removed + */ + const removeModulesWithSourceType = (info, sourceTypes) => { + for (const module of info.modules) { + const types = module.getSourceTypes(); + if (sourceTypes.some((type) => types.has(type))) { + info.modules.delete(module); + for (const type of types) { + info.sizes[type] -= module.size(type); + } + } + } + }; + + /** + * @param {ChunksInfoItem} info entry + * @returns {boolean} true, if entry become empty + */ + const removeMinSizeViolatingModules = (info) => { + if (!info.cacheGroup._validateSize) return false; + const violatingSizes = getViolatingMinSizes( + info.sizes, + info.cacheGroup.minSize + ); + if (violatingSizes === undefined) return false; + removeModulesWithSourceType(info, violatingSizes); + return info.modules.size === 0; + }; + + // Filter items were size < minSize + for (const [key, info] of chunksInfoMap) { + if (removeMinSizeViolatingModules(info)) { + chunksInfoMap.delete(key); + } else if ( + !checkMinSizeReduction( + info.sizes, + info.cacheGroup.minSizeReduction, + info.chunks.size + ) + ) { + chunksInfoMap.delete(key); + } + } + + /** + * @typedef {object} MaxSizeQueueItem + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {string} automaticNameDelimiter + * @property {string[]} keys + */ + + /** @type {Map} */ + const maxSizeQueueMap = new Map(); + + while (chunksInfoMap.size > 0) { + // Find best matching entry + let bestEntryKey; + let bestEntry; + for (const pair of chunksInfoMap) { + const key = pair[0]; + const info = pair[1]; + if ( + bestEntry === undefined || + compareEntries(bestEntry, info) < 0 + ) { + bestEntry = info; + bestEntryKey = key; + } + } + + const item = /** @type {ChunksInfoItem} */ (bestEntry); + chunksInfoMap.delete(/** @type {string} */ (bestEntryKey)); + + /** @type {ChunkName | undefined} */ + let chunkName = item.name; + // Variable for the new chunk (lazy created) + /** @type {Chunk | undefined} */ + let newChunk; + // When no chunk name, check if we can reuse a chunk instead of creating a new one + let isExistingChunk = false; + let isReusedWithAllModules = false; + if (chunkName) { + const chunkByName = compilation.namedChunks.get(chunkName); + if (chunkByName !== undefined) { + newChunk = chunkByName; + const oldSize = item.chunks.size; + item.chunks.delete(newChunk); + isExistingChunk = item.chunks.size !== oldSize; + } + } else if (item.cacheGroup.reuseExistingChunk) { + outer: for (const chunk of item.chunks) { + if ( + chunkGraph.getNumberOfChunkModules(chunk) !== + item.modules.size + ) { + continue; + } + if ( + item.chunks.size > 1 && + chunkGraph.getNumberOfEntryModules(chunk) > 0 + ) { + continue; + } + for (const module of item.modules) { + if (!chunkGraph.isModuleInChunk(module, chunk)) { + continue outer; + } + } + if (!newChunk || !newChunk.name) { + newChunk = chunk; + } else if ( + chunk.name && + chunk.name.length < newChunk.name.length + ) { + newChunk = chunk; + } else if ( + chunk.name && + chunk.name.length === newChunk.name.length && + chunk.name < newChunk.name + ) { + newChunk = chunk; + } + } + if (newChunk) { + item.chunks.delete(newChunk); + chunkName = undefined; + isExistingChunk = true; + isReusedWithAllModules = true; + } + } + + const enforced = + item.cacheGroup._conditionalEnforce && + checkMinSize(item.sizes, item.cacheGroup.enforceSizeThreshold); + + const usedChunks = new Set(item.chunks); + + // Check if maxRequests condition can be fulfilled + if ( + !enforced && + (Number.isFinite(item.cacheGroup.maxInitialRequests) || + Number.isFinite(item.cacheGroup.maxAsyncRequests)) + ) { + for (const chunk of usedChunks) { + // respect max requests + const maxRequests = chunk.isOnlyInitial() + ? item.cacheGroup.maxInitialRequests + : chunk.canBeInitial() + ? Math.min( + item.cacheGroup.maxInitialRequests, + item.cacheGroup.maxAsyncRequests + ) + : item.cacheGroup.maxAsyncRequests; + if ( + Number.isFinite(maxRequests) && + getRequests(chunk) >= maxRequests + ) { + usedChunks.delete(chunk); + } + } + } + + outer: for (const chunk of usedChunks) { + for (const module of item.modules) { + if (chunkGraph.isModuleInChunk(module, chunk)) continue outer; + } + usedChunks.delete(chunk); + } + + // Were some (invalid) chunks removed from usedChunks? + // => readd all modules to the queue, as things could have been changed + if (usedChunks.size < item.chunks.size) { + if (isExistingChunk) { + usedChunks.add(/** @type {Chunk} */ (newChunk)); + } + if (usedChunks.size >= item.cacheGroup.minChunks) { + const chunksArr = [...usedChunks]; + for (const module of item.modules) { + addModuleToChunksInfoMap( + item.cacheGroup, + item.cacheGroupIndex, + chunksArr, + getKey(usedChunks), + module + ); + } + } + continue; + } + + // Validate minRemainingSize constraint when a single chunk is left over + if ( + !enforced && + item.cacheGroup._validateRemainingSize && + usedChunks.size === 1 + ) { + const [chunk] = usedChunks; + const chunkSizes = Object.create(null); + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!item.modules.has(module)) { + for (const type of module.getSourceTypes()) { + chunkSizes[type] = + (chunkSizes[type] || 0) + module.size(type); + } + } + } + const violatingSizes = getViolatingMinSizes( + chunkSizes, + item.cacheGroup.minRemainingSize + ); + if (violatingSizes !== undefined) { + const oldModulesSize = item.modules.size; + removeModulesWithSourceType(item, violatingSizes); + if ( + item.modules.size > 0 && + item.modules.size !== oldModulesSize + ) { + // queue this item again to be processed again + // without violating modules + chunksInfoMap.set(/** @type {string} */ (bestEntryKey), item); + } + continue; + } + } + + // Create the new chunk if not reusing one + if (newChunk === undefined) { + newChunk = compilation.addChunk(chunkName); + } + // Walk through all chunks + for (const chunk of usedChunks) { + // Add graph connections for splitted chunk + chunk.split(newChunk); + } + + // Add a note to the chunk + newChunk.chunkReason = + (newChunk.chunkReason ? `${newChunk.chunkReason}, ` : "") + + (isReusedWithAllModules + ? "reused as split chunk" + : "split chunk"); + if (item.cacheGroup.key) { + newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; + } + if (chunkName) { + newChunk.chunkReason += ` (name: ${chunkName})`; + } + if (item.cacheGroup.filename) { + newChunk.filenameTemplate = item.cacheGroup.filename; + } + if (item.cacheGroup.idHint) { + newChunk.idNameHints.add(item.cacheGroup.idHint); + } + if (!isReusedWithAllModules) { + // Add all modules to the new chunk + for (const module of item.modules) { + if (!module.chunkCondition(newChunk, compilation)) continue; + // Add module to new chunk + chunkGraph.connectChunkAndModule(newChunk, module); + // Remove module from used chunks + for (const chunk of usedChunks) { + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } + } else { + // Remove all modules from used chunks + for (const module of item.modules) { + for (const chunk of usedChunks) { + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } + } + + if ( + Object.keys(item.cacheGroup.maxAsyncSize).length > 0 || + Object.keys(item.cacheGroup.maxInitialSize).length > 0 + ) { + const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); + maxSizeQueueMap.set(newChunk, { + minSize: oldMaxSizeSettings + ? combineSizes( + oldMaxSizeSettings.minSize, + item.cacheGroup._minSizeForMaxSize, + Math.max + ) + : item.cacheGroup.minSize, + maxAsyncSize: oldMaxSizeSettings + ? combineSizes( + oldMaxSizeSettings.maxAsyncSize, + item.cacheGroup.maxAsyncSize, + Math.min + ) + : item.cacheGroup.maxAsyncSize, + maxInitialSize: oldMaxSizeSettings + ? combineSizes( + oldMaxSizeSettings.maxInitialSize, + item.cacheGroup.maxInitialSize, + Math.min + ) + : item.cacheGroup.maxInitialSize, + automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, + keys: oldMaxSizeSettings + ? [...oldMaxSizeSettings.keys, item.cacheGroup.key] + : [item.cacheGroup.key] + }); + } + + // remove all modules from other entries and update size + for (const [key, info] of chunksInfoMap) { + if (isOverlap(info.chunks, usedChunks)) { + // update modules and total size + // may remove it from the map when < minSize + let updated = false; + for (const module of item.modules) { + if (info.modules.has(module)) { + // remove module + info.modules.delete(module); + // update size + for (const key of module.getSourceTypes()) { + info.sizes[key] -= module.size(key); + } + updated = true; + } + } + if (updated) { + if (info.modules.size === 0) { + chunksInfoMap.delete(key); + continue; + } + if ( + removeMinSizeViolatingModules(info) || + !checkMinSizeReduction( + info.sizes, + info.cacheGroup.minSizeReduction, + info.chunks.size + ) + ) { + chunksInfoMap.delete(key); + continue; + } + } + } + } + } + + logger.timeEnd("queue"); + + logger.time("maxSize"); + + /** @type {Set} */ + const incorrectMinMaxSizeSet = new Set(); + + const { outputOptions } = compilation; + + // Make sure that maxSize is fulfilled + const { fallbackCacheGroup } = this.options; + for (const chunk of compilation.chunks) { + const chunkConfig = maxSizeQueueMap.get(chunk); + const { + minSize, + maxAsyncSize, + maxInitialSize, + automaticNameDelimiter + } = chunkConfig || fallbackCacheGroup; + if (!chunkConfig && !fallbackCacheGroup.chunksFilter(chunk)) { + continue; + } + /** @type {SplitChunksSizes} */ + let maxSize; + if (chunk.isOnlyInitial()) { + maxSize = maxInitialSize; + } else if (chunk.canBeInitial()) { + maxSize = combineSizes(maxAsyncSize, maxInitialSize, Math.min); + } else { + maxSize = maxAsyncSize; + } + if (Object.keys(maxSize).length === 0) { + continue; + } + for (const key of Object.keys(maxSize)) { + const maxSizeValue = maxSize[key]; + const minSizeValue = minSize[key]; + if ( + typeof minSizeValue === "number" && + minSizeValue > maxSizeValue + ) { + const keys = chunkConfig && chunkConfig.keys; + const warningKey = `${ + keys && keys.join() + } ${minSizeValue} ${maxSizeValue}`; + if (!incorrectMinMaxSizeSet.has(warningKey)) { + incorrectMinMaxSizeSet.add(warningKey); + compilation.warnings.push( + new MinMaxSizeWarning(keys, minSizeValue, maxSizeValue) + ); + } + } + } + const results = deterministicGroupingForModules({ + minSize, + maxSize: mapObject(maxSize, (value, key) => { + const minSizeValue = minSize[key]; + return typeof minSizeValue === "number" + ? Math.max(value, minSizeValue) + : value; + }), + items: chunkGraph.getChunkModulesIterable(chunk), + getKey(module) { + const cache = getKeyCache.get(module); + if (cache !== undefined) return cache; + const ident = cachedMakePathsRelative(module.identifier()); + const nameForCondition = + module.nameForCondition && module.nameForCondition(); + const name = nameForCondition + ? cachedMakePathsRelative(nameForCondition) + : ident.replace(/^.*!|\?[^?!]*$/g, ""); + const fullKey = + name + + automaticNameDelimiter + + hashFilename(ident, outputOptions); + const key = requestToId(fullKey); + getKeyCache.set(module, key); + return key; + }, + getSize(module) { + const size = Object.create(null); + for (const key of module.getSourceTypes()) { + size[key] = module.size(key); + } + return size; + } + }); + if (results.length <= 1) { + continue; + } + for (let i = 0; i < results.length; i++) { + const group = results[i]; + const key = this.options.hidePathInfo + ? hashFilename(group.key, outputOptions) + : group.key; + let name = chunk.name + ? chunk.name + automaticNameDelimiter + key + : null; + if (name && name.length > 100) { + name = + name.slice(0, 100) + + automaticNameDelimiter + + hashFilename(name, outputOptions); + } + if (i !== results.length - 1) { + const newPart = compilation.addChunk(name); + chunk.split(newPart); + newPart.chunkReason = chunk.chunkReason; + if (chunk.filenameTemplate) { + newPart.filenameTemplate = chunk.filenameTemplate; + } + // Add all modules to the new chunk + for (const module of group.items) { + if (!module.chunkCondition(newPart, compilation)) { + continue; + } + // Add module to new chunk + chunkGraph.connectChunkAndModule(newPart, module); + // Remove module from used chunks + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } else { + // change the chunk to be a part + chunk.name = name; + } + } + } + logger.timeEnd("maxSize"); + } + ); + }); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/AssetsOverSizeLimitWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/AssetsOverSizeLimitWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..35c63c32a493897eac16d6281cbba45ba71126cb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/AssetsOverSizeLimitWarning.js @@ -0,0 +1,32 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + +"use strict"; + +const { formatSize } = require("../SizeFormatHelpers"); +const WebpackError = require("../WebpackError"); + +/** @typedef {import("./SizeLimitsPlugin").AssetDetails} AssetDetails */ + +module.exports = class AssetsOverSizeLimitWarning extends WebpackError { + /** + * @param {AssetDetails[]} assetsOverSizeLimit the assets + * @param {number} assetLimit the size limit + */ + constructor(assetsOverSizeLimit, assetLimit) { + const assetLists = assetsOverSizeLimit + .map((asset) => `\n ${asset.name} (${formatSize(asset.size)})`) + .join(""); + + super(`asset size limit: The following asset(s) exceed the recommended size limit (${formatSize( + assetLimit + )}). +This can impact web performance. +Assets: ${assetLists}`); + + this.name = "AssetsOverSizeLimitWarning"; + this.assets = assetsOverSizeLimit; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/EntrypointsOverSizeLimitWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/EntrypointsOverSizeLimitWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..4f4d986bfd22fe320a403b17017d5c2b6079e847 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/EntrypointsOverSizeLimitWarning.js @@ -0,0 +1,35 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + +"use strict"; + +const { formatSize } = require("../SizeFormatHelpers"); +const WebpackError = require("../WebpackError"); + +/** @typedef {import("./SizeLimitsPlugin").EntrypointDetails} EntrypointDetails */ + +module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { + /** + * @param {EntrypointDetails[]} entrypoints the entrypoints + * @param {number} entrypointLimit the size limit + */ + constructor(entrypoints, entrypointLimit) { + const entrypointList = entrypoints + .map( + (entrypoint) => + `\n ${entrypoint.name} (${formatSize( + entrypoint.size + )})\n${entrypoint.files.map((asset) => ` ${asset}`).join("\n")}` + ) + .join(""); + super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${formatSize( + entrypointLimit + )}). This can impact web performance. +Entrypoints:${entrypointList}\n`); + + this.name = "EntrypointsOverSizeLimitWarning"; + this.entrypoints = entrypoints; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/NoAsyncChunksWarning.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/NoAsyncChunksWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..a7319d5950bc336494e55b66234e87b2ff1787cb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/NoAsyncChunksWarning.js @@ -0,0 +1,20 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + +"use strict"; + +const WebpackError = require("../WebpackError"); + +module.exports = class NoAsyncChunksWarning extends WebpackError { + constructor() { + super( + "webpack performance recommendations: \n" + + "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); + + this.name = "NoAsyncChunksWarning"; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/SizeLimitsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/SizeLimitsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..a57f2a79754b9125a6312da74773baf0983f26d5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/performance/SizeLimitsPlugin.js @@ -0,0 +1,181 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + +"use strict"; + +const { find } = require("../util/SetHelpers"); +const AssetsOverSizeLimitWarning = require("./AssetsOverSizeLimitWarning"); +const EntrypointsOverSizeLimitWarning = require("./EntrypointsOverSizeLimitWarning"); +const NoAsyncChunksWarning = require("./NoAsyncChunksWarning"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").PerformanceOptions} PerformanceOptions */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation").Asset} Asset */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../WebpackError")} WebpackError */ + +/** + * @typedef {object} AssetDetails + * @property {string} name + * @property {number} size + */ + +/** + * @typedef {object} EntrypointDetails + * @property {string} name + * @property {number} size + * @property {string[]} files + */ + +const isOverSizeLimitSet = new WeakSet(); + +/** + * @param {Asset["name"]} name the name + * @param {Asset["source"]} source the source + * @param {Asset["info"]} info the info + * @returns {boolean} result + */ +const excludeSourceMap = (name, source, info) => !info.development; + +const PLUGIN_NAME = "SizeLimitsPlugin"; + +module.exports = class SizeLimitsPlugin { + /** + * @param {PerformanceOptions} options the plugin options + */ + constructor(options) { + this.hints = options.hints; + this.maxAssetSize = options.maxAssetSize; + this.maxEntrypointSize = options.maxEntrypointSize; + this.assetFilter = options.assetFilter; + } + + /** + * @param {ChunkGroup | Source} thing the resource to test + * @returns {boolean} true if over the limit + */ + static isOverSizeLimit(thing) { + return isOverSizeLimitSet.has(thing); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const entrypointSizeLimit = this.maxEntrypointSize; + const assetSizeLimit = this.maxAssetSize; + const hints = this.hints; + const assetFilter = this.assetFilter || excludeSourceMap; + + compiler.hooks.afterEmit.tap(PLUGIN_NAME, (compilation) => { + /** @type {WebpackError[]} */ + const warnings = []; + + /** + * @param {Entrypoint} entrypoint an entrypoint + * @returns {number} the size of the entrypoint + */ + const getEntrypointSize = (entrypoint) => { + let size = 0; + for (const file of entrypoint.getFiles()) { + const asset = compilation.getAsset(file); + if ( + asset && + assetFilter(asset.name, asset.source, asset.info) && + asset.source + ) { + size += asset.info.size || asset.source.size(); + } + } + return size; + }; + + /** @type {AssetDetails[]} */ + const assetsOverSizeLimit = []; + for (const { name, source, info } of compilation.getAssets()) { + if (!assetFilter(name, source, info) || !source) { + continue; + } + + const size = info.size || source.size(); + if (size > /** @type {number} */ (assetSizeLimit)) { + assetsOverSizeLimit.push({ + name, + size + }); + isOverSizeLimitSet.add(source); + } + } + + /** + * @param {Asset["name"]} name the name + * @returns {boolean | undefined} result + */ + const fileFilter = (name) => { + const asset = compilation.getAsset(name); + return asset && assetFilter(asset.name, asset.source, asset.info); + }; + + /** @type {EntrypointDetails[]} */ + const entrypointsOverLimit = []; + for (const [name, entry] of compilation.entrypoints) { + const size = getEntrypointSize(entry); + + if (size > /** @type {number} */ (entrypointSizeLimit)) { + entrypointsOverLimit.push({ + name, + size, + files: entry.getFiles().filter(fileFilter) + }); + isOverSizeLimitSet.add(entry); + } + } + + if (hints) { + // 1. Individual Chunk: Size < 250kb + // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb + // 3. No Async Chunks + // if !1, then 2, if !2 return + if (assetsOverSizeLimit.length > 0) { + warnings.push( + new AssetsOverSizeLimitWarning( + assetsOverSizeLimit, + /** @type {number} */ (assetSizeLimit) + ) + ); + } + if (entrypointsOverLimit.length > 0) { + warnings.push( + new EntrypointsOverSizeLimitWarning( + entrypointsOverLimit, + /** @type {number} */ (entrypointSizeLimit) + ) + ); + } + + if (warnings.length > 0) { + const someAsyncChunk = find( + compilation.chunks, + (chunk) => !chunk.canBeInitial() + ); + + if (!someAsyncChunk) { + warnings.push(new NoAsyncChunksWarning()); + } + + if (hints === "error") { + compilation.errors.push(...warnings); + } else { + compilation.warnings.push(...warnings); + } + } + } + }); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..a330b4a4d73bb6d7d915dd6a062cf59b4bf80181 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js @@ -0,0 +1,46 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPrefetchFunctionRuntimeModule extends RuntimeModule { + /** + * @param {string} childType TODO + * @param {string} runtimeFunction TODO + * @param {string} runtimeHandlers TODO + */ + constructor(childType, runtimeFunction, runtimeHandlers) { + super(`chunk ${childType} function`); + this.childType = childType; + this.runtimeFunction = runtimeFunction; + this.runtimeHandlers = runtimeHandlers; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { runtimeFunction, runtimeHandlers } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + return Template.asString([ + `${runtimeHandlers} = {};`, + `${runtimeFunction} = ${runtimeTemplate.basicFunction("chunkId", [ + // map is shorter than forEach + `Object.keys(${runtimeHandlers}).map(${runtimeTemplate.basicFunction( + "key", + `${runtimeHandlers}[key](chunkId);` + )});` + ])}` + ]); + } +} + +module.exports = ChunkPrefetchFunctionRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchPreloadPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchPreloadPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f992bfd1f25dc47e3fa6687aafd095fd608b5e6e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchPreloadPlugin.js @@ -0,0 +1,97 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const ChunkPrefetchFunctionRuntimeModule = require("./ChunkPrefetchFunctionRuntimeModule"); +const ChunkPrefetchStartupRuntimeModule = require("./ChunkPrefetchStartupRuntimeModule"); +const ChunkPrefetchTriggerRuntimeModule = require("./ChunkPrefetchTriggerRuntimeModule"); +const ChunkPreloadTriggerRuntimeModule = require("./ChunkPreloadTriggerRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "ChunkPrefetchPreloadPlugin"; + +class ChunkPrefetchPreloadPlugin { + /** + * @param {Compiler} compiler the compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set, { chunkGraph }) => { + if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; + const startupChildChunks = chunk.getChildrenOfTypeInOrder( + chunkGraph, + "prefetchOrder" + ); + if (startupChildChunks) { + set.add(RuntimeGlobals.prefetchChunk); + set.add(RuntimeGlobals.onChunksLoaded); + set.add(RuntimeGlobals.exports); + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchStartupRuntimeModule(startupChildChunks) + ); + } + } + ); + compilation.hooks.additionalTreeRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set, { chunkGraph }) => { + const chunkMap = chunk.getChildIdsByOrdersMap(chunkGraph); + + if (chunkMap.prefetch) { + set.add(RuntimeGlobals.prefetchChunk); + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchTriggerRuntimeModule(chunkMap.prefetch) + ); + } + if (chunkMap.preload) { + set.add(RuntimeGlobals.preloadChunk); + compilation.addRuntimeModule( + chunk, + new ChunkPreloadTriggerRuntimeModule(chunkMap.preload) + ); + } + } + ); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.prefetchChunk) + .tap(PLUGIN_NAME, (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchFunctionRuntimeModule( + "prefetch", + RuntimeGlobals.prefetchChunk, + RuntimeGlobals.prefetchChunkHandlers + ) + ); + set.add(RuntimeGlobals.prefetchChunkHandlers); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.preloadChunk) + .tap(PLUGIN_NAME, (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchFunctionRuntimeModule( + "preload", + RuntimeGlobals.preloadChunk, + RuntimeGlobals.preloadChunkHandlers + ) + ); + set.add(RuntimeGlobals.preloadChunkHandlers); + }); + }); + } +} + +module.exports = ChunkPrefetchPreloadPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..9deff8ced58316af3f7dd373a71a8d6141cc7ce1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js @@ -0,0 +1,55 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPrefetchStartupRuntimeModule extends RuntimeModule { + /** + * @param {{ onChunks: Chunk[], chunks: Set }[]} startupChunks chunk ids to trigger when chunks are loaded + */ + constructor(startupChunks) { + super("startup prefetch", RuntimeModule.STAGE_TRIGGER); + this.startupChunks = startupChunks; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { startupChunks } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunk = /** @type {Chunk} */ (this.chunk); + const { runtimeTemplate } = compilation; + return Template.asString( + startupChunks.map( + ({ onChunks, chunks }) => + `${RuntimeGlobals.onChunksLoaded}(0, ${JSON.stringify( + // This need to include itself to delay execution after this chunk has been fully loaded + onChunks.filter((c) => c === chunk).map((c) => c.id) + )}, ${runtimeTemplate.basicFunction( + "", + chunks.size < 3 + ? Array.from( + chunks, + (c) => + `${RuntimeGlobals.prefetchChunk}(${JSON.stringify(c.id)});` + ) + : `${JSON.stringify(Array.from(chunks, (c) => c.id))}.map(${ + RuntimeGlobals.prefetchChunk + });` + )}, 5);` + ) + ); + } +} + +module.exports = ChunkPrefetchStartupRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..74eb2bc613f7754918c171783599774c2e7fdfaa --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js @@ -0,0 +1,51 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPrefetchTriggerRuntimeModule extends RuntimeModule { + /** + * @param {Record} chunkMap map from chunk to + */ + constructor(chunkMap) { + super("chunk prefetch trigger", RuntimeModule.STAGE_TRIGGER); + this.chunkMap = chunkMap; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { chunkMap } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + const body = [ + "var chunks = chunkToChildrenMap[chunkId];", + `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.prefetchChunk});` + ]; + return Template.asString([ + Template.asString([ + `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.prefetch = ${runtimeTemplate.expressionFunction( + `Promise.all(promises).then(${runtimeTemplate.basicFunction( + "", + body + )})`, + "chunkId, promises" + )};` + ]) + ]); + } +} + +module.exports = ChunkPrefetchTriggerRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..8509def176dff7239b565e083185b7de56cc20ab --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js @@ -0,0 +1,45 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPreloadTriggerRuntimeModule extends RuntimeModule { + /** + * @param {Record} chunkMap map from chunk to chunks + */ + constructor(chunkMap) { + super("chunk preload trigger", RuntimeModule.STAGE_TRIGGER); + this.chunkMap = chunkMap; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { chunkMap } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + const body = [ + "var chunks = chunkToChildrenMap[chunkId];", + `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.preloadChunk});` + ]; + return Template.asString([ + Template.asString([ + `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.preload = ${runtimeTemplate.basicFunction("chunkId", body)};` + ]) + ]); + } +} + +module.exports = ChunkPreloadTriggerRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/BasicEffectRulePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/BasicEffectRulePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..c7ab48b578d96cb6f9183e96c88b19c17f6b7fac --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/BasicEffectRulePlugin.js @@ -0,0 +1,54 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ + +/** + * @template T + * @template {T[keyof T]} V + * @typedef {import("./RuleSetCompiler").KeysOfTypes} KeysOfTypes + */ + +/** @typedef {KeysOfTypes} BasicEffectRuleKeys */ + +const PLUGIN_NAME = "BasicEffectRulePlugin"; + +class BasicEffectRulePlugin { + /** + * @param {BasicEffectRuleKeys} ruleProperty the rule property + * @param {string=} effectType the effect type + */ + constructor(ruleProperty, effectType) { + this.ruleProperty = ruleProperty; + this.effectType = effectType || ruleProperty; + } + + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + ruleSetCompiler.hooks.rule.tap( + PLUGIN_NAME, + (path, rule, unhandledProperties, result) => { + if (unhandledProperties.has(this.ruleProperty)) { + unhandledProperties.delete(this.ruleProperty); + + const value = rule[this.ruleProperty]; + + result.effects.push({ + type: this.effectType, + value + }); + } + } + ); + } +} + +module.exports = BasicEffectRulePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/BasicMatcherRulePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/BasicMatcherRulePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..3e20878a9b0da8a046cb8866203a281d0776d193 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/BasicMatcherRulePlugin.js @@ -0,0 +1,67 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../../declarations/WebpackOptions").RuleSetConditionOrConditions} RuleSetConditionOrConditions */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetConditionOrConditionsAbsolute} RuleSetConditionOrConditionsAbsolute */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetLoaderOptions} RuleSetLoaderOptions */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ + +/** + * @template T + * @template {T[keyof T]} V + * @typedef {import("./RuleSetCompiler").KeysOfTypes} KeysOfTypes + */ + +/** @typedef {KeysOfTypes} BasicMatcherRuleKeys */ + +const PLUGIN_NAME = "BasicMatcherRulePlugin"; + +class BasicMatcherRulePlugin { + /** + * @param {BasicMatcherRuleKeys} ruleProperty the rule property + * @param {string=} dataProperty the data property + * @param {boolean=} invert if true, inverts the condition + */ + constructor(ruleProperty, dataProperty, invert) { + this.ruleProperty = ruleProperty; + this.dataProperty = dataProperty || ruleProperty; + this.invert = invert || false; + } + + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + ruleSetCompiler.hooks.rule.tap( + PLUGIN_NAME, + (path, rule, unhandledProperties, result) => { + if (unhandledProperties.has(this.ruleProperty)) { + unhandledProperties.delete(this.ruleProperty); + const value = rule[this.ruleProperty]; + const condition = ruleSetCompiler.compileCondition( + `${path}.${this.ruleProperty}`, + /** @type {RuleSetConditionOrConditions | RuleSetConditionOrConditionsAbsolute} */ + (value) + ); + const fn = condition.fn; + result.conditions.push({ + property: this.dataProperty, + matchWhenEmpty: this.invert + ? !condition.matchWhenEmpty + : condition.matchWhenEmpty, + fn: this.invert ? (v) => !fn(v) : fn + }); + } + } + ); + } +} + +module.exports = BasicMatcherRulePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/ObjectMatcherRulePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/ObjectMatcherRulePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..5ec7f8e523d8c78b0c040651771fba406293586d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/ObjectMatcherRulePlugin.js @@ -0,0 +1,76 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../../declarations/WebpackOptions").RuleSetConditionOrConditions} RuleSetConditionOrConditions */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +/** @typedef {import("./RuleSetCompiler").EffectData} EffectData */ +/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ +/** @typedef {import("./RuleSetCompiler").RuleConditionFunction} RuleConditionFunction */ + +/** + * @template T + * @template {T[keyof T]} V + * @typedef {import("./RuleSetCompiler").KeysOfTypes} KeysOfTypes + */ + +/** @typedef {KeysOfTypes} ObjectMatcherRuleKeys */ + +const PLUGIN_NAME = "ObjectMatcherRulePlugin"; + +class ObjectMatcherRulePlugin { + /** + * @param {ObjectMatcherRuleKeys} ruleProperty the rule property + * @param {keyof EffectData=} dataProperty the data property + * @param {RuleConditionFunction=} additionalConditionFunction need to check + */ + constructor(ruleProperty, dataProperty, additionalConditionFunction) { + this.ruleProperty = ruleProperty; + this.dataProperty = dataProperty || ruleProperty; + this.additionalConditionFunction = additionalConditionFunction; + } + + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + const { ruleProperty, dataProperty } = this; + ruleSetCompiler.hooks.rule.tap( + PLUGIN_NAME, + (path, rule, unhandledProperties, result) => { + if (unhandledProperties.has(ruleProperty)) { + unhandledProperties.delete(ruleProperty); + const value = + /** @type {Record} */ + (rule[ruleProperty]); + for (const property of Object.keys(value)) { + const nestedDataProperties = property.split("."); + const condition = ruleSetCompiler.compileCondition( + `${path}.${ruleProperty}.${property}`, + value[property] + ); + if (this.additionalConditionFunction) { + result.conditions.push({ + property: [dataProperty], + matchWhenEmpty: condition.matchWhenEmpty, + fn: this.additionalConditionFunction + }); + } + result.conditions.push({ + property: [dataProperty, ...nestedDataProperties], + matchWhenEmpty: condition.matchWhenEmpty, + fn: condition.fn + }); + } + } + } + ); + } +} + +module.exports = ObjectMatcherRulePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/RuleSetCompiler.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/RuleSetCompiler.js new file mode 100644 index 0000000000000000000000000000000000000000..9054026aa142b99fc941702e1724dda820222b1b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/RuleSetCompiler.js @@ -0,0 +1,439 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { SyncHook } = require("tapable"); + +/** @typedef {import("../../declarations/WebpackOptions").Falsy} Falsy */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetLoaderOptions} RuleSetLoaderOptions */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ +/** @typedef {import("../NormalModule").LoaderItem} LoaderItem */ + +/** @typedef {(Falsy | RuleSetRule)[]} RuleSetRules */ + +/** + * @typedef {(value: EffectData[keyof EffectData]) => boolean} RuleConditionFunction + */ + +/** + * @typedef {object} RuleCondition + * @property {string | string[]} property + * @property {boolean} matchWhenEmpty + * @property {RuleConditionFunction} fn + */ + +/** + * @typedef {object} Condition + * @property {boolean} matchWhenEmpty + * @property {RuleConditionFunction} fn + */ + +/** + * @typedef {object} EffectData + * @property {string=} resource + * @property {string=} realResource + * @property {string=} resourceQuery + * @property {string=} resourceFragment + * @property {string=} scheme + * @property {ImportAttributes=} assertions + * @property {string=} mimetype + * @property {string} dependency + * @property {Record=} descriptionData + * @property {string=} compiler + * @property {string} issuer + * @property {string} issuerLayer + */ + +/** + * @typedef {object} CompiledRule + * @property {RuleCondition[]} conditions + * @property {(Effect | ((effectData: EffectData) => Effect[]))[]} effects + * @property {CompiledRule[]=} rules + * @property {CompiledRule[]=} oneOf + */ + +/** @typedef {"use" | "use-pre" | "use-post"} EffectUseType */ + +/** + * @typedef {object} EffectUse + * @property {EffectUseType} type + * @property {{ loader: string, options?: string | null | Record, ident?: string }} value + */ + +/** + * @typedef {object} EffectBasic + * @property {string} type + * @property {EXPECTED_ANY} value + */ + +/** @typedef {EffectUse | EffectBasic} Effect */ + +/** @typedef {Map} References */ + +/** + * @typedef {object} RuleSet + * @property {References} references map of references in the rule set (may grow over time) + * @property {(effectData: EffectData) => Effect[]} exec execute the rule set + */ + +/** + * @template T + * @template {T[keyof T]} V + * @typedef {({ [P in keyof Required]: Required[P] extends V ? P : never })[keyof T]} KeysOfTypes + */ + +/** @typedef {{ apply: (ruleSetCompiler: RuleSetCompiler) => void }} RuleSetPlugin */ + +class RuleSetCompiler { + /** + * @param {RuleSetPlugin[]} plugins plugins + */ + constructor(plugins) { + this.hooks = Object.freeze({ + /** @type {SyncHook<[string, RuleSetRule, Set, CompiledRule, References]>} */ + rule: new SyncHook([ + "path", + "rule", + "unhandledProperties", + "compiledRule", + "references" + ]) + }); + if (plugins) { + for (const plugin of plugins) { + plugin.apply(this); + } + } + } + + /** + * @param {RuleSetRules} ruleSet raw user provided rules + * @returns {RuleSet} compiled RuleSet + */ + compile(ruleSet) { + const refs = new Map(); + const rules = this.compileRules("ruleSet", ruleSet, refs); + + /** + * @param {EffectData} data data passed in + * @param {CompiledRule} rule the compiled rule + * @param {Effect[]} effects an array where effects are pushed to + * @returns {boolean} true, if the rule has matched + */ + const execRule = (data, rule, effects) => { + for (const condition of rule.conditions) { + const p = condition.property; + if (Array.isArray(p)) { + /** @type {EffectData | EffectData[keyof EffectData] | undefined} */ + let current = data; + for (const subProperty of p) { + if ( + current && + typeof current === "object" && + Object.prototype.hasOwnProperty.call(current, subProperty) + ) { + current = current[/** @type {keyof EffectData} */ (subProperty)]; + } else { + current = undefined; + break; + } + } + if (current !== undefined) { + if (!condition.fn(current)) return false; + continue; + } + } else if (p in data) { + const value = data[/** @type {keyof EffectData} */ (p)]; + if (value !== undefined) { + if (!condition.fn(value)) return false; + continue; + } + } + if (!condition.matchWhenEmpty) { + return false; + } + } + for (const effect of rule.effects) { + if (typeof effect === "function") { + const returnedEffects = effect(data); + for (const effect of returnedEffects) { + effects.push(effect); + } + } else { + effects.push(effect); + } + } + if (rule.rules) { + for (const childRule of rule.rules) { + execRule(data, childRule, effects); + } + } + if (rule.oneOf) { + for (const childRule of rule.oneOf) { + if (execRule(data, childRule, effects)) { + break; + } + } + } + return true; + }; + + return { + references: refs, + exec: (data) => { + /** @type {Effect[]} */ + const effects = []; + for (const rule of rules) { + execRule(data, rule, effects); + } + return effects; + } + }; + } + + /** + * @param {string} path current path + * @param {RuleSetRules} rules the raw rules provided by user + * @param {References} refs references + * @returns {CompiledRule[]} rules + */ + compileRules(path, rules, refs) { + return rules + .filter(Boolean) + .map((rule, i) => + this.compileRule( + `${path}[${i}]`, + /** @type {RuleSetRule} */ (rule), + refs + ) + ); + } + + /** + * @param {string} path current path + * @param {RuleSetRule} rule the raw rule provided by user + * @param {References} refs references + * @returns {CompiledRule} normalized and compiled rule for processing + */ + compileRule(path, rule, refs) { + /** @type {Set} */ + const unhandledProperties = new Set( + Object.keys(rule).filter( + (key) => rule[/** @type {keyof RuleSetRule} */ (key)] !== undefined + ) + ); + + /** @type {CompiledRule} */ + const compiledRule = { + conditions: [], + effects: [], + rules: undefined, + oneOf: undefined + }; + + this.hooks.rule.call(path, rule, unhandledProperties, compiledRule, refs); + + if (unhandledProperties.has("rules")) { + unhandledProperties.delete("rules"); + const rules = rule.rules; + if (!Array.isArray(rules)) { + throw this.error(path, rules, "Rule.rules must be an array of rules"); + } + compiledRule.rules = this.compileRules(`${path}.rules`, rules, refs); + } + + if (unhandledProperties.has("oneOf")) { + unhandledProperties.delete("oneOf"); + const oneOf = rule.oneOf; + if (!Array.isArray(oneOf)) { + throw this.error(path, oneOf, "Rule.oneOf must be an array of rules"); + } + compiledRule.oneOf = this.compileRules(`${path}.oneOf`, oneOf, refs); + } + + if (unhandledProperties.size > 0) { + throw this.error( + path, + rule, + `Properties ${[...unhandledProperties].join(", ")} are unknown` + ); + } + + return compiledRule; + } + + /** + * @param {string} path current path + * @param {RuleSetLoaderOptions} condition user provided condition value + * @returns {Condition} compiled condition + */ + compileCondition(path, condition) { + if (condition === "") { + return { + matchWhenEmpty: true, + fn: (str) => str === "" + }; + } + if (!condition) { + throw this.error( + path, + condition, + "Expected condition but got falsy value" + ); + } + if (typeof condition === "string") { + return { + matchWhenEmpty: condition.length === 0, + fn: (str) => typeof str === "string" && str.startsWith(condition) + }; + } + if (typeof condition === "function") { + try { + return { + matchWhenEmpty: condition(""), + fn: /** @type {RuleConditionFunction} */ (condition) + }; + } catch (_err) { + throw this.error( + path, + condition, + "Evaluation of condition function threw error" + ); + } + } + if (condition instanceof RegExp) { + return { + matchWhenEmpty: condition.test(""), + fn: (v) => typeof v === "string" && condition.test(v) + }; + } + if (Array.isArray(condition)) { + const items = condition.map((c, i) => + this.compileCondition(`${path}[${i}]`, c) + ); + return this.combineConditionsOr(items); + } + + if (typeof condition !== "object") { + throw this.error( + path, + condition, + `Unexpected ${typeof condition} when condition was expected` + ); + } + + const conditions = []; + for (const key of Object.keys(condition)) { + const value = condition[key]; + switch (key) { + case "or": + if (value) { + if (!Array.isArray(value)) { + throw this.error( + `${path}.or`, + condition.or, + "Expected array of conditions" + ); + } + conditions.push(this.compileCondition(`${path}.or`, value)); + } + break; + case "and": + if (value) { + if (!Array.isArray(value)) { + throw this.error( + `${path}.and`, + condition.and, + "Expected array of conditions" + ); + } + let i = 0; + for (const item of value) { + conditions.push(this.compileCondition(`${path}.and[${i}]`, item)); + i++; + } + } + break; + case "not": + if (value) { + const matcher = this.compileCondition(`${path}.not`, value); + const fn = matcher.fn; + conditions.push({ + matchWhenEmpty: !matcher.matchWhenEmpty, + fn: /** @type {RuleConditionFunction} */ ((v) => !fn(v)) + }); + } + break; + default: + throw this.error( + `${path}.${key}`, + condition[key], + `Unexpected property ${key} in condition` + ); + } + } + if (conditions.length === 0) { + throw this.error( + path, + condition, + "Expected condition, but got empty thing" + ); + } + return this.combineConditionsAnd(conditions); + } + + /** + * @param {Condition[]} conditions some conditions + * @returns {Condition} merged condition + */ + combineConditionsOr(conditions) { + if (conditions.length === 0) { + return { + matchWhenEmpty: false, + fn: () => false + }; + } else if (conditions.length === 1) { + return conditions[0]; + } + return { + matchWhenEmpty: conditions.some((c) => c.matchWhenEmpty), + fn: (v) => conditions.some((c) => c.fn(v)) + }; + } + + /** + * @param {Condition[]} conditions some conditions + * @returns {Condition} merged condition + */ + combineConditionsAnd(conditions) { + if (conditions.length === 0) { + return { + matchWhenEmpty: false, + fn: () => false + }; + } else if (conditions.length === 1) { + return conditions[0]; + } + return { + matchWhenEmpty: conditions.every((c) => c.matchWhenEmpty), + fn: (v) => conditions.every((c) => c.fn(v)) + }; + } + + /** + * @param {string} path current path + * @param {EXPECTED_ANY} value value at the error location + * @param {string} message message explaining the problem + * @returns {Error} an error object + */ + error(path, value, message) { + return new Error( + `Compiling RuleSet failed: ${message} (at ${path}: ${value})` + ); + } +} + +module.exports = RuleSetCompiler; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/UseEffectRulePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/UseEffectRulePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..e90d10bab8861a1dc8f4e6d1ad9bfdd5dc6b5d73 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/rules/UseEffectRulePlugin.js @@ -0,0 +1,236 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); + +/** @typedef {import("../../declarations/WebpackOptions").Falsy} Falsy */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetLoader} RuleSetLoader */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetLoaderOptions} RuleSetLoaderOptions */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetUse} RuleSetUse */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetUseItem} RuleSetUseItem */ +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +/** @typedef {import("./RuleSetCompiler").Effect} Effect */ +/** @typedef {import("./RuleSetCompiler").EffectData} EffectData */ +/** @typedef {import("./RuleSetCompiler").EffectUseType} EffectUseType */ + +const PLUGIN_NAME = "UseEffectRulePlugin"; + +class UseEffectRulePlugin { + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + ruleSetCompiler.hooks.rule.tap( + PLUGIN_NAME, + (path, rule, unhandledProperties, result, references) => { + /** + * @param {keyof RuleSetRule} property property + * @param {string} correctProperty correct property + */ + const conflictWith = (property, correctProperty) => { + if (unhandledProperties.has(property)) { + throw ruleSetCompiler.error( + `${path}.${property}`, + rule[property], + `A Rule must not have a '${property}' property when it has a '${correctProperty}' property` + ); + } + }; + + if (unhandledProperties.has("use")) { + unhandledProperties.delete("use"); + unhandledProperties.delete("enforce"); + + conflictWith("loader", "use"); + conflictWith("options", "use"); + + const use = /** @type {RuleSetUse} */ (rule.use); + const enforce = rule.enforce; + + const type = + /** @type {EffectUseType} */ + (enforce ? `use-${enforce}` : "use"); + + /** + * @param {string} path options path + * @param {string} defaultIdent default ident when none is provided + * @param {RuleSetUseItem} item user provided use value + * @returns {(Effect | ((effectData: EffectData) => Effect[]))} effect + */ + const useToEffect = (path, defaultIdent, item) => { + if (typeof item === "function") { + return (data) => + useToEffectsWithoutIdent( + path, + /** @type {RuleSetUseItem | RuleSetUseItem[]} */ + (item(data)) + ); + } + return useToEffectRaw(path, defaultIdent, item); + }; + + /** + * @param {string} path options path + * @param {string} defaultIdent default ident when none is provided + * @param {Exclude, EXPECTED_FUNCTION>} item user provided use value + * @returns {Effect} effect + */ + const useToEffectRaw = (path, defaultIdent, item) => { + if (typeof item === "string") { + return { + type, + value: { + loader: item, + options: undefined, + ident: undefined + } + }; + } + const loader = /** @type {string} */ (item.loader); + const options = item.options; + let ident = item.ident; + if (options && typeof options === "object") { + if (!ident) ident = defaultIdent; + references.set(ident, options); + } + if (typeof options === "string") { + util.deprecate( + () => {}, + `Using a string as loader options is deprecated (${path}.options)`, + "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" + )(); + } + return { + type: enforce ? `use-${enforce}` : "use", + value: { + loader, + options, + ident + } + }; + }; + + /** + * @param {string} path options path + * @param {RuleSetUseItem | (Falsy | RuleSetUseItem)[]} items user provided use value + * @returns {Effect[]} effects + */ + const useToEffectsWithoutIdent = (path, items) => { + if (Array.isArray(items)) { + return items.filter(Boolean).map((item, idx) => + useToEffectRaw( + `${path}[${idx}]`, + "[[missing ident]]", + /** @type {Exclude} */ + (item) + ) + ); + } + return [ + useToEffectRaw( + path, + "[[missing ident]]", + /** @type {Exclude} */ + (items) + ) + ]; + }; + + /** + * @param {string} path current path + * @param {RuleSetUse} items user provided use value + * @returns {(Effect | ((effectData: EffectData) => Effect[]))[]} effects + */ + const useToEffects = (path, items) => { + if (Array.isArray(items)) { + return items.filter(Boolean).map((item, idx) => { + const subPath = `${path}[${idx}]`; + return useToEffect( + subPath, + subPath, + /** @type {RuleSetUseItem} */ + (item) + ); + }); + } + return [ + useToEffect(path, path, /** @type {RuleSetUseItem} */ (items)) + ]; + }; + + if (typeof use === "function") { + result.effects.push((data) => + useToEffectsWithoutIdent(`${path}.use`, use(data)) + ); + } else { + for (const effect of useToEffects(`${path}.use`, use)) { + result.effects.push(effect); + } + } + } + + if (unhandledProperties.has("loader")) { + unhandledProperties.delete("loader"); + unhandledProperties.delete("options"); + unhandledProperties.delete("enforce"); + + const loader = /** @type {RuleSetLoader} */ (rule.loader); + const options = rule.options; + const enforce = rule.enforce; + + if (loader.includes("!")) { + throw ruleSetCompiler.error( + `${path}.loader`, + loader, + "Exclamation mark separated loader lists has been removed in favor of the 'use' property with arrays" + ); + } + + if (loader.includes("?")) { + throw ruleSetCompiler.error( + `${path}.loader`, + loader, + "Query arguments on 'loader' has been removed in favor of the 'options' property" + ); + } + + if (typeof options === "string") { + util.deprecate( + () => {}, + `Using a string as loader options is deprecated (${path}.options)`, + "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" + )(); + } + + const ident = + options && typeof options === "object" ? path : undefined; + + if (ident) { + references.set( + ident, + /** @type {RuleSetLoaderOptions} */ + (options) + ); + } + + result.effects.push({ + type: enforce ? `use-${enforce}` : "use", + value: { + loader, + options, + ident + } + }); + } + } + ); + } +} + +module.exports = UseEffectRulePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/AsyncModuleRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/AsyncModuleRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..441480ba0881973cf4e40eec6bde0c0f45c93ac2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/AsyncModuleRuntimeModule.js @@ -0,0 +1,188 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class AsyncModuleRuntimeModule extends HelperRuntimeModule { + /** + * @param {boolean=} deferInterop if defer import is used. + */ + constructor(deferInterop = false) { + super("async module"); + this._deferInterop = deferInterop; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + const fn = RuntimeGlobals.asyncModule; + const defer = this._deferInterop; + return Template.asString([ + 'var hasSymbol = typeof Symbol === "function";', + 'var webpackQueues = hasSymbol ? Symbol("webpack queues") : "__webpack_queues__";', + `var webpackExports = ${ + defer ? `${RuntimeGlobals.asyncModuleExportSymbol}= ` : "" + }hasSymbol ? Symbol("webpack exports") : "${RuntimeGlobals.exports}";`, + 'var webpackError = hasSymbol ? Symbol("webpack error") : "__webpack_error__";', + defer + ? `var webpackDone = ${RuntimeGlobals.asyncModuleDoneSymbol} = hasSymbol ? Symbol("webpack done") : "__webpack_done__";` + : "", + defer + ? `var webpackDefer = ${RuntimeGlobals.makeDeferredNamespaceObjectSymbol} = hasSymbol ? Symbol("webpack defer") : "__webpack_defer__";` + : "", + `var resolveQueue = ${runtimeTemplate.basicFunction("queue", [ + "if(queue && queue.d < 1) {", + Template.indent([ + "queue.d = 1;", + `queue.forEach(${runtimeTemplate.expressionFunction( + "fn.r--", + "fn" + )});`, + `queue.forEach(${runtimeTemplate.expressionFunction( + "fn.r-- ? fn.r++ : fn()", + "fn" + )});` + ]), + "}" + ])}`, + `var wrapDeps = ${runtimeTemplate.returningFunction( + `deps.map(${runtimeTemplate.basicFunction("dep", [ + 'if(dep !== null && typeof dep === "object") {', + Template.indent([ + defer + ? Template.asString([ + "if(!dep[webpackQueues] && dep[webpackDefer]) {", + Template.indent([ + "var asyncDeps = dep[webpackDefer];", + `var hasUnresolvedAsyncSubgraph = asyncDeps.some(${runtimeTemplate.basicFunction( + "id", + [ + "var cache = __webpack_module_cache__[id];", + "return !cache || cache[webpackDone] === false;" + ] + )});`, + "if (hasUnresolvedAsyncSubgraph) {", + Template.indent([ + "var d = dep;", + "dep = {", + Template.indent([ + "then(callback) {", + Template.indent([ + "Promise.all(asyncDeps.map(__webpack_require__))", + `.then(${runtimeTemplate.returningFunction( + "callback(d)" + )});` + ]), + "}" + ]), + "};" + ]), + "} else return dep;" + ]), + "}" + ]) + : "", + "if(dep[webpackQueues]) return dep;", + "if(dep.then) {", + Template.indent([ + "var queue = [];", + "queue.d = 0;", + `dep.then(${runtimeTemplate.basicFunction("r", [ + "obj[webpackExports] = r;", + "resolveQueue(queue);" + ])}, ${runtimeTemplate.basicFunction("e", [ + "obj[webpackError] = e;", + "resolveQueue(queue);" + ])});`, + "var obj = {};", + defer ? "obj[webpackDefer] = false;" : "", + `obj[webpackQueues] = ${runtimeTemplate.expressionFunction( + "fn(queue)", + "fn" + )};`, + "return obj;" + ]), + "}" + ]), + "}", + "var ret = {};", + `ret[webpackQueues] = ${runtimeTemplate.emptyFunction()};`, + "ret[webpackExports] = dep;", + "return ret;" + ])})`, + "deps" + )};`, + `${fn} = ${runtimeTemplate.basicFunction("module, body, hasAwait", [ + "var queue;", + "hasAwait && ((queue = []).d = -1);", + "var depQueues = new Set();", + "var exports = module.exports;", + "var currentDeps;", + "var outerResolve;", + "var reject;", + `var promise = new Promise(${runtimeTemplate.basicFunction( + "resolve, rej", + ["reject = rej;", "outerResolve = resolve;"] + )});`, + "promise[webpackExports] = exports;", + `promise[webpackQueues] = ${runtimeTemplate.expressionFunction( + `queue && fn(queue), depQueues.forEach(fn), promise["catch"](${runtimeTemplate.emptyFunction()})`, + "fn" + )};`, + "module.exports = promise;", + `var handle = ${runtimeTemplate.basicFunction("deps", [ + "currentDeps = wrapDeps(deps);", + "var fn;", + `var getResult = ${runtimeTemplate.returningFunction( + `currentDeps.map(${runtimeTemplate.basicFunction("d", [ + defer ? "if(d[webpackDefer]) return d;" : "", + "if(d[webpackError]) throw d[webpackError];", + "return d[webpackExports];" + ])})` + )}`, + `var promise = new Promise(${runtimeTemplate.basicFunction( + "resolve", + [ + `fn = ${runtimeTemplate.expressionFunction( + "resolve(getResult)", + "" + )};`, + "fn.r = 0;", + `var fnQueue = ${runtimeTemplate.expressionFunction( + "q !== queue && !depQueues.has(q) && (depQueues.add(q), q && !q.d && (fn.r++, q.push(fn)))", + "q" + )};`, + `currentDeps.map(${runtimeTemplate.expressionFunction( + `${ + defer ? "dep[webpackDefer]||" : "" + }dep[webpackQueues](fnQueue)`, + "dep" + )});` + ] + )});`, + "return fn.r ? promise : getResult();" + ])}`, + `var done = ${runtimeTemplate.expressionFunction( + `(err ? reject(promise[webpackError] = err) : outerResolve(exports)), resolveQueue(queue)${ + defer ? ", promise[webpackDone] = true" : "" + }`, + "err" + )}`, + "body(handle, done);", + "queue && queue.d < 0 && (queue.d = 0);" + ])};` + ]); + } +} + +module.exports = AsyncModuleRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/AutoPublicPathRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/AutoPublicPathRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..0433194fb0976ea9dbcb6e74769de2c9dbece7c4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/AutoPublicPathRuntimeModule.js @@ -0,0 +1,85 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin"); +const { getUndoPath } = require("../util/identifier"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ + +class AutoPublicPathRuntimeModule extends RuntimeModule { + constructor() { + super("publicPath", RuntimeModule.STAGE_BASIC); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { scriptType, importMetaName, path } = compilation.outputOptions; + const chunkName = compilation.getPath( + JavascriptModulesPlugin.getChunkFilenameTemplate( + /** @type {Chunk} */ + (this.chunk), + compilation.outputOptions + ), + { + chunk: this.chunk, + contentHashType: "javascript" + } + ); + const undoPath = getUndoPath( + chunkName, + /** @type {string} */ (path), + false + ); + + return Template.asString([ + "var scriptUrl;", + scriptType === "module" + ? `if (typeof ${importMetaName}.url === "string") scriptUrl = ${importMetaName}.url` + : Template.asString([ + `if (${RuntimeGlobals.global}.importScripts) scriptUrl = ${RuntimeGlobals.global}.location + "";`, + `var document = ${RuntimeGlobals.global}.document;`, + "if (!scriptUrl && document) {", + Template.indent([ + // Technically we could use `document.currentScript instanceof window.HTMLScriptElement`, + // but an attacker could try to inject `` + // and use `` + "if (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT')", + Template.indent("scriptUrl = document.currentScript.src;"), + "if (!scriptUrl) {", + Template.indent([ + 'var scripts = document.getElementsByTagName("script");', + "if(scripts.length) {", + Template.indent([ + "var i = scripts.length - 1;", + "while (i > -1 && (!scriptUrl || !/^http(s?):/.test(scriptUrl))) scriptUrl = scripts[i--].src;" + ]), + "}" + ]), + "}" + ]), + "}" + ]), + "// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration", + '// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.', + 'if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");', + 'scriptUrl = scriptUrl.replace(/^blob:/, "").replace(/#.*$/, "").replace(/\\?.*$/, "").replace(/\\/[^\\/]+$/, "/");', + !undoPath + ? `${RuntimeGlobals.publicPath} = scriptUrl;` + : `${RuntimeGlobals.publicPath} = scriptUrl + ${JSON.stringify( + undoPath + )};` + ]); + } +} + +module.exports = AutoPublicPathRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/BaseUriRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/BaseUriRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..99609b762bd49c34aed0850daa7452b47b240cc0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/BaseUriRuntimeModule.js @@ -0,0 +1,35 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +/** @typedef {import("../../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescriptionNormalized */ +/** @typedef {import("../Chunk")} Chunk */ + +class BaseUriRuntimeModule extends RuntimeModule { + constructor() { + super("base uri", RuntimeModule.STAGE_ATTACH); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const chunk = /** @type {Chunk} */ (this.chunk); + const options = + /** @type {EntryDescriptionNormalized} */ + (chunk.getEntryOptions()); + return `${RuntimeGlobals.baseURI} = ${ + options.baseUri === undefined + ? "undefined" + : JSON.stringify(options.baseUri) + };`; + } +} + +module.exports = BaseUriRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/ChunkNameRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/ChunkNameRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..22149767907410cd07fd6afc204c5f312c0bd655 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/ChunkNameRuntimeModule.js @@ -0,0 +1,27 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +class ChunkNameRuntimeModule extends RuntimeModule { + /** + * @param {string} chunkName the chunk's name + */ + constructor(chunkName) { + super("chunkName"); + this.chunkName = chunkName; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + return `${RuntimeGlobals.chunkName} = ${JSON.stringify(this.chunkName)};`; + } +} + +module.exports = ChunkNameRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CompatGetDefaultExportRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CompatGetDefaultExportRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..1406e051fd96bb5744ccddb871ba1f2989bb0039 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CompatGetDefaultExportRuntimeModule.js @@ -0,0 +1,40 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class CompatGetDefaultExportRuntimeModule extends HelperRuntimeModule { + constructor() { + super("compat get default export"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + const fn = RuntimeGlobals.compatGetDefaultExport; + return Template.asString([ + "// getDefaultExport function for compatibility with non-harmony modules", + `${fn} = ${runtimeTemplate.basicFunction("module", [ + "var getter = module && module.__esModule ?", + Template.indent([ + `${runtimeTemplate.returningFunction("module['default']")} :`, + `${runtimeTemplate.returningFunction("module")};` + ]), + `${RuntimeGlobals.definePropertyGetters}(getter, { a: getter });`, + "return getter;" + ])};` + ]); + } +} + +module.exports = CompatGetDefaultExportRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CompatRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CompatRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..cf386c0886b9463766e39d470edd4a6ac061421a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CompatRuntimeModule.js @@ -0,0 +1,83 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../MainTemplate")} MainTemplate */ + +class CompatRuntimeModule extends RuntimeModule { + constructor() { + super("compat", RuntimeModule.STAGE_ATTACH); + this.fullHash = true; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const { + runtimeTemplate, + mainTemplate, + moduleTemplates, + dependencyTemplates + } = compilation; + const bootstrap = mainTemplate.hooks.bootstrap.call( + "", + chunk, + compilation.hash || "XXXX", + moduleTemplates.javascript, + dependencyTemplates + ); + const localVars = mainTemplate.hooks.localVars.call( + "", + chunk, + compilation.hash || "XXXX" + ); + const requireExtensions = mainTemplate.hooks.requireExtensions.call( + "", + chunk, + compilation.hash || "XXXX" + ); + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + let requireEnsure = ""; + if (runtimeRequirements.has(RuntimeGlobals.ensureChunk)) { + const requireEnsureHandler = mainTemplate.hooks.requireEnsure.call( + "", + chunk, + compilation.hash || "XXXX", + "chunkId" + ); + if (requireEnsureHandler) { + requireEnsure = `${ + RuntimeGlobals.ensureChunkHandlers + }.compat = ${runtimeTemplate.basicFunction( + "chunkId, promises", + requireEnsureHandler + )};`; + } + } + return [bootstrap, localVars, requireEnsure, requireExtensions] + .filter(Boolean) + .join("\n"); + } + + /** + * @returns {boolean} true, if the runtime module should get it's own scope + */ + shouldIsolate() { + // We avoid isolating this to have better backward-compat + return false; + } +} + +module.exports = CompatRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..b5f09df79525b23b91a652e5e10e108f4534cafb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js @@ -0,0 +1,69 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { + constructor() { + super("create fake namespace object"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + const fn = RuntimeGlobals.createFakeNamespaceObject; + return Template.asString([ + `var getProto = Object.getPrototypeOf ? ${runtimeTemplate.returningFunction( + "Object.getPrototypeOf(obj)", + "obj" + )} : ${runtimeTemplate.returningFunction("obj.__proto__", "obj")};`, + "var leafPrototypes;", + "// create a fake namespace object", + "// mode & 1: value is a module id, require it", + "// mode & 2: merge all properties of value into the ns", + "// mode & 4: return value when already ns object", + "// mode & 16: return value when it's Promise-like", + "// mode & 8|1: behave like require", + // Note: must be a function (not arrow), because this is used in body! + `${fn} = function(value, mode) {`, + Template.indent([ + "if(mode & 1) value = this(value);", + "if(mode & 8) return value;", + "if(typeof value === 'object' && value) {", + Template.indent([ + "if((mode & 4) && value.__esModule) return value;", + "if((mode & 16) && typeof value.then === 'function') return value;" + ]), + "}", + "var ns = Object.create(null);", + `${RuntimeGlobals.makeNamespaceObject}(ns);`, + "var def = {};", + "leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];", + "for(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {", + Template.indent([ + `Object.getOwnPropertyNames(current).forEach(${runtimeTemplate.expressionFunction( + `def[key] = ${runtimeTemplate.returningFunction("value[key]", "")}`, + "key" + )});` + ]), + "}", + `def['default'] = ${runtimeTemplate.returningFunction("value", "")};`, + `${RuntimeGlobals.definePropertyGetters}(ns, def);`, + "return ns;" + ]), + "};" + ]); + } +} + +module.exports = CreateFakeNamespaceObjectRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CreateScriptRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CreateScriptRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..7859e87d411d1244393f4893293b3474c7a9a96e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CreateScriptRuntimeModule.js @@ -0,0 +1,38 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class CreateScriptRuntimeModule extends HelperRuntimeModule { + constructor() { + super("trusted types script"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate, outputOptions } = compilation; + const { trustedTypes } = outputOptions; + const fn = RuntimeGlobals.createScript; + + return Template.asString( + `${fn} = ${runtimeTemplate.returningFunction( + trustedTypes + ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScript(script)` + : "script", + "script" + )};` + ); + } +} + +module.exports = CreateScriptRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CreateScriptUrlRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CreateScriptUrlRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..4c8960024d90a73dbc7667afc3184cf5d2168e5b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/CreateScriptUrlRuntimeModule.js @@ -0,0 +1,38 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class CreateScriptUrlRuntimeModule extends HelperRuntimeModule { + constructor() { + super("trusted types script url"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate, outputOptions } = compilation; + const { trustedTypes } = outputOptions; + const fn = RuntimeGlobals.createScriptUrl; + + return Template.asString( + `${fn} = ${runtimeTemplate.returningFunction( + trustedTypes + ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScriptURL(url)` + : "url", + "url" + )};` + ); + } +} + +module.exports = CreateScriptUrlRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/DefinePropertyGettersRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/DefinePropertyGettersRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..4dad207a93555552a91ba2e1f99efbedbf6be911 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/DefinePropertyGettersRuntimeModule.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class DefinePropertyGettersRuntimeModule extends HelperRuntimeModule { + constructor() { + super("define property getters"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + const fn = RuntimeGlobals.definePropertyGetters; + return Template.asString([ + "// define getter functions for harmony exports", + `${fn} = ${runtimeTemplate.basicFunction("exports, definition", [ + "for(var key in definition) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(definition, key) && !${RuntimeGlobals.hasOwnProperty}(exports, key)) {`, + Template.indent([ + "Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });" + ]), + "}" + ]), + "}" + ])};` + ]); + } +} + +module.exports = DefinePropertyGettersRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/EnsureChunkRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/EnsureChunkRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..bc6c0ecbdf1e3ec08c5fa3c7584e0a636c3647e8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/EnsureChunkRuntimeModule.js @@ -0,0 +1,68 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ + +class EnsureChunkRuntimeModule extends RuntimeModule { + /** + * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super("ensure chunk"); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + // Check if there are non initial chunks which need to be imported using require-ensure + if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) { + const withFetchPriority = this.runtimeRequirements.has( + RuntimeGlobals.hasFetchPriority + ); + const handlers = RuntimeGlobals.ensureChunkHandlers; + return Template.asString([ + `${handlers} = {};`, + "// This file contains only the entry chunk.", + "// The chunk loading function for additional chunks", + `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.basicFunction( + `chunkId${withFetchPriority ? ", fetchPriority" : ""}`, + [ + `return Promise.all(Object.keys(${handlers}).reduce(${runtimeTemplate.basicFunction( + "promises, key", + [ + `${handlers}[key](chunkId, promises${ + withFetchPriority ? ", fetchPriority" : "" + });`, + "return promises;" + ] + )}, []));` + ] + )};` + ]); + } + // There ensureChunk is used somewhere in the tree, so we need an empty requireEnsure + // function. This can happen with multiple entrypoints. + return Template.asString([ + "// The chunk loading function for additional chunks", + "// Since all referenced chunks are already included", + "// in this file, this function is empty here.", + `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.returningFunction( + "Promise.resolve()" + )};` + ]); + } +} + +module.exports = EnsureChunkRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetChunkFilenameRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetChunkFilenameRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..b74ddaa1f58053fb9aa50d00749f17a45694671b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetChunkFilenameRuntimeModule.js @@ -0,0 +1,294 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const { first } = require("../util/SetHelpers"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Chunk").ChunkId} ChunkId */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */ + +class GetChunkFilenameRuntimeModule extends RuntimeModule { + /** + * @param {string} contentType the contentType to use the content hash for + * @param {string} name kind of filename + * @param {string} global function name to be assigned + * @param {(chunk: Chunk) => TemplatePath | false} getFilenameForChunk functor to get the filename or function + * @param {boolean} allChunks when false, only async chunks are included + */ + constructor(contentType, name, global, getFilenameForChunk, allChunks) { + super(`get ${name} chunk filename`); + this.contentType = contentType; + this.global = global; + this.getFilenameForChunk = getFilenameForChunk; + this.allChunks = allChunks; + this.dependentHash = true; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { global, contentType, getFilenameForChunk, allChunks } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const { runtimeTemplate } = compilation; + + /** @type {Map>} */ + const chunkFilenames = new Map(); + let maxChunks = 0; + /** @type {string | undefined} */ + let dynamicFilename; + + /** + * @param {Chunk} c the chunk + * @returns {void} + */ + const addChunk = (c) => { + const chunkFilename = getFilenameForChunk(c); + if (chunkFilename) { + let set = chunkFilenames.get(chunkFilename); + if (set === undefined) { + chunkFilenames.set(chunkFilename, (set = new Set())); + } + set.add(c); + if (typeof chunkFilename === "string") { + if (set.size < maxChunks) return; + if (set.size === maxChunks) { + if ( + chunkFilename.length < + /** @type {string} */ (dynamicFilename).length + ) { + return; + } + + if ( + chunkFilename.length === + /** @type {string} */ (dynamicFilename).length && + chunkFilename < /** @type {string} */ (dynamicFilename) + ) { + return; + } + } + maxChunks = set.size; + dynamicFilename = chunkFilename; + } + } + }; + + /** @type {string[]} */ + const includedChunksMessages = []; + if (allChunks) { + includedChunksMessages.push("all chunks"); + for (const c of chunk.getAllReferencedChunks()) { + addChunk(c); + } + } else { + includedChunksMessages.push("async chunks"); + for (const c of chunk.getAllAsyncChunks()) { + addChunk(c); + } + const includeEntries = chunkGraph + .getTreeRuntimeRequirements(chunk) + .has(RuntimeGlobals.ensureChunkIncludeEntries); + if (includeEntries) { + includedChunksMessages.push("chunks that the entrypoint depends on"); + for (const c of chunkGraph.getRuntimeChunkDependentChunksIterable( + chunk + )) { + addChunk(c); + } + } + } + for (const entrypoint of chunk.getAllReferencedAsyncEntrypoints()) { + addChunk(entrypoint.chunks[entrypoint.chunks.length - 1]); + } + + /** @type {Map>} */ + const staticUrls = new Map(); + /** @type {Set} */ + const dynamicUrlChunks = new Set(); + + /** + * @param {Chunk} c the chunk + * @param {string | TemplatePath} chunkFilename the filename template for the chunk + * @returns {void} + */ + const addStaticUrl = (c, chunkFilename) => { + /** + * @param {string | number} value a value + * @returns {string} string to put in quotes + */ + const unquotedStringify = (value) => { + const str = `${value}`; + if (str.length >= 5 && str === `${c.id}`) { + // This is shorter and generates the same result + return '" + chunkId + "'; + } + const s = JSON.stringify(str); + return s.slice(1, -1); + }; + /** + * @param {string} value string + * @returns {(length: number) => string} string to put in quotes with length + */ + const unquotedStringifyWithLength = (value) => (length) => + unquotedStringify(`${value}`.slice(0, length)); + const chunkFilenameValue = + typeof chunkFilename === "function" + ? JSON.stringify( + chunkFilename({ + chunk: c, + contentHashType: contentType + }) + ) + : JSON.stringify(chunkFilename); + const staticChunkFilename = compilation.getPath(chunkFilenameValue, { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: (length) => + `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, + chunk: { + id: unquotedStringify(/** @type {ChunkId} */ (c.id)), + hash: unquotedStringify(/** @type {string} */ (c.renderedHash)), + hashWithLength: unquotedStringifyWithLength( + /** @type {string} */ (c.renderedHash) + ), + name: unquotedStringify(c.name || /** @type {ChunkId} */ (c.id)), + contentHash: { + [contentType]: unquotedStringify(c.contentHash[contentType]) + }, + contentHashWithLength: { + [contentType]: unquotedStringifyWithLength( + c.contentHash[contentType] + ) + } + }, + contentHashType: contentType + }); + let set = staticUrls.get(staticChunkFilename); + if (set === undefined) { + staticUrls.set(staticChunkFilename, (set = new Set())); + } + set.add(c.id); + }; + + for (const [filename, chunks] of chunkFilenames) { + if (filename !== dynamicFilename) { + for (const c of chunks) addStaticUrl(c, filename); + } else { + for (const c of chunks) dynamicUrlChunks.add(c); + } + } + + /** + * @param {(chunk: Chunk) => string | number} fn function from chunk to value + * @returns {string} code with static mapping of results of fn + */ + const createMap = (fn) => { + /** @type {Record} */ + const obj = {}; + let useId = false; + /** @type {number | string | undefined} */ + let lastKey; + let entries = 0; + for (const c of dynamicUrlChunks) { + const value = fn(c); + if (value === c.id) { + useId = true; + } else { + obj[/** @type {number | string} */ (c.id)] = value; + lastKey = /** @type {number | string} */ (c.id); + entries++; + } + } + if (entries === 0) return "chunkId"; + if (entries === 1) { + return useId + ? `(chunkId === ${JSON.stringify(lastKey)} ? ${JSON.stringify( + obj[/** @type {number | string} */ (lastKey)] + )} : chunkId)` + : JSON.stringify(obj[/** @type {number | string} */ (lastKey)]); + } + return useId + ? `(${JSON.stringify(obj)}[chunkId] || chunkId)` + : `${JSON.stringify(obj)}[chunkId]`; + }; + + /** + * @param {(chunk: Chunk) => string | number} fn function from chunk to value + * @returns {string} code with static mapping of results of fn for including in quoted string + */ + const mapExpr = (fn) => `" + ${createMap(fn)} + "`; + + /** + * @param {(chunk: Chunk) => string | number} fn function from chunk to value + * @returns {(length: number) => string} function which generates code with static mapping of results of fn for including in quoted string for specific length + */ + const mapExprWithLength = (fn) => (length) => + `" + ${createMap((c) => `${fn(c)}`.slice(0, length))} + "`; + + const url = + dynamicFilename && + compilation.getPath(JSON.stringify(dynamicFilename), { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: (length) => + `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, + chunk: { + id: '" + chunkId + "', + hash: mapExpr((c) => /** @type {string} */ (c.renderedHash)), + hashWithLength: mapExprWithLength( + (c) => /** @type {string} */ (c.renderedHash) + ), + name: mapExpr((c) => c.name || /** @type {number | string} */ (c.id)), + contentHash: { + [contentType]: mapExpr((c) => c.contentHash[contentType]) + }, + contentHashWithLength: { + [contentType]: mapExprWithLength((c) => c.contentHash[contentType]) + } + }, + contentHashType: contentType + }); + + return Template.asString([ + `// This function allow to reference ${includedChunksMessages.join( + " and " + )}`, + `${global} = ${runtimeTemplate.basicFunction( + "chunkId", + + staticUrls.size > 0 + ? [ + "// return url for filenames not based on template", + // it minimizes to `x===1?"...":x===2?"...":"..."` + Template.asString( + Array.from(staticUrls, ([url, ids]) => { + const condition = + ids.size === 1 + ? `chunkId === ${JSON.stringify(first(ids))}` + : `{${Array.from( + ids, + (id) => `${JSON.stringify(id)}:1` + ).join(",")}}[chunkId]`; + return `if (${condition}) return ${url};`; + }) + ), + "// return url for filenames based on template", + `return ${url};` + ] + : ["// return url for filenames based on template", `return ${url};`] + )};` + ]); + } +} + +module.exports = GetChunkFilenameRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetFullHashRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetFullHashRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..cf9949394fb29ebb0682034578bba704eed7f872 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetFullHashRuntimeModule.js @@ -0,0 +1,30 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class GetFullHashRuntimeModule extends RuntimeModule { + constructor() { + super("getFullHash"); + this.fullHash = true; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + return `${RuntimeGlobals.getFullHash} = ${runtimeTemplate.returningFunction( + JSON.stringify(compilation.hash || "XXXX") + )}`; + } +} + +module.exports = GetFullHashRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetMainFilenameRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetMainFilenameRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..f280163b5d7ff9699139539394a08df4081a1fb0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetMainFilenameRuntimeModule.js @@ -0,0 +1,47 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ + +class GetMainFilenameRuntimeModule extends RuntimeModule { + /** + * @param {string} name readable name + * @param {string} global global object binding + * @param {string} filename main file name + */ + constructor(name, global, filename) { + super(`get ${name} filename`); + this.global = global; + this.filename = filename; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { global, filename } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + const chunk = /** @type {Chunk} */ (this.chunk); + const { runtimeTemplate } = compilation; + const url = compilation.getPath(JSON.stringify(filename), { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: (length) => + `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, + chunk, + runtime: chunk.runtime + }); + return Template.asString([ + `${global} = ${runtimeTemplate.returningFunction(url)};` + ]); + } +} + +module.exports = GetMainFilenameRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..27bb37508852ab44e28ead05148fcbacf9ab8e92 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js @@ -0,0 +1,98 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ + +class GetTrustedTypesPolicyRuntimeModule extends HelperRuntimeModule { + /** + * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super("trusted types policy"); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate, outputOptions } = compilation; + const { trustedTypes } = outputOptions; + const fn = RuntimeGlobals.getTrustedTypesPolicy; + const wrapPolicyCreationInTryCatch = trustedTypes + ? trustedTypes.onPolicyCreationFailure === "continue" + : false; + + return Template.asString([ + "var policy;", + `${fn} = ${runtimeTemplate.basicFunction("", [ + "// Create Trusted Type policy if Trusted Types are available and the policy doesn't exist yet.", + "if (policy === undefined) {", + Template.indent([ + "policy = {", + Template.indent( + [ + ...(this.runtimeRequirements.has(RuntimeGlobals.createScript) + ? [ + `createScript: ${runtimeTemplate.returningFunction( + "script", + "script" + )}` + ] + : []), + ...(this.runtimeRequirements.has(RuntimeGlobals.createScriptUrl) + ? [ + `createScriptURL: ${runtimeTemplate.returningFunction( + "url", + "url" + )}` + ] + : []) + ].join(",\n") + ), + "};", + ...(trustedTypes + ? [ + 'if (typeof trustedTypes !== "undefined" && trustedTypes.createPolicy) {', + Template.indent([ + ...(wrapPolicyCreationInTryCatch ? ["try {"] : []), + ...[ + `policy = trustedTypes.createPolicy(${JSON.stringify( + trustedTypes.policyName + )}, policy);` + ].map((line) => + wrapPolicyCreationInTryCatch ? Template.indent(line) : line + ), + ...(wrapPolicyCreationInTryCatch + ? [ + "} catch (e) {", + Template.indent([ + `console.warn('Could not create trusted-types policy ${JSON.stringify( + trustedTypes.policyName + )}');` + ]), + "}" + ] + : []) + ]), + "}" + ] + : []) + ]), + "}", + "return policy;" + ])};` + ]); + } +} + +module.exports = GetTrustedTypesPolicyRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GlobalRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GlobalRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..89e556c08586c8ec1675b1312faba12a69378d04 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/GlobalRuntimeModule.js @@ -0,0 +1,47 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +class GlobalRuntimeModule extends RuntimeModule { + constructor() { + super("global"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.global} = (function() {`, + Template.indent([ + "if (typeof globalThis === 'object') return globalThis;", + "try {", + Template.indent( + // This works in non-strict mode + // or + // This works if eval is allowed (see CSP) + "return this || new Function('return this')();" + ), + "} catch (e) {", + Template.indent( + // This works if the window reference is available + "if (typeof window === 'object') return window;" + ), + "}" + // It can still be `undefined`, but nothing to do about it... + // We return `undefined`, instead of nothing here, so it's + // easier to handle this case: + // if (!global) { … } + ]), + "})();" + ]); + } +} + +module.exports = GlobalRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/HasOwnPropertyRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/HasOwnPropertyRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..78bf3afeb95d8bb2ef9f0e27815ef87d0fb3e311 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/HasOwnPropertyRuntimeModule.js @@ -0,0 +1,35 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Compilation")} Compilation */ + +class HasOwnPropertyRuntimeModule extends RuntimeModule { + constructor() { + super("hasOwnProperty shorthand"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + + return Template.asString([ + `${RuntimeGlobals.hasOwnProperty} = ${runtimeTemplate.returningFunction( + "Object.prototype.hasOwnProperty.call(obj, prop)", + "obj, prop" + )}` + ]); + } +} + +module.exports = HasOwnPropertyRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/HelperRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/HelperRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..012916c9228cb6579267c7fe69067e83d3b51760 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/HelperRuntimeModule.js @@ -0,0 +1,18 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeModule = require("../RuntimeModule"); + +class HelperRuntimeModule extends RuntimeModule { + /** + * @param {string} name a readable name + */ + constructor(name) { + super(name); + } +} + +module.exports = HelperRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/LoadScriptRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/LoadScriptRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..b6b2f3e381c1b9d51870de654b0c77ad3e3f3c92 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/LoadScriptRuntimeModule.js @@ -0,0 +1,174 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const { SyncWaterfallHook } = require("tapable"); +const Compilation = require("../Compilation"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {object} LoadScriptCompilationHooks + * @property {SyncWaterfallHook<[string, Chunk]>} createScript + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class LoadScriptRuntimeModule extends HelperRuntimeModule { + /** + * @param {Compilation} compilation the compilation + * @returns {LoadScriptCompilationHooks} hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + createScript: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** + * @param {boolean=} withCreateScriptUrl use create script url for trusted types + * @param {boolean=} withFetchPriority use `fetchPriority` attribute + */ + constructor(withCreateScriptUrl, withFetchPriority) { + super("load script"); + this._withCreateScriptUrl = withCreateScriptUrl; + this._withFetchPriority = withFetchPriority; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate, outputOptions } = compilation; + const { + scriptType, + chunkLoadTimeout: loadTimeout, + crossOriginLoading, + uniqueName, + charset + } = outputOptions; + const fn = RuntimeGlobals.loadScript; + + const { createScript } = + LoadScriptRuntimeModule.getCompilationHooks(compilation); + + const code = Template.asString([ + "script = document.createElement('script');", + scriptType ? `script.type = ${JSON.stringify(scriptType)};` : "", + charset ? "script.charset = 'utf-8';" : "", + `script.timeout = ${/** @type {number} */ (loadTimeout) / 1000};`, + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `script.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + uniqueName + ? 'script.setAttribute("data-webpack", dataWebpackPrefix + key);' + : "", + this._withFetchPriority + ? Template.asString([ + "if(fetchPriority) {", + Template.indent( + 'script.setAttribute("fetchpriority", fetchPriority);' + ), + "}" + ]) + : "", + `script.src = ${ + this._withCreateScriptUrl + ? `${RuntimeGlobals.createScriptUrl}(url)` + : "url" + };`, + crossOriginLoading + ? crossOriginLoading === "use-credentials" + ? 'script.crossOrigin = "use-credentials";' + : Template.asString([ + "if (script.src.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "" + ]); + + return Template.asString([ + "var inProgress = {};", + uniqueName + ? `var dataWebpackPrefix = ${JSON.stringify(`${uniqueName}:`)};` + : "// data-webpack is not used as build has no uniqueName", + "// loadScript function to load a script via script tag", + `${fn} = ${runtimeTemplate.basicFunction( + `url, done, key, chunkId${ + this._withFetchPriority ? ", fetchPriority" : "" + }`, + [ + "if(inProgress[url]) { inProgress[url].push(done); return; }", + "var script, needAttach;", + "if(key !== undefined) {", + Template.indent([ + 'var scripts = document.getElementsByTagName("script");', + "for(var i = 0; i < scripts.length; i++) {", + Template.indent([ + "var s = scripts[i];", + `if(s.getAttribute("src") == url${ + uniqueName + ? ' || s.getAttribute("data-webpack") == dataWebpackPrefix + key' + : "" + }) { script = s; break; }` + ]), + "}" + ]), + "}", + "if(!script) {", + Template.indent([ + "needAttach = true;", + createScript.call(code, /** @type {Chunk} */ (this.chunk)) + ]), + "}", + "inProgress[url] = [done];", + `var onScriptComplete = ${runtimeTemplate.basicFunction( + "prev, event", + Template.asString([ + "// avoid mem leaks in IE.", + "script.onerror = script.onload = null;", + "clearTimeout(timeout);", + "var doneFns = inProgress[url];", + "delete inProgress[url];", + "script.parentNode && script.parentNode.removeChild(script);", + `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction( + "fn(event)", + "fn" + )});`, + "if(prev) return prev(event);" + ]) + )}`, + `var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`, + "script.onerror = onScriptComplete.bind(null, script.onerror);", + "script.onload = onScriptComplete.bind(null, script.onload);", + "needAttach && document.head.appendChild(script);" + ] + )};` + ]); + } +} + +module.exports = LoadScriptRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/MakeDeferredNamespaceObjectRuntime.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/MakeDeferredNamespaceObjectRuntime.js new file mode 100644 index 0000000000000000000000000000000000000000..b1d91e422fd92e71cc50b725eb9d41dd218ef7cc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/MakeDeferredNamespaceObjectRuntime.js @@ -0,0 +1,214 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** + * @param {import("../Module").ExportsType} exportsType exports type + * @returns {string} mode + */ +function getMakeDeferredNamespaceModeFromExportsType(exportsType) { + if (exportsType === "namespace") return `/* ${exportsType} */ 0`; + if (exportsType === "default-only") return `/* ${exportsType} */ 1`; + if (exportsType === "default-with-named") return `/* ${exportsType} */ 2`; + if (exportsType === "dynamic") return `/* ${exportsType} */ 3`; + return ""; +} +/** + * @param {import("../ModuleTemplate").RuntimeTemplate} _runtimeTemplate runtimeTemplate + * @param {import("../Module").ExportsType} exportsType exportsType + * @param {string} moduleId moduleId + * @param {(import("../ChunkGraph").ModuleId | null)[]} asyncDepsIds asyncDepsIds + * @returns {string} function + */ +function getOptimizedDeferredModule( + _runtimeTemplate, + exportsType, + moduleId, + asyncDepsIds +) { + const isAsync = asyncDepsIds && asyncDepsIds.length; + const init = `${RuntimeGlobals.require}(${moduleId})${ + isAsync ? `[${RuntimeGlobals.asyncModuleExportSymbol}]` : "" + }`; + const props = [ + `/* ${exportsType} */ get a() {`, + // if exportsType is "namespace" we can generate the most optimized code, + // on the second access, we can avoid trigger the getter. + // we can also do this if exportsType is "dynamic" and there is a "__esModule" property on it. + exportsType === "namespace" || exportsType === "dynamic" + ? Template.indent([ + `var exports = ${init};`, + `${ + exportsType === "dynamic" ? "if (exports.__esModule) " : "" + }Object.defineProperty(this, "a", { value: exports });`, + "return exports;" + ]) + : Template.indent([`return ${init};`]), + isAsync ? "}," : "}", + isAsync + ? `[${ + RuntimeGlobals.makeDeferredNamespaceObjectSymbol + }]: ${JSON.stringify(asyncDepsIds.filter((x) => x !== null))}` + : "" + ]; + return Template.asString(["{", Template.indent(props), "}"]); +} + +const strictModuleCache = [ + "if (cachedModule && cachedModule.error === undefined) {", + Template.indent([ + "var exports = cachedModule.exports;", + "if (mode == 0) return exports;", + `if (mode == 1) return ${RuntimeGlobals.createFakeNamespaceObject}(exports);`, + `if (mode == 2) return ${RuntimeGlobals.createFakeNamespaceObject}(exports, 2);`, + `if (mode == 3) return ${RuntimeGlobals.createFakeNamespaceObject}(exports, 6);` // 2 | 4 + ]), + "}" +]; +const nonStrictModuleCache = [ + "// optimization not applied when output.strictModuleErrorHandling is off" +]; + +class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule { + /** + * @param {boolean} hasAsyncRuntime if async module is used. + */ + constructor(hasAsyncRuntime) { + super("make deferred namespace object"); + this.hasAsyncRuntime = hasAsyncRuntime; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + if (!this.compilation) return null; + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.makeDeferredNamespaceObject; + const hasAsync = this.hasAsyncRuntime; + const strictError = + this.compilation.options.output.strictModuleErrorHandling; + const init = runtimeTemplate.supportsOptionalChaining() + ? "init?.();" + : "if (init) init();"; + return `${fn} = ${runtimeTemplate.basicFunction("moduleId, mode", [ + "// mode: 0 => namespace (esm)", + "// mode: 1 => default-only (esm strict cjs)", + "// mode: 2 => default-with-named (esm-cjs compat)", + "// mode: 3 => dynamic (if exports has __esModule, then esm, otherwise default-with-named)", + "", + "var cachedModule = __webpack_module_cache__[moduleId];", + ...(strictError ? strictModuleCache : nonStrictModuleCache), + "", + `var init = ${runtimeTemplate.basicFunction("", [ + `ns = ${RuntimeGlobals.require}(moduleId);`, + hasAsync + ? `if (${RuntimeGlobals.asyncModuleExportSymbol} in ns) ns = ns[${RuntimeGlobals.asyncModuleExportSymbol}];` + : "", + "init = null;", + "if (mode == 0 || mode == 3 && ns.__esModule && typeof ns === 'object') {", + Template.indent([ + "delete handler.defineProperty;", + "delete handler.deleteProperty;", + "delete handler.set;", + "delete handler.get;", + "delete handler.has;", + "delete handler.ownKeys;", + "delete handler.getOwnPropertyDescriptor;" + ]), + "} else if (mode == 1) {", + Template.indent([ + `ns = ${RuntimeGlobals.createFakeNamespaceObject}(ns);` + ]), + "} else if (mode == 2) {", + Template.indent([ + `ns = ${RuntimeGlobals.createFakeNamespaceObject}(ns, 2);` + ]), + "} else if (mode == 3) {", + Template.indent([ + `ns = ${RuntimeGlobals.createFakeNamespaceObject}(ns, 6);` + ]), + "}" + ])};`, + "", + `var ns = ${ + strictError ? "" : "cachedModule && cachedModule.exports || " + }__webpack_module_deferred_exports__[moduleId] || (__webpack_module_deferred_exports__[moduleId] = { __proto__: null });`, + "var handler = {", + Template.indent([ + "__proto__: null,", + `get: ${runtimeTemplate.basicFunction("_, name", [ + "switch (name) {", + Template.indent([ + 'case "__esModule": return true;', + 'case Symbol.toStringTag: return "Deferred Module";', + 'case "then": return undefined;' + ]), + "}", + init, + "return ns[name];" + ])},`, + `has: ${runtimeTemplate.basicFunction("_, name", [ + "switch (name) {", + Template.indent( + [ + 'case "__esModule":', + "case Symbol.toStringTag:", + hasAsync + ? `case ${RuntimeGlobals.makeDeferredNamespaceObjectSymbol}:` + : "", + Template.indent("return true;"), + 'case "then":', + Template.indent("return false;") + ].filter(Boolean) + ), + "}", + init, + "return name in ns;" + ])},`, + `ownKeys: ${runtimeTemplate.basicFunction("", [ + init, + `var keys = Reflect.ownKeys(ns).filter(${runtimeTemplate.expressionFunction('x !== "then"', "x")}).concat([Symbol.toStringTag]);`, + "return keys;" + ])},`, + `getOwnPropertyDescriptor: ${runtimeTemplate.basicFunction("_, name", [ + "switch (name) {", + Template.indent([ + 'case "__esModule": return { value: true, configurable: !!mode };', + 'case Symbol.toStringTag: return { value: "Deferred Module", configurable: !!mode };', + 'case "then": return undefined;' + ]), + "}", + init, + "var desc = Reflect.getOwnPropertyDescriptor(ns, name);", + 'if (mode == 2 && name == "default" && !desc) {', + Template.indent("desc = { value: ns, configurable: true };"), + "}", + "return desc;" + ])},`, + `defineProperty: ${runtimeTemplate.basicFunction("_, name", [ + init, + // Note: This behavior does not match the spec one, but since webpack does not do it either + // for a normal Module Namespace object (in MakeNamespaceObjectRuntimeModule), let's keep it simple. + "return false;" + ])},`, + `deleteProperty: ${runtimeTemplate.returningFunction("false")},`, + `set: ${runtimeTemplate.returningFunction("false")},` + ]), + "}", + // we don't fully emulate ES Module semantics in this Proxy to align with normal webpack esm namespace object. + "return new Proxy(ns, handler);" + ])};`; + } +} + +module.exports = MakeDeferredNamespaceObjectRuntimeModule; +module.exports.getMakeDeferredNamespaceModeFromExportsType = + getMakeDeferredNamespaceModeFromExportsType; +module.exports.getOptimizedDeferredModule = getOptimizedDeferredModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/MakeNamespaceObjectRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/MakeNamespaceObjectRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..7b43080d02096ec65c27c0f1cb06c9305e280dd7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/MakeNamespaceObjectRuntimeModule.js @@ -0,0 +1,39 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class MakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { + constructor() { + super("make namespace object"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + const fn = RuntimeGlobals.makeNamespaceObject; + return Template.asString([ + "// define __esModule on exports", + `${fn} = ${runtimeTemplate.basicFunction("exports", [ + "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", + Template.indent([ + "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" + ]), + "}", + "Object.defineProperty(exports, '__esModule', { value: true });" + ])};` + ]); + } +} + +module.exports = MakeNamespaceObjectRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/NonceRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/NonceRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..238407c1ba6ef22cebcc815e8d80ed8ce162038b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/NonceRuntimeModule.js @@ -0,0 +1,24 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +class NonceRuntimeModule extends RuntimeModule { + constructor() { + super("nonce", RuntimeModule.STAGE_ATTACH); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + return `${RuntimeGlobals.scriptNonce} = undefined;`; + } +} + +module.exports = NonceRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/OnChunksLoadedRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/OnChunksLoadedRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..2224d02bb4a9cc52a8b477f8d346bc46158d5378 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/OnChunksLoadedRuntimeModule.js @@ -0,0 +1,78 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Compilation")} Compilation */ + +class OnChunksLoadedRuntimeModule extends RuntimeModule { + constructor() { + super("chunk loaded"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + return Template.asString([ + "var deferred = [];", + `${RuntimeGlobals.onChunksLoaded} = ${runtimeTemplate.basicFunction( + "result, chunkIds, fn, priority", + [ + "if(chunkIds) {", + Template.indent([ + "priority = priority || 0;", + "for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];", + "deferred[i] = [chunkIds, fn, priority];", + "return;" + ]), + "}", + "var notFulfilled = Infinity;", + "for (var i = 0; i < deferred.length; i++) {", + Template.indent([ + runtimeTemplate.destructureArray( + ["chunkIds", "fn", "priority"], + "deferred[i]" + ), + "var fulfilled = true;", + "for (var j = 0; j < chunkIds.length; j++) {", + Template.indent([ + `if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(${ + RuntimeGlobals.onChunksLoaded + }).every(${runtimeTemplate.returningFunction( + `${RuntimeGlobals.onChunksLoaded}[key](chunkIds[j])`, + "key" + )})) {`, + Template.indent(["chunkIds.splice(j--, 1);"]), + "} else {", + Template.indent([ + "fulfilled = false;", + "if(priority < notFulfilled) notFulfilled = priority;" + ]), + "}" + ]), + "}", + "if(fulfilled) {", + Template.indent([ + "deferred.splice(i--, 1)", + "var r = fn();", + "if (r !== undefined) result = r;" + ]), + "}" + ]), + "}", + "return result;" + ] + )};` + ]); + } +} + +module.exports = OnChunksLoadedRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/PublicPathRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/PublicPathRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..7ea226161c9f3c0f1b0b76fa44387b3fb11de739 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/PublicPathRuntimeModule.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../Compilation")} Compilation */ + +class PublicPathRuntimeModule extends RuntimeModule { + /** + * @param {OutputOptions["publicPath"]} publicPath public path + */ + constructor(publicPath) { + super("publicPath", RuntimeModule.STAGE_BASIC); + this.publicPath = publicPath; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const { publicPath } = this; + const compilation = /** @type {Compilation} */ (this.compilation); + + return `${RuntimeGlobals.publicPath} = ${JSON.stringify( + compilation.getPath(publicPath || "", { + hash: compilation.hash || "XXXX" + }) + )};`; + } +} + +module.exports = PublicPathRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/RelativeUrlRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/RelativeUrlRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..92e32daed9811ca625dd9515c302ab1513dbe491 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/RelativeUrlRuntimeModule.js @@ -0,0 +1,44 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const HelperRuntimeModule = require("./HelperRuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class RelativeUrlRuntimeModule extends HelperRuntimeModule { + constructor() { + super("relative url"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + return Template.asString([ + `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`, + Template.indent([ + 'var realUrl = new URL(url, "x:/");', + "var values = {};", + "for (var key in realUrl) values[key] = realUrl[key];", + "values.href = url;", + 'values.pathname = url.replace(/[?#].*/, "");', + 'values.origin = values.protocol = "";', + `values.toString = values.toJSON = ${runtimeTemplate.returningFunction( + "url" + )};`, + "for (var key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });" + ]), + "};", + `${RuntimeGlobals.relativeUrl}.prototype = URL.prototype;` + ]); + } +} + +module.exports = RelativeUrlRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/RuntimeIdRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/RuntimeIdRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..df75d22ca5978675f9694f94a0f6eeac31941f2c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/RuntimeIdRuntimeModule.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ + +class RuntimeIdRuntimeModule extends RuntimeModule { + constructor() { + super("runtimeId"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const runtime = chunk.runtime; + if (typeof runtime !== "string") { + throw new Error("RuntimeIdRuntimeModule must be in a single runtime"); + } + const id = chunkGraph.getRuntimeId(runtime); + return `${RuntimeGlobals.runtimeId} = ${JSON.stringify(id)};`; + } +} + +module.exports = RuntimeIdRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/StartupChunkDependenciesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/StartupChunkDependenciesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b37d7e72f91f65028bd0b168ba930f1c4e9e59dd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/StartupChunkDependenciesPlugin.js @@ -0,0 +1,86 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const StartupChunkDependenciesRuntimeModule = require("./StartupChunkDependenciesRuntimeModule"); +const StartupEntrypointRuntimeModule = require("./StartupEntrypointRuntimeModule"); + +/** @typedef {import("../../declarations/WebpackOptions").ChunkLoadingType} ChunkLoadingType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {object} Options + * @property {ChunkLoadingType} chunkLoading + * @property {boolean=} asyncChunkLoading + */ + +const PLUGIN_NAME = "StartupChunkDependenciesPlugin"; + +class StartupChunkDependenciesPlugin { + /** + * @param {Options} options options + */ + constructor(options) { + this.chunkLoading = options.chunkLoading; + this.asyncChunkLoading = + typeof options.asyncChunkLoading === "boolean" + ? options.asyncChunkLoading + : true; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + /** + * @param {Chunk} chunk chunk to check + * @returns {boolean} true, when the plugin is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === this.chunkLoading; + }; + compilation.hooks.additionalTreeRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if (chunkGraph.hasChunkEntryDependentChunks(chunk)) { + set.add(RuntimeGlobals.startup); + set.add(RuntimeGlobals.ensureChunk); + set.add(RuntimeGlobals.ensureChunkIncludeEntries); + compilation.addRuntimeModule( + chunk, + new StartupChunkDependenciesRuntimeModule(this.asyncChunkLoading) + ); + } + } + ); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.startupEntrypoint) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.require); + set.add(RuntimeGlobals.ensureChunk); + set.add(RuntimeGlobals.ensureChunkIncludeEntries); + compilation.addRuntimeModule( + chunk, + new StartupEntrypointRuntimeModule(this.asyncChunkLoading) + ); + }); + }); + } +} + +module.exports = StartupChunkDependenciesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/StartupChunkDependenciesRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/StartupChunkDependenciesRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..7ff0397835384164b33e24c2aed359b1455eaa2a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/StartupChunkDependenciesRuntimeModule.js @@ -0,0 +1,76 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ + +class StartupChunkDependenciesRuntimeModule extends RuntimeModule { + /** + * @param {boolean} asyncChunkLoading use async chunk loading + */ + constructor(asyncChunkLoading) { + super("startup chunk dependencies", RuntimeModule.STAGE_TRIGGER); + this.asyncChunkLoading = asyncChunkLoading; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const chunkIds = [ + ...chunkGraph.getChunkEntryDependentChunksIterable(chunk) + ].map((chunk) => chunk.id); + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + return Template.asString([ + `var next = ${RuntimeGlobals.startup};`, + `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction( + "", + !this.asyncChunkLoading + ? [ + ...chunkIds.map( + (id) => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});` + ), + "return next();" + ] + : chunkIds.length === 1 + ? `return ${RuntimeGlobals.ensureChunk}(${JSON.stringify( + chunkIds[0] + )}).then(next);` + : chunkIds.length > 2 + ? [ + // using map is shorter for 3 or more chunks + `return Promise.all(${JSON.stringify(chunkIds)}.map(${ + RuntimeGlobals.ensureChunk + }, ${RuntimeGlobals.require})).then(next);` + ] + : [ + // calling ensureChunk directly is shorter for 0 - 2 chunks + "return Promise.all([", + Template.indent( + chunkIds + .map( + (id) => + `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)})` + ) + .join(",\n") + ), + "]).then(next);" + ] + )};` + ]); + } +} + +module.exports = StartupChunkDependenciesRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/StartupEntrypointRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/StartupEntrypointRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..5133767dab3e67c175d5e682b00bea18fbc01d8a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/StartupEntrypointRuntimeModule.js @@ -0,0 +1,54 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../MainTemplate")} MainTemplate */ + +class StartupEntrypointRuntimeModule extends RuntimeModule { + /** + * @param {boolean} asyncChunkLoading use async chunk loading + */ + constructor(asyncChunkLoading) { + super("startup entrypoint"); + this.asyncChunkLoading = asyncChunkLoading; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { runtimeTemplate } = compilation; + return `${ + RuntimeGlobals.startupEntrypoint + } = ${runtimeTemplate.basicFunction("result, chunkIds, fn", [ + "// arguments: chunkIds, moduleId are deprecated", + "var moduleId = chunkIds;", + `if(!fn) chunkIds = result, fn = ${runtimeTemplate.returningFunction( + `${RuntimeGlobals.require}(${RuntimeGlobals.entryModuleId} = moduleId)` + )};`, + ...(this.asyncChunkLoading + ? [ + `return Promise.all(chunkIds.map(${RuntimeGlobals.ensureChunk}, ${ + RuntimeGlobals.require + })).then(${runtimeTemplate.basicFunction("", [ + "var r = fn();", + "return r === undefined ? result : r;" + ])})` + ] + : [ + `chunkIds.map(${RuntimeGlobals.ensureChunk}, ${RuntimeGlobals.require})`, + "var r = fn();", + "return r === undefined ? result : r;" + ]) + ])}`; + } +} + +module.exports = StartupEntrypointRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/SystemContextRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/SystemContextRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..b7663ffde1c452e23823057d150e88813b6e3c1e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/runtime/SystemContextRuntimeModule.js @@ -0,0 +1,25 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +/** @typedef {import("../Compilation")} Compilation */ + +class SystemContextRuntimeModule extends RuntimeModule { + constructor() { + super("__system_context__"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + return `${RuntimeGlobals.systemContext} = __system_context__;`; + } +} + +module.exports = SystemContextRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/DataUriPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/DataUriPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..0be6c64c593e6ae32312b2ec2676392314ba900b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/DataUriPlugin.js @@ -0,0 +1,73 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const NormalModule = require("../NormalModule"); + +/** @typedef {import("../Compiler")} Compiler */ + +// data URL scheme: "data:text/javascript;charset=utf-8;base64,some-string" +// http://www.ietf.org/rfc/rfc2397.txt +const URIRegEx = /^data:([^;,]+)?((?:;[^;,]+)*?)(?:;(base64)?)?,(.*)$/i; + +/** + * @param {string} uri data URI + * @returns {Buffer | null} decoded data + */ +const decodeDataURI = (uri) => { + const match = URIRegEx.exec(uri); + if (!match) return null; + + const isBase64 = match[3]; + const body = match[4]; + + if (isBase64) { + return Buffer.from(body, "base64"); + } + + // CSS allows to use `data:image/svg+xml;utf8,` + // so we return original body if we can't `decodeURIComponent` + try { + return Buffer.from(decodeURIComponent(body), "ascii"); + } catch (_) { + return Buffer.from(body, "ascii"); + } +}; + +const PLUGIN_NAME = "DataUriPlugin"; + +class DataUriPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.resolveForScheme + .for("data") + .tap(PLUGIN_NAME, (resourceData) => { + const match = URIRegEx.exec(resourceData.resource); + if (match) { + resourceData.data.mimetype = match[1] || ""; + resourceData.data.parameters = match[2] || ""; + resourceData.data.encoding = /** @type {"base64" | false} */ ( + match[3] || false + ); + resourceData.data.encodedContent = match[4] || ""; + } + }); + NormalModule.getCompilationHooks(compilation) + .readResourceForScheme.for("data") + .tap(PLUGIN_NAME, (resource) => decodeDataURI(resource)); + } + ); + } +} + +module.exports = DataUriPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/FileUriPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/FileUriPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..9d64ef807a148ab17bc1546f28826e67c49c2d44 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/FileUriPlugin.js @@ -0,0 +1,51 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { fileURLToPath } = require("url"); +const { NormalModule } = require(".."); + +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "FileUriPlugin"; + +class FileUriPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.resolveForScheme + .for("file") + .tap(PLUGIN_NAME, (resourceData) => { + const url = new URL(resourceData.resource); + const path = fileURLToPath(url); + const query = url.search; + const fragment = url.hash; + resourceData.path = path; + resourceData.query = query; + resourceData.fragment = fragment; + resourceData.resource = path + query + fragment; + return true; + }); + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.readResource + .for(undefined) + .tapAsync(PLUGIN_NAME, (loaderContext, callback) => { + const { resourcePath } = loaderContext; + loaderContext.addDependency(resourcePath); + loaderContext.fs.readFile(resourcePath, callback); + }); + } + ); + } +} + +module.exports = FileUriPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/HttpUriPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/HttpUriPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..85e3834fd5aef55d9ecdd0fff653560ec49ab3a8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/HttpUriPlugin.js @@ -0,0 +1,1302 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const EventEmitter = require("events"); +const { basename, extname } = require("path"); +const { + // eslint-disable-next-line n/no-unsupported-features/node-builtins + createBrotliDecompress, + createGunzip, + createInflate +} = require("zlib"); +const NormalModule = require("../NormalModule"); +const createSchemaValidation = require("../util/create-schema-validation"); +const createHash = require("../util/createHash"); +const { dirname, join, mkdirp } = require("../util/fs"); +const memoize = require("../util/memoize"); + +/** @typedef {import("http").IncomingMessage} IncomingMessage */ +/** @typedef {import("http").OutgoingHttpHeaders} OutgoingHttpHeaders */ +/** @typedef {import("http").RequestOptions} RequestOptions */ +/** @typedef {import("net").Socket} Socket */ +/** @typedef {import("stream").Readable} Readable */ +/** @typedef {import("../../declarations/plugins/schemes/HttpUriPlugin").HttpUriPluginOptions} HttpUriPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../NormalModuleFactory").ResourceDataWithData} ResourceDataWithData */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ + +const getHttp = memoize(() => require("http")); +const getHttps = memoize(() => require("https")); + +/** + * @param {typeof import("http") | typeof import("https")} request request + * @param {string | URL | undefined} proxy proxy + * @returns {(url: URL, requestOptions: RequestOptions, callback: (incomingMessage: IncomingMessage) => void) => EventEmitter} fn + */ +const proxyFetch = (request, proxy) => (url, options, callback) => { + const eventEmitter = new EventEmitter(); + + /** + * @param {Socket=} socket socket + * @returns {void} + */ + const doRequest = (socket) => { + request + .get(url, { ...options, ...(socket && { socket }) }, callback) + .on("error", eventEmitter.emit.bind(eventEmitter, "error")); + }; + + if (proxy) { + const { hostname: host, port } = new URL(proxy); + + getHttp() + .request({ + host, // IP address of proxy server + port, // port of proxy server + method: "CONNECT", + path: url.host + }) + .on("connect", (res, socket) => { + if (res.statusCode === 200) { + // connected to proxy server + doRequest(socket); + } + }) + .on("error", (err) => { + eventEmitter.emit( + "error", + new Error( + `Failed to connect to proxy server "${proxy}": ${err.message}` + ) + ); + }) + .end(); + } else { + doRequest(); + } + + return eventEmitter; +}; + +/** @typedef {() => void} InProgressWriteItem */ +/** @type {InProgressWriteItem[] | undefined} */ +let inProgressWrite; + +const validate = createSchemaValidation( + require("../../schemas/plugins/schemes/HttpUriPlugin.check"), + () => require("../../schemas/plugins/schemes/HttpUriPlugin.json"), + { + name: "Http Uri Plugin", + baseDataPath: "options" + } +); + +/** + * @param {string} str path + * @returns {string} safe path + */ +const toSafePath = (str) => + str + .replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "") + .replace(/[^a-zA-Z0-9._-]+/g, "_"); + +/** + * @param {Buffer} content content + * @returns {string} integrity + */ +const computeIntegrity = (content) => { + const hash = createHash("sha512"); + hash.update(content); + const integrity = `sha512-${hash.digest("base64")}`; + return integrity; +}; + +/** + * @param {Buffer} content content + * @param {string} integrity integrity + * @returns {boolean} true, if integrity matches + */ +const verifyIntegrity = (content, integrity) => { + if (integrity === "ignore") return true; + return computeIntegrity(content) === integrity; +}; + +/** + * @param {string} str input + * @returns {Record} parsed + */ +const parseKeyValuePairs = (str) => { + /** @type {Record} */ + const result = {}; + for (const item of str.split(",")) { + const i = item.indexOf("="); + if (i >= 0) { + const key = item.slice(0, i).trim(); + const value = item.slice(i + 1).trim(); + result[key] = value; + } else { + const key = item.trim(); + if (!key) continue; + result[key] = key; + } + } + return result; +}; + +/** + * @param {string | undefined} cacheControl Cache-Control header + * @param {number} requestTime timestamp of request + * @returns {{ storeCache: boolean, storeLock: boolean, validUntil: number }} Logic for storing in cache and lockfile cache + */ +const parseCacheControl = (cacheControl, requestTime) => { + // When false resource is not stored in cache + let storeCache = true; + // When false resource is not stored in lockfile cache + let storeLock = true; + // Resource is only revalidated, after that timestamp and when upgrade is chosen + let validUntil = 0; + if (cacheControl) { + const parsed = parseKeyValuePairs(cacheControl); + if (parsed["no-cache"]) storeCache = storeLock = false; + if (parsed["max-age"] && !Number.isNaN(Number(parsed["max-age"]))) { + validUntil = requestTime + Number(parsed["max-age"]) * 1000; + } + if (parsed["must-revalidate"]) validUntil = 0; + } + return { + storeLock, + storeCache, + validUntil + }; +}; + +/** + * @typedef {object} LockfileEntry + * @property {string} resolved + * @property {string} integrity + * @property {string} contentType + */ + +/** + * @param {LockfileEntry} a first lockfile entry + * @param {LockfileEntry} b second lockfile entry + * @returns {boolean} true when equal, otherwise false + */ +const areLockfileEntriesEqual = (a, b) => + a.resolved === b.resolved && + a.integrity === b.integrity && + a.contentType === b.contentType; + +/** + * @param {LockfileEntry} entry lockfile entry + * @returns {`resolved: ${string}, integrity: ${string}, contentType: ${string}`} stringified entry + */ +const entryToString = (entry) => + `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`; + +class Lockfile { + constructor() { + this.version = 1; + /** @type {Map} */ + this.entries = new Map(); + } + + /** + * @param {string} content content of the lockfile + * @returns {Lockfile} lockfile + */ + static parse(content) { + // TODO handle merge conflicts + const data = JSON.parse(content); + if (data.version !== 1) { + throw new Error(`Unsupported lockfile version ${data.version}`); + } + const lockfile = new Lockfile(); + for (const key of Object.keys(data)) { + if (key === "version") continue; + const entry = data[key]; + lockfile.entries.set( + key, + typeof entry === "string" + ? entry + : { + resolved: key, + ...entry + } + ); + } + return lockfile; + } + + /** + * @returns {string} stringified lockfile + */ + toString() { + let str = "{\n"; + const entries = [...this.entries].sort(([a], [b]) => (a < b ? -1 : 1)); + for (const [key, entry] of entries) { + if (typeof entry === "string") { + str += ` ${JSON.stringify(key)}: ${JSON.stringify(entry)},\n`; + } else { + str += ` ${JSON.stringify(key)}: { `; + if (entry.resolved !== key) { + str += `"resolved": ${JSON.stringify(entry.resolved)}, `; + } + str += `"integrity": ${JSON.stringify( + entry.integrity + )}, "contentType": ${JSON.stringify(entry.contentType)} },\n`; + } + } + str += ` "version": ${this.version}\n}\n`; + return str; + } +} + +/** + * @template R + * @typedef {(err: Error | null, result?: R) => void} FnWithoutKeyCallback + */ + +/** + * @template R + * @typedef {(callback: FnWithoutKeyCallback) => void} FnWithoutKey + */ + +/** + * @template R + * @param {FnWithoutKey} fn function + * @returns {FnWithoutKey} cached function + */ +const cachedWithoutKey = (fn) => { + let inFlight = false; + /** @type {Error | undefined} */ + let cachedError; + /** @type {R | undefined} */ + let cachedResult; + /** @type {FnWithoutKeyCallback[] | undefined} */ + let cachedCallbacks; + return (callback) => { + if (inFlight) { + if (cachedResult !== undefined) return callback(null, cachedResult); + if (cachedError !== undefined) return callback(cachedError); + if (cachedCallbacks === undefined) cachedCallbacks = [callback]; + else cachedCallbacks.push(callback); + return; + } + inFlight = true; + fn((err, result) => { + if (err) cachedError = err; + else cachedResult = result; + const callbacks = cachedCallbacks; + cachedCallbacks = undefined; + callback(err, result); + if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); + }); + }; +}; + +/** + * @template R + * @typedef {(err: Error | null, result?: R) => void} FnWithKeyCallback + */ + +/** + * @template T + * @template R + * @typedef {(item: T, callback: FnWithKeyCallback) => void} FnWithKey + */ + +/** + * @template T + * @template R + * @param {FnWithKey} fn function + * @param {FnWithKey=} forceFn function for the second try + * @returns {(FnWithKey) & { force: FnWithKey }} cached function + */ +const cachedWithKey = (fn, forceFn = fn) => { + /** + * @template R + * @typedef {{ result?: R, error?: Error, callbacks?: FnWithKeyCallback[], force?: true }} CacheEntry + */ + /** @type {Map>} */ + const cache = new Map(); + /** + * @param {T} arg arg + * @param {FnWithKeyCallback} callback callback + * @returns {void} + */ + const resultFn = (arg, callback) => { + const cacheEntry = cache.get(arg); + if (cacheEntry !== undefined) { + if (cacheEntry.result !== undefined) { + return callback(null, cacheEntry.result); + } + if (cacheEntry.error !== undefined) return callback(cacheEntry.error); + if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; + else cacheEntry.callbacks.push(callback); + return; + } + /** @type {CacheEntry} */ + const newCacheEntry = { + result: undefined, + error: undefined, + callbacks: undefined + }; + cache.set(arg, newCacheEntry); + fn(arg, (err, result) => { + if (err) newCacheEntry.error = err; + else newCacheEntry.result = result; + const callbacks = newCacheEntry.callbacks; + newCacheEntry.callbacks = undefined; + callback(err, result); + if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); + }); + }; + /** + * @param {T} arg arg + * @param {FnWithKeyCallback} callback callback + * @returns {void} + */ + resultFn.force = (arg, callback) => { + const cacheEntry = cache.get(arg); + if (cacheEntry !== undefined && cacheEntry.force) { + if (cacheEntry.result !== undefined) { + return callback(null, cacheEntry.result); + } + if (cacheEntry.error !== undefined) return callback(cacheEntry.error); + if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; + else cacheEntry.callbacks.push(callback); + return; + } + /** @type {CacheEntry} */ + const newCacheEntry = { + result: undefined, + error: undefined, + callbacks: undefined, + force: true + }; + cache.set(arg, newCacheEntry); + forceFn(arg, (err, result) => { + if (err) newCacheEntry.error = err; + else newCacheEntry.result = result; + const callbacks = newCacheEntry.callbacks; + newCacheEntry.callbacks = undefined; + callback(err, result); + if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); + }); + }; + return resultFn; +}; + +/** + * @typedef {object} LockfileCache + * @property {Lockfile} lockfile lockfile + * @property {Snapshot} snapshot snapshot + */ + +/** + * @typedef {object} ResolveContentResult + * @property {LockfileEntry} entry lockfile entry + * @property {Buffer} content content + * @property {boolean} storeLock need store lockfile + */ + +/** @typedef {{ storeCache: boolean, storeLock: boolean, validUntil: number, etag: string | undefined, fresh: boolean }} FetchResultMeta */ +/** @typedef {FetchResultMeta & { location: string }} RedirectFetchResult */ +/** @typedef {FetchResultMeta & { entry: LockfileEntry, content: Buffer }} ContentFetchResult */ +/** @typedef {RedirectFetchResult | ContentFetchResult} FetchResult */ + +const PLUGIN_NAME = "HttpUriPlugin"; + +class HttpUriPlugin { + /** + * @param {HttpUriPluginOptions} options options + */ + constructor(options) { + validate(options); + this._lockfileLocation = options.lockfileLocation; + this._cacheLocation = options.cacheLocation; + this._upgrade = options.upgrade; + this._frozen = options.frozen; + this._allowedUris = options.allowedUris; + this._proxy = options.proxy; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const proxy = + this._proxy || process.env.http_proxy || process.env.HTTP_PROXY; + const schemes = [ + { + scheme: "http", + fetch: proxyFetch(getHttp(), proxy) + }, + { + scheme: "https", + fetch: proxyFetch(getHttps(), proxy) + } + ]; + /** @type {LockfileCache} */ + let lockfileCache; + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + const intermediateFs = + /** @type {IntermediateFileSystem} */ + (compiler.intermediateFileSystem); + const fs = compilation.inputFileSystem; + const cache = compilation.getCache(`webpack.${PLUGIN_NAME}`); + const logger = compilation.getLogger(`webpack.${PLUGIN_NAME}`); + /** @type {string} */ + const lockfileLocation = + this._lockfileLocation || + join( + intermediateFs, + compiler.context, + compiler.name + ? `${toSafePath(compiler.name)}.webpack.lock` + : "webpack.lock" + ); + /** @type {string | false} */ + const cacheLocation = + this._cacheLocation !== undefined + ? this._cacheLocation + : `${lockfileLocation}.data`; + const upgrade = this._upgrade || false; + const frozen = this._frozen || false; + const hashFunction = "sha512"; + const hashDigest = "hex"; + const hashDigestLength = 20; + const allowedUris = this._allowedUris; + + let warnedAboutEol = false; + + /** @type {Map} */ + const cacheKeyCache = new Map(); + /** + * @param {string} url the url + * @returns {string} the key + */ + const getCacheKey = (url) => { + const cachedResult = cacheKeyCache.get(url); + if (cachedResult !== undefined) return cachedResult; + const result = _getCacheKey(url); + cacheKeyCache.set(url, result); + return result; + }; + + /** + * @param {string} url the url + * @returns {string} the key + */ + const _getCacheKey = (url) => { + const parsedUrl = new URL(url); + const folder = toSafePath(parsedUrl.origin); + const name = toSafePath(parsedUrl.pathname); + const query = toSafePath(parsedUrl.search); + let ext = extname(name); + if (ext.length > 20) ext = ""; + const basename = ext ? name.slice(0, -ext.length) : name; + const hash = createHash(hashFunction); + hash.update(url); + const digest = hash.digest(hashDigest).slice(0, hashDigestLength); + return `${folder.slice(-50)}/${`${basename}${ + query ? `_${query}` : "" + }`.slice(0, 150)}_${digest}${ext}`; + }; + + const getLockfile = cachedWithoutKey( + /** + * @param {(err: Error | null, lockfile?: Lockfile) => void} callback callback + * @returns {void} + */ + (callback) => { + const readLockfile = () => { + intermediateFs.readFile(lockfileLocation, (err, buffer) => { + if (err && err.code !== "ENOENT") { + compilation.missingDependencies.add(lockfileLocation); + return callback(err); + } + compilation.fileDependencies.add(lockfileLocation); + compilation.fileSystemInfo.createSnapshot( + compiler.fsStartTime, + buffer ? [lockfileLocation] : [], + [], + buffer ? [] : [lockfileLocation], + { timestamp: true }, + (err, s) => { + if (err) return callback(err); + const lockfile = buffer + ? Lockfile.parse(buffer.toString("utf8")) + : new Lockfile(); + lockfileCache = { + lockfile, + snapshot: /** @type {Snapshot} */ (s) + }; + callback(null, lockfile); + } + ); + }); + }; + if (lockfileCache) { + compilation.fileSystemInfo.checkSnapshotValid( + lockfileCache.snapshot, + (err, valid) => { + if (err) return callback(err); + if (!valid) return readLockfile(); + callback(null, lockfileCache.lockfile); + } + ); + } else { + readLockfile(); + } + } + ); + + /** @typedef {Map} LockfileUpdates */ + + /** @type {LockfileUpdates | undefined} */ + let lockfileUpdates; + + /** + * @param {Lockfile} lockfile lockfile instance + * @param {string} url url to store + * @param {LockfileEntry | "ignore" | "no-cache"} entry lockfile entry + */ + const storeLockEntry = (lockfile, url, entry) => { + const oldEntry = lockfile.entries.get(url); + if (lockfileUpdates === undefined) lockfileUpdates = new Map(); + lockfileUpdates.set(url, entry); + lockfile.entries.set(url, entry); + if (!oldEntry) { + logger.log(`${url} added to lockfile`); + } else if (typeof oldEntry === "string") { + if (typeof entry === "string") { + logger.log(`${url} updated in lockfile: ${oldEntry} -> ${entry}`); + } else { + logger.log( + `${url} updated in lockfile: ${oldEntry} -> ${entry.resolved}` + ); + } + } else if (typeof entry === "string") { + logger.log( + `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry}` + ); + } else if (oldEntry.resolved !== entry.resolved) { + logger.log( + `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry.resolved}` + ); + } else if (oldEntry.integrity !== entry.integrity) { + logger.log(`${url} updated in lockfile: content changed`); + } else if (oldEntry.contentType !== entry.contentType) { + logger.log( + `${url} updated in lockfile: ${oldEntry.contentType} -> ${entry.contentType}` + ); + } else { + logger.log(`${url} updated in lockfile`); + } + }; + + /** + * @param {Lockfile} lockfile lockfile + * @param {string} url url + * @param {ResolveContentResult} result result + * @param {(err: Error | null, result?: ResolveContentResult) => void} callback callback + * @returns {void} + */ + const storeResult = (lockfile, url, result, callback) => { + if (result.storeLock) { + storeLockEntry(lockfile, url, result.entry); + if (!cacheLocation || !result.content) { + return callback(null, result); + } + const key = getCacheKey(result.entry.resolved); + const filePath = join(intermediateFs, cacheLocation, key); + mkdirp(intermediateFs, dirname(intermediateFs, filePath), (err) => { + if (err) return callback(err); + intermediateFs.writeFile(filePath, result.content, (err) => { + if (err) return callback(err); + callback(null, result); + }); + }); + } else { + storeLockEntry(lockfile, url, "no-cache"); + callback(null, result); + } + }; + + for (const { scheme, fetch } of schemes) { + /** + * @param {string} url URL + * @param {string | null} integrity integrity + * @param {(err: Error | null, resolveContentResult?: ResolveContentResult) => void} callback callback + */ + const resolveContent = (url, integrity, callback) => { + /** + * @param {Error | null} err error + * @param {FetchResult=} _result fetch result + * @returns {void} + */ + const handleResult = (err, _result) => { + if (err) return callback(err); + + const result = /** @type {FetchResult} */ (_result); + + if ("location" in result) { + return resolveContent( + result.location, + integrity, + (err, innerResult) => { + if (err) return callback(err); + const { entry, content, storeLock } = + /** @type {ResolveContentResult} */ (innerResult); + callback(null, { + entry, + content, + storeLock: storeLock && result.storeLock + }); + } + ); + } + + if ( + !result.fresh && + integrity && + result.entry.integrity !== integrity && + !verifyIntegrity(result.content, integrity) + ) { + return fetchContent.force(url, handleResult); + } + + return callback(null, { + entry: result.entry, + content: result.content, + storeLock: result.storeLock + }); + }; + + fetchContent(url, handleResult); + }; + + /** + * @param {string} url URL + * @param {FetchResult | RedirectFetchResult | undefined} cachedResult result from cache + * @param {(err: Error | null, fetchResult?: FetchResult) => void} callback callback + * @returns {void} + */ + const fetchContentRaw = (url, cachedResult, callback) => { + const requestTime = Date.now(); + /** @type {OutgoingHttpHeaders} */ + const headers = { + "accept-encoding": "gzip, deflate, br", + "user-agent": "webpack" + }; + + if (cachedResult && cachedResult.etag) { + headers["if-none-match"] = cachedResult.etag; + } + + fetch(new URL(url), { headers }, (res) => { + const etag = res.headers.etag; + const location = res.headers.location; + const cacheControl = res.headers["cache-control"]; + const { storeLock, storeCache, validUntil } = parseCacheControl( + cacheControl, + requestTime + ); + /** + * @param {Partial> & (Pick | Pick)} partialResult result + * @returns {void} + */ + const finishWith = (partialResult) => { + if ("location" in partialResult) { + logger.debug( + `GET ${url} [${res.statusCode}] -> ${partialResult.location}` + ); + } else { + logger.debug( + `GET ${url} [${res.statusCode}] ${Math.ceil( + partialResult.content.length / 1024 + )} kB${!storeLock ? " no-cache" : ""}` + ); + } + const result = { + ...partialResult, + fresh: true, + storeLock, + storeCache, + validUntil, + etag + }; + if (!storeCache) { + logger.log( + `${url} can't be stored in cache, due to Cache-Control header: ${cacheControl}` + ); + return callback(null, result); + } + cache.store( + url, + null, + { + ...result, + fresh: false + }, + (err) => { + if (err) { + logger.warn( + `${url} can't be stored in cache: ${err.message}` + ); + logger.debug(err.stack); + } + callback(null, result); + } + ); + }; + if (res.statusCode === 304) { + const result = /** @type {FetchResult} */ (cachedResult); + if ( + result.validUntil < validUntil || + result.storeLock !== storeLock || + result.storeCache !== storeCache || + result.etag !== etag + ) { + return finishWith(result); + } + logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`); + return callback(null, { ...result, fresh: true }); + } + if ( + location && + res.statusCode && + res.statusCode >= 301 && + res.statusCode <= 308 + ) { + const result = { + location: new URL(location, url).href + }; + if ( + !cachedResult || + !("location" in cachedResult) || + cachedResult.location !== result.location || + cachedResult.validUntil < validUntil || + cachedResult.storeLock !== storeLock || + cachedResult.storeCache !== storeCache || + cachedResult.etag !== etag + ) { + return finishWith(result); + } + logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`); + return callback(null, { + ...result, + fresh: true, + storeLock, + storeCache, + validUntil, + etag + }); + } + const contentType = res.headers["content-type"] || ""; + /** @type {Buffer[]} */ + const bufferArr = []; + + const contentEncoding = res.headers["content-encoding"]; + /** @type {Readable} */ + let stream = res; + if (contentEncoding === "gzip") { + stream = stream.pipe(createGunzip()); + } else if (contentEncoding === "br") { + stream = stream.pipe(createBrotliDecompress()); + } else if (contentEncoding === "deflate") { + stream = stream.pipe(createInflate()); + } + + stream.on("data", (chunk) => { + bufferArr.push(chunk); + }); + + stream.on("end", () => { + if (!res.complete) { + logger.log(`GET ${url} [${res.statusCode}] (terminated)`); + return callback(new Error(`${url} request was terminated`)); + } + + const content = Buffer.concat(bufferArr); + + if (res.statusCode !== 200) { + logger.log(`GET ${url} [${res.statusCode}]`); + return callback( + new Error( + `${url} request status code = ${ + res.statusCode + }\n${content.toString("utf8")}` + ) + ); + } + + const integrity = computeIntegrity(content); + const entry = { resolved: url, integrity, contentType }; + + finishWith({ + entry, + content + }); + }); + }).on("error", (err) => { + logger.log(`GET ${url} (error)`); + err.message += `\nwhile fetching ${url}`; + callback(err); + }); + }; + + const fetchContent = cachedWithKey( + /** + * @param {string} url URL + * @param {(err: Error | null, result?: FetchResult) => void} callback callback + * @returns {void} + */ + (url, callback) => { + cache.get(url, null, (err, cachedResult) => { + if (err) return callback(err); + if (cachedResult) { + const isValid = cachedResult.validUntil >= Date.now(); + if (isValid) return callback(null, cachedResult); + } + fetchContentRaw(url, cachedResult, callback); + }); + }, + (url, callback) => fetchContentRaw(url, undefined, callback) + ); + + /** + * @param {string} uri uri + * @returns {boolean} true when allowed, otherwise false + */ + const isAllowed = (uri) => { + for (const allowed of allowedUris) { + if (typeof allowed === "string") { + if (uri.startsWith(allowed)) return true; + } else if (typeof allowed === "function") { + if (allowed(uri)) return true; + } else if (allowed.test(uri)) { + return true; + } + } + return false; + }; + + /** @typedef {{ entry: LockfileEntry, content: Buffer }} Info */ + + const getInfo = cachedWithKey( + /** + * @param {string} url the url + * @param {(err: Error | null, info?: Info) => void} callback callback + * @returns {void} + */ + // eslint-disable-next-line no-loop-func + (url, callback) => { + if (!isAllowed(url)) { + return callback( + new Error( + `${url} doesn't match the allowedUris policy. These URIs are allowed:\n${allowedUris + .map((uri) => ` - ${uri}`) + .join("\n")}` + ) + ); + } + getLockfile((err, _lockfile) => { + if (err) return callback(err); + const lockfile = /** @type {Lockfile} */ (_lockfile); + const entryOrString = lockfile.entries.get(url); + if (!entryOrString) { + if (frozen) { + return callback( + new Error( + `${url} has no lockfile entry and lockfile is frozen` + ) + ); + } + resolveContent(url, null, (err, result) => { + if (err) return callback(err); + storeResult( + /** @type {Lockfile} */ + (lockfile), + url, + /** @type {ResolveContentResult} */ + (result), + callback + ); + }); + return; + } + if (typeof entryOrString === "string") { + const entryTag = entryOrString; + resolveContent(url, null, (err, _result) => { + if (err) return callback(err); + const result = + /** @type {ResolveContentResult} */ + (_result); + if (!result.storeLock || entryTag === "ignore") { + return callback(null, result); + } + if (frozen) { + return callback( + new Error( + `${url} used to have ${entryTag} lockfile entry and has content now, but lockfile is frozen` + ) + ); + } + if (!upgrade) { + return callback( + new Error( + `${url} used to have ${entryTag} lockfile entry and has content now. +This should be reflected in the lockfile, so this lockfile entry must be upgraded, but upgrading is not enabled. +Remove this line from the lockfile to force upgrading.` + ) + ); + } + storeResult(lockfile, url, result, callback); + }); + return; + } + let entry = entryOrString; + /** + * @param {Buffer=} lockedContent locked content + */ + const doFetch = (lockedContent) => { + resolveContent(url, entry.integrity, (err, _result) => { + if (err) { + if (lockedContent) { + logger.warn( + `Upgrade request to ${url} failed: ${err.message}` + ); + logger.debug(err.stack); + return callback(null, { + entry, + content: lockedContent + }); + } + return callback(err); + } + const result = + /** @type {ResolveContentResult} */ + (_result); + if (!result.storeLock) { + // When the lockfile entry should be no-cache + // we need to update the lockfile + if (frozen) { + return callback( + new Error( + `${url} has a lockfile entry and is no-cache now, but lockfile is frozen\nLockfile: ${entryToString( + entry + )}` + ) + ); + } + storeResult(lockfile, url, result, callback); + return; + } + if (!areLockfileEntriesEqual(result.entry, entry)) { + // When the lockfile entry is outdated + // we need to update the lockfile + if (frozen) { + return callback( + new Error( + `${url} has an outdated lockfile entry, but lockfile is frozen\nLockfile: ${entryToString( + entry + )}\nExpected: ${entryToString(result.entry)}` + ) + ); + } + storeResult(lockfile, url, result, callback); + return; + } + if (!lockedContent && cacheLocation) { + // When the lockfile cache content is missing + // we need to update the lockfile + if (frozen) { + return callback( + new Error( + `${url} is missing content in the lockfile cache, but lockfile is frozen\nLockfile: ${entryToString( + entry + )}` + ) + ); + } + storeResult(lockfile, url, result, callback); + return; + } + return callback(null, result); + }); + }; + if (cacheLocation) { + // When there is a lockfile cache + // we read the content from there + const key = getCacheKey(entry.resolved); + const filePath = join(intermediateFs, cacheLocation, key); + fs.readFile(filePath, (err, result) => { + if (err) { + if (err.code === "ENOENT") return doFetch(); + return callback(err); + } + const content = /** @type {Buffer} */ (result); + /** + * @param {Buffer | undefined} _result result + * @returns {void} + */ + const continueWithCachedContent = (_result) => { + if (!upgrade) { + // When not in upgrade mode, we accept the result from the lockfile cache + return callback(null, { entry, content }); + } + return doFetch(content); + }; + if (!verifyIntegrity(content, entry.integrity)) { + /** @type {Buffer | undefined} */ + let contentWithChangedEol; + let isEolChanged = false; + try { + contentWithChangedEol = Buffer.from( + content.toString("utf8").replace(/\r\n/g, "\n") + ); + isEolChanged = verifyIntegrity( + contentWithChangedEol, + entry.integrity + ); + } catch (_err) { + // ignore + } + if (isEolChanged) { + if (!warnedAboutEol) { + const explainer = `Incorrect end of line sequence was detected in the lockfile cache. +The lockfile cache is protected by integrity checks, so any external modification will lead to a corrupted lockfile cache. +When using git make sure to configure .gitattributes correctly for the lockfile cache: + **/*webpack.lock.data/** -text +This will avoid that the end of line sequence is changed by git on Windows.`; + if (frozen) { + logger.error(explainer); + } else { + logger.warn(explainer); + logger.info( + "Lockfile cache will be automatically fixed now, but when lockfile is frozen this would result in an error." + ); + } + warnedAboutEol = true; + } + if (!frozen) { + // "fix" the end of line sequence of the lockfile content + logger.log( + `${filePath} fixed end of line sequence (\\r\\n instead of \\n).` + ); + intermediateFs.writeFile( + filePath, + /** @type {Buffer} */ + (contentWithChangedEol), + (err) => { + if (err) return callback(err); + continueWithCachedContent( + /** @type {Buffer} */ + (contentWithChangedEol) + ); + } + ); + return; + } + } + if (frozen) { + return callback( + new Error( + `${ + entry.resolved + } integrity mismatch, expected content with integrity ${ + entry.integrity + } but got ${computeIntegrity(content)}. +Lockfile corrupted (${ + isEolChanged + ? "end of line sequence was unexpectedly changed" + : "incorrectly merged? changed by other tools?" + }). +Run build with un-frozen lockfile to automatically fix lockfile.` + ) + ); + } + // "fix" the lockfile entry to the correct integrity + // the content has priority over the integrity value + entry = { + ...entry, + integrity: computeIntegrity(content) + }; + storeLockEntry(lockfile, url, entry); + } + continueWithCachedContent(result); + }); + } else { + doFetch(); + } + }); + } + ); + + /** + * @param {URL} url url + * @param {ResourceDataWithData} resourceData resource data + * @param {(err: Error | null, result: true | void) => void} callback callback + */ + const respondWithUrlModule = (url, resourceData, callback) => { + getInfo(url.href, (err, _result) => { + if (err) return callback(err); + const result = /** @type {Info} */ (_result); + resourceData.resource = url.href; + resourceData.path = url.origin + url.pathname; + resourceData.query = url.search; + resourceData.fragment = url.hash; + resourceData.context = new URL( + ".", + result.entry.resolved + ).href.slice(0, -1); + resourceData.data.mimetype = result.entry.contentType; + callback(null, true); + }); + }; + normalModuleFactory.hooks.resolveForScheme + .for(scheme) + .tapAsync(PLUGIN_NAME, (resourceData, resolveData, callback) => { + respondWithUrlModule( + new URL(resourceData.resource), + resourceData, + callback + ); + }); + normalModuleFactory.hooks.resolveInScheme + .for(scheme) + .tapAsync(PLUGIN_NAME, (resourceData, data, callback) => { + // Only handle relative urls (./xxx, ../xxx, /xxx, //xxx) + if ( + data.dependencyType !== "url" && + !/^\.{0,2}\//.test(resourceData.resource) + ) { + return callback(); + } + respondWithUrlModule( + new URL(resourceData.resource, `${data.context}/`), + resourceData, + callback + ); + }); + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.readResourceForScheme + .for(scheme) + .tapAsync(PLUGIN_NAME, (resource, module, callback) => + getInfo(resource, (err, _result) => { + if (err) return callback(err); + const result = /** @type {Info} */ (_result); + /** @type {BuildInfo} */ + (module.buildInfo).resourceIntegrity = result.entry.integrity; + callback(null, result.content); + }) + ); + hooks.needBuild.tapAsync(PLUGIN_NAME, (module, context, callback) => { + if (module.resource && module.resource.startsWith(`${scheme}://`)) { + getInfo(module.resource, (err, _result) => { + if (err) return callback(err); + const result = /** @type {Info} */ (_result); + if ( + result.entry.integrity !== + /** @type {BuildInfo} */ + (module.buildInfo).resourceIntegrity + ) { + return callback(null, true); + } + callback(); + }); + } else { + return callback(); + } + }); + } + compilation.hooks.finishModules.tapAsync( + PLUGIN_NAME, + (modules, callback) => { + if (!lockfileUpdates) return callback(); + const ext = extname(lockfileLocation); + const tempFile = join( + intermediateFs, + dirname(intermediateFs, lockfileLocation), + `.${basename(lockfileLocation, ext)}.${ + (Math.random() * 10000) | 0 + }${ext}` + ); + + const writeDone = () => { + const nextOperation = + /** @type {InProgressWriteItem[]} */ + (inProgressWrite).shift(); + if (nextOperation) { + nextOperation(); + } else { + inProgressWrite = undefined; + } + }; + const runWrite = () => { + intermediateFs.readFile(lockfileLocation, (err, buffer) => { + if (err && err.code !== "ENOENT") { + writeDone(); + return callback(err); + } + const lockfile = buffer + ? Lockfile.parse(buffer.toString("utf8")) + : new Lockfile(); + for (const [key, value] of /** @type {LockfileUpdates} */ ( + lockfileUpdates + )) { + lockfile.entries.set(key, value); + } + intermediateFs.writeFile( + tempFile, + lockfile.toString(), + (err) => { + if (err) { + writeDone(); + return ( + /** @type {NonNullable} */ + (intermediateFs.unlink)(tempFile, () => callback(err)) + ); + } + intermediateFs.rename(tempFile, lockfileLocation, (err) => { + if (err) { + writeDone(); + return ( + /** @type {NonNullable} */ + (intermediateFs.unlink)(tempFile, () => callback(err)) + ); + } + writeDone(); + callback(); + }); + } + ); + }); + }; + if (inProgressWrite) { + inProgressWrite.push(runWrite); + } else { + inProgressWrite = []; + runWrite(); + } + } + ); + } + ); + } +} + +module.exports = HttpUriPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/VirtualUrlPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/VirtualUrlPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7f405c80b5e889c898c859eb263ad195a7acd235 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/schemes/VirtualUrlPlugin.js @@ -0,0 +1,222 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx +*/ + +"use strict"; + +const { NormalModule } = require(".."); +const ModuleNotFoundError = require("../ModuleNotFoundError"); +const { parseResourceWithoutFragment } = require("../util/identifier"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").ValueCacheVersions} ValueCacheVersions */ +/** @typedef {string | Set} ValueCacheVersion */ + +/** + * @template T + * @typedef {import("../../declarations/LoaderContext").LoaderContext} LoaderContext + */ + +const PLUGIN_NAME = "VirtualUrlPlugin"; +const DEFAULT_SCHEME = "virtual"; + +/** + * @typedef {object} VirtualModuleConfig + * @property {string=} type - The module type + * @property {(loaderContext: LoaderContext) => Promise | string} source - The source function + * @property {(() => string) | true | string=} version - Optional version function or value + */ + +/** + * @typedef {string | ((loaderContext: LoaderContext) => Promise | string) | VirtualModuleConfig} VirtualModuleInput + */ + +/** @typedef {{[key: string]: VirtualModuleInput}} VirtualModules */ + +/** + * Normalizes a virtual module definition into a standard format + * @param {VirtualModuleInput} virtualConfig The virtual module to normalize + * @returns {VirtualModuleConfig} The normalized virtual module + */ +function normalizeModule(virtualConfig) { + if (typeof virtualConfig === "string") { + return { + type: "", + source() { + return virtualConfig; + } + }; + } else if (typeof virtualConfig === "function") { + return { + type: "", + source: virtualConfig + }; + } + return virtualConfig; +} + +/** + * Normalizes all virtual modules with the given scheme + * @param {VirtualModules} virtualConfigs The virtual modules to normalize + * @param {string} scheme The URL scheme to use + * @returns {{[key: string]: VirtualModuleConfig}} The normalized virtual modules + */ +function normalizeModules(virtualConfigs, scheme) { + return Object.keys(virtualConfigs).reduce((pre, id) => { + pre[toVid(id, scheme)] = normalizeModule(virtualConfigs[id]); + return pre; + }, /** @type {{[key: string]: VirtualModuleConfig}} */ ({})); +} + +/** + * Converts a module id and scheme to a virtual module id + * @param {string} id The module id + * @param {string} scheme The URL scheme + * @returns {string} The virtual module id + */ +function toVid(id, scheme) { + return `${scheme}:${id}`; +} + +const VALUE_DEP_VERSION = `webpack/${PLUGIN_NAME}/version`; + +/** + * Converts a module id and scheme to a cache key + * @param {string} id The module id + * @param {string} scheme The URL scheme + * @returns {string} The cache key + */ +function toCacheKey(id, scheme) { + return `${VALUE_DEP_VERSION}/${toVid(id, scheme)}`; +} + +/** + * @typedef {object} VirtualUrlPluginOptions + * @property {VirtualModules} modules - The virtual modules + * @property {string=} scheme - The URL scheme to use + */ + +class VirtualUrlPlugin { + /** + * @param {VirtualModules} modules The virtual modules + * @param {string=} scheme The URL scheme to use + */ + constructor(modules, scheme) { + this.scheme = scheme || DEFAULT_SCHEME; + this.modules = normalizeModules(modules, this.scheme); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const scheme = this.scheme; + const cachedParseResourceWithoutFragment = + parseResourceWithoutFragment.bindCache(compiler.root); + + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.resolveForScheme + .for(scheme) + .tap(PLUGIN_NAME, (resourceData) => { + const virtualConfig = this.findVirtualModuleConfigById( + resourceData.resource + ); + const url = cachedParseResourceWithoutFragment( + resourceData.resource + ); + const path = url.path; + const type = virtualConfig.type; + resourceData.path = path + type; + resourceData.resource = path; + + if (virtualConfig.version) { + const cacheKey = toCacheKey(resourceData.resource, scheme); + const cacheVersion = this.getCacheVersion(virtualConfig.version); + compilation.valueCacheVersions.set( + cacheKey, + /** @type {string} */ (cacheVersion) + ); + } + + return true; + }); + + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.readResource + .for(scheme) + .tapAsync(PLUGIN_NAME, async (loaderContext, callback) => { + const { resourcePath } = loaderContext; + const module = /** @type {NormalModule} */ (loaderContext._module); + const cacheKey = toCacheKey(resourcePath, scheme); + + const addVersionValueDependency = () => { + if (!module || !module.buildInfo) return; + + const buildInfo = module.buildInfo; + if (!buildInfo.valueDependencies) { + buildInfo.valueDependencies = new Map(); + } + + const cacheVersion = compilation.valueCacheVersions.get(cacheKey); + if (compilation.valueCacheVersions.has(cacheKey)) { + buildInfo.valueDependencies.set( + cacheKey, + /** @type {string} */ (cacheVersion) + ); + } + }; + + try { + const virtualConfig = + this.findVirtualModuleConfigById(resourcePath); + const content = await virtualConfig.source(loaderContext); + addVersionValueDependency(); + callback(null, content); + } catch (err) { + callback(/** @type {Error} */ (err)); + } + }); + } + ); + } + + /** + * @param {string} id The module id + * @returns {VirtualModuleConfig} The virtual module config + */ + findVirtualModuleConfigById(id) { + const config = this.modules[id]; + if (!config) { + throw new ModuleNotFoundError( + null, + new Error(`Can't resolve virtual module ${id}`), + { + name: `virtual module ${id}` + } + ); + } + return config; + } + + /** + * Get the cache version for a given version value + * @param {(() => string) | true | string} version The version value or function + * @returns {string | undefined} The cache version + */ + getCacheVersion(version) { + return version === true + ? undefined + : (typeof version === "function" ? version() : version) || "unset"; + } +} + +VirtualUrlPlugin.DEFAULT_SCHEME = DEFAULT_SCHEME; + +module.exports = VirtualUrlPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/AggregateErrorSerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/AggregateErrorSerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..82ec4314bc43f5f6be9509be2bb662c5fdb732db --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/AggregateErrorSerializer.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** @typedef {Error & { cause: unknown, errors: EXPECTED_ANY[] }} AggregateError */ + +class AggregateErrorSerializer { + /** + * @param {AggregateError} obj error + * @param {ObjectSerializerContext} context context + */ + serialize(obj, context) { + context.write(obj.errors); + context.write(obj.message); + context.write(obj.stack); + context.write(obj.cause); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {AggregateError} error + */ + deserialize(context) { + const errors = context.read(); + // @ts-expect-error ES2018 doesn't `AggregateError`, but it can be used by developers + // eslint-disable-next-line n/no-unsupported-features/es-builtins, n/no-unsupported-features/es-syntax, unicorn/error-message + const err = new AggregateError(errors); + + err.message = context.read(); + err.stack = context.read(); + err.cause = context.read(); + + return err; + } +} + +module.exports = AggregateErrorSerializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/ArraySerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/ArraySerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..021c82ca5d4941ae584cd6afb00497f404a56d05 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/ArraySerializer.js @@ -0,0 +1,38 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class ArraySerializer { + /** + * @template T + * @param {T[]} array array + * @param {ObjectSerializerContext} context context + */ + serialize(array, context) { + context.write(array.length); + for (const item of array) context.write(item); + } + + /** + * @template T + * @param {ObjectDeserializerContext} context context + * @returns {T[]} array + */ + deserialize(context) { + /** @type {number} */ + const length = context.read(); + /** @type {T[]} */ + const array = []; + for (let i = 0; i < length; i++) { + array.push(context.read()); + } + return array; + } +} + +module.exports = ArraySerializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/BinaryMiddleware.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/BinaryMiddleware.js new file mode 100644 index 0000000000000000000000000000000000000000..d6eb71ac49256b576644a9dfcf4a8c4c309f3038 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/BinaryMiddleware.js @@ -0,0 +1,1160 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const memoize = require("../util/memoize"); +const SerializerMiddleware = require("./SerializerMiddleware"); + +/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ +/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ + +/* +Format: + +File -> Section* + +Section -> NullsSection | + BooleansSection | + F64NumbersSection | + I32NumbersSection | + I8NumbersSection | + ShortStringSection | + BigIntSection | + I32BigIntSection | + I8BigIntSection + StringSection | + BufferSection | + NopSection + + + +NullsSection -> + NullHeaderByte | Null2HeaderByte | Null3HeaderByte | + Nulls8HeaderByte 0xnn (n:count - 4) | + Nulls32HeaderByte n:ui32 (n:count - 260) | +BooleansSection -> TrueHeaderByte | FalseHeaderByte | BooleansSectionHeaderByte BooleansCountAndBitsByte +F64NumbersSection -> F64NumbersSectionHeaderByte f64* +I32NumbersSection -> I32NumbersSectionHeaderByte i32* +I8NumbersSection -> I8NumbersSectionHeaderByte i8* +ShortStringSection -> ShortStringSectionHeaderByte ascii-byte* +StringSection -> StringSectionHeaderByte i32:length utf8-byte* +BufferSection -> BufferSectionHeaderByte i32:length byte* +NopSection --> NopSectionHeaderByte +BigIntSection -> BigIntSectionHeaderByte i32:length ascii-byte* +I32BigIntSection -> I32BigIntSectionHeaderByte i32 +I8BigIntSection -> I8BigIntSectionHeaderByte i8 + +ShortStringSectionHeaderByte -> 0b1nnn_nnnn (n:length) + +F64NumbersSectionHeaderByte -> 0b001n_nnnn (n:count - 1) +I32NumbersSectionHeaderByte -> 0b010n_nnnn (n:count - 1) +I8NumbersSectionHeaderByte -> 0b011n_nnnn (n:count - 1) + +NullsSectionHeaderByte -> 0b0001_nnnn (n:count - 1) +BooleansCountAndBitsByte -> + 0b0000_1xxx (count = 3) | + 0b0001_xxxx (count = 4) | + 0b001x_xxxx (count = 5) | + 0b01xx_xxxx (count = 6) | + 0b1nnn_nnnn (n:count - 7, 7 <= count <= 133) + 0xff n:ui32 (n:count, 134 <= count < 2^32) + +StringSectionHeaderByte -> 0b0000_1110 +BufferSectionHeaderByte -> 0b0000_1111 +NopSectionHeaderByte -> 0b0000_1011 +BigIntSectionHeaderByte -> 0b0001_1010 +I32BigIntSectionHeaderByte -> 0b0001_1100 +I8BigIntSectionHeaderByte -> 0b0001_1011 +FalseHeaderByte -> 0b0000_1100 +TrueHeaderByte -> 0b0000_1101 + +RawNumber -> n (n <= 10) + +*/ + +const LAZY_HEADER = 0x0b; +const TRUE_HEADER = 0x0c; +const FALSE_HEADER = 0x0d; +const BOOLEANS_HEADER = 0x0e; +const NULL_HEADER = 0x10; +const NULL2_HEADER = 0x11; +const NULL3_HEADER = 0x12; +const NULLS8_HEADER = 0x13; +const NULLS32_HEADER = 0x14; +const NULL_AND_I8_HEADER = 0x15; +const NULL_AND_I32_HEADER = 0x16; +const NULL_AND_TRUE_HEADER = 0x17; +const NULL_AND_FALSE_HEADER = 0x18; +const BIGINT_HEADER = 0x1a; +const BIGINT_I8_HEADER = 0x1b; +const BIGINT_I32_HEADER = 0x1c; +const STRING_HEADER = 0x1e; +const BUFFER_HEADER = 0x1f; +const I8_HEADER = 0x60; +const I32_HEADER = 0x40; +const F64_HEADER = 0x20; +const SHORT_STRING_HEADER = 0x80; + +/** Uplift high-order bits */ +const NUMBERS_HEADER_MASK = 0xe0; // 0b1010_0000 +const NUMBERS_COUNT_MASK = 0x1f; // 0b0001_1111 +const SHORT_STRING_LENGTH_MASK = 0x7f; // 0b0111_1111 + +const HEADER_SIZE = 1; +const I8_SIZE = 1; +const I32_SIZE = 4; +const F64_SIZE = 8; + +const MEASURE_START_OPERATION = Symbol("MEASURE_START_OPERATION"); +const MEASURE_END_OPERATION = Symbol("MEASURE_END_OPERATION"); + +/** @typedef {typeof MEASURE_START_OPERATION} MEASURE_START_OPERATION_TYPE */ +/** @typedef {typeof MEASURE_END_OPERATION} MEASURE_END_OPERATION_TYPE */ + +/** + * @param {number} n number + * @returns {0 | 1 | 2} type of number for serialization + */ +const identifyNumber = (n) => { + if (n === (n | 0)) { + if (n <= 127 && n >= -128) return 0; + if (n <= 2147483647 && n >= -2147483648) return 1; + } + return 2; +}; + +/** + * @param {bigint} n bigint + * @returns {0 | 1 | 2} type of bigint for serialization + */ +const identifyBigInt = (n) => { + if (n <= BigInt(127) && n >= BigInt(-128)) return 0; + if (n <= BigInt(2147483647) && n >= BigInt(-2147483648)) return 1; + return 2; +}; + +/** @typedef {PrimitiveSerializableType[]} DeserializedType */ +/** @typedef {BufferSerializableType[]} SerializedType} */ +/** @typedef {{ retainedBuffer?: (x: Buffer) => Buffer }} Context} */ + +/** + * @template LazyInputValue + * @template LazyOutputValue + * @typedef {import("./SerializerMiddleware").LazyFunction} LazyFunction + */ + +/** + * @extends {SerializerMiddleware} + */ +class BinaryMiddleware extends SerializerMiddleware { + /** + * @param {DeserializedType} data data + * @param {Context} context context object + * @returns {SerializedType | Promise | null} serialized data + */ + serialize(data, context) { + return this._serialize(data, context); + } + + /** + * @param {LazyFunction} fn lazy function + * @param {Context} context serialize function + * @returns {LazyFunction} new lazy + */ + _serializeLazy(fn, context) { + return SerializerMiddleware.serializeLazy(fn, (data) => + this._serialize(data, context) + ); + } + + /** + * @param {DeserializedType} data data + * @param {Context} context context object + * @param {{ leftOverBuffer: Buffer | null, allocationSize: number, increaseCounter: number }} allocationScope allocation scope + * @returns {SerializedType} serialized data + */ + _serialize( + data, + context, + allocationScope = { + allocationSize: 1024, + increaseCounter: 0, + leftOverBuffer: null + } + ) { + /** @type {Buffer | null} */ + let leftOverBuffer = null; + /** @type {BufferSerializableType[]} */ + let buffers = []; + /** @type {Buffer | null} */ + let currentBuffer = allocationScope ? allocationScope.leftOverBuffer : null; + allocationScope.leftOverBuffer = null; + let currentPosition = 0; + if (currentBuffer === null) { + currentBuffer = Buffer.allocUnsafe(allocationScope.allocationSize); + } + /** + * @param {number} bytesNeeded bytes needed + */ + const allocate = (bytesNeeded) => { + if (currentBuffer !== null) { + if (currentBuffer.length - currentPosition >= bytesNeeded) return; + flush(); + } + if (leftOverBuffer && leftOverBuffer.length >= bytesNeeded) { + currentBuffer = leftOverBuffer; + leftOverBuffer = null; + } else { + currentBuffer = Buffer.allocUnsafe( + Math.max(bytesNeeded, allocationScope.allocationSize) + ); + if ( + !(allocationScope.increaseCounter = + (allocationScope.increaseCounter + 1) % 4) && + allocationScope.allocationSize < 16777216 + ) { + allocationScope.allocationSize <<= 1; + } + } + }; + const flush = () => { + if (currentBuffer !== null) { + if (currentPosition > 0) { + buffers.push( + Buffer.from( + currentBuffer.buffer, + currentBuffer.byteOffset, + currentPosition + ) + ); + } + if ( + !leftOverBuffer || + leftOverBuffer.length < currentBuffer.length - currentPosition + ) { + leftOverBuffer = Buffer.from( + currentBuffer.buffer, + currentBuffer.byteOffset + currentPosition, + currentBuffer.byteLength - currentPosition + ); + } + + currentBuffer = null; + currentPosition = 0; + } + }; + /** + * @param {number} byte byte + */ + const writeU8 = (byte) => { + /** @type {Buffer} */ + (currentBuffer).writeUInt8(byte, currentPosition++); + }; + /** + * @param {number} ui32 ui32 + */ + const writeU32 = (ui32) => { + /** @type {Buffer} */ + (currentBuffer).writeUInt32LE(ui32, currentPosition); + currentPosition += 4; + }; + /** @type {number[]} */ + const measureStack = []; + const measureStart = () => { + measureStack.push(buffers.length, currentPosition); + }; + /** + * @returns {number} size + */ + const measureEnd = () => { + const oldPos = /** @type {number} */ (measureStack.pop()); + const buffersIndex = /** @type {number} */ (measureStack.pop()); + let size = currentPosition - oldPos; + for (let i = buffersIndex; i < buffers.length; i++) { + size += buffers[i].length; + } + return size; + }; + for (let i = 0; i < data.length; i++) { + const thing = data[i]; + switch (typeof thing) { + case "function": { + if (!SerializerMiddleware.isLazy(thing)) { + throw new Error(`Unexpected function ${thing}`); + } + /** @type {SerializedType | LazyFunction | undefined} */ + let serializedData = + SerializerMiddleware.getLazySerializedValue(thing); + if (serializedData === undefined) { + if (SerializerMiddleware.isLazy(thing, this)) { + flush(); + allocationScope.leftOverBuffer = leftOverBuffer; + const result = + /** @type {PrimitiveSerializableType[]} */ + (thing()); + const data = this._serialize(result, context, allocationScope); + leftOverBuffer = allocationScope.leftOverBuffer; + allocationScope.leftOverBuffer = null; + SerializerMiddleware.setLazySerializedValue(thing, data); + serializedData = data; + } else { + serializedData = this._serializeLazy(thing, context); + flush(); + buffers.push(serializedData); + break; + } + } else if (typeof serializedData === "function") { + flush(); + buffers.push(serializedData); + break; + } + /** @type {number[]} */ + const lengths = []; + for (const item of serializedData) { + let last; + if (typeof item === "function") { + lengths.push(0); + } else if (item.length === 0) { + // ignore + } else if ( + lengths.length > 0 && + (last = lengths[lengths.length - 1]) !== 0 + ) { + const remaining = 0xffffffff - last; + if (remaining >= item.length) { + lengths[lengths.length - 1] += item.length; + } else { + lengths.push(item.length - remaining); + lengths[lengths.length - 2] = 0xffffffff; + } + } else { + lengths.push(item.length); + } + } + allocate(5 + lengths.length * 4); + writeU8(LAZY_HEADER); + writeU32(lengths.length); + for (const l of lengths) { + writeU32(l); + } + flush(); + for (const item of serializedData) { + buffers.push(item); + } + break; + } + case "string": { + const len = Buffer.byteLength(thing); + if (len >= 128 || len !== thing.length) { + allocate(len + HEADER_SIZE + I32_SIZE); + writeU8(STRING_HEADER); + writeU32(len); + currentBuffer.write(thing, currentPosition); + currentPosition += len; + } else if (len >= 70) { + allocate(len + HEADER_SIZE); + writeU8(SHORT_STRING_HEADER | len); + + currentBuffer.write(thing, currentPosition, "latin1"); + currentPosition += len; + } else { + allocate(len + HEADER_SIZE); + writeU8(SHORT_STRING_HEADER | len); + + for (let i = 0; i < len; i++) { + currentBuffer[currentPosition++] = thing.charCodeAt(i); + } + } + break; + } + case "bigint": { + const type = identifyBigInt(thing); + if (type === 0 && thing >= 0 && thing <= BigInt(10)) { + // shortcut for very small bigints + allocate(HEADER_SIZE + I8_SIZE); + writeU8(BIGINT_I8_HEADER); + writeU8(Number(thing)); + break; + } + + switch (type) { + case 0: { + let n = 1; + allocate(HEADER_SIZE + I8_SIZE * n); + writeU8(BIGINT_I8_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeInt8( + Number(/** @type {bigint} */ (data[i])), + currentPosition + ); + currentPosition += I8_SIZE; + n--; + i++; + } + i--; + break; + } + case 1: { + let n = 1; + allocate(HEADER_SIZE + I32_SIZE * n); + writeU8(BIGINT_I32_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeInt32LE( + Number(/** @type {bigint} */ (data[i])), + currentPosition + ); + currentPosition += I32_SIZE; + n--; + i++; + } + i--; + break; + } + default: { + const value = thing.toString(); + const len = Buffer.byteLength(value); + allocate(len + HEADER_SIZE + I32_SIZE); + writeU8(BIGINT_HEADER); + writeU32(len); + currentBuffer.write(value, currentPosition); + currentPosition += len; + break; + } + } + break; + } + case "number": { + const type = identifyNumber(thing); + if (type === 0 && thing >= 0 && thing <= 10) { + // shortcut for very small numbers + allocate(I8_SIZE); + writeU8(thing); + break; + } + /** + * amount of numbers to write + * @type {number} + */ + let n = 1; + for (; n < 32 && i + n < data.length; n++) { + const item = data[i + n]; + if (typeof item !== "number") break; + if (identifyNumber(item) !== type) break; + } + switch (type) { + case 0: + allocate(HEADER_SIZE + I8_SIZE * n); + writeU8(I8_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeInt8( + /** @type {number} */ (data[i]), + currentPosition + ); + currentPosition += I8_SIZE; + n--; + i++; + } + break; + case 1: + allocate(HEADER_SIZE + I32_SIZE * n); + writeU8(I32_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeInt32LE( + /** @type {number} */ (data[i]), + currentPosition + ); + currentPosition += I32_SIZE; + n--; + i++; + } + break; + case 2: + allocate(HEADER_SIZE + F64_SIZE * n); + writeU8(F64_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeDoubleLE( + /** @type {number} */ (data[i]), + currentPosition + ); + currentPosition += F64_SIZE; + n--; + i++; + } + break; + } + + i--; + break; + } + case "boolean": { + let lastByte = thing === true ? 1 : 0; + const bytes = []; + let count = 1; + let n; + for (n = 1; n < 0xffffffff && i + n < data.length; n++) { + const item = data[i + n]; + if (typeof item !== "boolean") break; + const pos = count & 0x7; + if (pos === 0) { + bytes.push(lastByte); + lastByte = item === true ? 1 : 0; + } else if (item === true) { + lastByte |= 1 << pos; + } + count++; + } + i += count - 1; + if (count === 1) { + allocate(HEADER_SIZE); + writeU8(lastByte === 1 ? TRUE_HEADER : FALSE_HEADER); + } else if (count === 2) { + allocate(HEADER_SIZE * 2); + writeU8(lastByte & 1 ? TRUE_HEADER : FALSE_HEADER); + writeU8(lastByte & 2 ? TRUE_HEADER : FALSE_HEADER); + } else if (count <= 6) { + allocate(HEADER_SIZE + I8_SIZE); + writeU8(BOOLEANS_HEADER); + writeU8((1 << count) | lastByte); + } else if (count <= 133) { + allocate(HEADER_SIZE + I8_SIZE + I8_SIZE * bytes.length + I8_SIZE); + writeU8(BOOLEANS_HEADER); + writeU8(0x80 | (count - 7)); + for (const byte of bytes) writeU8(byte); + writeU8(lastByte); + } else { + allocate( + HEADER_SIZE + + I8_SIZE + + I32_SIZE + + I8_SIZE * bytes.length + + I8_SIZE + ); + writeU8(BOOLEANS_HEADER); + writeU8(0xff); + writeU32(count); + for (const byte of bytes) writeU8(byte); + writeU8(lastByte); + } + break; + } + case "object": { + if (thing === null) { + let n; + for (n = 1; n < 0x100000104 && i + n < data.length; n++) { + const item = data[i + n]; + if (item !== null) break; + } + i += n - 1; + if (n === 1) { + if (i + 1 < data.length) { + const next = data[i + 1]; + if (next === true) { + allocate(HEADER_SIZE); + writeU8(NULL_AND_TRUE_HEADER); + i++; + } else if (next === false) { + allocate(HEADER_SIZE); + writeU8(NULL_AND_FALSE_HEADER); + i++; + } else if (typeof next === "number") { + const type = identifyNumber(next); + if (type === 0) { + allocate(HEADER_SIZE + I8_SIZE); + writeU8(NULL_AND_I8_HEADER); + currentBuffer.writeInt8(next, currentPosition); + currentPosition += I8_SIZE; + i++; + } else if (type === 1) { + allocate(HEADER_SIZE + I32_SIZE); + writeU8(NULL_AND_I32_HEADER); + currentBuffer.writeInt32LE(next, currentPosition); + currentPosition += I32_SIZE; + i++; + } else { + allocate(HEADER_SIZE); + writeU8(NULL_HEADER); + } + } else { + allocate(HEADER_SIZE); + writeU8(NULL_HEADER); + } + } else { + allocate(HEADER_SIZE); + writeU8(NULL_HEADER); + } + } else if (n === 2) { + allocate(HEADER_SIZE); + writeU8(NULL2_HEADER); + } else if (n === 3) { + allocate(HEADER_SIZE); + writeU8(NULL3_HEADER); + } else if (n < 260) { + allocate(HEADER_SIZE + I8_SIZE); + writeU8(NULLS8_HEADER); + writeU8(n - 4); + } else { + allocate(HEADER_SIZE + I32_SIZE); + writeU8(NULLS32_HEADER); + writeU32(n - 260); + } + } else if (Buffer.isBuffer(thing)) { + if (thing.length < 8192) { + allocate(HEADER_SIZE + I32_SIZE + thing.length); + writeU8(BUFFER_HEADER); + writeU32(thing.length); + thing.copy(currentBuffer, currentPosition); + currentPosition += thing.length; + } else { + allocate(HEADER_SIZE + I32_SIZE); + writeU8(BUFFER_HEADER); + writeU32(thing.length); + flush(); + buffers.push(thing); + } + } + break; + } + case "symbol": { + if (thing === MEASURE_START_OPERATION) { + measureStart(); + } else if (thing === MEASURE_END_OPERATION) { + const size = measureEnd(); + allocate(HEADER_SIZE + I32_SIZE); + writeU8(I32_HEADER); + currentBuffer.writeInt32LE(size, currentPosition); + currentPosition += I32_SIZE; + } + break; + } + default: { + throw new Error( + `Unknown typeof "${typeof thing}" in binary middleware` + ); + } + } + } + flush(); + + allocationScope.leftOverBuffer = leftOverBuffer; + + // avoid leaking memory + currentBuffer = null; + leftOverBuffer = null; + allocationScope = /** @type {EXPECTED_ANY} */ (undefined); + const _buffers = buffers; + buffers = /** @type {EXPECTED_ANY} */ (undefined); + return _buffers; + } + + /** + * @param {SerializedType} data data + * @param {Context} context context object + * @returns {DeserializedType | Promise} deserialized data + */ + deserialize(data, context) { + return this._deserialize(data, context); + } + + /** + * @private + * @param {SerializedType} content content + * @param {Context} context context object + * @returns {LazyFunction} lazy function + */ + _createLazyDeserialized(content, context) { + return SerializerMiddleware.createLazy( + memoize(() => this._deserialize(content, context)), + this, + undefined, + content + ); + } + + /** + * @private + * @param {LazyFunction} fn lazy function + * @param {Context} context context object + * @returns {LazyFunction} new lazy + */ + _deserializeLazy(fn, context) { + return SerializerMiddleware.deserializeLazy(fn, (data) => + this._deserialize(data, context) + ); + } + + /** + * @param {SerializedType} data data + * @param {Context} context context object + * @returns {DeserializedType} deserialized data + */ + _deserialize(data, context) { + let currentDataItem = 0; + /** @type {BufferSerializableType | null} */ + let currentBuffer = data[0]; + let currentIsBuffer = Buffer.isBuffer(currentBuffer); + let currentPosition = 0; + + const retainedBuffer = context.retainedBuffer || ((x) => x); + + const checkOverflow = () => { + if (currentPosition >= /** @type {Buffer} */ (currentBuffer).length) { + currentPosition = 0; + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + } + }; + /** + * @param {number} n n + * @returns {boolean} true when in current buffer, otherwise false + */ + const isInCurrentBuffer = (n) => + currentIsBuffer && + n + currentPosition <= /** @type {Buffer} */ (currentBuffer).length; + const ensureBuffer = () => { + if (!currentIsBuffer) { + throw new Error( + currentBuffer === null + ? "Unexpected end of stream" + : "Unexpected lazy element in stream" + ); + } + }; + /** + * Reads n bytes + * @param {number} n amount of bytes to read + * @returns {Buffer} buffer with bytes + */ + const read = (n) => { + ensureBuffer(); + const rem = + /** @type {Buffer} */ (currentBuffer).length - currentPosition; + if (rem < n) { + const buffers = [read(rem)]; + n -= rem; + ensureBuffer(); + while (/** @type {Buffer} */ (currentBuffer).length < n) { + const b = /** @type {Buffer} */ (currentBuffer); + buffers.push(b); + n -= b.length; + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + ensureBuffer(); + } + buffers.push(read(n)); + return Buffer.concat(buffers); + } + const b = /** @type {Buffer} */ (currentBuffer); + const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); + currentPosition += n; + checkOverflow(); + return res; + }; + /** + * Reads up to n bytes + * @param {number} n amount of bytes to read + * @returns {Buffer} buffer with bytes + */ + const readUpTo = (n) => { + ensureBuffer(); + const rem = + /** @type {Buffer} */ + (currentBuffer).length - currentPosition; + if (rem < n) { + n = rem; + } + const b = /** @type {Buffer} */ (currentBuffer); + const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); + currentPosition += n; + checkOverflow(); + return res; + }; + /** + * @returns {number} U8 + */ + const readU8 = () => { + ensureBuffer(); + /** + * There is no need to check remaining buffer size here + * since {@link checkOverflow} guarantees at least one byte remaining + */ + const byte = + /** @type {Buffer} */ + (currentBuffer).readUInt8(currentPosition); + currentPosition += I8_SIZE; + checkOverflow(); + return byte; + }; + /** + * @returns {number} U32 + */ + const readU32 = () => read(I32_SIZE).readUInt32LE(0); + /** + * @param {number} data data + * @param {number} n n + */ + const readBits = (data, n) => { + let mask = 1; + while (n !== 0) { + result.push((data & mask) !== 0); + mask <<= 1; + n--; + } + }; + const dispatchTable = Array.from({ length: 256 }).map((_, header) => { + switch (header) { + case LAZY_HEADER: + return () => { + const count = readU32(); + const lengths = Array.from({ length: count }).map(() => readU32()); + /** @type {(Buffer | LazyFunction)[]} */ + const content = []; + for (let l of lengths) { + if (l === 0) { + if (typeof currentBuffer !== "function") { + throw new Error("Unexpected non-lazy element in stream"); + } + content.push(currentBuffer); + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + } else { + do { + const buf = readUpTo(l); + l -= buf.length; + content.push(retainedBuffer(buf)); + } while (l > 0); + } + } + result.push(this._createLazyDeserialized(content, context)); + }; + case BUFFER_HEADER: + return () => { + const len = readU32(); + result.push(retainedBuffer(read(len))); + }; + case TRUE_HEADER: + return () => result.push(true); + case FALSE_HEADER: + return () => result.push(false); + case NULL3_HEADER: + return () => result.push(null, null, null); + case NULL2_HEADER: + return () => result.push(null, null); + case NULL_HEADER: + return () => result.push(null); + case NULL_AND_TRUE_HEADER: + return () => result.push(null, true); + case NULL_AND_FALSE_HEADER: + return () => result.push(null, false); + case NULL_AND_I8_HEADER: + return () => { + if (currentIsBuffer) { + result.push( + null, + /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) + ); + currentPosition += I8_SIZE; + checkOverflow(); + } else { + result.push(null, read(I8_SIZE).readInt8(0)); + } + }; + case NULL_AND_I32_HEADER: + return () => { + result.push(null); + if (isInCurrentBuffer(I32_SIZE)) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt32LE( + currentPosition + ) + ); + currentPosition += I32_SIZE; + checkOverflow(); + } else { + result.push(read(I32_SIZE).readInt32LE(0)); + } + }; + case NULLS8_HEADER: + return () => { + const len = readU8() + 4; + for (let i = 0; i < len; i++) { + result.push(null); + } + }; + case NULLS32_HEADER: + return () => { + const len = readU32() + 260; + for (let i = 0; i < len; i++) { + result.push(null); + } + }; + case BOOLEANS_HEADER: + return () => { + const innerHeader = readU8(); + if ((innerHeader & 0xf0) === 0) { + readBits(innerHeader, 3); + } else if ((innerHeader & 0xe0) === 0) { + readBits(innerHeader, 4); + } else if ((innerHeader & 0xc0) === 0) { + readBits(innerHeader, 5); + } else if ((innerHeader & 0x80) === 0) { + readBits(innerHeader, 6); + } else if (innerHeader !== 0xff) { + let count = (innerHeader & 0x7f) + 7; + while (count > 8) { + readBits(readU8(), 8); + count -= 8; + } + readBits(readU8(), count); + } else { + let count = readU32(); + while (count > 8) { + readBits(readU8(), 8); + count -= 8; + } + readBits(readU8(), count); + } + }; + case STRING_HEADER: + return () => { + const len = readU32(); + if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) { + result.push( + /** @type {Buffer} */ + (currentBuffer).toString( + undefined, + currentPosition, + currentPosition + len + ) + ); + currentPosition += len; + checkOverflow(); + } else { + result.push(read(len).toString()); + } + }; + case SHORT_STRING_HEADER: + return () => result.push(""); + case SHORT_STRING_HEADER | 1: + return () => { + if (currentIsBuffer && currentPosition < 0x7ffffffe) { + result.push( + /** @type {Buffer} */ + (currentBuffer).toString( + "latin1", + currentPosition, + currentPosition + 1 + ) + ); + currentPosition++; + checkOverflow(); + } else { + result.push(read(1).toString("latin1")); + } + }; + case I8_HEADER: + return () => { + if (currentIsBuffer) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) + ); + currentPosition++; + checkOverflow(); + } else { + result.push(read(1).readInt8(0)); + } + }; + case BIGINT_I8_HEADER: { + const len = 1; + return () => { + const need = I8_SIZE * len; + + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + const value = + /** @type {Buffer} */ + (currentBuffer).readInt8(currentPosition); + result.push(BigInt(value)); + currentPosition += I8_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + const value = buf.readInt8(i * I8_SIZE); + result.push(BigInt(value)); + } + } + }; + } + case BIGINT_I32_HEADER: { + const len = 1; + return () => { + const need = I32_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + const value = /** @type {Buffer} */ (currentBuffer).readInt32LE( + currentPosition + ); + result.push(BigInt(value)); + currentPosition += I32_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + const value = buf.readInt32LE(i * I32_SIZE); + result.push(BigInt(value)); + } + } + }; + } + case BIGINT_HEADER: { + return () => { + const len = readU32(); + if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) { + const value = + /** @type {Buffer} */ + (currentBuffer).toString( + undefined, + currentPosition, + currentPosition + len + ); + + result.push(BigInt(value)); + currentPosition += len; + checkOverflow(); + } else { + const value = read(len).toString(); + result.push(BigInt(value)); + } + }; + } + default: + if (header <= 10) { + return () => result.push(header); + } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) { + const len = header & SHORT_STRING_LENGTH_MASK; + return () => { + if ( + isInCurrentBuffer(len) && + currentPosition + len < 0x7fffffff + ) { + result.push( + /** @type {Buffer} */ + (currentBuffer).toString( + "latin1", + currentPosition, + currentPosition + len + ) + ); + currentPosition += len; + checkOverflow(); + } else { + result.push(read(len).toString("latin1")); + } + }; + } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) { + const len = (header & NUMBERS_COUNT_MASK) + 1; + return () => { + const need = F64_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + result.push( + /** @type {Buffer} */ (currentBuffer).readDoubleLE( + currentPosition + ) + ); + currentPosition += F64_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + result.push(buf.readDoubleLE(i * F64_SIZE)); + } + } + }; + } else if ((header & NUMBERS_HEADER_MASK) === I32_HEADER) { + const len = (header & NUMBERS_COUNT_MASK) + 1; + return () => { + const need = I32_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt32LE( + currentPosition + ) + ); + currentPosition += I32_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + result.push(buf.readInt32LE(i * I32_SIZE)); + } + } + }; + } else if ((header & NUMBERS_HEADER_MASK) === I8_HEADER) { + const len = (header & NUMBERS_COUNT_MASK) + 1; + return () => { + const need = I8_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt8( + currentPosition + ) + ); + currentPosition += I8_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + result.push(buf.readInt8(i * I8_SIZE)); + } + } + }; + } + return () => { + throw new Error(`Unexpected header byte 0x${header.toString(16)}`); + }; + } + }); + + /** @type {DeserializedType} */ + let result = []; + while (currentBuffer !== null) { + if (typeof currentBuffer === "function") { + result.push(this._deserializeLazy(currentBuffer, context)); + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + } else { + const header = readU8(); + dispatchTable[header](); + } + } + + // avoid leaking memory in context + // eslint-disable-next-line prefer-const + let _result = result; + result = /** @type {EXPECTED_ANY} */ (undefined); + return _result; + } +} + +module.exports = BinaryMiddleware; + +module.exports.MEASURE_END_OPERATION = MEASURE_END_OPERATION; +module.exports.MEASURE_START_OPERATION = MEASURE_START_OPERATION; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/DateObjectSerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/DateObjectSerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..c69ccfe8c7cb127c27f154e856a34d136f87b192 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/DateObjectSerializer.js @@ -0,0 +1,28 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class DateObjectSerializer { + /** + * @param {Date} obj date + * @param {ObjectSerializerContext} context context + */ + serialize(obj, context) { + context.write(obj.getTime()); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {Date} date + */ + deserialize(context) { + return new Date(context.read()); + } +} + +module.exports = DateObjectSerializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/ErrorObjectSerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/ErrorObjectSerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..caf6192974e1a4c48466b94496be86848718fd8b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/ErrorObjectSerializer.js @@ -0,0 +1,49 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** @typedef {Error & { cause?: unknown }} ErrorWithCause */ + +class ErrorObjectSerializer { + /** + * @param {ErrorConstructor | EvalErrorConstructor | RangeErrorConstructor | ReferenceErrorConstructor | SyntaxErrorConstructor | TypeErrorConstructor} Type error type + */ + constructor(Type) { + this.Type = Type; + } + + /** + * @param {Error | EvalError | RangeError | ReferenceError | SyntaxError | TypeError} obj error + * @param {ObjectSerializerContext} context context + */ + serialize(obj, context) { + context.write(obj.message); + context.write(obj.stack); + context.write( + /** @type {ErrorWithCause} */ + (obj).cause + ); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {Error | EvalError | RangeError | ReferenceError | SyntaxError | TypeError} error + */ + deserialize(context) { + const err = new this.Type(); + + err.message = context.read(); + err.stack = context.read(); + /** @type {ErrorWithCause} */ + (err).cause = context.read(); + + return err; + } +} + +module.exports = ErrorObjectSerializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/FileMiddleware.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/FileMiddleware.js new file mode 100644 index 0000000000000000000000000000000000000000..741140e666f4f3300d48c6145b1c44169fe08118 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/FileMiddleware.js @@ -0,0 +1,761 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const { constants } = require("buffer"); +const { pipeline } = require("stream"); +const { + constants: zConstants, + // eslint-disable-next-line n/no-unsupported-features/node-builtins + createBrotliCompress, + // eslint-disable-next-line n/no-unsupported-features/node-builtins + createBrotliDecompress, + createGunzip, + createGzip +} = require("zlib"); +const { DEFAULTS } = require("../config/defaults"); +const createHash = require("../util/createHash"); +const { dirname, join, mkdirp } = require("../util/fs"); +const memoize = require("../util/memoize"); +const SerializerMiddleware = require("./SerializerMiddleware"); + +/** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").IStats} IStats */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ + +/* +Format: + +File -> Header Section* + +Version -> u32 +AmountOfSections -> u32 +SectionSize -> i32 (if less than zero represents lazy value) + +Header -> Version AmountOfSections SectionSize* + +Buffer -> n bytes +Section -> Buffer + +*/ + +// "wpc" + 1 in little-endian +const VERSION = 0x01637077; +const WRITE_LIMIT_TOTAL = 0x7fff0000; +const WRITE_LIMIT_CHUNK = 511 * 1024 * 1024; + +/** + * @param {Buffer[]} buffers buffers + * @param {string | Hash} hashFunction hash function to use + * @returns {string} hash + */ +const hashForName = (buffers, hashFunction) => { + const hash = createHash(hashFunction); + for (const buf of buffers) hash.update(buf); + return /** @type {string} */ (hash.digest("hex")); +}; + +const COMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; +const DECOMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; + +/** @type {(buffer: Buffer, value: number, offset: number) => void} */ +const writeUInt64LE = Buffer.prototype.writeBigUInt64LE + ? (buf, value, offset) => { + buf.writeBigUInt64LE(BigInt(value), offset); + } + : (buf, value, offset) => { + const low = value % 0x100000000; + const high = (value - low) / 0x100000000; + buf.writeUInt32LE(low, offset); + buf.writeUInt32LE(high, offset + 4); + }; + +/** @type {(buffer: Buffer, offset: number) => void} */ +const readUInt64LE = Buffer.prototype.readBigUInt64LE + ? (buf, offset) => Number(buf.readBigUInt64LE(offset)) + : (buf, offset) => { + const low = buf.readUInt32LE(offset); + const high = buf.readUInt32LE(offset + 4); + return high * 0x100000000 + low; + }; + +/** @typedef {Promise} BackgroundJob */ + +/** + * @typedef {object} SerializeResult + * @property {string | false} name + * @property {number} size + * @property {BackgroundJob=} backgroundJob + */ + +/** @typedef {{ name: string, size: number }} LazyOptions */ +/** + * @typedef {import("./SerializerMiddleware").LazyFunction} LazyFunction + */ + +/** + * @param {FileMiddleware} middleware this + * @param {(BufferSerializableType | LazyFunction)[]} data data to be serialized + * @param {string | boolean} name file base name + * @param {(name: string | false, buffers: Buffer[], size: number) => Promise} writeFile writes a file + * @param {string | Hash} hashFunction hash function to use + * @returns {Promise} resulting file pointer and promise + */ +const serialize = async ( + middleware, + data, + name, + writeFile, + hashFunction = DEFAULTS.HASH_FUNCTION +) => { + /** @type {(Buffer[] | Buffer | Promise)[]} */ + const processedData = []; + /** @type {WeakMap} */ + const resultToLazy = new WeakMap(); + /** @type {Buffer[] | undefined} */ + let lastBuffers; + for (const item of await data) { + if (typeof item === "function") { + if (!SerializerMiddleware.isLazy(item)) { + throw new Error("Unexpected function"); + } + if (!SerializerMiddleware.isLazy(item, middleware)) { + throw new Error( + "Unexpected lazy value with non-this target (can't pass through lazy values)" + ); + } + lastBuffers = undefined; + const serializedInfo = SerializerMiddleware.getLazySerializedValue(item); + if (serializedInfo) { + if (typeof serializedInfo === "function") { + throw new Error( + "Unexpected lazy value with non-this target (can't pass through lazy values)" + ); + } else { + processedData.push(serializedInfo); + } + } else { + const content = item(); + if (content) { + const options = SerializerMiddleware.getLazyOptions(item); + processedData.push( + serialize( + middleware, + /** @type {BufferSerializableType[]} */ + (content), + (options && options.name) || true, + writeFile, + hashFunction + ).then((result) => { + /** @type {LazyOptions} */ + (item.options).size = result.size; + resultToLazy.set(result, item); + return result; + }) + ); + } else { + throw new Error( + "Unexpected falsy value returned by lazy value function" + ); + } + } + } else if (item) { + if (lastBuffers) { + lastBuffers.push(item); + } else { + lastBuffers = [item]; + processedData.push(lastBuffers); + } + } else { + throw new Error("Unexpected falsy value in items array"); + } + } + /** @type {BackgroundJob[]} */ + const backgroundJobs = []; + const resolvedData = (await Promise.all(processedData)).map((item) => { + if (Array.isArray(item) || Buffer.isBuffer(item)) return item; + + backgroundJobs.push( + /** @type {BackgroundJob} */ + (item.backgroundJob) + ); + // create pointer buffer from size and name + const name = /** @type {string} */ (item.name); + const nameBuffer = Buffer.from(name); + const buf = Buffer.allocUnsafe(8 + nameBuffer.length); + writeUInt64LE(buf, item.size, 0); + nameBuffer.copy(buf, 8, 0); + const lazy = + /** @type {LazyFunction} */ + (resultToLazy.get(item)); + SerializerMiddleware.setLazySerializedValue(lazy, buf); + return buf; + }); + /** @type {number[]} */ + const lengths = []; + for (const item of resolvedData) { + if (Array.isArray(item)) { + let l = 0; + for (const b of item) l += b.length; + while (l > 0x7fffffff) { + lengths.push(0x7fffffff); + l -= 0x7fffffff; + } + lengths.push(l); + } else if (item) { + lengths.push(-item.length); + } else { + throw new Error(`Unexpected falsy value in resolved data ${item}`); + } + } + const header = Buffer.allocUnsafe(8 + lengths.length * 4); + header.writeUInt32LE(VERSION, 0); + header.writeUInt32LE(lengths.length, 4); + for (let i = 0; i < lengths.length; i++) { + header.writeInt32LE(lengths[i], 8 + i * 4); + } + /** @type {Buffer[]} */ + const buf = [header]; + for (const item of resolvedData) { + if (Array.isArray(item)) { + for (const b of item) buf.push(b); + } else if (item) { + buf.push(item); + } + } + if (name === true) { + name = hashForName(buf, hashFunction); + } + let size = 0; + for (const b of buf) size += b.length; + backgroundJobs.push(writeFile(name, buf, size)); + return { + size, + name, + backgroundJob: + backgroundJobs.length === 1 + ? backgroundJobs[0] + : /** @type {BackgroundJob} */ (Promise.all(backgroundJobs)) + }; +}; + +/** + * @param {FileMiddleware} middleware this + * @param {string | false} name filename + * @param {(name: string | false) => Promise} readFile read content of a file + * @returns {Promise} deserialized data + */ +const deserialize = async (middleware, name, readFile) => { + const contents = await readFile(name); + if (contents.length === 0) throw new Error(`Empty file ${name}`); + let contentsIndex = 0; + let contentItem = contents[0]; + let contentItemLength = contentItem.length; + let contentPosition = 0; + if (contentItemLength === 0) throw new Error(`Empty file ${name}`); + const nextContent = () => { + contentsIndex++; + contentItem = contents[contentsIndex]; + contentItemLength = contentItem.length; + contentPosition = 0; + }; + /** + * @param {number} n number of bytes to ensure + */ + const ensureData = (n) => { + if (contentPosition === contentItemLength) { + nextContent(); + } + while (contentItemLength - contentPosition < n) { + const remaining = contentItem.slice(contentPosition); + let lengthFromNext = n - remaining.length; + /** @type {Buffer[]} */ + const buffers = [remaining]; + for (let i = contentsIndex + 1; i < contents.length; i++) { + const l = contents[i].length; + if (l > lengthFromNext) { + buffers.push(contents[i].slice(0, lengthFromNext)); + contents[i] = contents[i].slice(lengthFromNext); + lengthFromNext = 0; + break; + } else { + buffers.push(contents[i]); + contentsIndex = i; + lengthFromNext -= l; + } + } + if (lengthFromNext > 0) throw new Error("Unexpected end of data"); + contentItem = Buffer.concat(buffers, n); + contentItemLength = n; + contentPosition = 0; + } + }; + /** + * @returns {number} value value + */ + const readUInt32LE = () => { + ensureData(4); + const value = contentItem.readUInt32LE(contentPosition); + contentPosition += 4; + return value; + }; + /** + * @returns {number} value value + */ + const readInt32LE = () => { + ensureData(4); + const value = contentItem.readInt32LE(contentPosition); + contentPosition += 4; + return value; + }; + /** + * @param {number} l length + * @returns {Buffer} buffer + */ + const readSlice = (l) => { + ensureData(l); + if (contentPosition === 0 && contentItemLength === l) { + const result = contentItem; + if (contentsIndex + 1 < contents.length) { + nextContent(); + } else { + contentPosition = l; + } + return result; + } + const result = contentItem.slice(contentPosition, contentPosition + l); + contentPosition += l; + // we clone the buffer here to allow the original content to be garbage collected + return l * 2 < contentItem.buffer.byteLength ? Buffer.from(result) : result; + }; + const version = readUInt32LE(); + if (version !== VERSION) { + throw new Error("Invalid file version"); + } + const sectionCount = readUInt32LE(); + const lengths = []; + let lastLengthPositive = false; + for (let i = 0; i < sectionCount; i++) { + const value = readInt32LE(); + const valuePositive = value >= 0; + if (lastLengthPositive && valuePositive) { + lengths[lengths.length - 1] += value; + } else { + lengths.push(value); + lastLengthPositive = valuePositive; + } + } + /** @type {BufferSerializableType[]} */ + const result = []; + for (let length of lengths) { + if (length < 0) { + const slice = readSlice(-length); + const size = Number(readUInt64LE(slice, 0)); + const nameBuffer = slice.slice(8); + const name = nameBuffer.toString(); + const lazy = + /** @type {LazyFunction} */ + ( + SerializerMiddleware.createLazy( + memoize(() => deserialize(middleware, name, readFile)), + middleware, + { name, size }, + slice + ) + ); + result.push(lazy); + } else { + if (contentPosition === contentItemLength) { + nextContent(); + } else if (contentPosition !== 0) { + if (length <= contentItemLength - contentPosition) { + result.push( + Buffer.from( + contentItem.buffer, + contentItem.byteOffset + contentPosition, + length + ) + ); + contentPosition += length; + length = 0; + } else { + const l = contentItemLength - contentPosition; + result.push( + Buffer.from( + contentItem.buffer, + contentItem.byteOffset + contentPosition, + l + ) + ); + length -= l; + contentPosition = contentItemLength; + } + } else if (length >= contentItemLength) { + result.push(contentItem); + length -= contentItemLength; + contentPosition = contentItemLength; + } else { + result.push( + Buffer.from(contentItem.buffer, contentItem.byteOffset, length) + ); + contentPosition += length; + length = 0; + } + while (length > 0) { + nextContent(); + if (length >= contentItemLength) { + result.push(contentItem); + length -= contentItemLength; + contentPosition = contentItemLength; + } else { + result.push( + Buffer.from(contentItem.buffer, contentItem.byteOffset, length) + ); + contentPosition += length; + length = 0; + } + } + } + } + return result; +}; + +/** @typedef {BufferSerializableType[]} DeserializedType */ +/** @typedef {true} SerializedType */ +/** @typedef {{ filename: string, extension?: string }} Context */ + +/** + * @extends {SerializerMiddleware} + */ +class FileMiddleware extends SerializerMiddleware { + /** + * @param {IntermediateFileSystem} fs filesystem + * @param {string | Hash} hashFunction hash function to use + */ + constructor(fs, hashFunction = DEFAULTS.HASH_FUNCTION) { + super(); + this.fs = fs; + this._hashFunction = hashFunction; + } + + /** + * @param {DeserializedType} data data + * @param {Context} context context object + * @returns {SerializedType | Promise | null} serialized data + */ + serialize(data, context) { + const { filename, extension = "" } = context; + return new Promise((resolve, reject) => { + mkdirp(this.fs, dirname(this.fs, filename), (err) => { + if (err) return reject(err); + + // It's important that we don't touch existing files during serialization + // because serialize may read existing files (when deserializing) + const allWrittenFiles = new Set(); + /** + * @param {string | false} name name + * @param {Buffer[]} content content + * @param {number} size size + * @returns {Promise} + */ + const writeFile = async (name, content, size) => { + const file = name + ? join(this.fs, filename, `../${name}${extension}`) + : filename; + await new Promise( + /** + * @param {(value?: undefined) => void} resolve resolve + * @param {(reason?: Error | null) => void} reject reject + */ + (resolve, reject) => { + let stream = this.fs.createWriteStream(`${file}_`); + let compression; + if (file.endsWith(".gz")) { + compression = createGzip({ + chunkSize: COMPRESSION_CHUNK_SIZE, + level: zConstants.Z_BEST_SPEED + }); + } else if (file.endsWith(".br")) { + compression = createBrotliCompress({ + chunkSize: COMPRESSION_CHUNK_SIZE, + params: { + [zConstants.BROTLI_PARAM_MODE]: zConstants.BROTLI_MODE_TEXT, + [zConstants.BROTLI_PARAM_QUALITY]: 2, + [zConstants.BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING]: true, + [zConstants.BROTLI_PARAM_SIZE_HINT]: size + } + }); + } + if (compression) { + pipeline(compression, stream, reject); + stream = compression; + stream.on("finish", () => resolve()); + } else { + stream.on("error", (err) => reject(err)); + stream.on("finish", () => resolve()); + } + // split into chunks for WRITE_LIMIT_CHUNK size + /** @type {Buffer[]} */ + const chunks = []; + for (const b of content) { + if (b.length < WRITE_LIMIT_CHUNK) { + chunks.push(b); + } else { + for (let i = 0; i < b.length; i += WRITE_LIMIT_CHUNK) { + chunks.push(b.slice(i, i + WRITE_LIMIT_CHUNK)); + } + } + } + + const len = chunks.length; + let i = 0; + /** + * @param {(Error | null)=} err err + */ + const batchWrite = (err) => { + // will be handled in "on" error handler + if (err) return; + + if (i === len) { + stream.end(); + return; + } + + // queue up a batch of chunks up to the write limit + // end is exclusive + let end = i; + let sum = chunks[end++].length; + while (end < len) { + sum += chunks[end].length; + if (sum > WRITE_LIMIT_TOTAL) break; + end++; + } + while (i < end - 1) { + stream.write(chunks[i++]); + } + stream.write(chunks[i++], batchWrite); + }; + batchWrite(); + } + ); + if (name) allWrittenFiles.add(file); + }; + + resolve( + serialize(this, data, false, writeFile, this._hashFunction).then( + async ({ backgroundJob }) => { + await backgroundJob; + + // Rename the index file to disallow access during inconsistent file state + await new Promise( + /** + * @param {(value?: undefined) => void} resolve resolve + */ + (resolve) => { + this.fs.rename(filename, `${filename}.old`, (_err) => { + resolve(); + }); + } + ); + + // update all written files + await Promise.all( + Array.from( + allWrittenFiles, + (file) => + new Promise( + /** + * @param {(value?: undefined) => void} resolve resolve + * @param {(reason?: Error | null) => void} reject reject + * @returns {void} + */ + (resolve, reject) => { + this.fs.rename(`${file}_`, file, (err) => { + if (err) return reject(err); + resolve(); + }); + } + ) + ) + ); + + // As final step automatically update the index file to have a consistent pack again + await new Promise( + /** + * @param {(value?: undefined) => void} resolve resolve + * @returns {void} + */ + (resolve) => { + this.fs.rename(`${filename}_`, filename, (err) => { + if (err) return reject(err); + resolve(); + }); + } + ); + return /** @type {true} */ (true); + } + ) + ); + }); + }); + } + + /** + * @param {SerializedType} data data + * @param {Context} context context object + * @returns {DeserializedType | Promise} deserialized data + */ + deserialize(data, context) { + const { filename, extension = "" } = context; + /** + * @param {string | boolean} name name + * @returns {Promise} result + */ + const readFile = (name) => + new Promise((resolve, reject) => { + const file = name + ? join(this.fs, filename, `../${name}${extension}`) + : filename; + this.fs.stat(file, (err, stats) => { + if (err) { + reject(err); + return; + } + let remaining = /** @type {IStats} */ (stats).size; + /** @type {Buffer | undefined} */ + let currentBuffer; + /** @type {number | undefined} */ + let currentBufferUsed; + /** @type {Buffer[]} */ + const buf = []; + /** @type {import("zlib").Zlib & import("stream").Transform | undefined} */ + let decompression; + if (file.endsWith(".gz")) { + decompression = createGunzip({ + chunkSize: DECOMPRESSION_CHUNK_SIZE + }); + } else if (file.endsWith(".br")) { + decompression = createBrotliDecompress({ + chunkSize: DECOMPRESSION_CHUNK_SIZE + }); + } + if (decompression) { + /** @typedef {(value: Buffer[] | PromiseLike) => void} NewResolve */ + /** @typedef {(reason?: Error) => void} NewReject */ + + /** @type {NewResolve | undefined} */ + let newResolve; + /** @type {NewReject | undefined} */ + let newReject; + resolve( + Promise.all([ + new Promise((rs, rj) => { + newResolve = rs; + newReject = rj; + }), + new Promise( + /** + * @param {(value?: undefined) => void} resolve resolve + * @param {(reason?: Error) => void} reject reject + */ + (resolve, reject) => { + decompression.on("data", (chunk) => buf.push(chunk)); + decompression.on("end", () => resolve()); + decompression.on("error", (err) => reject(err)); + } + ) + ]).then(() => buf) + ); + resolve = /** @type {NewResolve} */ (newResolve); + reject = /** @type {NewReject} */ (newReject); + } + this.fs.open(file, "r", (err, _fd) => { + if (err) { + reject(err); + return; + } + const fd = /** @type {number} */ (_fd); + const read = () => { + if (currentBuffer === undefined) { + currentBuffer = Buffer.allocUnsafeSlow( + Math.min( + constants.MAX_LENGTH, + remaining, + decompression ? DECOMPRESSION_CHUNK_SIZE : Infinity + ) + ); + currentBufferUsed = 0; + } + let readBuffer = currentBuffer; + let readOffset = /** @type {number} */ (currentBufferUsed); + let readLength = + currentBuffer.length - + /** @type {number} */ (currentBufferUsed); + // values passed to fs.read must be valid int32 values + if (readOffset > 0x7fffffff) { + readBuffer = currentBuffer.slice(readOffset); + readOffset = 0; + } + if (readLength > 0x7fffffff) { + readLength = 0x7fffffff; + } + this.fs.read( + fd, + readBuffer, + readOffset, + readLength, + null, + (err, bytesRead) => { + if (err) { + this.fs.close(fd, () => { + reject(err); + }); + return; + } + /** @type {number} */ + (currentBufferUsed) += bytesRead; + remaining -= bytesRead; + if ( + currentBufferUsed === + /** @type {Buffer} */ + (currentBuffer).length + ) { + if (decompression) { + decompression.write(currentBuffer); + } else { + buf.push( + /** @type {Buffer} */ + (currentBuffer) + ); + } + currentBuffer = undefined; + if (remaining === 0) { + if (decompression) { + decompression.end(); + } + this.fs.close(fd, (err) => { + if (err) { + reject(err); + return; + } + resolve(buf); + }); + return; + } + } + read(); + } + ); + }; + read(); + }); + }); + }); + return deserialize(this, false, readFile); + } +} + +module.exports = FileMiddleware; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/MapObjectSerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/MapObjectSerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..0b1f4182b9658db5dac466a8bd9b215ae3183c20 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/MapObjectSerializer.js @@ -0,0 +1,48 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class MapObjectSerializer { + /** + * @template K, V + * @param {Map} obj map + * @param {ObjectSerializerContext} context context + */ + serialize(obj, context) { + context.write(obj.size); + for (const key of obj.keys()) { + context.write(key); + } + for (const value of obj.values()) { + context.write(value); + } + } + + /** + * @template K, V + * @param {ObjectDeserializerContext} context context + * @returns {Map} map + */ + deserialize(context) { + /** @type {number} */ + const size = context.read(); + /** @type {Map} */ + const map = new Map(); + /** @type {K[]} */ + const keys = []; + for (let i = 0; i < size; i++) { + keys.push(context.read()); + } + for (let i = 0; i < size; i++) { + map.set(keys[i], context.read()); + } + return map; + } +} + +module.exports = MapObjectSerializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/NullPrototypeObjectSerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/NullPrototypeObjectSerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..32adaeaaede0c3f9cda2ed444c43f00c4f20ab55 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/NullPrototypeObjectSerializer.js @@ -0,0 +1,51 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class NullPrototypeObjectSerializer { + /** + * @template {object} T + * @param {T} obj null object + * @param {ObjectSerializerContext} context context + */ + serialize(obj, context) { + /** @type {string[]} */ + const keys = Object.keys(obj); + for (const key of keys) { + context.write(key); + } + context.write(null); + for (const key of keys) { + context.write(obj[/** @type {keyof T} */ (key)]); + } + } + + /** + * @template {object} T + * @param {ObjectDeserializerContext} context context + * @returns {T} null object + */ + deserialize(context) { + /** @type {T} */ + const obj = Object.create(null); + /** @type {string[]} */ + const keys = []; + /** @type {string | null} */ + let key = context.read(); + while (key !== null) { + keys.push(key); + key = context.read(); + } + for (const key of keys) { + obj[/** @type {keyof T} */ (key)] = context.read(); + } + return obj; + } +} + +module.exports = NullPrototypeObjectSerializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/ObjectMiddleware.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/ObjectMiddleware.js new file mode 100644 index 0000000000000000000000000000000000000000..9a414cd2c85a6604cce2c384df8d263024cde55d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/ObjectMiddleware.js @@ -0,0 +1,845 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const { DEFAULTS } = require("../config/defaults"); +const createHash = require("../util/createHash"); +const AggregateErrorSerializer = require("./AggregateErrorSerializer"); +const ArraySerializer = require("./ArraySerializer"); +const DateObjectSerializer = require("./DateObjectSerializer"); +const ErrorObjectSerializer = require("./ErrorObjectSerializer"); +const MapObjectSerializer = require("./MapObjectSerializer"); +const NullPrototypeObjectSerializer = require("./NullPrototypeObjectSerializer"); +const PlainObjectSerializer = require("./PlainObjectSerializer"); +const RegExpObjectSerializer = require("./RegExpObjectSerializer"); +const SerializerMiddleware = require("./SerializerMiddleware"); +const SetObjectSerializer = require("./SetObjectSerializer"); + +/** @typedef {import("../logging/Logger").Logger} Logger */ +/** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("./SerializerMiddleware").LazyOptions} LazyOptions */ +/** @typedef {import("./types").ComplexSerializableType} ComplexSerializableType */ +/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ + +/** @typedef {new (...params: EXPECTED_ANY[]) => EXPECTED_ANY} Constructor */ + +/* + +Format: + +File -> Section* +Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection + +ObjectSection -> ESCAPE ( + number:relativeOffset (number > 0) | + string:request (string|null):export +) Section:value* ESCAPE ESCAPE_END_OBJECT +ReferenceSection -> ESCAPE number:relativeOffset (number < 0) +EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE) +EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE) +OtherSection -> any (except ESCAPE) + +Why using null as escape value? +Multiple null values can merged by the BinaryMiddleware, which makes it very efficient +Technically any value can be used. + +*/ + +/** + * @typedef {object} ObjectSerializerSnapshot + * @property {number} length + * @property {number} cycleStackSize + * @property {number} referenceableSize + * @property {number} currentPos + * @property {number} objectTypeLookupSize + * @property {number} currentPosTypeLookup + */ +/** @typedef {TODO} Value */ +/** @typedef {EXPECTED_OBJECT | string} ReferenceableItem */ + +/** + * @typedef {object} ObjectSerializerContext + * @property {(value: Value) => void} write + * @property {(value: ReferenceableItem) => void} setCircularReference + * @property {() => ObjectSerializerSnapshot} snapshot + * @property {(snapshot: ObjectSerializerSnapshot) => void} rollback + * @property {((item: Value | (() => Value)) => void)=} writeLazy + * @property {((item: (Value | (() => Value)), obj: LazyOptions | undefined) => import("./SerializerMiddleware").LazyFunction)=} writeSeparate + */ + +/** + * @typedef {object} ObjectDeserializerContext + * @property {() => Value} read + * @property {(value: ReferenceableItem) => void} setCircularReference + */ + +/** + * @typedef {object} ObjectSerializer + * @property {(value: Value, context: ObjectSerializerContext) => void} serialize + * @property {(context: ObjectDeserializerContext) => Value} deserialize + */ + +/** + * @template T + * @param {Set} set set + * @param {number} size count of items to keep + */ +const setSetSize = (set, size) => { + let i = 0; + for (const item of set) { + if (i++ >= size) { + set.delete(item); + } + } +}; + +/** + * @template K, X + * @param {Map} map map + * @param {number} size count of items to keep + */ +const setMapSize = (map, size) => { + let i = 0; + for (const item of map.keys()) { + if (i++ >= size) { + map.delete(item); + } + } +}; + +/** + * @param {Buffer} buffer buffer + * @param {string | Hash} hashFunction hash function to use + * @returns {string} hash + */ +const toHash = (buffer, hashFunction) => { + const hash = createHash(hashFunction); + hash.update(buffer); + return /** @type {string} */ (hash.digest("latin1")); +}; + +const ESCAPE = null; +const ESCAPE_ESCAPE_VALUE = null; +const ESCAPE_END_OBJECT = true; +const ESCAPE_UNDEFINED = false; + +const CURRENT_VERSION = 2; + +/** @typedef {{ request?: string, name?: string | number | null, serializer?: ObjectSerializer }} SerializerConfig */ +/** @typedef {{ request?: string, name?: string | number | null, serializer: ObjectSerializer }} SerializerConfigWithSerializer */ + +/** @type {Map} */ +const serializers = new Map(); +/** @type {Map} */ +const serializerInversed = new Map(); + +/** @type {Set} */ +const loadedRequests = new Set(); + +const NOT_SERIALIZABLE = {}; + +const jsTypes = new Map(); + +jsTypes.set(Object, new PlainObjectSerializer()); +jsTypes.set(Array, new ArraySerializer()); +jsTypes.set(null, new NullPrototypeObjectSerializer()); +jsTypes.set(Map, new MapObjectSerializer()); +jsTypes.set(Set, new SetObjectSerializer()); +jsTypes.set(Date, new DateObjectSerializer()); +jsTypes.set(RegExp, new RegExpObjectSerializer()); +jsTypes.set(Error, new ErrorObjectSerializer(Error)); +jsTypes.set(EvalError, new ErrorObjectSerializer(EvalError)); +jsTypes.set(RangeError, new ErrorObjectSerializer(RangeError)); +jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError)); +jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError)); +jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError)); + +// @ts-expect-error ES2018 doesn't `AggregateError`, but it can be used by developers +// eslint-disable-next-line n/no-unsupported-features/es-builtins, n/no-unsupported-features/es-syntax +if (typeof AggregateError !== "undefined") { + jsTypes.set( + // @ts-expect-error ES2018 doesn't `AggregateError`, but it can be used by developers + // eslint-disable-next-line n/no-unsupported-features/es-builtins, n/no-unsupported-features/es-syntax + AggregateError, + new AggregateErrorSerializer() + ); +} + +// If in a sandboxed environment (e.g. jest), this escapes the sandbox and registers +// real Object and Array types to. These types may occur in the wild too, e.g. when +// using Structured Clone in postMessage. +// eslint-disable-next-line n/exports-style +if (exports.constructor !== Object) { + // eslint-disable-next-line n/exports-style + const Obj = /** @type {ObjectConstructor} */ (exports.constructor); + const Fn = /** @type {FunctionConstructor} */ (Obj.constructor); + for (const [type, config] of jsTypes) { + if (type) { + const Type = new Fn(`return ${type.name};`)(); + jsTypes.set(Type, config); + } + } +} + +{ + let i = 1; + for (const [type, serializer] of jsTypes) { + serializers.set(type, { + request: "", + name: i++, + serializer + }); + } +} + +for (const { request, name, serializer } of serializers.values()) { + serializerInversed.set( + `${request}/${name}`, + /** @type {ObjectSerializer} */ (serializer) + ); +} + +/** @type {Map boolean>} */ +const loaders = new Map(); + +/** @typedef {ComplexSerializableType[]} DeserializedType */ +/** @typedef {PrimitiveSerializableType[]} SerializedType */ +/** @typedef {{ logger: Logger }} Context */ + +/** + * @extends {SerializerMiddleware} + */ +class ObjectMiddleware extends SerializerMiddleware { + /** + * @param {(context: ObjectSerializerContext | ObjectDeserializerContext) => void} extendContext context extensions + * @param {string | Hash} hashFunction hash function to use + */ + constructor(extendContext, hashFunction = DEFAULTS.HASH_FUNCTION) { + super(); + this.extendContext = extendContext; + this._hashFunction = hashFunction; + } + + /** + * @param {RegExp} regExp RegExp for which the request is tested + * @param {(request: string) => boolean} loader loader to load the request, returns true when successful + * @returns {void} + */ + static registerLoader(regExp, loader) { + loaders.set(regExp, loader); + } + + /** + * @param {Constructor} Constructor the constructor + * @param {string} request the request which will be required when deserializing + * @param {string | null} name the name to make multiple serializer unique when sharing a request + * @param {ObjectSerializer} serializer the serializer + * @returns {void} + */ + static register(Constructor, request, name, serializer) { + const key = `${request}/${name}`; + + if (serializers.has(Constructor)) { + throw new Error( + `ObjectMiddleware.register: serializer for ${Constructor.name} is already registered` + ); + } + + if (serializerInversed.has(key)) { + throw new Error( + `ObjectMiddleware.register: serializer for ${key} is already registered` + ); + } + + serializers.set(Constructor, { + request, + name, + serializer + }); + + serializerInversed.set(key, serializer); + } + + /** + * @param {Constructor} Constructor the constructor + * @returns {void} + */ + static registerNotSerializable(Constructor) { + if (serializers.has(Constructor)) { + throw new Error( + `ObjectMiddleware.registerNotSerializable: serializer for ${Constructor.name} is already registered` + ); + } + + serializers.set(Constructor, NOT_SERIALIZABLE); + } + + /** + * @param {Constructor} object for serialization + * @returns {SerializerConfigWithSerializer} Serializer config + */ + static getSerializerFor(object) { + const proto = Object.getPrototypeOf(object); + let c; + if (proto === null) { + // Object created with Object.create(null) + c = null; + } else { + c = proto.constructor; + if (!c) { + throw new Error( + "Serialization of objects with prototype without valid constructor property not possible" + ); + } + } + const config = serializers.get(c); + + if (!config) throw new Error(`No serializer registered for ${c.name}`); + if (config === NOT_SERIALIZABLE) throw NOT_SERIALIZABLE; + + return /** @type {SerializerConfigWithSerializer} */ (config); + } + + /** + * @param {string} request request + * @param {string} name name + * @returns {ObjectSerializer} serializer + */ + static getDeserializerFor(request, name) { + const key = `${request}/${name}`; + const serializer = serializerInversed.get(key); + + if (serializer === undefined) { + throw new Error(`No deserializer registered for ${key}`); + } + + return serializer; + } + + /** + * @param {string} request request + * @param {string} name name + * @returns {ObjectSerializer | undefined} serializer + */ + static _getDeserializerForWithoutError(request, name) { + const key = `${request}/${name}`; + const serializer = serializerInversed.get(key); + return serializer; + } + + /** + * @param {DeserializedType} data data + * @param {Context} context context object + * @returns {SerializedType | Promise | null} serialized data + */ + serialize(data, context) { + /** @type {Value[]} */ + let result = [CURRENT_VERSION]; + let currentPos = 0; + /** @type {Map} */ + let referenceable = new Map(); + /** + * @param {ReferenceableItem} item referenceable item + */ + const addReferenceable = (item) => { + referenceable.set(item, currentPos++); + }; + let bufferDedupeMap = new Map(); + /** + * @param {Buffer} buf buffer + * @returns {Buffer} deduped buffer + */ + const dedupeBuffer = (buf) => { + const len = buf.length; + const entry = bufferDedupeMap.get(len); + if (entry === undefined) { + bufferDedupeMap.set(len, buf); + return buf; + } + if (Buffer.isBuffer(entry)) { + if (len < 32) { + if (buf.equals(entry)) { + return entry; + } + bufferDedupeMap.set(len, [entry, buf]); + return buf; + } + const hash = toHash(entry, this._hashFunction); + const newMap = new Map(); + newMap.set(hash, entry); + bufferDedupeMap.set(len, newMap); + const hashBuf = toHash(buf, this._hashFunction); + if (hash === hashBuf) { + return entry; + } + return buf; + } else if (Array.isArray(entry)) { + if (entry.length < 16) { + for (const item of entry) { + if (buf.equals(item)) { + return item; + } + } + entry.push(buf); + return buf; + } + const newMap = new Map(); + const hash = toHash(buf, this._hashFunction); + let found; + for (const item of entry) { + const itemHash = toHash(item, this._hashFunction); + newMap.set(itemHash, item); + if (found === undefined && itemHash === hash) found = item; + } + bufferDedupeMap.set(len, newMap); + if (found === undefined) { + newMap.set(hash, buf); + return buf; + } + return found; + } + const hash = toHash(buf, this._hashFunction); + const item = entry.get(hash); + if (item !== undefined) { + return item; + } + entry.set(hash, buf); + return buf; + }; + let currentPosTypeLookup = 0; + let objectTypeLookup = new Map(); + const cycleStack = new Set(); + /** + * @param {Value} item item to stack + * @returns {string} stack + */ + const stackToString = (item) => { + const arr = [...cycleStack]; + arr.push(item); + return arr + .map((item) => { + if (typeof item === "string") { + if (item.length > 100) { + return `String ${JSON.stringify(item.slice(0, 100)).slice( + 0, + -1 + )}..."`; + } + return `String ${JSON.stringify(item)}`; + } + try { + const { request, name } = ObjectMiddleware.getSerializerFor(item); + if (request) { + return `${request}${name ? `.${name}` : ""}`; + } + } catch (_err) { + // ignore -> fallback + } + if (typeof item === "object" && item !== null) { + if (item.constructor) { + if (item.constructor === Object) { + return `Object { ${Object.keys(item).join(", ")} }`; + } + if (item.constructor === Map) return `Map { ${item.size} items }`; + if (item.constructor === Array) { + return `Array { ${item.length} items }`; + } + if (item.constructor === Set) return `Set { ${item.size} items }`; + if (item.constructor === RegExp) return item.toString(); + return `${item.constructor.name}`; + } + return `Object [null prototype] { ${Object.keys(item).join( + ", " + )} }`; + } + if (typeof item === "bigint") { + return `BigInt ${item}n`; + } + try { + return `${item}`; + } catch (err) { + return `(${/** @type {Error} */ (err).message})`; + } + }) + .join(" -> "); + }; + /** @type {WeakSet} */ + let hasDebugInfoAttached; + /** @type {ObjectSerializerContext} */ + let ctx = { + write(value) { + try { + process(value); + } catch (err) { + if (err !== NOT_SERIALIZABLE) { + if (hasDebugInfoAttached === undefined) { + hasDebugInfoAttached = new WeakSet(); + } + if (!hasDebugInfoAttached.has(/** @type {Error} */ (err))) { + /** @type {Error} */ + (err).message += `\nwhile serializing ${stackToString(value)}`; + hasDebugInfoAttached.add(/** @type {Error} */ (err)); + } + } + throw err; + } + }, + setCircularReference(ref) { + addReferenceable(ref); + }, + snapshot() { + return { + length: result.length, + cycleStackSize: cycleStack.size, + referenceableSize: referenceable.size, + currentPos, + objectTypeLookupSize: objectTypeLookup.size, + currentPosTypeLookup + }; + }, + rollback(snapshot) { + result.length = snapshot.length; + setSetSize(cycleStack, snapshot.cycleStackSize); + setMapSize(referenceable, snapshot.referenceableSize); + currentPos = snapshot.currentPos; + setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize); + currentPosTypeLookup = snapshot.currentPosTypeLookup; + }, + ...context + }; + this.extendContext(ctx); + /** + * @param {Value} item item to serialize + */ + const process = (item) => { + if (Buffer.isBuffer(item)) { + // check if we can emit a reference + const ref = referenceable.get(item); + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + return; + } + const alreadyUsedBuffer = dedupeBuffer(item); + if (alreadyUsedBuffer !== item) { + const ref = referenceable.get(alreadyUsedBuffer); + if (ref !== undefined) { + referenceable.set(item, ref); + result.push(ESCAPE, ref - currentPos); + return; + } + item = alreadyUsedBuffer; + } + addReferenceable(item); + + result.push(item); + } else if (item === ESCAPE) { + result.push(ESCAPE, ESCAPE_ESCAPE_VALUE); + } else if ( + typeof item === "object" + // We don't have to check for null as ESCAPE is null and this has been checked before + ) { + // check if we can emit a reference + const ref = referenceable.get(item); + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + return; + } + + if (cycleStack.has(item)) { + throw new Error( + "This is a circular references. To serialize circular references use 'setCircularReference' somewhere in the circle during serialize and deserialize." + ); + } + + const { request, name, serializer } = + ObjectMiddleware.getSerializerFor(item); + const key = `${request}/${name}`; + const lastIndex = objectTypeLookup.get(key); + + if (lastIndex === undefined) { + objectTypeLookup.set(key, currentPosTypeLookup++); + + result.push(ESCAPE, request, name); + } else { + result.push(ESCAPE, currentPosTypeLookup - lastIndex); + } + + cycleStack.add(item); + + try { + serializer.serialize(item, ctx); + } finally { + cycleStack.delete(item); + } + + result.push(ESCAPE, ESCAPE_END_OBJECT); + + addReferenceable(item); + } else if (typeof item === "string") { + if (item.length > 1) { + // short strings are shorter when not emitting a reference (this saves 1 byte per empty string) + // check if we can emit a reference + const ref = referenceable.get(item); + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + return; + } + addReferenceable(item); + } + + if (item.length > 102400 && context.logger) { + context.logger.warn( + `Serializing big strings (${Math.round( + item.length / 1024 + )}kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)` + ); + } + + result.push(item); + } else if (typeof item === "function") { + if (!SerializerMiddleware.isLazy(item)) { + throw new Error(`Unexpected function ${item}`); + } + + /** @type {SerializedType | undefined} */ + const serializedData = + SerializerMiddleware.getLazySerializedValue(item); + + if (serializedData !== undefined) { + if (typeof serializedData === "function") { + result.push(serializedData); + } else { + throw new Error("Not implemented"); + } + } else if (SerializerMiddleware.isLazy(item, this)) { + throw new Error("Not implemented"); + } else { + const data = SerializerMiddleware.serializeLazy(item, (data) => + this.serialize([data], context) + ); + SerializerMiddleware.setLazySerializedValue(item, data); + result.push(data); + } + } else if (item === undefined) { + result.push(ESCAPE, ESCAPE_UNDEFINED); + } else { + result.push(item); + } + }; + + try { + for (const item of data) { + process(item); + } + return result; + } catch (err) { + if (err === NOT_SERIALIZABLE) return null; + + throw err; + } finally { + // Get rid of these references to avoid leaking memory + // This happens because the optimized code v8 generates + // is optimized for our "ctx.write" method so it will reference + // it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write + data = + result = + referenceable = + bufferDedupeMap = + objectTypeLookup = + ctx = + /** @type {EXPECTED_ANY} */ + (undefined); + } + } + + /** + * @param {SerializedType} data data + * @param {Context} context context object + * @returns {DeserializedType | Promise} deserialized data + */ + deserialize(data, context) { + let currentDataPos = 0; + const read = () => { + if (currentDataPos >= data.length) { + throw new Error("Unexpected end of stream"); + } + + return data[currentDataPos++]; + }; + + if (read() !== CURRENT_VERSION) { + throw new Error("Version mismatch, serializer changed"); + } + + let currentPos = 0; + /** @type {ReferenceableItem[]} */ + let referenceable = []; + /** + * @param {Value} item referenceable item + */ + const addReferenceable = (item) => { + referenceable.push(item); + currentPos++; + }; + let currentPosTypeLookup = 0; + /** @type {ObjectSerializer[]} */ + let objectTypeLookup = []; + let result = []; + /** @type {ObjectDeserializerContext} */ + let ctx = { + read() { + return decodeValue(); + }, + setCircularReference(ref) { + addReferenceable(ref); + }, + ...context + }; + this.extendContext(ctx); + const decodeValue = () => { + const item = read(); + + if (item === ESCAPE) { + const nextItem = read(); + + if (nextItem === ESCAPE_ESCAPE_VALUE) { + return ESCAPE; + } else if (nextItem === ESCAPE_UNDEFINED) { + // Nothing + } else if (nextItem === ESCAPE_END_OBJECT) { + throw new Error( + `Unexpected end of object at position ${currentDataPos - 1}` + ); + } else { + const request = nextItem; + let serializer; + + if (typeof request === "number") { + if (request < 0) { + // relative reference + return referenceable[currentPos + request]; + } + serializer = objectTypeLookup[currentPosTypeLookup - request]; + } else { + if (typeof request !== "string") { + throw new Error( + `Unexpected type (${typeof request}) of request ` + + `at position ${currentDataPos - 1}` + ); + } + const name = /** @type {string} */ (read()); + + serializer = ObjectMiddleware._getDeserializerForWithoutError( + request, + name + ); + + if (serializer === undefined) { + if (request && !loadedRequests.has(request)) { + let loaded = false; + for (const [regExp, loader] of loaders) { + if (regExp.test(request) && loader(request)) { + loaded = true; + break; + } + } + if (!loaded) { + require(request); + } + + loadedRequests.add(request); + } + + serializer = ObjectMiddleware.getDeserializerFor(request, name); + } + + objectTypeLookup.push(serializer); + currentPosTypeLookup++; + } + try { + const item = serializer.deserialize(ctx); + const end1 = read(); + + if (end1 !== ESCAPE) { + throw new Error("Expected end of object"); + } + + const end2 = read(); + + if (end2 !== ESCAPE_END_OBJECT) { + throw new Error("Expected end of object"); + } + + addReferenceable(item); + + return item; + } catch (err) { + // As this is only for error handling, we omit creating a Map for + // faster access to this information, as this would affect performance + // in the good case + let serializerEntry; + for (const entry of serializers) { + if (entry[1].serializer === serializer) { + serializerEntry = entry; + break; + } + } + const name = !serializerEntry + ? "unknown" + : !serializerEntry[1].request + ? serializerEntry[0].name + : serializerEntry[1].name + ? `${serializerEntry[1].request} ${serializerEntry[1].name}` + : serializerEntry[1].request; + /** @type {Error} */ + (err).message += `\n(during deserialization of ${name})`; + throw err; + } + } + } else if (typeof item === "string") { + if (item.length > 1) { + addReferenceable(item); + } + + return item; + } else if (Buffer.isBuffer(item)) { + addReferenceable(item); + + return item; + } else if (typeof item === "function") { + return SerializerMiddleware.deserializeLazy( + item, + (data) => + /** @type {[DeserializedType]} */ + (this.deserialize(data, context))[0] + ); + } else { + return item; + } + }; + + try { + while (currentDataPos < data.length) { + result.push(decodeValue()); + } + return result; + } finally { + // Get rid of these references to avoid leaking memory + // This happens because the optimized code v8 generates + // is optimized for our "ctx.read" method so it will reference + // it from e. g. Dependency.prototype.deserialize -(IC)-> ctx.read + result = + referenceable = + data = + objectTypeLookup = + ctx = + /** @type {EXPECTED_ANY} */ + (undefined); + } + } +} + +module.exports = ObjectMiddleware; +module.exports.NOT_SERIALIZABLE = NOT_SERIALIZABLE; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/PlainObjectSerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/PlainObjectSerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..2d04aa4a4893669af348ecf8fff3f44e539d337f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/PlainObjectSerializer.js @@ -0,0 +1,117 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** @typedef {EXPECTED_FUNCTION} CacheAssoc */ + +/** + * @template T + * @typedef {WeakMap>} + */ +const cache = new WeakMap(); + +/** + * @template T + */ +class ObjectStructure { + constructor() { + this.keys = undefined; + this.children = undefined; + } + + /** + * @param {keyof T[]} keys keys + * @returns {keyof T[]} keys + */ + getKeys(keys) { + if (this.keys === undefined) this.keys = keys; + return this.keys; + } + + /** + * @param {keyof T} key key + * @returns {ObjectStructure} object structure + */ + key(key) { + if (this.children === undefined) this.children = new Map(); + const child = this.children.get(key); + if (child !== undefined) return child; + const newChild = new ObjectStructure(); + this.children.set(key, newChild); + return newChild; + } +} + +/** + * @template T + * @param {(keyof T)[]} keys keys + * @param {CacheAssoc} cacheAssoc cache assoc fn + * @returns {(keyof T)[]} keys + */ +const getCachedKeys = (keys, cacheAssoc) => { + let root = cache.get(cacheAssoc); + if (root === undefined) { + root = new ObjectStructure(); + cache.set(cacheAssoc, root); + } + let current = root; + for (const key of keys) { + current = current.key(key); + } + return current.getKeys(keys); +}; + +class PlainObjectSerializer { + /** + * @template {object} T + * @param {T} obj plain object + * @param {ObjectSerializerContext} context context + */ + serialize(obj, context) { + const keys = /** @type {(keyof T)[]} */ (Object.keys(obj)); + if (keys.length > 128) { + // Objects with so many keys are unlikely to share structure + // with other objects + context.write(keys); + for (const key of keys) { + context.write(obj[key]); + } + } else if (keys.length > 1) { + context.write(getCachedKeys(keys, context.write)); + for (const key of keys) { + context.write(obj[key]); + } + } else if (keys.length === 1) { + const key = keys[0]; + context.write(key); + context.write(obj[key]); + } else { + context.write(null); + } + } + + /** + * @template {object} T + * @param {ObjectDeserializerContext} context context + * @returns {T} plain object + */ + deserialize(context) { + const keys = context.read(); + const obj = /** @type {T} */ ({}); + if (Array.isArray(keys)) { + for (const key of keys) { + obj[/** @type {keyof T} */ (key)] = context.read(); + } + } else if (keys !== null) { + obj[/** @type {keyof T} */ (keys)] = context.read(); + } + return obj; + } +} + +module.exports = PlainObjectSerializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/RegExpObjectSerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/RegExpObjectSerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..5ac7eec5105e3cfa72cb4bbd9cee05fa9f63f99c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/RegExpObjectSerializer.js @@ -0,0 +1,29 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class RegExpObjectSerializer { + /** + * @param {RegExp} obj regexp + * @param {ObjectSerializerContext} context context + */ + serialize(obj, context) { + context.write(obj.source); + context.write(obj.flags); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {RegExp} regexp + */ + deserialize(context) { + return new RegExp(context.read(), context.read()); + } +} + +module.exports = RegExpObjectSerializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/Serializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/Serializer.js new file mode 100644 index 0000000000000000000000000000000000000000..a3cafc3b3b5693069204e669ae9fc8b263ff4b80 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/Serializer.js @@ -0,0 +1,82 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** + * @template T, K, C + * @typedef {import("./SerializerMiddleware")} SerializerMiddleware + */ + +/** + * @template DeserializedValue + * @template SerializedValue + * @template Context + */ +class Serializer { + /** + * @param {SerializerMiddleware[]} middlewares serializer middlewares + * @param {Context=} context context + */ + constructor(middlewares, context) { + this.serializeMiddlewares = [...middlewares]; + this.deserializeMiddlewares = [...middlewares].reverse(); + this.context = context; + } + + /** + * @template ExtendedContext + * @param {DeserializedValue | Promise} obj object + * @param {Context & ExtendedContext} context context object + * @returns {Promise} result + */ + serialize(obj, context) { + const ctx = { ...context, ...this.context }; + let current = obj; + for (const middleware of this.serializeMiddlewares) { + if ( + current && + typeof (/** @type {Promise} */ (current).then) === + "function" + ) { + current = + /** @type {Promise} */ + (current).then((data) => data && middleware.serialize(data, ctx)); + } else if (current) { + try { + current = middleware.serialize(current, ctx); + } catch (err) { + current = Promise.reject(err); + } + } else { + break; + } + } + return /** @type {Promise} */ (current); + } + + /** + * @template ExtendedContext + * @param {SerializedValue | Promise} value value + * @param {Context & ExtendedContext} context object + * @returns {Promise} result + */ + deserialize(value, context) { + const ctx = { ...context, ...this.context }; + let current = value; + for (const middleware of this.deserializeMiddlewares) { + current = + current && + typeof (/** @type {Promise} */ (current).then) === + "function" + ? /** @type {Promise} */ (current).then((data) => + middleware.deserialize(data, ctx) + ) + : middleware.deserialize(current, ctx); + } + return /** @type {Promise} */ (current); + } +} + +module.exports = Serializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/SerializerMiddleware.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/SerializerMiddleware.js new file mode 100644 index 0000000000000000000000000000000000000000..91e8bdff9dfbff0df729e2324248215d761422f8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/SerializerMiddleware.js @@ -0,0 +1,228 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const memoize = require("../util/memoize"); + +const LAZY_TARGET = Symbol("lazy serialization target"); +const LAZY_SERIALIZED_VALUE = Symbol("lazy serialization data"); + +/** @typedef {SerializerMiddleware>} LazyTarget */ +/** @typedef {Record} LazyOptions */ + +/** + * @template InputValue + * @template OutputValue + * @template {LazyTarget} InternalLazyTarget + * @template {LazyOptions | undefined} InternalLazyOptions + * @typedef {(() => InputValue | Promise) & Partial<{ [LAZY_TARGET]: InternalLazyTarget, options: InternalLazyOptions, [LAZY_SERIALIZED_VALUE]?: OutputValue | LazyFunction | undefined }>} LazyFunction + */ + +/** + * @template DeserializedType + * @template SerializedType + * @template Context + */ +class SerializerMiddleware { + /* istanbul ignore next */ + /** + * @abstract + * @param {DeserializedType} data data + * @param {Context} context context object + * @returns {SerializedType | Promise | null} serialized data + */ + serialize(data, context) { + const AbstractMethodError = require("../AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {SerializedType} data data + * @param {Context} context context object + * @returns {DeserializedType | Promise} deserialized data + */ + deserialize(data, context) { + const AbstractMethodError = require("../AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /** + * @template TLazyInputValue + * @template TLazyOutputValue + * @template {LazyTarget} TLazyTarget + * @template {LazyOptions | undefined} TLazyOptions + * @param {TLazyInputValue | (() => TLazyInputValue)} value contained value or function to value + * @param {TLazyTarget} target target middleware + * @param {TLazyOptions=} options lazy options + * @param {TLazyOutputValue=} serializedValue serialized value + * @returns {LazyFunction} lazy function + */ + static createLazy( + value, + target, + options = /** @type {TLazyOptions} */ ({}), + serializedValue = undefined + ) { + if (SerializerMiddleware.isLazy(value, target)) return value; + const fn = + /** @type {LazyFunction} */ + (typeof value === "function" ? value : () => value); + fn[LAZY_TARGET] = target; + fn.options = options; + fn[LAZY_SERIALIZED_VALUE] = serializedValue; + return fn; + } + + /** + * @template {LazyTarget} TLazyTarget + * @param {EXPECTED_ANY} fn lazy function + * @param {TLazyTarget=} target target middleware + * @returns {fn is LazyFunction} true, when fn is a lazy function (optionally of that target) + */ + static isLazy(fn, target) { + if (typeof fn !== "function") return false; + const t = fn[LAZY_TARGET]; + return target ? t === target : Boolean(t); + } + + /** + * @template TLazyInputValue + * @template TLazyOutputValue + * @template {LazyTarget} TLazyTarget + * @template {Record} TLazyOptions + * @template TLazySerializedValue + * @param {LazyFunction} fn lazy function + * @returns {LazyOptions | undefined} options + */ + static getLazyOptions(fn) { + if (typeof fn !== "function") return; + return fn.options; + } + + /** + * @template TLazyInputValue + * @template TLazyOutputValue + * @template {LazyTarget} TLazyTarget + * @template {LazyOptions} TLazyOptions + * @param {LazyFunction | EXPECTED_ANY} fn lazy function + * @returns {TLazyOutputValue | undefined} serialized value + */ + static getLazySerializedValue(fn) { + if (typeof fn !== "function") return; + return fn[LAZY_SERIALIZED_VALUE]; + } + + /** + * @template TLazyInputValue + * @template TLazyOutputValue + * @template {LazyTarget} TLazyTarget + * @template {LazyOptions} TLazyOptions + * @param {LazyFunction} fn lazy function + * @param {TLazyOutputValue} value serialized value + * @returns {void} + */ + static setLazySerializedValue(fn, value) { + fn[LAZY_SERIALIZED_VALUE] = value; + } + + /** + * @template TLazyInputValue DeserializedValue + * @template TLazyOutputValue SerializedValue + * @template {LazyTarget} TLazyTarget + * @template {LazyOptions | undefined} TLazyOptions + * @param {LazyFunction} lazy lazy function + * @param {(value: TLazyInputValue) => TLazyOutputValue} serialize serialize function + * @returns {LazyFunction} new lazy + */ + static serializeLazy(lazy, serialize) { + const fn = + /** @type {LazyFunction} */ + ( + memoize(() => { + const r = lazy(); + if ( + r && + typeof (/** @type {Promise} */ (r).then) === + "function" + ) { + return ( + /** @type {Promise} */ + (r).then((data) => data && serialize(data)) + ); + } + return serialize(/** @type {TLazyInputValue} */ (r)); + }) + ); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + fn.options = lazy.options; + lazy[LAZY_SERIALIZED_VALUE] = fn; + return fn; + } + + /** + * @template TLazyInputValue SerializedValue + * @template TLazyOutputValue DeserializedValue + * @template SerializedValue + * @template {LazyTarget} TLazyTarget + * @template {LazyOptions | undefined} TLazyOptions + * @param {LazyFunction} lazy lazy function + * @param {(data: TLazyInputValue) => TLazyOutputValue} deserialize deserialize function + * @returns {LazyFunction} new lazy + */ + static deserializeLazy(lazy, deserialize) { + const fn = + /** @type {LazyFunction} */ ( + memoize(() => { + const r = lazy(); + if ( + r && + typeof (/** @type {Promise} */ (r).then) === + "function" + ) { + return ( + /** @type {Promise} */ + (r).then((data) => deserialize(data)) + ); + } + return deserialize(/** @type {TLazyInputValue} */ (r)); + }) + ); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + fn.options = lazy.options; + fn[LAZY_SERIALIZED_VALUE] = lazy; + return fn; + } + + /** + * @template TLazyInputValue + * @template TLazyOutputValue + * @template {LazyTarget} TLazyTarget + * @template {LazyOptions} TLazyOptions + * @param {LazyFunction | undefined} lazy lazy function + * @returns {LazyFunction | undefined} new lazy + */ + static unMemoizeLazy(lazy) { + if (!SerializerMiddleware.isLazy(lazy)) return lazy; + /** @type {LazyFunction} */ + const fn = () => { + throw new Error( + "A lazy value that has been unmemorized can't be called again" + ); + }; + fn[LAZY_SERIALIZED_VALUE] = SerializerMiddleware.unMemoizeLazy( + /** @type {LazyFunction} */ + (lazy[LAZY_SERIALIZED_VALUE]) + ); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + fn.options = lazy.options; + return fn; + } +} + +module.exports = SerializerMiddleware; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/SetObjectSerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/SetObjectSerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..66811b87d160ffd18f7f0a048c8a17bfd4529e00 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/SetObjectSerializer.js @@ -0,0 +1,40 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class SetObjectSerializer { + /** + * @template T + * @param {Set} obj set + * @param {ObjectSerializerContext} context context + */ + serialize(obj, context) { + context.write(obj.size); + for (const value of obj) { + context.write(value); + } + } + + /** + * @template T + * @param {ObjectDeserializerContext} context context + * @returns {Set} date + */ + deserialize(context) { + /** @type {number} */ + const size = context.read(); + /** @type {Set} */ + const set = new Set(); + for (let i = 0; i < size; i++) { + set.add(context.read()); + } + return set; + } +} + +module.exports = SetObjectSerializer; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/SingleItemMiddleware.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/SingleItemMiddleware.js new file mode 100644 index 0000000000000000000000000000000000000000..43b1fe6ae9d900132dcf0e3d523e137a99d65114 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/SingleItemMiddleware.js @@ -0,0 +1,36 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const SerializerMiddleware = require("./SerializerMiddleware"); + +/** @typedef {EXPECTED_ANY} DeserializedType */ +/** @typedef {EXPECTED_ANY[]} SerializedType */ +/** @typedef {{}} Context */ + +/** + * @extends {SerializerMiddleware} + */ +class SingleItemMiddleware extends SerializerMiddleware { + /** + * @param {DeserializedType} data data + * @param {Context} context context object + * @returns {SerializedType | Promise | null} serialized data + */ + serialize(data, context) { + return [data]; + } + + /** + * @param {SerializedType} data data + * @param {Context} context context object + * @returns {DeserializedType | Promise} deserialized data + */ + deserialize(data, context) { + return data[0]; + } +} + +module.exports = SingleItemMiddleware; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/types.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/types.js new file mode 100644 index 0000000000000000000000000000000000000000..4c5a9de0d4665b93f57f38b1ee236b1ce600e211 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/serialization/types.js @@ -0,0 +1,13 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** @typedef {undefined | null | number | string | boolean | Buffer | EXPECTED_OBJECT | (() => ComplexSerializableType[] | Promise)} ComplexSerializableType */ + +/** @typedef {undefined | null | number | bigint | string | boolean | Buffer | (() => PrimitiveSerializableType[] | Promise)} PrimitiveSerializableType */ + +/** @typedef {Buffer | (() => BufferSerializableType[] | Promise)} BufferSerializableType */ + +module.exports = {}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedFallbackDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedFallbackDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..bd6eefef13f2c6f68571b06e150374dcfdc40bb0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedFallbackDependency.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleDependency = require("../dependencies/ModuleDependency"); +const makeSerializable = require("../util/makeSerializable"); + +class ConsumeSharedFallbackDependency extends ModuleDependency { + /** + * @param {string} request the request + */ + constructor(request) { + super(request); + } + + get type() { + return "consume shared fallback"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + ConsumeSharedFallbackDependency, + "webpack/lib/sharing/ConsumeSharedFallbackDependency" +); + +module.exports = ConsumeSharedFallbackDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedModule.js new file mode 100644 index 0000000000000000000000000000000000000000..7e14b716bc9630c41361f29461481b679a1a892f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedModule.js @@ -0,0 +1,269 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const Module = require("../Module"); +const { CONSUME_SHARED_TYPES } = require("../ModuleSourceTypesConstants"); +const { + WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE +} = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const { rangeToString, stringifyHoley } = require("../util/semver"); +const ConsumeSharedFallbackDependency = require("./ConsumeSharedFallbackDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").BuildCallback} BuildCallback */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("../util/semver").SemVerRange} SemVerRange */ + +/** + * @typedef {object} ConsumeOptions + * @property {string=} import fallback request + * @property {string=} importResolved resolved fallback request + * @property {string} shareKey global share key + * @property {string} shareScope share scope + * @property {SemVerRange | false | undefined} requiredVersion version requirement + * @property {string=} packageName package name to determine required version automatically + * @property {boolean} strictVersion don't use shared version even if version isn't valid + * @property {boolean} singleton use single global version + * @property {boolean} eager include the fallback module in a sync way + */ + +class ConsumeSharedModule extends Module { + /** + * @param {string} context context + * @param {ConsumeOptions} options consume options + */ + constructor(context, options) { + super(WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE, context); + this.options = options; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + const { + shareKey, + shareScope, + importResolved, + requiredVersion, + strictVersion, + singleton, + eager + } = this.options; + return `${WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE}|${shareScope}|${shareKey}|${ + requiredVersion && rangeToString(requiredVersion) + }|${strictVersion}|${importResolved}|${singleton}|${eager}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + const { + shareKey, + shareScope, + importResolved, + requiredVersion, + strictVersion, + singleton, + eager + } = this.options; + return `consume shared module (${shareScope}) ${shareKey}@${ + requiredVersion ? rangeToString(requiredVersion) : "*" + }${strictVersion ? " (strict)" : ""}${singleton ? " (singleton)" : ""}${ + importResolved + ? ` (fallback: ${requestShortener.shorten(importResolved)})` + : "" + }${eager ? " (eager)" : ""}`; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + const { shareKey, shareScope, import: request } = this.options; + return `${ + this.layer ? `(${this.layer})/` : "" + }webpack/sharing/consume/${shareScope}/${shareKey}${ + request ? `/${request}` : "" + }`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = {}; + if (this.options.import) { + const dep = new ConsumeSharedFallbackDependency(this.options.import); + if (this.options.eager) { + this.addDependency(dep); + } else { + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); + } + } + callback(); + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return CONSUME_SHARED_TYPES; + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return 42; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(JSON.stringify(this.options)); + super.updateHash(hash, context); + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ chunkGraph, runtimeTemplate }) { + const runtimeRequirements = new Set([RuntimeGlobals.shareScopeMap]); + const { + shareScope, + shareKey, + strictVersion, + requiredVersion, + import: request, + singleton, + eager + } = this.options; + let fallbackCode; + if (request) { + if (eager) { + const dep = this.dependencies[0]; + fallbackCode = runtimeTemplate.syncModuleFactory({ + dependency: dep, + chunkGraph, + runtimeRequirements, + request: this.options.import + }); + } else { + const block = this.blocks[0]; + fallbackCode = runtimeTemplate.asyncModuleFactory({ + block, + chunkGraph, + runtimeRequirements, + request: this.options.import + }); + } + } + + const args = [ + JSON.stringify(shareScope), + JSON.stringify(shareKey), + JSON.stringify(eager) + ]; + if (requiredVersion) { + args.push(stringifyHoley(requiredVersion)); + } + if (fallbackCode) { + args.push(fallbackCode); + } + + let fn; + + if (requiredVersion) { + if (strictVersion) { + fn = singleton ? "loadStrictSingletonVersion" : "loadStrictVersion"; + } else { + fn = singleton ? "loadSingletonVersion" : "loadVersion"; + } + } else { + fn = singleton ? "loadSingleton" : "load"; + } + + const code = runtimeTemplate.returningFunction(`${fn}(${args.join(", ")})`); + const sources = new Map(); + sources.set("consume-shared", new RawSource(code)); + return { + runtimeRequirements, + sources + }; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this.options); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + */ + deserialize(context) { + const { read } = context; + this.options = read(); + super.deserialize(context); + } +} + +makeSerializable( + ConsumeSharedModule, + "webpack/lib/sharing/ConsumeSharedModule" +); + +module.exports = ConsumeSharedModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..767fcd126c57e30d21a3532ed37076a8ef9e536c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedPlugin.js @@ -0,0 +1,379 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleNotFoundError = require("../ModuleNotFoundError"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const WebpackError = require("../WebpackError"); +const { parseOptions } = require("../container/options"); +const LazySet = require("../util/LazySet"); +const createSchemaValidation = require("../util/create-schema-validation"); +const { parseRange } = require("../util/semver"); +const ConsumeSharedFallbackDependency = require("./ConsumeSharedFallbackDependency"); +const ConsumeSharedModule = require("./ConsumeSharedModule"); +const ConsumeSharedRuntimeModule = require("./ConsumeSharedRuntimeModule"); +const ProvideForSharedDependency = require("./ProvideForSharedDependency"); +const { resolveMatchedConfigs } = require("./resolveMatchedConfigs"); +const { + getDescriptionFile, + getRequiredVersionFromDescriptionFile, + isRequiredVersion +} = require("./utils"); + +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ +/** @typedef {import("../util/semver").SemVerRange} SemVerRange */ +/** @typedef {import("./ConsumeSharedModule").ConsumeOptions} ConsumeOptions */ +/** @typedef {import("./utils").DescriptionFile} DescriptionFile */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/sharing/ConsumeSharedPlugin.check"), + () => require("../../schemas/plugins/sharing/ConsumeSharedPlugin.json"), + { + name: "Consume Shared Plugin", + baseDataPath: "options" + } +); + +/** @type {ResolveOptionsWithDependencyType} */ +const RESOLVE_OPTIONS = { dependencyType: "esm" }; +const PLUGIN_NAME = "ConsumeSharedPlugin"; + +class ConsumeSharedPlugin { + /** + * @param {ConsumeSharedPluginOptions} options options + */ + constructor(options) { + if (typeof options !== "string") { + validate(options); + } + + /** @type {[string, ConsumeOptions][]} */ + this._consumes = parseOptions( + options.consumes, + (item, key) => { + if (Array.isArray(item)) throw new Error("Unexpected array in options"); + /** @type {ConsumeOptions} */ + const result = + item === key || !isRequiredVersion(item) + ? // item is a request/key + { + import: key, + shareScope: options.shareScope || "default", + shareKey: key, + requiredVersion: undefined, + packageName: undefined, + strictVersion: false, + singleton: false, + eager: false + } + : // key is a request/key + // item is a version + { + import: key, + shareScope: options.shareScope || "default", + shareKey: key, + requiredVersion: parseRange(item), + strictVersion: true, + packageName: undefined, + singleton: false, + eager: false + }; + return result; + }, + (item, key) => ({ + import: item.import === false ? undefined : item.import || key, + shareScope: item.shareScope || options.shareScope || "default", + shareKey: item.shareKey || key, + requiredVersion: + typeof item.requiredVersion === "string" + ? parseRange(item.requiredVersion) + : item.requiredVersion, + strictVersion: + typeof item.strictVersion === "boolean" + ? item.strictVersion + : item.import !== false && !item.singleton, + packageName: item.packageName, + singleton: Boolean(item.singleton), + eager: Boolean(item.eager) + }) + ); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + ConsumeSharedFallbackDependency, + normalModuleFactory + ); + + /** @type {Map} */ + let unresolvedConsumes; + /** @type {Map} */ + let resolvedConsumes; + /** @type {Map} */ + let prefixedConsumes; + const promise = resolveMatchedConfigs(compilation, this._consumes).then( + ({ resolved, unresolved, prefixed }) => { + resolvedConsumes = resolved; + unresolvedConsumes = unresolved; + prefixedConsumes = prefixed; + } + ); + + const resolver = compilation.resolverFactory.get( + "normal", + RESOLVE_OPTIONS + ); + + /** + * @param {string} context issuer directory + * @param {string} request request + * @param {ConsumeOptions} config options + * @returns {Promise} create module + */ + const createConsumeSharedModule = (context, request, config) => { + /** + * @param {string} details details + */ + const requiredVersionWarning = (details) => { + const error = new WebpackError( + `No required version specified and unable to automatically determine one. ${details}` + ); + error.file = `shared module ${request}`; + compilation.warnings.push(error); + }; + const directFallback = + config.import && + /^(\.\.?(\/|$)|\/|[A-Za-z]:|\\\\)/.test(config.import); + return Promise.all([ + new Promise( + /** + * @param {(value?: string) => void} resolve resolve + */ + (resolve) => { + if (!config.import) { + resolve(); + return; + } + const resolveContext = { + /** @type {LazySet} */ + fileDependencies: new LazySet(), + /** @type {LazySet} */ + contextDependencies: new LazySet(), + /** @type {LazySet} */ + missingDependencies: new LazySet() + }; + resolver.resolve( + {}, + directFallback ? compiler.context : context, + config.import, + resolveContext, + (err, result) => { + compilation.contextDependencies.addAll( + resolveContext.contextDependencies + ); + compilation.fileDependencies.addAll( + resolveContext.fileDependencies + ); + compilation.missingDependencies.addAll( + resolveContext.missingDependencies + ); + if (err) { + compilation.errors.push( + new ModuleNotFoundError(null, err, { + name: `resolving fallback for shared module ${request}` + }) + ); + return resolve(); + } + resolve(/** @type {string} */ (result)); + } + ); + } + ), + new Promise( + /** + * @param {(value?: SemVerRange) => void} resolve resolve + */ + (resolve) => { + if (config.requiredVersion !== undefined) { + resolve(/** @type {SemVerRange} */ (config.requiredVersion)); + return; + } + let packageName = config.packageName; + if (packageName === undefined) { + if (/^(\/|[A-Za-z]:|\\\\)/.test(request)) { + // For relative or absolute requests we don't automatically use a packageName. + // If wished one can specify one with the packageName option. + resolve(); + return; + } + const match = /^((?:@[^\\/]+[\\/])?[^\\/]+)/.exec(request); + if (!match) { + requiredVersionWarning( + "Unable to extract the package name from request." + ); + resolve(); + return; + } + packageName = match[0]; + } + + getDescriptionFile( + compilation.inputFileSystem, + context, + ["package.json"], + (err, result, checkedDescriptionFilePaths) => { + if (err) { + requiredVersionWarning( + `Unable to read description file: ${err}` + ); + return resolve(); + } + const { data } = + /** @type {DescriptionFile} */ + (result || {}); + if (!data) { + if (checkedDescriptionFilePaths) { + requiredVersionWarning( + [ + `Unable to find required version for "${packageName}" in description file/s`, + checkedDescriptionFilePaths.join("\n"), + "It need to be in dependencies, devDependencies or peerDependencies." + ].join("\n") + ); + } else { + requiredVersionWarning( + `Unable to find description file in ${context}.` + ); + } + + return resolve(); + } + if (data.name === packageName) { + // Package self-referencing + return resolve(); + } + const requiredVersion = + getRequiredVersionFromDescriptionFile(data, packageName); + + if (requiredVersion) { + return resolve(parseRange(requiredVersion)); + } + + resolve(); + }, + (result) => { + if (!result) return false; + const maybeRequiredVersion = + getRequiredVersionFromDescriptionFile( + result.data, + packageName + ); + return ( + result.data.name === packageName || + typeof maybeRequiredVersion === "string" + ); + } + ); + } + ) + ]).then( + ([importResolved, requiredVersion]) => + new ConsumeSharedModule( + directFallback ? compiler.context : context, + { + ...config, + importResolved, + import: importResolved ? config.import : undefined, + requiredVersion + } + ) + ); + }; + + normalModuleFactory.hooks.factorize.tapPromise( + PLUGIN_NAME, + ({ context, request, dependencies }) => + // wait for resolving to be complete + promise.then(() => { + if ( + dependencies[0] instanceof ConsumeSharedFallbackDependency || + dependencies[0] instanceof ProvideForSharedDependency + ) { + return; + } + const match = unresolvedConsumes.get(request); + if (match !== undefined) { + return createConsumeSharedModule(context, request, match); + } + for (const [prefix, options] of prefixedConsumes) { + if (request.startsWith(prefix)) { + const remainder = request.slice(prefix.length); + return createConsumeSharedModule(context, request, { + ...options, + import: options.import + ? options.import + remainder + : undefined, + shareKey: options.shareKey + remainder + }); + } + } + }) + ); + normalModuleFactory.hooks.createModule.tapPromise( + PLUGIN_NAME, + ({ resource }, { context, dependencies }) => { + if ( + dependencies[0] instanceof ConsumeSharedFallbackDependency || + dependencies[0] instanceof ProvideForSharedDependency + ) { + return Promise.resolve(); + } + const options = resolvedConsumes.get( + /** @type {string} */ (resource) + ); + if (options !== undefined) { + return createConsumeSharedModule( + context, + /** @type {string} */ (resource), + options + ); + } + return Promise.resolve(); + } + ); + compilation.hooks.additionalTreeRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.shareScopeMap); + set.add(RuntimeGlobals.initializeSharing); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ConsumeSharedRuntimeModule(set) + ); + } + ); + } + ); + } +} + +module.exports = ConsumeSharedPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..6ee44fe0792a1031750dbdbfd609c9022229121d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ConsumeSharedRuntimeModule.js @@ -0,0 +1,355 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const { + parseVersionRuntimeCode, + rangeToStringRuntimeCode, + satisfyRuntimeCode, + versionLtRuntimeCode +} = require("../util/semver"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Chunk").ChunkId} ChunkId */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ +/** @typedef {import("./ConsumeSharedModule")} ConsumeSharedModule */ + +class ConsumeSharedRuntimeModule extends RuntimeModule { + /** + * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super("consumes", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const { runtimeTemplate, codeGenerationResults } = compilation; + /** @type {Record} */ + const chunkToModuleMapping = {}; + /** @type {Map} */ + const moduleIdToSourceMapping = new Map(); + /** @type {(string | number)[]} */ + const initialConsumes = []; + /** + * @param {Iterable} modules modules + * @param {Chunk} chunk the chunk + * @param {(string | number)[]} list list of ids + */ + const addModules = (modules, chunk, list) => { + for (const m of modules) { + const module = m; + const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module)); + list.push(id); + moduleIdToSourceMapping.set( + id, + codeGenerationResults.getSource( + module, + chunk.runtime, + "consume-shared" + ) + ); + } + }; + for (const chunk of /** @type {Chunk} */ ( + this.chunk + ).getAllReferencedChunks()) { + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "consume-shared" + ); + if (!modules) continue; + addModules( + modules, + chunk, + (chunkToModuleMapping[/** @type {ChunkId} */ (chunk.id)] = []) + ); + } + for (const chunk of /** @type {Chunk} */ ( + this.chunk + ).getAllInitialChunks()) { + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "consume-shared" + ); + if (!modules) continue; + addModules(modules, chunk, initialConsumes); + } + if (moduleIdToSourceMapping.size === 0) return null; + return Template.asString([ + parseVersionRuntimeCode(runtimeTemplate), + versionLtRuntimeCode(runtimeTemplate), + rangeToStringRuntimeCode(runtimeTemplate), + satisfyRuntimeCode(runtimeTemplate), + `var exists = ${runtimeTemplate.basicFunction("scope, key", [ + `return scope && ${RuntimeGlobals.hasOwnProperty}(scope, key);` + ])}`, + `var get = ${runtimeTemplate.basicFunction("entry", [ + "entry.loaded = 1;", + "return entry.get()" + ])};`, + `var eagerOnly = ${runtimeTemplate.basicFunction("versions", [ + `return Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "filtered, version", + Template.indent([ + "if (versions[version].eager) {", + Template.indent(["filtered[version] = versions[version];"]), + "}", + "return filtered;" + ]) + )}, {});` + ])};`, + `var findLatestVersion = ${runtimeTemplate.basicFunction( + "scope, key, eager", + [ + "var versions = eager ? eagerOnly(scope[key]) : scope[key];", + `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "a, b", + ["return !a || versionLt(a, b) ? b : a;"] + )}, 0);`, + "return key && versions[key];" + ] + )};`, + `var findSatisfyingVersion = ${runtimeTemplate.basicFunction( + "scope, key, requiredVersion, eager", + [ + "var versions = eager ? eagerOnly(scope[key]) : scope[key];", + `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "a, b", + [ + "if (!satisfy(requiredVersion, b)) return a;", + "return !a || versionLt(a, b) ? b : a;" + ] + )}, 0);`, + "return key && versions[key]" + ] + )};`, + `var findSingletonVersionKey = ${runtimeTemplate.basicFunction( + "scope, key, eager", + [ + "var versions = eager ? eagerOnly(scope[key]) : scope[key];", + `return Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "a, b", + ["return !a || (!versions[a].loaded && versionLt(a, b)) ? b : a;"] + )}, 0);` + ] + )};`, + `var getInvalidSingletonVersionMessage = ${runtimeTemplate.basicFunction( + "scope, key, version, requiredVersion", + [ + 'return "Unsatisfied version " + version + " from " + (version && scope[key][version].from) + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")"' + ] + )};`, + `var getInvalidVersionMessage = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion, eager", + [ + "var versions = scope[key];", + 'return "No satisfying version (" + rangeToString(requiredVersion) + ")" + (eager ? " for eager consumption" : "") + " of shared module " + key + " found in shared scope " + scopeName + ".\\n" +', + `\t"Available versions: " + Object.keys(versions).map(${runtimeTemplate.basicFunction( + "key", + ['return key + " from " + versions[key].from;'] + )}).join(", ");` + ] + )};`, + `var fail = ${runtimeTemplate.basicFunction("msg", [ + "throw new Error(msg);" + ])}`, + `var failAsNotExist = ${runtimeTemplate.basicFunction("scopeName, key", [ + 'return fail("Shared module " + key + " doesn\'t exist in shared scope " + scopeName);' + ])}`, + `var warn = /*#__PURE__*/ ${ + compilation.outputOptions.ignoreBrowserWarnings + ? runtimeTemplate.basicFunction("", "") + : runtimeTemplate.basicFunction("msg", [ + 'if (typeof console !== "undefined" && console.warn) console.warn(msg);' + ]) + };`, + `var init = ${runtimeTemplate.returningFunction( + Template.asString([ + "function(scopeName, key, eager, c, d) {", + Template.indent([ + `var promise = ${RuntimeGlobals.initializeSharing}(scopeName);`, + // if we require eager shared, we expect it to be already loaded before it requested, no need to wait the whole scope loaded. + "if (promise && promise.then && !eager) { ", + Template.indent([ + `return promise.then(fn.bind(fn, scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], key, false, c, d));` + ]), + "}", + `return fn(scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], key, eager, c, d);` + ]), + "}" + ]), + "fn" + )};`, + "", + `var useFallback = ${runtimeTemplate.basicFunction( + "scopeName, key, fallback", + ["return fallback ? fallback() : failAsNotExist(scopeName, key);"] + )}`, + `var load = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, eager, fallback", + [ + "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", + "return get(findLatestVersion(scope, key, eager));" + ] + )});`, + `var loadVersion = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, eager, requiredVersion, fallback", + [ + "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", + "var satisfyingVersion = findSatisfyingVersion(scope, key, requiredVersion, eager);", + "if (satisfyingVersion) return get(satisfyingVersion);", + "warn(getInvalidVersionMessage(scope, scopeName, key, requiredVersion, eager))", + "return get(findLatestVersion(scope, key, eager));" + ] + )});`, + `var loadStrictVersion = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, eager, requiredVersion, fallback", + [ + "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", + "var satisfyingVersion = findSatisfyingVersion(scope, key, requiredVersion, eager);", + "if (satisfyingVersion) return get(satisfyingVersion);", + "if (fallback) return fallback();", + "fail(getInvalidVersionMessage(scope, scopeName, key, requiredVersion, eager));" + ] + )});`, + `var loadSingleton = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, eager, fallback", + [ + "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", + "var version = findSingletonVersionKey(scope, key, eager);", + "return get(scope[key][version]);" + ] + )});`, + `var loadSingletonVersion = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, eager, requiredVersion, fallback", + [ + "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", + "var version = findSingletonVersionKey(scope, key, eager);", + "if (!satisfy(requiredVersion, version)) {", + Template.indent([ + "warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));" + ]), + "}", + "return get(scope[key][version]);" + ] + )});`, + `var loadStrictSingletonVersion = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, eager, requiredVersion, fallback", + [ + "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", + "var version = findSingletonVersionKey(scope, key, eager);", + "if (!satisfy(requiredVersion, version)) {", + Template.indent([ + "fail(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));" + ]), + "}", + "return get(scope[key][version]);" + ] + )});`, + "var installedModules = {};", + "var moduleToHandlerMapping = {", + Template.indent( + Array.from( + moduleIdToSourceMapping, + ([key, source]) => `${JSON.stringify(key)}: ${source.source()}` + ).join(",\n") + ), + "};", + + initialConsumes.length > 0 + ? Template.asString([ + `var initialConsumes = ${JSON.stringify(initialConsumes)};`, + `initialConsumes.forEach(${runtimeTemplate.basicFunction("id", [ + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + "// Handle case when module is used sync", + "installedModules[id] = 0;", + `delete ${RuntimeGlobals.moduleCache}[id];`, + "var factory = moduleToHandlerMapping[id]();", + 'if(typeof factory !== "function") throw new Error("Shared module is not available for eager consumption: " + id);', + "module.exports = factory();" + ])}` + ])});` + ]) + : "// no consumes in initial chunks", + this._runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) + ? Template.asString([ + `var chunkMapping = ${JSON.stringify( + chunkToModuleMapping, + null, + "\t" + )};`, + "var startedInstallModules = {};", + `${ + RuntimeGlobals.ensureChunkHandlers + }.consumes = ${runtimeTemplate.basicFunction("chunkId, promises", [ + `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, + Template.indent([ + `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction( + "id", + [ + `if(${RuntimeGlobals.hasOwnProperty}(installedModules, id)) return promises.push(installedModules[id]);`, + "if(!startedInstallModules[id]) {", + `var onFactory = ${runtimeTemplate.basicFunction( + "factory", + [ + "installedModules[id] = 0;", + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + `delete ${RuntimeGlobals.moduleCache}[id];`, + "module.exports = factory();" + ])}` + ] + )};`, + "startedInstallModules[id] = true;", + `var onError = ${runtimeTemplate.basicFunction("error", [ + "delete installedModules[id];", + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + `delete ${RuntimeGlobals.moduleCache}[id];`, + "throw error;" + ])}` + ])};`, + "try {", + Template.indent([ + "var promise = moduleToHandlerMapping[id]();", + "if(promise.then) {", + Template.indent( + "promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError));" + ), + "} else onFactory(promise);" + ]), + "} catch(e) { onError(e); }", + "}" + ] + )});` + ]), + "}" + ])}` + ]) + : "// no chunk loading of consumes" + ]); + } +} + +module.exports = ConsumeSharedRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideForSharedDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideForSharedDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..4de679a6a745872bccb8594d38c1dc44e0f30c82 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideForSharedDependency.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleDependency = require("../dependencies/ModuleDependency"); +const makeSerializable = require("../util/makeSerializable"); + +class ProvideForSharedDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { + super(request); + } + + get type() { + return "provide module for shared"; + } + + get category() { + return "esm"; + } +} + +makeSerializable( + ProvideForSharedDependency, + "webpack/lib/sharing/ProvideForSharedDependency" +); + +module.exports = ProvideForSharedDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedDependency.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedDependency.js new file mode 100644 index 0000000000000000000000000000000000000000..2df18a618ed7bcc03582d9ec7f2142285433972a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedDependency.js @@ -0,0 +1,80 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Dependency = require("../Dependency"); +const makeSerializable = require("../util/makeSerializable"); + +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +class ProvideSharedDependency extends Dependency { + /** + * @param {string} shareScope share scope + * @param {string} name module name + * @param {string | false} version version + * @param {string} request request + * @param {boolean} eager true, if this is an eager dependency + */ + constructor(shareScope, name, version, request, eager) { + super(); + this.shareScope = shareScope; + this.name = name; + this.version = version; + this.request = request; + this.eager = eager; + } + + get type() { + return "provide shared module"; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `provide module (${this.shareScope}) ${this.request} as ${ + this.name + } @ ${this.version}${this.eager ? " (eager)" : ""}`; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + context.write(this.shareScope); + context.write(this.name); + context.write(this.request); + context.write(this.version); + context.write(this.eager); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {ProvideSharedDependency} deserialize fallback dependency + */ + static deserialize(context) { + const { read } = context; + const obj = new ProvideSharedDependency( + read(), + read(), + read(), + read(), + read() + ); + this.shareScope = context.read(); + obj.deserialize(context); + return obj; + } +} + +makeSerializable( + ProvideSharedDependency, + "webpack/lib/sharing/ProvideSharedDependency" +); + +module.exports = ProvideSharedDependency; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedModule.js new file mode 100644 index 0000000000000000000000000000000000000000..e4c83e6c99a6024871c4acd5336686cc6c16f2bb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedModule.js @@ -0,0 +1,196 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy +*/ + +"use strict"; + +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const Module = require("../Module"); +const { SHARED_INIT_TYPES } = require("../ModuleSourceTypesConstants"); +const { WEBPACK_MODULE_TYPE_PROVIDE } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const makeSerializable = require("../util/makeSerializable"); +const ProvideForSharedDependency = require("./ProvideForSharedDependency"); + +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").BuildCallback} BuildCallback */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + +class ProvideSharedModule extends Module { + /** + * @param {string} shareScope shared scope name + * @param {string} name shared key + * @param {string | false} version version + * @param {string} request request to the provided module + * @param {boolean} eager include the module in sync way + */ + constructor(shareScope, name, version, request, eager) { + super(WEBPACK_MODULE_TYPE_PROVIDE); + this._shareScope = shareScope; + this._name = name; + this._version = version; + this._request = request; + this._eager = eager; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `provide module (${this._shareScope}) ${this._name}@${this._version} = ${this._request}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `provide shared module (${this._shareScope}) ${this._name}@${ + this._version + } = ${requestShortener.shorten(this._request)}`; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/provide/${ + this._shareScope + }/${this._name}`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {BuildCallback} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + strict: true + }; + + this.clearDependenciesAndBlocks(); + const dep = new ProvideForSharedDependency(this._request); + if (this._eager) { + this.addDependency(dep); + } else { + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); + } + + callback(); + } + + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return 42; + } + + /** + * @returns {SourceTypes} types available (do not mutate) + */ + getSourceTypes() { + return SHARED_INIT_TYPES; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ runtimeTemplate, chunkGraph }) { + const runtimeRequirements = new Set([RuntimeGlobals.initializeSharing]); + const code = `register(${JSON.stringify(this._name)}, ${JSON.stringify( + this._version || "0" + )}, ${ + this._eager + ? runtimeTemplate.syncModuleFactory({ + dependency: this.dependencies[0], + chunkGraph, + request: this._request, + runtimeRequirements + }) + : runtimeTemplate.asyncModuleFactory({ + block: this.blocks[0], + chunkGraph, + request: this._request, + runtimeRequirements + }) + }${this._eager ? ", 1" : ""});`; + const sources = new Map(); + const data = new Map(); + data.set("share-init", [ + { + shareScope: this._shareScope, + initStage: 10, + init: code + } + ]); + return { sources, data, runtimeRequirements }; + } + + /** + * @param {ObjectSerializerContext} context context + */ + serialize(context) { + const { write } = context; + write(this._shareScope); + write(this._name); + write(this._version); + write(this._request); + write(this._eager); + super.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {ProvideSharedModule} deserialize fallback dependency + */ + static deserialize(context) { + const { read } = context; + const obj = new ProvideSharedModule(read(), read(), read(), read(), read()); + obj.deserialize(context); + return obj; + } +} + +makeSerializable( + ProvideSharedModule, + "webpack/lib/sharing/ProvideSharedModule" +); + +module.exports = ProvideSharedModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedModuleFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedModuleFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..b10b8f3996e7a1d4ae8a2adb2d4391910bac89fd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedModuleFactory.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy +*/ + +"use strict"; + +const ModuleFactory = require("../ModuleFactory"); +const ProvideSharedModule = require("./ProvideSharedModule"); + +/** @typedef {import("../ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ProvideSharedDependency")} ProvideSharedDependency */ + +class ProvideSharedModuleFactory extends ModuleFactory { + /** + * @param {ModuleFactoryCreateData} data data object + * @param {ModuleFactoryCallback} callback callback + * @returns {void} + */ + create(data, callback) { + const dep = + /** @type {ProvideSharedDependency} */ + (data.dependencies[0]); + callback(null, { + module: new ProvideSharedModule( + dep.shareScope, + dep.name, + dep.version, + dep.request, + dep.eager + ) + }); + } +} + +module.exports = ProvideSharedModuleFactory; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..5ad4c3d08eabe23d6c55c2961fe0082d6167468e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ProvideSharedPlugin.js @@ -0,0 +1,249 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy +*/ + +"use strict"; + +const WebpackError = require("../WebpackError"); +const { parseOptions } = require("../container/options"); +const createSchemaValidation = require("../util/create-schema-validation"); +const ProvideForSharedDependency = require("./ProvideForSharedDependency"); +const ProvideSharedDependency = require("./ProvideSharedDependency"); +const ProvideSharedModuleFactory = require("./ProvideSharedModuleFactory"); + +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../NormalModuleFactory").NormalModuleCreateData} NormalModuleCreateData */ + +const validate = createSchemaValidation( + require("../../schemas/plugins/sharing/ProvideSharedPlugin.check"), + () => require("../../schemas/plugins/sharing/ProvideSharedPlugin.json"), + { + name: "Provide Shared Plugin", + baseDataPath: "options" + } +); + +/** + * @typedef {object} ProvideOptions + * @property {string} shareKey + * @property {string} shareScope + * @property {string | undefined | false} version + * @property {boolean} eager + */ + +/** @typedef {Map} ResolvedProvideMap */ + +const PLUGIN_NAME = "ProvideSharedPlugin"; + +class ProvideSharedPlugin { + /** + * @param {ProvideSharedPluginOptions} options options + */ + constructor(options) { + validate(options); + + this._provides = /** @type {[string, ProvideOptions][]} */ ( + parseOptions( + options.provides, + (item) => { + if (Array.isArray(item)) { + throw new Error("Unexpected array of provides"); + } + /** @type {ProvideOptions} */ + const result = { + shareKey: item, + version: undefined, + shareScope: options.shareScope || "default", + eager: false + }; + return result; + }, + (item) => ({ + shareKey: item.shareKey, + version: item.version, + shareScope: item.shareScope || options.shareScope || "default", + eager: Boolean(item.eager) + }) + ) + ); + this._provides.sort(([a], [b]) => { + if (a < b) return -1; + if (b < a) return 1; + return 0; + }); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + /** @type {WeakMap} */ + const compilationData = new WeakMap(); + + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + /** @type {ResolvedProvideMap} */ + const resolvedProvideMap = new Map(); + /** @type {Map} */ + const matchProvides = new Map(); + /** @type {Map} */ + const prefixMatchProvides = new Map(); + for (const [request, config] of this._provides) { + if (/^(\/|[A-Za-z]:\\|\\\\|\.\.?(\/|$))/.test(request)) { + // relative request + resolvedProvideMap.set(request, { + config, + version: config.version + }); + } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { + // absolute path + resolvedProvideMap.set(request, { + config, + version: config.version + }); + } else if (request.endsWith("/")) { + // module request prefix + prefixMatchProvides.set(request, config); + } else { + // module request + matchProvides.set(request, config); + } + } + compilationData.set(compilation, resolvedProvideMap); + /** + * @param {string} key key + * @param {ProvideOptions} config config + * @param {NormalModuleCreateData["resource"]} resource resource + * @param {NormalModuleCreateData["resourceResolveData"]} resourceResolveData resource resolve data + */ + const provideSharedModule = ( + key, + config, + resource, + resourceResolveData + ) => { + let version = config.version; + if (version === undefined) { + let details = ""; + if (!resourceResolveData) { + details = "No resolve data provided from resolver."; + } else { + const descriptionFileData = + resourceResolveData.descriptionFileData; + if (!descriptionFileData) { + details = + "No description file (usually package.json) found. Add description file with name and version, or manually specify version in shared config."; + } else if (!descriptionFileData.version) { + details = `No version in description file (usually package.json). Add version to description file ${resourceResolveData.descriptionFilePath}, or manually specify version in shared config.`; + } else { + version = /** @type {string | false | undefined} */ ( + descriptionFileData.version + ); + } + } + if (!version) { + const error = new WebpackError( + `No version specified and unable to automatically determine one. ${details}` + ); + error.file = `shared module ${key} -> ${resource}`; + compilation.warnings.push(error); + } + } + resolvedProvideMap.set(resource, { + config, + version + }); + }; + normalModuleFactory.hooks.module.tap( + PLUGIN_NAME, + (module, { resource, resourceResolveData }, resolveData) => { + if (resolvedProvideMap.has(/** @type {string} */ (resource))) { + return module; + } + const { request } = resolveData; + { + const config = matchProvides.get(request); + if (config !== undefined) { + provideSharedModule( + request, + config, + /** @type {string} */ (resource), + resourceResolveData + ); + resolveData.cacheable = false; + } + } + for (const [prefix, config] of prefixMatchProvides) { + if (request.startsWith(prefix)) { + const remainder = request.slice(prefix.length); + provideSharedModule( + /** @type {string} */ (resource), + { + ...config, + shareKey: config.shareKey + remainder + }, + /** @type {string} */ (resource), + resourceResolveData + ); + resolveData.cacheable = false; + } + } + return module; + } + ); + } + ); + compiler.hooks.finishMake.tapPromise(PLUGIN_NAME, (compilation) => { + const resolvedProvideMap = compilationData.get(compilation); + if (!resolvedProvideMap) return Promise.resolve(); + return Promise.all( + Array.from( + resolvedProvideMap, + ([resource, { config, version }]) => + new Promise((resolve, reject) => { + compilation.addInclude( + compiler.context, + new ProvideSharedDependency( + config.shareScope, + config.shareKey, + version || false, + resource, + config.eager + ), + { + name: undefined + }, + (err) => { + if (err) return reject(err); + resolve(null); + } + ); + }) + ) + ).then(() => {}); + }); + + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + ProvideForSharedDependency, + normalModuleFactory + ); + + compilation.dependencyFactories.set( + ProvideSharedDependency, + new ProvideSharedModuleFactory() + ); + } + ); + } +} + +module.exports = ProvideSharedPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/SharePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/SharePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d447cdbc74279e5968389aab82ef84bc83054c5f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/SharePlugin.js @@ -0,0 +1,93 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy +*/ + +"use strict"; + +const { parseOptions } = require("../container/options"); +const ConsumeSharedPlugin = require("./ConsumeSharedPlugin"); +const ProvideSharedPlugin = require("./ProvideSharedPlugin"); +const { isRequiredVersion } = require("./utils"); + +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvidesConfig} ProvidesConfig */ +/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharePluginOptions} SharePluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharedConfig} SharedConfig */ +/** @typedef {import("../Compiler")} Compiler */ + +class SharePlugin { + /** + * @param {SharePluginOptions} options options + */ + constructor(options) { + /** @type {[string, SharedConfig][]} */ + const sharedOptions = parseOptions( + options.shared, + (item, key) => { + if (typeof item !== "string") { + throw new Error("Unexpected array in shared"); + } + /** @type {SharedConfig} */ + const config = + item === key || !isRequiredVersion(item) + ? { + import: item + } + : { + import: key, + requiredVersion: item + }; + return config; + }, + (item) => item + ); + /** @type {Record[]} */ + const consumes = sharedOptions.map(([key, options]) => ({ + [key]: { + import: options.import, + shareKey: options.shareKey || key, + shareScope: options.shareScope, + requiredVersion: options.requiredVersion, + strictVersion: options.strictVersion, + singleton: options.singleton, + packageName: options.packageName, + eager: options.eager + } + })); + /** @type {Record[]} */ + const provides = sharedOptions + .filter(([, options]) => options.import !== false) + .map(([key, options]) => ({ + [options.import || key]: { + shareKey: options.shareKey || key, + shareScope: options.shareScope, + version: options.version, + eager: options.eager + } + })); + this._shareScope = options.shareScope; + this._consumes = consumes; + this._provides = provides; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + new ConsumeSharedPlugin({ + shareScope: this._shareScope, + consumes: this._consumes + }).apply(compiler); + new ProvideSharedPlugin({ + shareScope: this._shareScope, + provides: this._provides + }).apply(compiler); + } +} + +module.exports = SharePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ShareRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ShareRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..8b4574fa2abce39214006ea1659554cc4b0302e7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/ShareRuntimeModule.js @@ -0,0 +1,149 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const { + compareModulesByIdentifier, + compareStrings +} = require("../util/comparators"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ + +class ShareRuntimeModule extends RuntimeModule { + constructor() { + super("sharing"); + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { + runtimeTemplate, + codeGenerationResults, + outputOptions: { uniqueName, ignoreBrowserWarnings } + } = compilation; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + /** @type {Map>>} */ + const initCodePerScope = new Map(); + for (const chunk of /** @type {Chunk} */ ( + this.chunk + ).getAllReferencedChunks()) { + const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "share-init", + compareModulesByIdentifier + ); + if (!modules) continue; + for (const m of modules) { + const data = codeGenerationResults.getData( + m, + chunk.runtime, + "share-init" + ); + if (!data) continue; + for (const item of data) { + const { shareScope, initStage, init } = item; + let stages = initCodePerScope.get(shareScope); + if (stages === undefined) { + initCodePerScope.set(shareScope, (stages = new Map())); + } + let list = stages.get(initStage || 0); + if (list === undefined) { + stages.set(initStage || 0, (list = new Set())); + } + list.add(init); + } + } + } + return Template.asString([ + `${RuntimeGlobals.shareScopeMap} = {};`, + "var initPromises = {};", + "var initTokens = {};", + `${RuntimeGlobals.initializeSharing} = ${runtimeTemplate.basicFunction( + "name, initScope", + [ + "if(!initScope) initScope = [];", + "// handling circular init calls", + "var initToken = initTokens[name];", + "if(!initToken) initToken = initTokens[name] = {};", + "if(initScope.indexOf(initToken) >= 0) return;", + "initScope.push(initToken);", + "// only runs once", + "if(initPromises[name]) return initPromises[name];", + "// creates a new share scope if needed", + `if(!${RuntimeGlobals.hasOwnProperty}(${RuntimeGlobals.shareScopeMap}, name)) ${RuntimeGlobals.shareScopeMap}[name] = {};`, + "// runs all init snippets from all modules reachable", + `var scope = ${RuntimeGlobals.shareScopeMap}[name];`, + `var warn = ${ + ignoreBrowserWarnings + ? runtimeTemplate.basicFunction("", "") + : runtimeTemplate.basicFunction("msg", [ + 'if (typeof console !== "undefined" && console.warn) console.warn(msg);' + ]) + };`, + `var uniqueName = ${JSON.stringify(uniqueName || undefined)};`, + `var register = ${runtimeTemplate.basicFunction( + "name, version, factory, eager", + [ + "var versions = scope[name] = scope[name] || {};", + "var activeVersion = versions[version];", + "if(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager };" + ] + )};`, + `var initExternal = ${runtimeTemplate.basicFunction("id", [ + `var handleError = ${runtimeTemplate.expressionFunction( + 'warn("Initialization of sharing external failed: " + err)', + "err" + )};`, + "try {", + Template.indent([ + `var module = ${RuntimeGlobals.require}(id);`, + "if(!module) return;", + `var initFn = ${runtimeTemplate.returningFunction( + `module && module.init && module.init(${RuntimeGlobals.shareScopeMap}[name], initScope)`, + "module" + )}`, + "if(module.then) return promises.push(module.then(initFn, handleError));", + "var initResult = initFn(module);", + "if(initResult && initResult.then) return promises.push(initResult['catch'](handleError));" + ]), + "} catch(err) { handleError(err); }" + ])}`, + "var promises = [];", + "switch(name) {", + ...[...initCodePerScope] + .sort(([a], [b]) => compareStrings(a, b)) + .map(([name, stages]) => + Template.indent([ + `case ${JSON.stringify(name)}: {`, + Template.indent( + [...stages] + .sort(([a], [b]) => a - b) + .map(([, initCode]) => Template.asString([...initCode])) + ), + "}", + "break;" + ]) + ), + "}", + "if(!promises.length) return initPromises[name] = 1;", + `return initPromises[name] = Promise.all(promises).then(${runtimeTemplate.returningFunction( + "initPromises[name] = 1" + )});` + ] + )};` + ]); + } +} + +module.exports = ShareRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/resolveMatchedConfigs.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/resolveMatchedConfigs.js new file mode 100644 index 0000000000000000000000000000000000000000..7fd74655218a31af0fef04204522b5ab003eb7eb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/resolveMatchedConfigs.js @@ -0,0 +1,92 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ModuleNotFoundError = require("../ModuleNotFoundError"); +const LazySet = require("../util/LazySet"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ + +/** + * @template T + * @typedef {object} MatchedConfigs + * @property {Map} resolved + * @property {Map} unresolved + * @property {Map} prefixed + */ + +/** @type {ResolveOptionsWithDependencyType} */ +const RESOLVE_OPTIONS = { dependencyType: "esm" }; + +/** + * @template T + * @param {Compilation} compilation the compilation + * @param {[string, T][]} configs to be processed configs + * @returns {Promise>} resolved matchers + */ +module.exports.resolveMatchedConfigs = (compilation, configs) => { + /** @type {Map} */ + const resolved = new Map(); + /** @type {Map} */ + const unresolved = new Map(); + /** @type {Map} */ + const prefixed = new Map(); + const resolveContext = { + /** @type {LazySet} */ + fileDependencies: new LazySet(), + /** @type {LazySet} */ + contextDependencies: new LazySet(), + /** @type {LazySet} */ + missingDependencies: new LazySet() + }; + const resolver = compilation.resolverFactory.get("normal", RESOLVE_OPTIONS); + const context = compilation.compiler.context; + + return Promise.all( + // eslint-disable-next-line array-callback-return + configs.map(([request, config]) => { + if (/^\.\.?(\/|$)/.test(request)) { + // relative request + return new Promise((resolve) => { + resolver.resolve( + {}, + context, + request, + resolveContext, + (err, result) => { + if (err || result === false) { + err = err || new Error(`Can't resolve ${request}`); + compilation.errors.push( + new ModuleNotFoundError(null, err, { + name: `shared module ${request}` + }) + ); + return resolve(null); + } + resolved.set(/** @type {string} */ (result), config); + resolve(null); + } + ); + }); + } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { + // absolute path + resolved.set(request, config); + } else if (request.endsWith("/")) { + // module request prefix + prefixed.set(request, config); + } else { + // module request + unresolved.set(request, config); + } + }) + ).then(() => { + compilation.contextDependencies.addAll(resolveContext.contextDependencies); + compilation.fileDependencies.addAll(resolveContext.fileDependencies); + compilation.missingDependencies.addAll(resolveContext.missingDependencies); + return { resolved, unresolved, prefixed }; + }); +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/utils.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..26eac0ac6fbcf84e6aa2adca94a4c1017ff8b44d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/sharing/utils.js @@ -0,0 +1,425 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { dirname, join, readJson } = require("../util/fs"); + +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("../util/fs").JsonObject} JsonObject */ +/** @typedef {import("../util/fs").JsonPrimitive} JsonPrimitive */ + +// Extreme shorthand only for github. eg: foo/bar +const RE_URL_GITHUB_EXTREME_SHORT = /^[^/@:.\s][^/@:\s]*\/[^@:\s]*[^/@:\s]#\S+/; + +// Short url with specific protocol. eg: github:foo/bar +const RE_GIT_URL_SHORT = /^(github|gitlab|bitbucket|gist):\/?[^/.]+\/?/i; + +// Currently supported protocols +const RE_PROTOCOL = + /^((git\+)?(ssh|https?|file)|git|github|gitlab|bitbucket|gist):$/i; + +// Has custom protocol +const RE_CUSTOM_PROTOCOL = /^((git\+)?(ssh|https?|file)|git):\/\//i; + +// Valid hash format for npm / yarn ... +const RE_URL_HASH_VERSION = /#(?:semver:)?(.+)/; + +// Simple hostname validate +const RE_HOSTNAME = /^(?:[^/.]+(\.[^/]+)+|localhost)$/; + +// For hostname with colon. eg: ssh://user@github.com:foo/bar +const RE_HOSTNAME_WITH_COLON = + /([^/@#:.]+(?:\.[^/@#:.]+)+|localhost):([^#/0-9]+)/; + +// Reg for url without protocol +const RE_NO_PROTOCOL = /^([^/@#:.]+(?:\.[^/@#:.]+)+)/; + +// RegExp for version string +const VERSION_PATTERN_REGEXP = /^([\d^=v<>~]|[*xX]$)/; + +// Specific protocol for short url without normal hostname +const PROTOCOLS_FOR_SHORT = [ + "github:", + "gitlab:", + "bitbucket:", + "gist:", + "file:" +]; + +// Default protocol for git url +const DEF_GIT_PROTOCOL = "git+ssh://"; + +// thanks to https://github.com/npm/hosted-git-info/blob/latest/git-host-info.js +const extractCommithashByDomain = { + /** + * @param {string} pathname pathname + * @param {string} hash hash + * @returns {string | undefined} hash + */ + "github.com": (pathname, hash) => { + let [, user, project, type, commithash] = pathname.split("/", 5); + if (type && type !== "tree") { + return; + } + + commithash = !type ? hash : `#${commithash}`; + + if (project && project.endsWith(".git")) { + project = project.slice(0, -4); + } + + if (!user || !project) { + return; + } + + return commithash; + }, + /** + * @param {string} pathname pathname + * @param {string} hash hash + * @returns {string | undefined} hash + */ + "gitlab.com": (pathname, hash) => { + const path = pathname.slice(1); + if (path.includes("/-/") || path.includes("/archive.tar.gz")) { + return; + } + + const segments = path.split("/"); + let project = /** @type {string} */ (segments.pop()); + if (project.endsWith(".git")) { + project = project.slice(0, -4); + } + + const user = segments.join("/"); + if (!user || !project) { + return; + } + + return hash; + }, + /** + * @param {string} pathname pathname + * @param {string} hash hash + * @returns {string | undefined} hash + */ + "bitbucket.org": (pathname, hash) => { + let [, user, project, aux] = pathname.split("/", 4); + if (["get"].includes(aux)) { + return; + } + + if (project && project.endsWith(".git")) { + project = project.slice(0, -4); + } + + if (!user || !project) { + return; + } + + return hash; + }, + /** + * @param {string} pathname pathname + * @param {string} hash hash + * @returns {string | undefined} hash + */ + "gist.github.com": (pathname, hash) => { + let [, user, project, aux] = pathname.split("/", 4); + if (aux === "raw") { + return; + } + + if (!project) { + if (!user) { + return; + } + + project = user; + } + + if (project.endsWith(".git")) { + project = project.slice(0, -4); + } + + return hash; + } +}; + +/** + * extract commit hash from parsed url + * @inner + * @param {URL} urlParsed parsed url + * @returns {string} commithash + */ +function getCommithash(urlParsed) { + let { hostname, pathname, hash } = urlParsed; + hostname = hostname.replace(/^www\./, ""); + + try { + hash = decodeURIComponent(hash); + // eslint-disable-next-line no-empty + } catch (_err) {} + + if ( + extractCommithashByDomain[ + /** @type {keyof extractCommithashByDomain} */ (hostname) + ] + ) { + return ( + extractCommithashByDomain[ + /** @type {keyof extractCommithashByDomain} */ (hostname) + ](pathname, hash) || "" + ); + } + + return hash; +} + +/** + * make url right for URL parse + * @inner + * @param {string} gitUrl git url + * @returns {string} fixed url + */ +function correctUrl(gitUrl) { + // like: + // proto://hostname.com:user/repo -> proto://hostname.com/user/repo + return gitUrl.replace(RE_HOSTNAME_WITH_COLON, "$1/$2"); +} + +/** + * make url protocol right for URL parse + * @inner + * @param {string} gitUrl git url + * @returns {string} fixed url + */ +function correctProtocol(gitUrl) { + // eg: github:foo/bar#v1.0. Should not add double slash, in case of error parsed `pathname` + if (RE_GIT_URL_SHORT.test(gitUrl)) { + return gitUrl; + } + + // eg: user@github.com:foo/bar + if (!RE_CUSTOM_PROTOCOL.test(gitUrl)) { + return `${DEF_GIT_PROTOCOL}${gitUrl}`; + } + + return gitUrl; +} + +/** + * extract git dep version from hash + * @inner + * @param {string} hash hash + * @returns {string} git dep version + */ +function getVersionFromHash(hash) { + const matched = hash.match(RE_URL_HASH_VERSION); + + return (matched && matched[1]) || ""; +} + +/** + * if string can be decoded + * @inner + * @param {string} str str to be checked + * @returns {boolean} if can be decoded + */ +function canBeDecoded(str) { + try { + decodeURIComponent(str); + } catch (_err) { + return false; + } + + return true; +} + +/** + * get right dep version from git url + * @inner + * @param {string} gitUrl git url + * @returns {string} dep version + */ +function getGitUrlVersion(gitUrl) { + const oriGitUrl = gitUrl; + // github extreme shorthand + gitUrl = RE_URL_GITHUB_EXTREME_SHORT.test(gitUrl) + ? `github:${gitUrl}` + : correctProtocol(gitUrl); + + gitUrl = correctUrl(gitUrl); + + let parsed; + try { + parsed = new URL(gitUrl); + // eslint-disable-next-line no-empty + } catch (_err) {} + + if (!parsed) { + return ""; + } + + const { protocol, hostname, pathname, username, password } = parsed; + if (!RE_PROTOCOL.test(protocol)) { + return ""; + } + + // pathname shouldn't be empty or URL malformed + if (!pathname || !canBeDecoded(pathname)) { + return ""; + } + + // without protocol, there should have auth info + if (RE_NO_PROTOCOL.test(oriGitUrl) && !username && !password) { + return ""; + } + + if (!PROTOCOLS_FOR_SHORT.includes(protocol.toLowerCase())) { + if (!RE_HOSTNAME.test(hostname)) { + return ""; + } + + const commithash = getCommithash(parsed); + return getVersionFromHash(commithash) || commithash; + } + + // for protocol short + return getVersionFromHash(gitUrl); +} + +/** @typedef {{ data: JsonObject, path: string }} DescriptionFile */ + +/** + * @param {InputFileSystem} fs file system + * @param {string} directory directory to start looking into + * @param {string[]} descriptionFiles possible description filenames + * @param {(err?: Error | null, descriptionFile?: DescriptionFile, paths?: string[]) => void} callback callback + * @param {(descriptionFile?: DescriptionFile) => boolean} satisfiesDescriptionFileData file data compliance check + * @param {Set} checkedFilePaths set of file paths that have been checked + */ +const getDescriptionFile = ( + fs, + directory, + descriptionFiles, + callback, + satisfiesDescriptionFileData, + checkedFilePaths = new Set() +) => { + let i = 0; + + const satisfiesDescriptionFileDataInternal = { + check: satisfiesDescriptionFileData, + checkedFilePaths + }; + + const tryLoadCurrent = () => { + if (i >= descriptionFiles.length) { + const parentDirectory = dirname(fs, directory); + if (!parentDirectory || parentDirectory === directory) { + return callback(null, undefined, [ + ...satisfiesDescriptionFileDataInternal.checkedFilePaths + ]); + } + return getDescriptionFile( + fs, + parentDirectory, + descriptionFiles, + callback, + satisfiesDescriptionFileDataInternal.check, + satisfiesDescriptionFileDataInternal.checkedFilePaths + ); + } + const filePath = join(fs, directory, descriptionFiles[i]); + readJson(fs, filePath, (err, data) => { + if (err) { + if ("code" in err && err.code === "ENOENT") { + i++; + return tryLoadCurrent(); + } + return callback(err); + } + if (!data || typeof data !== "object" || Array.isArray(data)) { + return callback( + new Error(`Description file ${filePath} is not an object`) + ); + } + if ( + typeof satisfiesDescriptionFileDataInternal.check === "function" && + !satisfiesDescriptionFileDataInternal.check({ data, path: filePath }) + ) { + i++; + satisfiesDescriptionFileDataInternal.checkedFilePaths.add(filePath); + return tryLoadCurrent(); + } + callback(null, { data, path: filePath }); + }); + }; + tryLoadCurrent(); +}; + +module.exports.getDescriptionFile = getDescriptionFile; + +/** + * @param {JsonObject} data description file data i.e.: package.json + * @param {string} packageName name of the dependency + * @returns {string | undefined} normalized version + */ +const getRequiredVersionFromDescriptionFile = (data, packageName) => { + const dependencyTypes = [ + "optionalDependencies", + "dependencies", + "peerDependencies", + "devDependencies" + ]; + + for (const dependencyType of dependencyTypes) { + const dependency = /** @type {JsonObject} */ (data[dependencyType]); + if ( + dependency && + typeof dependency === "object" && + packageName in dependency + ) { + return normalizeVersion( + /** @type {Exclude} */ ( + dependency[packageName] + ) + ); + } + } +}; + +module.exports.getRequiredVersionFromDescriptionFile = + getRequiredVersionFromDescriptionFile; + +/** + * @param {string} str maybe required version + * @returns {boolean} true, if it looks like a version + */ +function isRequiredVersion(str) { + return VERSION_PATTERN_REGEXP.test(str); +} + +module.exports.isRequiredVersion = isRequiredVersion; + +/** + * @see https://docs.npmjs.com/cli/v7/configuring-npm/package-json#urls-as-dependencies + * @param {string} versionDesc version to be normalized + * @returns {string} normalized version + */ +function normalizeVersion(versionDesc) { + versionDesc = (versionDesc && versionDesc.trim()) || ""; + + if (isRequiredVersion(versionDesc)) { + return versionDesc; + } + + // add handle for URL Dependencies + return getGitUrlVersion(versionDesc.toLowerCase()); +} + +module.exports.normalizeVersion = normalizeVersion; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/DefaultStatsFactoryPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/DefaultStatsFactoryPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..28d3d333f6d00479f6d132a4d912f90a11363d70 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/DefaultStatsFactoryPlugin.js @@ -0,0 +1,2696 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const { WEBPACK_MODULE_TYPE_RUNTIME } = require("../ModuleTypeConstants"); +const ModuleDependency = require("../dependencies/ModuleDependency"); +const formatLocation = require("../formatLocation"); +const { LogType } = require("../logging/Logger"); +const AggressiveSplittingPlugin = require("../optimize/AggressiveSplittingPlugin"); +const SizeLimitsPlugin = require("../performance/SizeLimitsPlugin"); +const { countIterable } = require("../util/IterableHelpers"); +const { + compareChunksById, + compareIds, + compareLocations, + compareModulesByIdentifier, + compareNumbers, + compareSelect, + concatComparators +} = require("../util/comparators"); +const { makePathsRelative, parseResource } = require("../util/identifier"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Chunk").ChunkId} ChunkId */ +/** @typedef {import("../Chunk").ChunkName} ChunkName */ +/** @typedef {import("../ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").Asset} Asset */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compilation").ExcludeModulesType} ExcludeModulesType */ +/** @typedef {import("../Compilation").KnownNormalizedStatsOptions} KnownNormalizedStatsOptions */ +/** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleProfile")} ModuleProfile */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./StatsFactory")} StatsFactory */ +/** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */ + +/** + * @template T + * @typedef {import("../util/comparators").Comparator} Comparator + */ + +/** + * @template T, R + * @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig + */ + +/** @typedef {KnownStatsCompilation & Record} StatsCompilation */ +/** + * @typedef {object} KnownStatsCompilation + * @property {EXPECTED_ANY=} env + * @property {string=} name + * @property {string=} hash + * @property {string=} version + * @property {number=} time + * @property {number=} builtAt + * @property {boolean=} needAdditionalPass + * @property {string=} publicPath + * @property {string=} outputPath + * @property {Record=} assetsByChunkName + * @property {StatsAsset[]=} assets + * @property {number=} filteredAssets + * @property {StatsChunk[]=} chunks + * @property {StatsModule[]=} modules + * @property {number=} filteredModules + * @property {Record=} entrypoints + * @property {Record=} namedChunkGroups + * @property {StatsError[]=} errors + * @property {number=} errorsCount + * @property {StatsError[]=} warnings + * @property {number=} warningsCount + * @property {StatsCompilation[]=} children + * @property {Record=} logging + * @property {number=} filteredWarningDetailsCount + * @property {number=} filteredErrorDetailsCount + */ + +/** @typedef {KnownStatsLogging & Record} StatsLogging */ +/** + * @typedef {object} KnownStatsLogging + * @property {StatsLoggingEntry[]} entries + * @property {number} filteredEntries + * @property {boolean} debug + */ + +/** @typedef {KnownStatsLoggingEntry & Record} StatsLoggingEntry */ +/** + * @typedef {object} KnownStatsLoggingEntry + * @property {string} type + * @property {string=} message + * @property {string[]=} trace + * @property {StatsLoggingEntry[]=} children + * @property {EXPECTED_ANY[]=} args + * @property {number=} time + */ + +/** @typedef {KnownStatsAsset & Record} StatsAsset */ +/** @typedef {ChunkId} KnownStatsAssetChunk */ +/** @typedef {ChunkName} KnownStatsAssetChunkName */ +/** @typedef {string} KnownStatsAssetChunkIdHint */ +/** + * @typedef {object} KnownStatsAsset + * @property {string} type + * @property {string} name + * @property {AssetInfo} info + * @property {number} size + * @property {boolean} emitted + * @property {boolean} comparedForEmit + * @property {boolean} cached + * @property {StatsAsset[]=} related + * @property {KnownStatsAssetChunk[]=} chunks + * @property {KnownStatsAssetChunkName[]=} chunkNames + * @property {KnownStatsAssetChunkIdHint[]=} chunkIdHints + * @property {KnownStatsAssetChunk[]=} auxiliaryChunks + * @property {KnownStatsAssetChunkName[]=} auxiliaryChunkNames + * @property {KnownStatsAssetChunkIdHint[]=} auxiliaryChunkIdHints + * @property {number=} filteredRelated + * @property {boolean=} isOverSizeLimit + */ + +/** @typedef {KnownStatsChunkGroup & Record} StatsChunkGroup */ +/** + * @typedef {object} KnownStatsChunkGroup + * @property {(string | null)=} name + * @property {(string | number)[]=} chunks + * @property {({ name: string, size?: number })[]=} assets + * @property {number=} filteredAssets + * @property {number=} assetsSize + * @property {({ name: string, size?: number })[]=} auxiliaryAssets + * @property {number=} filteredAuxiliaryAssets + * @property {number=} auxiliaryAssetsSize + * @property {{ [x: string]: StatsChunkGroup[] }=} children + * @property {{ [x: string]: string[] }=} childAssets + * @property {boolean=} isOverSizeLimit + */ + +/** @typedef {Module[]} ModuleIssuerPath */ +/** @typedef {KnownStatsModule & Record} StatsModule */ +/** + * @typedef {object} KnownStatsModule + * @property {string=} type + * @property {string=} moduleType + * @property {(string | null)=} layer + * @property {string=} identifier + * @property {string=} name + * @property {(string | null)=} nameForCondition + * @property {number=} index + * @property {number=} preOrderIndex + * @property {number=} index2 + * @property {number=} postOrderIndex + * @property {number=} size + * @property {{ [x: string]: number }=} sizes + * @property {boolean=} cacheable + * @property {boolean=} built + * @property {boolean=} codeGenerated + * @property {boolean=} buildTimeExecuted + * @property {boolean=} cached + * @property {boolean=} optional + * @property {boolean=} orphan + * @property {string | number=} id + * @property {string | number | null=} issuerId + * @property {(string | number)[]=} chunks + * @property {(string | number)[]=} assets + * @property {boolean=} dependent + * @property {(string | null)=} issuer + * @property {(string | null)=} issuerName + * @property {StatsModuleIssuer[] | null=} issuerPath + * @property {boolean=} failed + * @property {number=} errors + * @property {number=} warnings + * @property {StatsProfile=} profile + * @property {StatsModuleReason[]=} reasons + * @property {(boolean | null | string[])=} usedExports + * @property {(string[] | null)=} providedExports + * @property {string[]=} optimizationBailout + * @property {(number | null)=} depth + * @property {StatsModule[]=} modules + * @property {number=} filteredModules + * @property {ReturnType=} source + */ + +/** @typedef {KnownStatsProfile & Record} StatsProfile */ +/** + * @typedef {object} KnownStatsProfile + * @property {number} total + * @property {number} resolving + * @property {number} restoring + * @property {number} building + * @property {number} integration + * @property {number} storing + * @property {number} additionalResolving + * @property {number} additionalIntegration + * @property {number} factory + * @property {number} dependencies + */ + +/** @typedef {KnownStatsModuleIssuer & Record} StatsModuleIssuer */ +/** + * @typedef {object} KnownStatsModuleIssuer + * @property {string} identifier + * @property {string} name + * @property {(string|number)=} id + * @property {StatsProfile} profile + */ + +/** @typedef {KnownStatsModuleReason & Record} StatsModuleReason */ +/** + * @typedef {object} KnownStatsModuleReason + * @property {string | null} moduleIdentifier + * @property {string | null} module + * @property {string | null} moduleName + * @property {string | null} resolvedModuleIdentifier + * @property {string | null} resolvedModule + * @property {string | null} type + * @property {boolean} active + * @property {string | null} explanation + * @property {string | null} userRequest + * @property {(string | null)=} loc + * @property {(string | number | null)=} moduleId + * @property {(string | number | null)=} resolvedModuleId + */ + +/** @typedef {KnownStatsChunk & Record} StatsChunk */ +/** + * @typedef {object} KnownStatsChunk + * @property {boolean} rendered + * @property {boolean} initial + * @property {boolean} entry + * @property {boolean} recorded + * @property {string=} reason + * @property {number} size + * @property {Record} sizes + * @property {string[]} names + * @property {string[]} idHints + * @property {string[]=} runtime + * @property {string[]} files + * @property {string[]} auxiliaryFiles + * @property {string} hash + * @property {Record} childrenByOrder + * @property {(string|number)=} id + * @property {(string|number)[]=} siblings + * @property {(string|number)[]=} parents + * @property {(string|number)[]=} children + * @property {StatsModule[]=} modules + * @property {number=} filteredModules + * @property {StatsChunkOrigin[]=} origins + */ + +/** @typedef {KnownStatsChunkOrigin & Record} StatsChunkOrigin */ +/** + * @typedef {object} KnownStatsChunkOrigin + * @property {string} module + * @property {string} moduleIdentifier + * @property {string} moduleName + * @property {string} loc + * @property {string} request + * @property {(string | number)=} moduleId + */ + +/** @typedef {KnownStatsModuleTraceItem & Record} StatsModuleTraceItem */ +/** + * @typedef {object} KnownStatsModuleTraceItem + * @property {string=} originIdentifier + * @property {string=} originName + * @property {string=} moduleIdentifier + * @property {string=} moduleName + * @property {StatsModuleTraceDependency[]=} dependencies + * @property {(string|number)=} originId + * @property {(string|number)=} moduleId + */ + +/** @typedef {KnownStatsModuleTraceDependency & Record} StatsModuleTraceDependency */ +/** + * @typedef {object} KnownStatsModuleTraceDependency + * @property {string=} loc + */ + +/** @typedef {KnownStatsError & Record} StatsError */ +/** + * @typedef {object} KnownStatsError + * @property {string} message + * @property {string=} chunkName + * @property {boolean=} chunkEntry + * @property {boolean=} chunkInitial + * @property {string=} file + * @property {string=} moduleIdentifier + * @property {string=} moduleName + * @property {string=} loc + * @property {ChunkId=} chunkId + * @property {string|number=} moduleId + * @property {StatsModuleTraceItem[]=} moduleTrace + * @property {string=} details + * @property {string=} stack + * @property {KnownStatsError=} cause + * @property {KnownStatsError[]=} errors + * @property {string=} compilerPath + */ + +/** @typedef {Asset & { type: string, related: PreprocessedAsset[] | undefined }} PreprocessedAsset */ + +/** + * @template T + * @template O + * @typedef {Record void>} ExtractorsByOption + */ + +/** @typedef {{ name: string, chunkGroup: ChunkGroup }} ChunkGroupInfoWithName */ +/** @typedef {{ origin: Module, module: Module }} ModuleTrace */ + +/** + * @typedef {object} SimpleExtractors + * @property {ExtractorsByOption} compilation + * @property {ExtractorsByOption} asset + * @property {ExtractorsByOption} asset$visible + * @property {ExtractorsByOption} chunkGroup + * @property {ExtractorsByOption} module + * @property {ExtractorsByOption} module$visible + * @property {ExtractorsByOption} moduleIssuer + * @property {ExtractorsByOption} profile + * @property {ExtractorsByOption} moduleReason + * @property {ExtractorsByOption} chunk + * @property {ExtractorsByOption} chunkOrigin + * @property {ExtractorsByOption} error + * @property {ExtractorsByOption} warning + * @property {ExtractorsByOption} cause + * @property {ExtractorsByOption} moduleTraceItem + * @property {ExtractorsByOption} moduleTraceDependency + */ + +/** + * @template T + * @template I + * @param {Iterable} items items to select from + * @param {(item: T) => Iterable} selector selector function to select values from item + * @returns {I[]} array of values + */ +const uniqueArray = (items, selector) => { + /** @type {Set} */ + const set = new Set(); + for (const item of items) { + for (const i of selector(item)) { + set.add(i); + } + } + return [...set]; +}; + +/** + * @template T + * @template I + * @param {Iterable} items items to select from + * @param {(item: T) => Iterable} selector selector function to select values from item + * @param {Comparator} comparator comparator function + * @returns {I[]} array of values + */ +const uniqueOrderedArray = (items, selector, comparator) => + uniqueArray(items, selector).sort(comparator); + +/** @template T @template R @typedef {{ [P in keyof T]: R }} MappedValues */ + +/** + * @template {object} T + * @template {object} R + * @param {T} obj object to be mapped + * @param {function(T[keyof T], keyof T): R} fn mapping function + * @returns {MappedValues} mapped object + */ +const mapObject = (obj, fn) => { + const newObj = Object.create(null); + for (const key of Object.keys(obj)) { + newObj[key] = fn( + obj[/** @type {keyof T} */ (key)], + /** @type {keyof T} */ (key) + ); + } + return newObj; +}; + +/** + * @template T + * @param {Compilation} compilation the compilation + * @param {(compilation: Compilation, name: string) => T[]} getItems get items + * @returns {number} total number + */ +const countWithChildren = (compilation, getItems) => { + let count = getItems(compilation, "").length; + for (const child of compilation.children) { + count += countWithChildren(child, (c, type) => + getItems(c, `.children[].compilation${type}`) + ); + } + return count; +}; + +/** @typedef {Error & { cause?: unknown }} ErrorWithCause */ +/** @typedef {Error & { errors: EXPECTED_ANY[] }} AggregateError */ + +/** @type {ExtractorsByOption} */ +const EXTRACT_ERROR = { + _: (object, error, context, { requestShortener }) => { + // TODO webpack 6 disallow strings in the errors/warnings list + if (typeof error === "string") { + object.message = error; + } else { + if (/** @type {WebpackError} */ (error).chunk) { + const chunk = /** @type {WebpackError} */ (error).chunk; + object.chunkName = + /** @type {string | undefined} */ + (chunk.name); + object.chunkEntry = chunk.hasRuntime(); + object.chunkInitial = chunk.canBeInitial(); + } + + if (/** @type {WebpackError} */ (error).file) { + object.file = /** @type {WebpackError} */ (error).file; + } + + if (/** @type {WebpackError} */ (error).module) { + object.moduleIdentifier = + /** @type {WebpackError} */ + (error).module.identifier(); + object.moduleName = + /** @type {WebpackError} */ + (error).module.readableIdentifier(requestShortener); + } + + if (/** @type {WebpackError} */ (error).loc) { + object.loc = formatLocation(/** @type {WebpackError} */ (error).loc); + } + + object.message = error.message; + } + }, + ids: (object, error, { compilation: { chunkGraph } }) => { + if (typeof error !== "string") { + if (/** @type {WebpackError} */ (error).chunk) { + object.chunkId = /** @type {ChunkId} */ ( + /** @type {WebpackError} */ + (error).chunk.id + ); + } + + if (/** @type {WebpackError} */ (error).module) { + object.moduleId = + /** @type {ModuleId} */ + (chunkGraph.getModuleId(/** @type {WebpackError} */ (error).module)); + } + } + }, + moduleTrace: (object, error, context, options, factory) => { + if ( + typeof error !== "string" && + /** @type {WebpackError} */ (error).module + ) { + const { + type, + compilation: { moduleGraph } + } = context; + /** @type {Set} */ + const visitedModules = new Set(); + /** @type {ModuleTrace[]} */ + const moduleTrace = []; + let current = /** @type {WebpackError} */ (error).module; + while (current) { + if (visitedModules.has(current)) break; // circular (technically impossible, but how knows) + visitedModules.add(current); + const origin = moduleGraph.getIssuer(current); + if (!origin) break; + moduleTrace.push({ origin, module: current }); + current = origin; + } + object.moduleTrace = factory.create( + `${type}.moduleTrace`, + moduleTrace, + context + ); + } + }, + errorDetails: ( + object, + error, + { type, compilation, cachedGetErrors }, + { errorDetails } + ) => { + if ( + typeof error !== "string" && + (errorDetails === true || + (type.endsWith(".error") && cachedGetErrors(compilation).length < 3)) + ) { + object.details = /** @type {WebpackError} */ (error).details; + } + }, + errorStack: (object, error) => { + if (typeof error !== "string") { + object.stack = error.stack; + } + }, + errorCause: (object, error, context, options, factory) => { + if ( + typeof error !== "string" && + /** @type {ErrorWithCause} */ (error).cause + ) { + const rawCause = /** @type {ErrorWithCause} */ (error).cause; + /** @type {Error} */ + const cause = + typeof rawCause === "string" + ? /** @type {Error} */ ({ message: rawCause }) + : /** @type {Error} */ (rawCause); + const { type } = context; + + object.cause = factory.create(`${type}.cause`, cause, context); + } + }, + errorErrors: (object, error, context, options, factory) => { + if ( + typeof error !== "string" && + /** @type {AggregateError} */ + (error).errors + ) { + const { type } = context; + object.errors = factory.create( + `${type}.errors`, + /** @type {Error[]} */ + (/** @type {AggregateError} */ (error).errors), + context + ); + } + } +}; + +/** @type {SimpleExtractors} */ +const SIMPLE_EXTRACTORS = { + compilation: { + _: (object, compilation, context, options) => { + if (!context.makePathsRelative) { + context.makePathsRelative = makePathsRelative.bindContextCache( + compilation.compiler.context, + compilation.compiler.root + ); + } + if (!context.cachedGetErrors) { + const map = new WeakMap(); + context.cachedGetErrors = (compilation) => + map.get(compilation) || + // eslint-disable-next-line no-sequences + ((errors) => (map.set(compilation, errors), errors))( + compilation.getErrors() + ); + } + if (!context.cachedGetWarnings) { + const map = new WeakMap(); + context.cachedGetWarnings = (compilation) => + map.get(compilation) || + // eslint-disable-next-line no-sequences + ((warnings) => (map.set(compilation, warnings), warnings))( + compilation.getWarnings() + ); + } + if (compilation.name) { + object.name = compilation.name; + } + if (compilation.needAdditionalPass) { + object.needAdditionalPass = true; + } + + const { logging, loggingDebug, loggingTrace } = options; + if (logging || (loggingDebug && loggingDebug.length > 0)) { + const util = require("util"); + + object.logging = {}; + let acceptedTypes; + let collapsedGroups = false; + switch (logging) { + case "error": + acceptedTypes = new Set([LogType.error]); + break; + case "warn": + acceptedTypes = new Set([LogType.error, LogType.warn]); + break; + case "info": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info + ]); + break; + case "log": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info, + LogType.log, + LogType.group, + LogType.groupEnd, + LogType.groupCollapsed, + LogType.clear + ]); + break; + case "verbose": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info, + LogType.log, + LogType.group, + LogType.groupEnd, + LogType.groupCollapsed, + LogType.profile, + LogType.profileEnd, + LogType.time, + LogType.status, + LogType.clear + ]); + collapsedGroups = true; + break; + default: + acceptedTypes = new Set(); + break; + } + const cachedMakePathsRelative = makePathsRelative.bindContextCache( + options.context, + compilation.compiler.root + ); + let depthInCollapsedGroup = 0; + for (const [origin, logEntries] of compilation.logging) { + const debugMode = loggingDebug.some((fn) => fn(origin)); + if (logging === false && !debugMode) continue; + /** @type {KnownStatsLoggingEntry[]} */ + const groupStack = []; + /** @type {KnownStatsLoggingEntry[]} */ + const rootList = []; + let currentList = rootList; + let processedLogEntries = 0; + for (const entry of logEntries) { + let type = entry.type; + if (!debugMode && !acceptedTypes.has(type)) continue; + + // Expand groups in verbose and debug modes + if ( + type === LogType.groupCollapsed && + (debugMode || collapsedGroups) + ) { + type = LogType.group; + } + + if (depthInCollapsedGroup === 0) { + processedLogEntries++; + } + + if (type === LogType.groupEnd) { + groupStack.pop(); + currentList = + groupStack.length > 0 + ? /** @type {KnownStatsLoggingEntry[]} */ ( + groupStack[groupStack.length - 1].children + ) + : rootList; + if (depthInCollapsedGroup > 0) depthInCollapsedGroup--; + continue; + } + let message; + if (entry.type === LogType.time) { + const [label, first, second] = + /** @type {[string, number, number]} */ + (entry.args); + message = `${label}: ${first * 1000 + second / 1000000} ms`; + } else if (entry.args && entry.args.length > 0) { + message = util.format(entry.args[0], ...entry.args.slice(1)); + } + /** @type {KnownStatsLoggingEntry} */ + const newEntry = { + ...entry, + type, + message, + trace: loggingTrace ? entry.trace : undefined, + children: + type === LogType.group || type === LogType.groupCollapsed + ? [] + : undefined + }; + currentList.push(newEntry); + if (newEntry.children) { + groupStack.push(newEntry); + currentList = newEntry.children; + if (depthInCollapsedGroup > 0) { + depthInCollapsedGroup++; + } else if (type === LogType.groupCollapsed) { + depthInCollapsedGroup = 1; + } + } + } + let name = cachedMakePathsRelative(origin).replace(/\|/g, " "); + if (name in object.logging) { + let i = 1; + while (`${name}#${i}` in object.logging) { + i++; + } + name = `${name}#${i}`; + } + object.logging[name] = { + entries: rootList, + filteredEntries: logEntries.length - processedLogEntries, + debug: debugMode + }; + } + } + }, + hash: (object, compilation) => { + object.hash = /** @type {string} */ (compilation.hash); + }, + version: (object) => { + object.version = require("../../package.json").version; + }, + env: (object, compilation, context, { _env }) => { + object.env = _env; + }, + timings: (object, compilation) => { + object.time = + /** @type {number} */ (compilation.endTime) - + /** @type {number} */ (compilation.startTime); + }, + builtAt: (object, compilation) => { + object.builtAt = /** @type {number} */ (compilation.endTime); + }, + publicPath: (object, compilation) => { + object.publicPath = compilation.getPath( + /** @type {TemplatePath} */ + (compilation.outputOptions.publicPath) + ); + }, + outputPath: (object, compilation) => { + object.outputPath = /** @type {string} */ ( + compilation.outputOptions.path + ); + }, + assets: (object, compilation, context, options, factory) => { + const { type } = context; + /** @type {Map} */ + const compilationFileToChunks = new Map(); + /** @type {Map} */ + const compilationAuxiliaryFileToChunks = new Map(); + for (const chunk of compilation.chunks) { + for (const file of chunk.files) { + let array = compilationFileToChunks.get(file); + if (array === undefined) { + array = []; + compilationFileToChunks.set(file, array); + } + array.push(chunk); + } + for (const file of chunk.auxiliaryFiles) { + let array = compilationAuxiliaryFileToChunks.get(file); + if (array === undefined) { + array = []; + compilationAuxiliaryFileToChunks.set(file, array); + } + array.push(chunk); + } + } + /** @type {Map} */ + const assetMap = new Map(); + /** @type {Set} */ + const assets = new Set(); + for (const asset of compilation.getAssets()) { + /** @type {PreprocessedAsset} */ + const item = { + ...asset, + type: "asset", + related: undefined + }; + assets.add(item); + assetMap.set(asset.name, item); + } + for (const item of assetMap.values()) { + const related = item.info.related; + if (!related) continue; + for (const type of Object.keys(related)) { + const relatedEntry = related[type]; + const deps = Array.isArray(relatedEntry) + ? relatedEntry + : [relatedEntry]; + for (const dep of deps) { + if (!dep) continue; + const depItem = assetMap.get(dep); + if (!depItem) continue; + assets.delete(depItem); + depItem.type = type; + item.related = item.related || []; + item.related.push(depItem); + } + } + } + + object.assetsByChunkName = {}; + for (const [file, chunks] of compilationFileToChunks) { + for (const chunk of chunks) { + const name = chunk.name; + if (!name) continue; + if ( + !Object.prototype.hasOwnProperty.call( + object.assetsByChunkName, + name + ) + ) { + object.assetsByChunkName[name] = []; + } + object.assetsByChunkName[name].push(file); + } + } + + const groupedAssets = factory.create(`${type}.assets`, [...assets], { + ...context, + compilationFileToChunks, + compilationAuxiliaryFileToChunks + }); + const limited = spaceLimited( + groupedAssets, + /** @type {number} */ (options.assetsSpace) + ); + object.assets = limited.children; + object.filteredAssets = limited.filteredChildren; + }, + chunks: (object, compilation, context, options, factory) => { + const { type } = context; + object.chunks = factory.create( + `${type}.chunks`, + [...compilation.chunks], + context + ); + }, + modules: (object, compilation, context, options, factory) => { + const { type } = context; + const array = [...compilation.modules]; + const groupedModules = factory.create(`${type}.modules`, array, context); + const limited = spaceLimited(groupedModules, options.modulesSpace); + object.modules = limited.children; + object.filteredModules = limited.filteredChildren; + }, + entrypoints: ( + object, + compilation, + context, + { entrypoints, chunkGroups, chunkGroupAuxiliary, chunkGroupChildren }, + factory + ) => { + const { type } = context; + /** @type {ChunkGroupInfoWithName[]} */ + const array = Array.from(compilation.entrypoints, ([key, value]) => ({ + name: key, + chunkGroup: value + })); + if (entrypoints === "auto" && !chunkGroups) { + if (array.length > 5) return; + if ( + !chunkGroupChildren && + array.every(({ chunkGroup }) => { + if (chunkGroup.chunks.length !== 1) return false; + const chunk = chunkGroup.chunks[0]; + return ( + chunk.files.size === 1 && + (!chunkGroupAuxiliary || chunk.auxiliaryFiles.size === 0) + ); + }) + ) { + return; + } + } + object.entrypoints = factory.create( + `${type}.entrypoints`, + array, + context + ); + }, + chunkGroups: (object, compilation, context, options, factory) => { + const { type } = context; + const array = Array.from( + compilation.namedChunkGroups, + ([key, value]) => ({ + name: key, + chunkGroup: value + }) + ); + object.namedChunkGroups = factory.create( + `${type}.namedChunkGroups`, + array, + context + ); + }, + errors: (object, compilation, context, options, factory) => { + const { type, cachedGetErrors } = context; + const rawErrors = cachedGetErrors(compilation); + const factorizedErrors = factory.create( + `${type}.errors`, + cachedGetErrors(compilation), + context + ); + let filtered = 0; + if (options.errorDetails === "auto" && rawErrors.length >= 3) { + filtered = rawErrors + .map((e) => typeof e !== "string" && e.details) + .filter(Boolean).length; + } + if ( + options.errorDetails === true || + !Number.isFinite(options.errorsSpace) + ) { + object.errors = factorizedErrors; + if (filtered) object.filteredErrorDetailsCount = filtered; + return; + } + const [errors, filteredBySpace] = errorsSpaceLimit( + factorizedErrors, + /** @type {number} */ + (options.errorsSpace) + ); + object.filteredErrorDetailsCount = filtered + filteredBySpace; + object.errors = errors; + }, + errorsCount: (object, compilation, { cachedGetErrors }) => { + object.errorsCount = countWithChildren(compilation, (c) => + cachedGetErrors(c) + ); + }, + warnings: (object, compilation, context, options, factory) => { + const { type, cachedGetWarnings } = context; + const rawWarnings = factory.create( + `${type}.warnings`, + cachedGetWarnings(compilation), + context + ); + let filtered = 0; + if (options.errorDetails === "auto") { + filtered = cachedGetWarnings(compilation) + .map((e) => typeof e !== "string" && e.details) + .filter(Boolean).length; + } + if ( + options.errorDetails === true || + !Number.isFinite(options.warningsSpace) + ) { + object.warnings = rawWarnings; + if (filtered) object.filteredWarningDetailsCount = filtered; + return; + } + const [warnings, filteredBySpace] = errorsSpaceLimit( + rawWarnings, + /** @type {number} */ + (options.warningsSpace) + ); + object.filteredWarningDetailsCount = filtered + filteredBySpace; + object.warnings = warnings; + }, + warningsCount: ( + object, + compilation, + context, + { warningsFilter }, + factory + ) => { + const { type, cachedGetWarnings } = context; + object.warningsCount = countWithChildren(compilation, (c, childType) => { + if ( + !warningsFilter && + /** @type {KnownNormalizedStatsOptions["warningsFilter"]} */ + (warningsFilter).length === 0 + ) { + // Type is wrong, because we don't need the real value for counting + return /** @type {EXPECTED_ANY[]} */ (cachedGetWarnings(c)); + } + return factory + .create(`${type}${childType}.warnings`, cachedGetWarnings(c), context) + .filter( + /** + * @param {StatsError} warning warning + * @returns {boolean} result + */ + (warning) => { + const warningString = Object.keys(warning) + .map( + (key) => + `${warning[/** @type {keyof KnownStatsError} */ (key)]}` + ) + .join("\n"); + return !warningsFilter.some((filter) => + filter(warning, warningString) + ); + } + ); + }); + }, + children: (object, compilation, context, options, factory) => { + const { type } = context; + object.children = factory.create( + `${type}.children`, + compilation.children, + context + ); + } + }, + asset: { + _: (object, asset, context, options, factory) => { + const { compilation } = context; + object.type = asset.type; + object.name = asset.name; + object.size = asset.source.size(); + object.emitted = compilation.emittedAssets.has(asset.name); + object.comparedForEmit = compilation.comparedForEmitAssets.has( + asset.name + ); + const cached = !object.emitted && !object.comparedForEmit; + object.cached = cached; + object.info = asset.info; + if (!cached || options.cachedAssets) { + Object.assign( + object, + factory.create(`${context.type}$visible`, asset, context) + ); + } + } + }, + asset$visible: { + _: ( + object, + asset, + { compilationFileToChunks, compilationAuxiliaryFileToChunks } + ) => { + const chunks = compilationFileToChunks.get(asset.name) || []; + const auxiliaryChunks = + compilationAuxiliaryFileToChunks.get(asset.name) || []; + object.chunkNames = uniqueOrderedArray( + chunks, + (c) => (c.name ? [c.name] : []), + compareIds + ); + object.chunkIdHints = uniqueOrderedArray( + chunks, + (c) => [...c.idNameHints], + compareIds + ); + object.auxiliaryChunkNames = uniqueOrderedArray( + auxiliaryChunks, + (c) => (c.name ? [c.name] : []), + compareIds + ); + object.auxiliaryChunkIdHints = uniqueOrderedArray( + auxiliaryChunks, + (c) => [...c.idNameHints], + compareIds + ); + object.filteredRelated = asset.related ? asset.related.length : undefined; + }, + relatedAssets: (object, asset, context, options, factory) => { + const { type } = context; + object.related = factory.create( + `${type.slice(0, -8)}.related`, + asset.related || [], + context + ); + object.filteredRelated = asset.related + ? asset.related.length - + /** @type {StatsAsset[]} */ (object.related).length + : undefined; + }, + ids: ( + object, + asset, + { compilationFileToChunks, compilationAuxiliaryFileToChunks } + ) => { + const chunks = compilationFileToChunks.get(asset.name) || []; + const auxiliaryChunks = + compilationAuxiliaryFileToChunks.get(asset.name) || []; + object.chunks = uniqueOrderedArray( + chunks, + (c) => /** @type {ChunkId[]} */ (c.ids), + compareIds + ); + object.auxiliaryChunks = uniqueOrderedArray( + auxiliaryChunks, + (c) => /** @type {ChunkId[]} */ (c.ids), + compareIds + ); + }, + performance: (object, asset) => { + object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(asset.source); + } + }, + chunkGroup: { + _: ( + object, + { name, chunkGroup }, + { compilation, compilation: { moduleGraph, chunkGraph } }, + { ids, chunkGroupAuxiliary, chunkGroupChildren, chunkGroupMaxAssets } + ) => { + const children = + chunkGroupChildren && + chunkGroup.getChildrenByOrders(moduleGraph, chunkGraph); + /** + * @param {string} name Name + * @returns {{ name: string, size: number }} Asset object + */ + const toAsset = (name) => { + const asset = compilation.getAsset(name); + return { + name, + size: /** @type {number} */ (asset ? asset.info.size : -1) + }; + }; + /** @type {(total: number, asset: { size: number }) => number} */ + const sizeReducer = (total, { size }) => total + size; + const assets = uniqueArray(chunkGroup.chunks, (c) => c.files).map( + toAsset + ); + const auxiliaryAssets = uniqueOrderedArray( + chunkGroup.chunks, + (c) => c.auxiliaryFiles, + compareIds + ).map(toAsset); + const assetsSize = assets.reduce(sizeReducer, 0); + const auxiliaryAssetsSize = auxiliaryAssets.reduce(sizeReducer, 0); + /** @type {KnownStatsChunkGroup} */ + const statsChunkGroup = { + name, + chunks: ids + ? /** @type {ChunkId[]} */ (chunkGroup.chunks.map((c) => c.id)) + : undefined, + assets: assets.length <= chunkGroupMaxAssets ? assets : undefined, + filteredAssets: + assets.length <= chunkGroupMaxAssets ? 0 : assets.length, + assetsSize, + auxiliaryAssets: + chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets + ? auxiliaryAssets + : undefined, + filteredAuxiliaryAssets: + chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets + ? 0 + : auxiliaryAssets.length, + auxiliaryAssetsSize, + children: children + ? mapObject(children, (groups) => + groups.map((group) => { + const assets = uniqueArray(group.chunks, (c) => c.files).map( + toAsset + ); + const auxiliaryAssets = uniqueOrderedArray( + group.chunks, + (c) => c.auxiliaryFiles, + compareIds + ).map(toAsset); + + /** @type {KnownStatsChunkGroup} */ + const childStatsChunkGroup = { + name: group.name, + chunks: ids + ? /** @type {ChunkId[]} */ + (group.chunks.map((c) => c.id)) + : undefined, + assets: + assets.length <= chunkGroupMaxAssets ? assets : undefined, + filteredAssets: + assets.length <= chunkGroupMaxAssets ? 0 : assets.length, + auxiliaryAssets: + chunkGroupAuxiliary && + auxiliaryAssets.length <= chunkGroupMaxAssets + ? auxiliaryAssets + : undefined, + filteredAuxiliaryAssets: + chunkGroupAuxiliary && + auxiliaryAssets.length <= chunkGroupMaxAssets + ? 0 + : auxiliaryAssets.length + }; + + return childStatsChunkGroup; + }) + ) + : undefined, + childAssets: children + ? mapObject(children, (groups) => { + /** @type {Set} */ + const set = new Set(); + for (const group of groups) { + for (const chunk of group.chunks) { + for (const asset of chunk.files) { + set.add(asset); + } + } + } + return [...set]; + }) + : undefined + }; + Object.assign(object, statsChunkGroup); + }, + performance: (object, { chunkGroup }) => { + object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(chunkGroup); + } + }, + module: { + _: (object, module, context, options, factory) => { + const { type } = context; + const compilation = /** @type {Compilation} */ (context.compilation); + const built = compilation.builtModules.has(module); + const codeGenerated = compilation.codeGeneratedModules.has(module); + const buildTimeExecuted = + compilation.buildTimeExecutedModules.has(module); + /** @type {{[x: string]: number}} */ + const sizes = {}; + for (const sourceType of module.getSourceTypes()) { + sizes[sourceType] = module.size(sourceType); + } + /** @type {KnownStatsModule} */ + const statsModule = { + type: "module", + moduleType: module.type, + layer: module.layer, + size: module.size(), + sizes, + built, + codeGenerated, + buildTimeExecuted, + cached: !built && !codeGenerated + }; + Object.assign(object, statsModule); + if (built || codeGenerated || options.cachedModules) { + Object.assign( + object, + factory.create(`${type}$visible`, module, context) + ); + } + } + }, + module$visible: { + _: (object, module, context, { requestShortener }, factory) => { + const { type, rootModules } = context; + const compilation = /** @type {Compilation} */ (context.compilation); + const { moduleGraph } = compilation; + /** @type {ModuleIssuerPath} */ + const path = []; + const issuer = moduleGraph.getIssuer(module); + let current = issuer; + while (current) { + path.push(current); + current = moduleGraph.getIssuer(current); + } + path.reverse(); + const profile = moduleGraph.getProfile(module); + const errors = module.getErrors(); + const errorsCount = errors !== undefined ? countIterable(errors) : 0; + const warnings = module.getWarnings(); + const warningsCount = + warnings !== undefined ? countIterable(warnings) : 0; + /** @type {KnownStatsModule} */ + const statsModule = { + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener), + nameForCondition: module.nameForCondition(), + index: /** @type {number} */ (moduleGraph.getPreOrderIndex(module)), + preOrderIndex: /** @type {number} */ ( + moduleGraph.getPreOrderIndex(module) + ), + index2: /** @type {number} */ (moduleGraph.getPostOrderIndex(module)), + postOrderIndex: /** @type {number} */ ( + moduleGraph.getPostOrderIndex(module) + ), + cacheable: /** @type {BuildInfo} */ (module.buildInfo).cacheable, + optional: module.isOptional(moduleGraph), + orphan: + !type.endsWith("module.modules[].module$visible") && + compilation.chunkGraph.getNumberOfModuleChunks(module) === 0, + dependent: rootModules ? !rootModules.has(module) : undefined, + issuer: issuer && issuer.identifier(), + issuerName: issuer && issuer.readableIdentifier(requestShortener), + issuerPath: + issuer && + /** @type {StatsModuleIssuer[] | undefined} */ + (factory.create(`${type.slice(0, -8)}.issuerPath`, path, context)), + failed: errorsCount > 0, + errors: errorsCount, + warnings: warningsCount + }; + Object.assign(object, statsModule); + if (profile) { + object.profile = factory.create( + `${type.slice(0, -8)}.profile`, + profile, + context + ); + } + }, + ids: (object, module, { compilation: { chunkGraph, moduleGraph } }) => { + object.id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module)); + const issuer = moduleGraph.getIssuer(module); + object.issuerId = issuer && chunkGraph.getModuleId(issuer); + object.chunks = + /** @type {ChunkId[]} */ + ( + Array.from( + chunkGraph.getOrderedModuleChunksIterable( + module, + compareChunksById + ), + (chunk) => chunk.id + ) + ); + }, + moduleAssets: (object, module) => { + object.assets = /** @type {BuildInfo} */ (module.buildInfo).assets + ? Object.keys(/** @type {BuildInfo} */ (module.buildInfo).assets) + : []; + }, + reasons: (object, module, context, options, factory) => { + const { + type, + compilation: { moduleGraph } + } = context; + const groupsReasons = factory.create( + `${type.slice(0, -8)}.reasons`, + [...moduleGraph.getIncomingConnections(module)], + context + ); + const limited = spaceLimited( + groupsReasons, + /** @type {number} */ + (options.reasonsSpace) + ); + object.reasons = limited.children; + object.filteredReasons = limited.filteredChildren; + }, + usedExports: ( + object, + module, + { runtime, compilation: { moduleGraph } } + ) => { + const usedExports = moduleGraph.getUsedExports(module, runtime); + if (usedExports === null) { + object.usedExports = null; + } else if (typeof usedExports === "boolean") { + object.usedExports = usedExports; + } else { + object.usedExports = [...usedExports]; + } + }, + providedExports: (object, module, { compilation: { moduleGraph } }) => { + const providedExports = moduleGraph.getProvidedExports(module); + object.providedExports = Array.isArray(providedExports) + ? providedExports + : null; + }, + optimizationBailout: ( + object, + module, + { compilation: { moduleGraph } }, + { requestShortener } + ) => { + object.optimizationBailout = moduleGraph + .getOptimizationBailout(module) + .map((item) => { + if (typeof item === "function") return item(requestShortener); + return item; + }); + }, + depth: (object, module, { compilation: { moduleGraph } }) => { + object.depth = moduleGraph.getDepth(module); + }, + nestedModules: (object, module, context, options, factory) => { + const { type } = context; + const innerModules = /** @type {Module & { modules?: Module[] }} */ ( + module + ).modules; + if (Array.isArray(innerModules)) { + const groupedModules = factory.create( + `${type.slice(0, -8)}.modules`, + innerModules, + context + ); + const limited = spaceLimited( + groupedModules, + options.nestedModulesSpace + ); + object.modules = limited.children; + object.filteredModules = limited.filteredChildren; + } + }, + source: (object, module) => { + const originalSource = module.originalSource(); + if (originalSource) { + object.source = originalSource.source(); + } + } + }, + profile: { + _: (object, profile) => { + /** @type {KnownStatsProfile} */ + const statsProfile = { + total: + profile.factory + + profile.restoring + + profile.integration + + profile.building + + profile.storing, + resolving: profile.factory, + restoring: profile.restoring, + building: profile.building, + integration: profile.integration, + storing: profile.storing, + additionalResolving: profile.additionalFactories, + additionalIntegration: profile.additionalIntegration, + // TODO remove this in webpack 6 + factory: profile.factory, + // TODO remove this in webpack 6 + dependencies: profile.additionalFactories + }; + Object.assign(object, statsProfile); + } + }, + moduleIssuer: { + _: (object, module, context, { requestShortener }, factory) => { + const { type } = context; + const compilation = /** @type {Compilation} */ (context.compilation); + const { moduleGraph } = compilation; + const profile = moduleGraph.getProfile(module); + /** @type {Partial} */ + const statsModuleIssuer = { + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener) + }; + Object.assign(object, statsModuleIssuer); + if (profile) { + object.profile = factory.create(`${type}.profile`, profile, context); + } + }, + ids: (object, module, { compilation: { chunkGraph } }) => { + object.id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module)); + } + }, + moduleReason: { + _: (object, reason, { runtime }, { requestShortener }) => { + const dep = reason.dependency; + const moduleDep = + dep && dep instanceof ModuleDependency ? dep : undefined; + /** @type {KnownStatsModuleReason} */ + const statsModuleReason = { + moduleIdentifier: reason.originModule + ? reason.originModule.identifier() + : null, + module: reason.originModule + ? reason.originModule.readableIdentifier(requestShortener) + : null, + moduleName: reason.originModule + ? reason.originModule.readableIdentifier(requestShortener) + : null, + resolvedModuleIdentifier: reason.resolvedOriginModule + ? reason.resolvedOriginModule.identifier() + : null, + resolvedModule: reason.resolvedOriginModule + ? reason.resolvedOriginModule.readableIdentifier(requestShortener) + : null, + type: reason.dependency ? reason.dependency.type : null, + active: reason.isActive(runtime), + explanation: reason.explanation, + userRequest: (moduleDep && moduleDep.userRequest) || null + }; + Object.assign(object, statsModuleReason); + if (reason.dependency) { + const locInfo = formatLocation(reason.dependency.loc); + if (locInfo) { + object.loc = locInfo; + } + } + }, + ids: (object, reason, { compilation: { chunkGraph } }) => { + object.moduleId = reason.originModule + ? chunkGraph.getModuleId(reason.originModule) + : null; + object.resolvedModuleId = reason.resolvedOriginModule + ? chunkGraph.getModuleId(reason.resolvedOriginModule) + : null; + } + }, + chunk: { + _: (object, chunk, { makePathsRelative, compilation: { chunkGraph } }) => { + const childIdByOrder = chunk.getChildIdsByOrders(chunkGraph); + + /** @type {KnownStatsChunk} */ + const statsChunk = { + rendered: chunk.rendered, + initial: chunk.canBeInitial(), + entry: chunk.hasRuntime(), + recorded: AggressiveSplittingPlugin.wasChunkRecorded(chunk), + reason: chunk.chunkReason, + size: chunkGraph.getChunkModulesSize(chunk), + sizes: chunkGraph.getChunkModulesSizes(chunk), + names: chunk.name ? [chunk.name] : [], + idHints: [...chunk.idNameHints], + runtime: + chunk.runtime === undefined + ? undefined + : typeof chunk.runtime === "string" + ? [makePathsRelative(chunk.runtime)] + : Array.from(chunk.runtime.sort(), makePathsRelative), + files: [...chunk.files], + auxiliaryFiles: [...chunk.auxiliaryFiles].sort(compareIds), + hash: /** @type {string} */ (chunk.renderedHash), + childrenByOrder: childIdByOrder + }; + Object.assign(object, statsChunk); + }, + ids: (object, chunk) => { + object.id = /** @type {ChunkId} */ (chunk.id); + }, + chunkRelations: (object, chunk, _context) => { + /** @type {Set} */ + const parents = new Set(); + /** @type {Set} */ + const children = new Set(); + /** @type {Set} */ + const siblings = new Set(); + + for (const chunkGroup of chunk.groupsIterable) { + for (const parentGroup of chunkGroup.parentsIterable) { + for (const chunk of parentGroup.chunks) { + parents.add(/** @type {ChunkId} */ (chunk.id)); + } + } + for (const childGroup of chunkGroup.childrenIterable) { + for (const chunk of childGroup.chunks) { + children.add(/** @type {ChunkId} */ (chunk.id)); + } + } + for (const sibling of chunkGroup.chunks) { + if (sibling !== chunk) { + siblings.add(/** @type {ChunkId} */ (sibling.id)); + } + } + } + object.siblings = [...siblings].sort(compareIds); + object.parents = [...parents].sort(compareIds); + object.children = [...children].sort(compareIds); + }, + chunkModules: (object, chunk, context, options, factory) => { + const { + type, + compilation: { chunkGraph } + } = context; + const array = chunkGraph.getChunkModules(chunk); + const groupedModules = factory.create(`${type}.modules`, array, { + ...context, + runtime: chunk.runtime, + rootModules: new Set(chunkGraph.getChunkRootModules(chunk)) + }); + const limited = spaceLimited(groupedModules, options.chunkModulesSpace); + object.modules = limited.children; + object.filteredModules = limited.filteredChildren; + }, + chunkOrigins: (object, chunk, context, options, factory) => { + const { + type, + compilation: { chunkGraph } + } = context; + /** @type {Set} */ + const originsKeySet = new Set(); + /** @type {OriginRecord[]} */ + const origins = []; + for (const g of chunk.groupsIterable) { + origins.push(...g.origins); + } + const array = origins.filter((origin) => { + const key = [ + origin.module ? chunkGraph.getModuleId(origin.module) : undefined, + formatLocation(origin.loc), + origin.request + ].join(); + if (originsKeySet.has(key)) return false; + originsKeySet.add(key); + return true; + }); + object.origins = factory.create(`${type}.origins`, array, context); + } + }, + chunkOrigin: { + _: (object, origin, context, { requestShortener }) => { + /** @type {KnownStatsChunkOrigin} */ + const statsChunkOrigin = { + module: origin.module ? origin.module.identifier() : "", + moduleIdentifier: origin.module ? origin.module.identifier() : "", + moduleName: origin.module + ? origin.module.readableIdentifier(requestShortener) + : "", + loc: formatLocation(origin.loc), + request: origin.request + }; + Object.assign(object, statsChunkOrigin); + }, + ids: (object, origin, { compilation: { chunkGraph } }) => { + object.moduleId = origin.module + ? /** @type {ModuleId} */ (chunkGraph.getModuleId(origin.module)) + : undefined; + } + }, + error: EXTRACT_ERROR, + warning: EXTRACT_ERROR, + cause: EXTRACT_ERROR, + moduleTraceItem: { + _: (object, { origin, module }, context, { requestShortener }, factory) => { + const { + type, + compilation: { moduleGraph } + } = context; + object.originIdentifier = origin.identifier(); + object.originName = origin.readableIdentifier(requestShortener); + object.moduleIdentifier = module.identifier(); + object.moduleName = module.readableIdentifier(requestShortener); + const dependencies = [...moduleGraph.getIncomingConnections(module)] + .filter((c) => c.resolvedOriginModule === origin && c.dependency) + .map((c) => c.dependency); + object.dependencies = factory.create( + `${type}.dependencies`, + /** @type {Dependency[]} */ + ([...new Set(dependencies)]), + context + ); + }, + ids: (object, { origin, module }, { compilation: { chunkGraph } }) => { + object.originId = + /** @type {ModuleId} */ + (chunkGraph.getModuleId(origin)); + object.moduleId = + /** @type {ModuleId} */ + (chunkGraph.getModuleId(module)); + } + }, + moduleTraceDependency: { + _: (object, dependency) => { + object.loc = formatLocation(dependency.loc); + } + } +}; + +/** @type {Record boolean | undefined>>} */ +const FILTER = { + "module.reasons": { + "!orphanModules": (reason, { compilation: { chunkGraph } }) => { + if ( + reason.originModule && + chunkGraph.getNumberOfModuleChunks(reason.originModule) === 0 + ) { + return false; + } + } + } +}; + +/** @type {Record boolean | undefined>>} */ +const FILTER_RESULTS = { + "compilation.warnings": { + warningsFilter: util.deprecate( + (warning, context, { warningsFilter }) => { + const warningString = Object.keys(warning) + .map( + (key) => `${warning[/** @type {keyof KnownStatsError} */ (key)]}` + ) + .join("\n"); + return !warningsFilter.some((filter) => filter(warning, warningString)); + }, + "config.stats.warningsFilter is deprecated in favor of config.ignoreWarnings", + "DEP_WEBPACK_STATS_WARNINGS_FILTER" + ) + } +}; + +/** @type {Record[], context: StatsFactoryContext) => void>} */ +const MODULES_SORTER = { + _: (comparators, { compilation: { moduleGraph } }) => { + comparators.push( + compareSelect((m) => moduleGraph.getDepth(m), compareNumbers), + compareSelect((m) => moduleGraph.getPreOrderIndex(m), compareNumbers), + compareSelect((m) => m.identifier(), compareIds) + ); + } +}; + +/** @type {Record[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>>} */ +const SORTERS = { + "compilation.chunks": { + _: (comparators) => { + comparators.push(compareSelect((c) => c.id, compareIds)); + } + }, + "compilation.modules": MODULES_SORTER, + "chunk.rootModules": MODULES_SORTER, + "chunk.modules": MODULES_SORTER, + "module.modules": MODULES_SORTER, + "module.reasons": { + _: (comparators, _context) => { + comparators.push( + compareSelect((x) => x.originModule, compareModulesByIdentifier) + ); + comparators.push( + compareSelect((x) => x.resolvedOriginModule, compareModulesByIdentifier) + ); + comparators.push( + compareSelect( + (x) => x.dependency, + concatComparators( + compareSelect( + /** + * @param {Dependency} x dependency + * @returns {DependencyLocation} location + */ + (x) => x.loc, + compareLocations + ), + compareSelect((x) => x.type, compareIds) + ) + ) + ); + } + }, + "chunk.origins": { + _: (comparators, { compilation: { chunkGraph } }) => { + comparators.push( + compareSelect( + (origin) => + origin.module ? chunkGraph.getModuleId(origin.module) : undefined, + compareIds + ), + compareSelect((origin) => formatLocation(origin.loc), compareIds), + compareSelect((origin) => origin.request, compareIds) + ); + } + } +}; + +/** + * @template T + * @typedef {T & { children?: Children[] | undefined, filteredChildren?: number }} Children + */ + +/** + * @template T + * @param {Children} item item + * @returns {number} item size + */ +const getItemSize = (item) => + // Each item takes 1 line + // + the size of the children + // + 1 extra line when it has children and filteredChildren + !item.children + ? 1 + : item.filteredChildren + ? 2 + getTotalSize(item.children) + : 1 + getTotalSize(item.children); + +/** + * @template T + * @param {Children[]} children children + * @returns {number} total size + */ +const getTotalSize = (children) => { + let size = 0; + for (const child of children) { + size += getItemSize(child); + } + return size; +}; + +/** + * @template T + * @param {Children[]} children children + * @returns {number} total items + */ +const getTotalItems = (children) => { + let count = 0; + for (const child of children) { + if (!child.children && !child.filteredChildren) { + count++; + } else { + if (child.children) count += getTotalItems(child.children); + if (child.filteredChildren) count += child.filteredChildren; + } + } + return count; +}; + +/** + * @template T + * @param {Children[]} children children + * @returns {Children[]} collapsed children + */ +const collapse = (children) => { + // After collapse each child must take exactly one line + const newChildren = []; + for (const child of children) { + if (child.children) { + let filteredChildren = child.filteredChildren || 0; + filteredChildren += getTotalItems(child.children); + newChildren.push({ + ...child, + children: undefined, + filteredChildren + }); + } else { + newChildren.push(child); + } + } + return newChildren; +}; + +/** + * @template T + * @param {Children[]} itemsAndGroups item and groups + * @param {number} max max + * @param {boolean=} filteredChildrenLineReserved filtered children line reserved + * @returns {Children} result + */ +const spaceLimited = ( + itemsAndGroups, + max, + filteredChildrenLineReserved = false +) => { + if (max < 1) { + return /** @type {Children} */ ({ + children: undefined, + filteredChildren: getTotalItems(itemsAndGroups) + }); + } + /** @type {Children[] | undefined} */ + let children; + /** @type {number | undefined} */ + let filteredChildren; + // This are the groups, which take 1+ lines each + /** @type {Children[] | undefined} */ + const groups = []; + // The sizes of the groups are stored in groupSizes + /** @type {number[]} */ + const groupSizes = []; + // This are the items, which take 1 line each + const items = []; + // The total of group sizes + let groupsSize = 0; + + for (const itemOrGroup of itemsAndGroups) { + // is item + if (!itemOrGroup.children && !itemOrGroup.filteredChildren) { + items.push(itemOrGroup); + } else { + groups.push(itemOrGroup); + const size = getItemSize(itemOrGroup); + groupSizes.push(size); + groupsSize += size; + } + } + + if (groupsSize + items.length <= max) { + // The total size in the current state fits into the max + // keep all + children = groups.length > 0 ? [...groups, ...items] : items; + } else if (groups.length === 0) { + // slice items to max + // inner space marks that lines for filteredChildren already reserved + const limit = max - (filteredChildrenLineReserved ? 0 : 1); + filteredChildren = items.length - limit; + items.length = limit; + children = items; + } else { + // limit is the size when all groups are collapsed + const limit = + groups.length + + (filteredChildrenLineReserved || items.length === 0 ? 0 : 1); + if (limit < max) { + // calculate how much we are over the size limit + // this allows to approach the limit faster + let oversize; + // If each group would take 1 line the total would be below the maximum + // collapse some groups, keep items + while ( + (oversize = + groupsSize + + items.length + + (filteredChildren && !filteredChildrenLineReserved ? 1 : 0) - + max) > 0 + ) { + // Find the maximum group and process only this one + const maxGroupSize = Math.max(...groupSizes); + if (maxGroupSize < items.length) { + filteredChildren = items.length; + items.length = 0; + continue; + } + for (let i = 0; i < groups.length; i++) { + if (groupSizes[i] === maxGroupSize) { + const group = groups[i]; + // run this algorithm recursively and limit the size of the children to + // current size - oversize / number of groups + // So it should always end up being smaller + const headerSize = group.filteredChildren ? 2 : 1; + const limited = spaceLimited( + /** @type {Children[]} */ (group.children), + maxGroupSize - + // we should use ceil to always feet in max + Math.ceil(oversize / groups.length) - + // we substitute size of group head + headerSize, + headerSize === 2 + ); + groups[i] = { + ...group, + children: limited.children, + filteredChildren: limited.filteredChildren + ? (group.filteredChildren || 0) + limited.filteredChildren + : group.filteredChildren + }; + const newSize = getItemSize(groups[i]); + groupsSize -= maxGroupSize - newSize; + groupSizes[i] = newSize; + break; + } + } + } + children = [...groups, ...items]; + } else if (limit === max) { + // If we have only enough space to show one line per group and one line for the filtered items + // collapse all groups and items + children = collapse(groups); + filteredChildren = items.length; + } else { + // If we have no space + // collapse complete group + filteredChildren = getTotalItems(itemsAndGroups); + } + } + + return /** @type {Children} */ ({ children, filteredChildren }); +}; + +/** + * @param {StatsError[]} errors errors + * @param {number} max max + * @returns {[StatsError[], number]} error space limit + */ +const errorsSpaceLimit = (errors, max) => { + let filtered = 0; + // Can not fit into limit + // print only messages + if (errors.length + 1 >= max) { + return [ + errors.map((error) => { + if (typeof error === "string" || !error.details) return error; + filtered++; + return { ...error, details: "" }; + }), + filtered + ]; + } + let fullLength = errors.length; + let result = errors; + + let i = 0; + for (; i < errors.length; i++) { + const error = errors[i]; + if (typeof error !== "string" && error.details) { + const splitted = error.details.split("\n"); + const len = splitted.length; + fullLength += len; + if (fullLength > max) { + result = i > 0 ? errors.slice(0, i) : []; + const overLimit = fullLength - max + 1; + const error = errors[i++]; + result.push({ + ...error, + details: + /** @type {string} */ + (error.details).split("\n").slice(0, -overLimit).join("\n"), + filteredDetails: overLimit + }); + filtered = errors.length - i; + for (; i < errors.length; i++) { + const error = errors[i]; + if (typeof error === "string" || !error.details) result.push(error); + result.push({ ...error, details: "" }); + } + break; + } else if (fullLength === max) { + result = errors.slice(0, ++i); + filtered = errors.length - i; + for (; i < errors.length; i++) { + const error = errors[i]; + if (typeof error === "string" || !error.details) result.push(error); + result.push({ ...error, details: "" }); + } + break; + } + } + } + + return [result, filtered]; +}; + +/** + * @template {{ size: number }} T + * @template {{ size: number }} R + * @param {(R | T)[]} children children + * @param {T[]} assets assets + * @returns {{ size: number }} asset size + */ +const assetGroup = (children, assets) => { + let size = 0; + for (const asset of children) { + size += asset.size; + } + return { size }; +}; + +/** + * @template {{ size: number, sizes: Record }} T + * @param {Children[]} children children + * @param {KnownStatsModule[]} modules modules + * @returns {{ size: number, sizes: Record}} size and sizes + */ +const moduleGroup = (children, modules) => { + let size = 0; + /** @type {Record} */ + const sizes = {}; + for (const module of children) { + size += module.size; + for (const key of Object.keys(module.sizes)) { + sizes[key] = (sizes[key] || 0) + module.sizes[key]; + } + } + return { + size, + sizes + }; +}; + +/** + * @template {{ active: boolean }} T + * @param {Children[]} children children + * @param {KnownStatsModuleReason[]} reasons reasons + * @returns {{ active: boolean }} reason group + */ +const reasonGroup = (children, reasons) => { + let active = false; + for (const reason of children) { + active = active || reason.active; + } + return { + active + }; +}; + +const GROUP_EXTENSION_REGEXP = /(\.[^.]+?)(?:\?|(?: \+ \d+ modules?)?$)/; +const GROUP_PATH_REGEXP = /(.+)[/\\][^/\\]+?(?:\?|(?: \+ \d+ modules?)?$)/; + +/** @typedef {Record[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} AssetsGroupers */ + +/** @type {AssetsGroupers} */ +const ASSETS_GROUPERS = { + _: (groupConfigs, context, options) => { + /** + * @param {keyof KnownStatsAsset} name name + * @param {boolean=} exclude need exclude? + */ + const groupByFlag = (name, exclude) => { + groupConfigs.push({ + getKeys: (asset) => (asset[name] ? ["1"] : undefined), + getOptions: () => ({ + groupChildren: !exclude, + force: exclude + }), + createGroup: (key, children, assets) => + exclude + ? { + type: "assets by status", + [name]: Boolean(key), + filteredChildren: assets.length, + ...assetGroup(children, assets) + } + : { + type: "assets by status", + [name]: Boolean(key), + children, + ...assetGroup(children, assets) + } + }); + }; + const { + groupAssetsByEmitStatus, + groupAssetsByPath, + groupAssetsByExtension + } = options; + if (groupAssetsByEmitStatus) { + groupByFlag("emitted"); + groupByFlag("comparedForEmit"); + groupByFlag("isOverSizeLimit"); + } + if (groupAssetsByEmitStatus || !options.cachedAssets) { + groupByFlag("cached", !options.cachedAssets); + } + if (groupAssetsByPath || groupAssetsByExtension) { + groupConfigs.push({ + getKeys: (asset) => { + const extensionMatch = + groupAssetsByExtension && GROUP_EXTENSION_REGEXP.exec(asset.name); + const extension = extensionMatch ? extensionMatch[1] : ""; + const pathMatch = + groupAssetsByPath && GROUP_PATH_REGEXP.exec(asset.name); + const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; + /** @type {string[]} */ + const keys = []; + if (groupAssetsByPath) { + keys.push("."); + if (extension) { + keys.push( + path.length + ? `${path.join("/")}/*${extension}` + : `*${extension}` + ); + } + while (path.length > 0) { + keys.push(`${path.join("/")}/`); + path.pop(); + } + } else if (extension) { + keys.push(`*${extension}`); + } + return keys; + }, + createGroup: (key, children, assets) => ({ + type: groupAssetsByPath ? "assets by path" : "assets by extension", + name: key, + children, + ...assetGroup(children, assets) + }) + }); + } + }, + groupAssetsByInfo: (groupConfigs, _context, _options) => { + /** + * @param {string} name name + */ + const groupByAssetInfoFlag = (name) => { + groupConfigs.push({ + getKeys: (asset) => + asset.info && asset.info[name] ? ["1"] : undefined, + createGroup: (key, children, assets) => ({ + type: "assets by info", + info: { + [name]: Boolean(key) + }, + children, + ...assetGroup(children, assets) + }) + }); + }; + groupByAssetInfoFlag("immutable"); + groupByAssetInfoFlag("development"); + groupByAssetInfoFlag("hotModuleReplacement"); + }, + groupAssetsByChunk: (groupConfigs, _context, _options) => { + /** + * @param {keyof KnownStatsAsset} name name + */ + const groupByNames = (name) => { + groupConfigs.push({ + getKeys: (asset) => /** @type {string[]} */ (asset[name]), + createGroup: (key, children, assets) => ({ + type: "assets by chunk", + [name]: [key], + children, + ...assetGroup(children, assets) + }) + }); + }; + groupByNames("chunkNames"); + groupByNames("auxiliaryChunkNames"); + groupByNames("chunkIdHints"); + groupByNames("auxiliaryChunkIdHints"); + }, + excludeAssets: (groupConfigs, context, { excludeAssets }) => { + groupConfigs.push({ + getKeys: (asset) => { + const ident = asset.name; + const excluded = excludeAssets.some((fn) => fn(ident, asset)); + if (excluded) return ["excluded"]; + }, + getOptions: () => ({ + groupChildren: false, + force: true + }), + createGroup: (key, children, assets) => ({ + type: "hidden assets", + filteredChildren: assets.length, + ...assetGroup(children, assets) + }) + }); + } +}; + +/** @typedef {Record[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} ModulesGroupers */ + +/** @type {(type: ExcludeModulesType) => ModulesGroupers} */ +const MODULES_GROUPERS = (type) => ({ + _: (groupConfigs, context, options) => { + /** + * @param {keyof KnownStatsModule} name name + * @param {string} type type + * @param {boolean=} exclude need exclude? + */ + const groupByFlag = (name, type, exclude) => { + groupConfigs.push({ + getKeys: (module) => (module[name] ? ["1"] : undefined), + getOptions: () => ({ + groupChildren: !exclude, + force: exclude + }), + createGroup: (key, children, modules) => ({ + type, + [name]: Boolean(key), + ...(exclude ? { filteredChildren: modules.length } : { children }), + ...moduleGroup(children, modules) + }) + }); + }; + const { + groupModulesByCacheStatus, + groupModulesByLayer, + groupModulesByAttributes, + groupModulesByType, + groupModulesByPath, + groupModulesByExtension + } = options; + if (groupModulesByAttributes) { + groupByFlag("errors", "modules with errors"); + groupByFlag("warnings", "modules with warnings"); + groupByFlag("assets", "modules with assets"); + groupByFlag("optional", "optional modules"); + } + if (groupModulesByCacheStatus) { + groupByFlag("cacheable", "cacheable modules"); + groupByFlag("built", "built modules"); + groupByFlag("codeGenerated", "code generated modules"); + } + if (groupModulesByCacheStatus || !options.cachedModules) { + groupByFlag("cached", "cached modules", !options.cachedModules); + } + if (groupModulesByAttributes || !options.orphanModules) { + groupByFlag("orphan", "orphan modules", !options.orphanModules); + } + if (groupModulesByAttributes || !options.dependentModules) { + groupByFlag("dependent", "dependent modules", !options.dependentModules); + } + if (groupModulesByType || !options.runtimeModules) { + groupConfigs.push({ + getKeys: (module) => { + if (!module.moduleType) return; + if (groupModulesByType) { + return [module.moduleType.split("/", 1)[0]]; + } else if (module.moduleType === WEBPACK_MODULE_TYPE_RUNTIME) { + return [WEBPACK_MODULE_TYPE_RUNTIME]; + } + }, + getOptions: (key) => { + const exclude = + key === WEBPACK_MODULE_TYPE_RUNTIME && !options.runtimeModules; + return { + groupChildren: !exclude, + force: exclude + }; + }, + createGroup: (key, children, modules) => { + const exclude = + key === WEBPACK_MODULE_TYPE_RUNTIME && !options.runtimeModules; + return { + type: `${key} modules`, + moduleType: key, + ...(exclude ? { filteredChildren: modules.length } : { children }), + ...moduleGroup(children, modules) + }; + } + }); + } + if (groupModulesByLayer) { + groupConfigs.push({ + getKeys: (module) => /** @type {string[]} */ ([module.layer]), + createGroup: (key, children, modules) => ({ + type: "modules by layer", + layer: key, + children, + ...moduleGroup(children, modules) + }) + }); + } + if (groupModulesByPath || groupModulesByExtension) { + groupConfigs.push({ + getKeys: (module) => { + if (!module.name) return; + const resource = parseResource( + /** @type {string} */ (module.name.split("!").pop()) + ).path; + const dataUrl = /^data:[^,;]+/.exec(resource); + if (dataUrl) return [dataUrl[0]]; + const extensionMatch = + groupModulesByExtension && GROUP_EXTENSION_REGEXP.exec(resource); + const extension = extensionMatch ? extensionMatch[1] : ""; + const pathMatch = + groupModulesByPath && GROUP_PATH_REGEXP.exec(resource); + const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; + const keys = []; + if (groupModulesByPath) { + if (extension) { + keys.push( + path.length + ? `${path.join("/")}/*${extension}` + : `*${extension}` + ); + } + while (path.length > 0) { + keys.push(`${path.join("/")}/`); + path.pop(); + } + } else if (extension) { + keys.push(`*${extension}`); + } + return keys; + }, + createGroup: (key, children, modules) => { + const isDataUrl = key.startsWith("data:"); + return { + type: isDataUrl + ? "modules by mime type" + : groupModulesByPath + ? "modules by path" + : "modules by extension", + name: isDataUrl ? key.slice(/* 'data:'.length */ 5) : key, + children, + ...moduleGroup(children, modules) + }; + } + }); + } + }, + excludeModules: (groupConfigs, context, { excludeModules }) => { + groupConfigs.push({ + getKeys: (module) => { + const name = module.name; + if (name) { + const excluded = excludeModules.some((fn) => fn(name, module, type)); + if (excluded) return ["1"]; + } + }, + getOptions: () => ({ + groupChildren: false, + force: true + }), + createGroup: (key, children, modules) => ({ + type: "hidden modules", + filteredChildren: children.length, + ...moduleGroup(children, modules) + }) + }); + } +}); + +/** @typedef {Record[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} ModuleReasonsGroupers */ + +/** @type {ModuleReasonsGroupers} */ +const MODULE_REASONS_GROUPERS = { + groupReasonsByOrigin: (groupConfigs) => { + groupConfigs.push({ + getKeys: (reason) => /** @type {string[]} */ ([reason.module]), + createGroup: (key, children, reasons) => ({ + type: "from origin", + module: key, + children, + ...reasonGroup(children, reasons) + }) + }); + } +}; + +/** @type {Record} */ +const RESULT_GROUPERS = { + "compilation.assets": ASSETS_GROUPERS, + "asset.related": ASSETS_GROUPERS, + "compilation.modules": MODULES_GROUPERS("module"), + "chunk.modules": MODULES_GROUPERS("chunk"), + "chunk.rootModules": MODULES_GROUPERS("root-of-chunk"), + "module.modules": MODULES_GROUPERS("nested"), + "module.reasons": MODULE_REASONS_GROUPERS +}; + +// remove a prefixed "!" that can be specified to reverse sort order +/** + * @param {string} field a field name + * @returns {field} normalized field + */ +const normalizeFieldKey = (field) => { + if (field[0] === "!") { + return field.slice(1); + } + return field; +}; + +// if a field is prefixed by a "!" reverse sort order +/** + * @param {string} field a field name + * @returns {boolean} result + */ +const sortOrderRegular = (field) => { + if (field[0] === "!") { + return false; + } + return true; +}; + +/** + * @template T + * @param {string | false} field field name + * @returns {(a: T, b: T) => 0 | 1 | -1} comparators + */ +const sortByField = (field) => { + if (!field) { + /** + * @param {T} a first + * @param {T} b second + * @returns {-1 | 0 | 1} zero + */ + const noSort = (a, b) => 0; + return noSort; + } + + const fieldKey = normalizeFieldKey(field); + + let sortFn = compareSelect((m) => m[fieldKey], compareIds); + + // if a field is prefixed with a "!" the sort is reversed! + const sortIsRegular = sortOrderRegular(field); + + if (!sortIsRegular) { + const oldSortFn = sortFn; + sortFn = (a, b) => oldSortFn(b, a); + } + + return sortFn; +}; + +/** @type {Record[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} */ +const ASSET_SORTERS = { + assetsSort: (comparators, context, { assetsSort }) => { + comparators.push(sortByField(assetsSort)); + }, + _: (comparators) => { + comparators.push(compareSelect((a) => a.name, compareIds)); + } +}; + +/** @type {Record[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>>} */ +const RESULT_SORTERS = { + "compilation.chunks": { + chunksSort: (comparators, context, { chunksSort }) => { + comparators.push(sortByField(chunksSort)); + } + }, + "compilation.modules": { + modulesSort: (comparators, context, { modulesSort }) => { + comparators.push(sortByField(modulesSort)); + } + }, + "chunk.modules": { + chunkModulesSort: (comparators, context, { chunkModulesSort }) => { + comparators.push(sortByField(chunkModulesSort)); + } + }, + "module.modules": { + nestedModulesSort: (comparators, context, { nestedModulesSort }) => { + comparators.push(sortByField(nestedModulesSort)); + } + }, + "compilation.assets": ASSET_SORTERS, + "asset.related": ASSET_SORTERS +}; + +/** + * @template T + * @param {Record>} config the config see above + * @param {NormalizedStatsOptions} options stats options + * @param {(hookFor: string, fn: T) => void} fn handler function called for every active line in config + * @returns {void} + */ +const iterateConfig = (config, options, fn) => { + for (const hookFor of Object.keys(config)) { + const subConfig = config[hookFor]; + for (const option of Object.keys(subConfig)) { + if (option !== "_") { + if (option.startsWith("!")) { + if (options[option.slice(1)]) continue; + } else { + const value = options[option]; + if ( + value === false || + value === undefined || + (Array.isArray(value) && value.length === 0) + ) { + continue; + } + } + } + fn(hookFor, subConfig[option]); + } + } +}; + +/** @type {Record} */ +const ITEM_NAMES = { + "compilation.children[]": "compilation", + "compilation.modules[]": "module", + "compilation.entrypoints[]": "chunkGroup", + "compilation.namedChunkGroups[]": "chunkGroup", + "compilation.errors[]": "error", + "compilation.warnings[]": "warning", + "error.errors[]": "error", + "warning.errors[]": "error", + "chunk.modules[]": "module", + "chunk.rootModules[]": "module", + "chunk.origins[]": "chunkOrigin", + "compilation.chunks[]": "chunk", + "compilation.assets[]": "asset", + "asset.related[]": "asset", + "module.issuerPath[]": "moduleIssuer", + "module.reasons[]": "moduleReason", + "module.modules[]": "module", + "module.children[]": "module", + "moduleTrace[]": "moduleTraceItem", + "moduleTraceItem.dependencies[]": "moduleTraceDependency" +}; + +/** + * @template T + * @typedef {{ name: T }} NamedObject + */ + +/** + * @template {{ name: string }} T + * @param {T[]} items items to be merged + * @returns {NamedObject} an object + */ +const mergeToObject = (items) => { + const obj = Object.create(null); + for (const item of items) { + obj[item.name] = item; + } + return obj; +}; + +/** + * @template {{ name: string }} T + * @type {Record NamedObject>} + */ +const MERGER = { + "compilation.entrypoints": mergeToObject, + "compilation.namedChunkGroups": mergeToObject +}; + +const PLUGIN_NAME = "DefaultStatsFactoryPlugin"; + +class DefaultStatsFactoryPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.statsFactory.tap( + PLUGIN_NAME, + /** + * @param {StatsFactory} stats stats factory + * @param {NormalizedStatsOptions} options stats options + */ + (stats, options) => { + iterateConfig( + /** @type {TODO} */ + (SIMPLE_EXTRACTORS), + options, + (hookFor, fn) => { + stats.hooks.extract + .for(hookFor) + .tap(PLUGIN_NAME, (obj, data, ctx) => + fn(obj, data, ctx, options, stats) + ); + } + ); + iterateConfig(FILTER, options, (hookFor, fn) => { + stats.hooks.filter + .for(hookFor) + .tap(PLUGIN_NAME, (item, ctx, idx, i) => + fn(item, ctx, options, idx, i) + ); + }); + iterateConfig(FILTER_RESULTS, options, (hookFor, fn) => { + stats.hooks.filterResults + .for(hookFor) + .tap(PLUGIN_NAME, (item, ctx, idx, i) => + fn(item, ctx, options, idx, i) + ); + }); + iterateConfig(SORTERS, options, (hookFor, fn) => { + stats.hooks.sort + .for(hookFor) + .tap(PLUGIN_NAME, (comparators, ctx) => + fn(comparators, ctx, options) + ); + }); + iterateConfig(RESULT_SORTERS, options, (hookFor, fn) => { + stats.hooks.sortResults + .for(hookFor) + .tap(PLUGIN_NAME, (comparators, ctx) => + fn(comparators, ctx, options) + ); + }); + iterateConfig( + /** @type {TODO} */ + (RESULT_GROUPERS), + options, + (hookFor, fn) => { + stats.hooks.groupResults + .for(hookFor) + .tap(PLUGIN_NAME, (groupConfigs, ctx) => + fn(groupConfigs, ctx, options) + ); + } + ); + for (const key of Object.keys(ITEM_NAMES)) { + const itemName = ITEM_NAMES[key]; + stats.hooks.getItemName.for(key).tap(PLUGIN_NAME, () => itemName); + } + for (const key of Object.keys(MERGER)) { + const merger = MERGER[key]; + stats.hooks.merge.for(key).tap(PLUGIN_NAME, merger); + } + if (options.children) { + if (Array.isArray(options.children)) { + stats.hooks.getItemFactory + .for("compilation.children[].compilation") + .tap( + PLUGIN_NAME, + /** + * @param {Compilation} comp compilation + * @param {StatsFactoryContext} options options + * @returns {StatsFactory | undefined} stats factory + */ + (comp, { _index: idx }) => { + const children = + /** @type {TODO} */ + (options.children); + if (idx < children.length) { + return compilation.createStatsFactory( + compilation.createStatsOptions(children[idx]) + ); + } + } + ); + } else if (options.children !== true) { + const childFactory = compilation.createStatsFactory( + compilation.createStatsOptions(options.children) + ); + stats.hooks.getItemFactory + .for("compilation.children[].compilation") + .tap(PLUGIN_NAME, () => childFactory); + } + } + } + ); + }); + } +} + +module.exports = DefaultStatsFactoryPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/DefaultStatsPresetPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/DefaultStatsPresetPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..016e7d5064aab3edddfbe14dca65979b25fddb50 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/DefaultStatsPresetPlugin.js @@ -0,0 +1,411 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RequestShortener = require("../RequestShortener"); + +/** @typedef {import("../../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../../declarations/WebpackOptions").StatsValue} StatsValue */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */ +/** @typedef {import("../Compilation").KnownNormalizedStatsOptions} KnownNormalizedStatsOptions */ +/** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsError} StatsError */ + +/** + * @param {Partial} options options + * @param {StatsOptions} defaults default options + */ +const applyDefaults = (options, defaults) => { + for (const _k of Object.keys(defaults)) { + const key = /** @type {keyof StatsOptions} */ (_k); + if (typeof options[key] === "undefined") { + options[/** @type {keyof NormalizedStatsOptions} */ (key)] = + defaults[key]; + } + } +}; + +/** @typedef {{ [Key in Exclude]: StatsOptions }} NamedPresets */ + +/** @type {NamedPresets} */ +const NAMED_PRESETS = { + verbose: { + hash: true, + builtAt: true, + relatedAssets: true, + entrypoints: true, + chunkGroups: true, + ids: true, + modules: false, + chunks: true, + chunkRelations: true, + chunkModules: true, + dependentModules: true, + chunkOrigins: true, + depth: true, + env: true, + reasons: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + errorStack: true, + errorCause: true, + errorErrors: true, + publicPath: true, + logging: "verbose", + orphanModules: true, + runtimeModules: true, + exclude: false, + errorsSpace: Infinity, + warningsSpace: Infinity, + modulesSpace: Infinity, + chunkModulesSpace: Infinity, + assetsSpace: Infinity, + reasonsSpace: Infinity, + children: true + }, + detailed: { + hash: true, + builtAt: true, + relatedAssets: true, + entrypoints: true, + chunkGroups: true, + ids: true, + chunks: true, + chunkRelations: true, + chunkModules: false, + chunkOrigins: true, + depth: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + errorCause: true, + errorErrors: true, + publicPath: true, + logging: true, + runtimeModules: true, + exclude: false, + errorsSpace: 1000, + warningsSpace: 1000, + modulesSpace: 1000, + assetsSpace: 1000, + reasonsSpace: 1000 + }, + minimal: { + all: false, + version: true, + timings: true, + modules: true, + errorsSpace: 0, + warningsSpace: 0, + modulesSpace: 0, + assets: true, + assetsSpace: 0, + errors: true, + errorsCount: true, + warnings: true, + warningsCount: true, + logging: "warn" + }, + "errors-only": { + all: false, + errors: true, + errorsCount: true, + errorsSpace: Infinity, + moduleTrace: true, + logging: "error" + }, + "errors-warnings": { + all: false, + errors: true, + errorsCount: true, + errorsSpace: Infinity, + warnings: true, + warningsCount: true, + warningsSpace: Infinity, + logging: "warn" + }, + summary: { + all: false, + version: true, + errorsCount: true, + warningsCount: true + }, + none: { + all: false + } +}; + +/** + * @param {Partial} all stats options + * @returns {boolean} true when enabled, otherwise false + */ +const NORMAL_ON = ({ all }) => all !== false; +/** + * @param {Partial} all stats options + * @returns {boolean} true when enabled, otherwise false + */ +const NORMAL_OFF = ({ all }) => all === true; +/** + * @param {Partial} all stats options + * @param {CreateStatsOptionsContext} forToString stats options context + * @returns {boolean} true when enabled, otherwise false + */ +const ON_FOR_TO_STRING = ({ all }, { forToString }) => + forToString ? all !== false : all === true; +/** + * @param {Partial} all stats options + * @param {CreateStatsOptionsContext} forToString stats options context + * @returns {boolean} true when enabled, otherwise false + */ +const OFF_FOR_TO_STRING = ({ all }, { forToString }) => + forToString ? all === true : all !== false; +/** + * @param {Partial} all stats options + * @param {CreateStatsOptionsContext} forToString stats options context + * @returns {boolean | "auto"} true when enabled, otherwise false + */ +const AUTO_FOR_TO_STRING = ({ all }, { forToString }) => { + if (all === false) return false; + if (all === true) return true; + if (forToString) return "auto"; + return true; +}; + +/** @typedef {keyof NormalizedStatsOptions} DefaultsKeys */ +/** @typedef {{ [Key in DefaultsKeys]: (options: Partial, context: CreateStatsOptionsContext, compilation: Compilation) => NormalizedStatsOptions[Key] | RequestShortener }} Defaults */ + +/** @type {Defaults} */ +const DEFAULTS = { + context: (options, context, compilation) => compilation.compiler.context, + requestShortener: (options, context, compilation) => + compilation.compiler.context === options.context + ? compilation.requestShortener + : new RequestShortener( + /** @type {string} */ + (options.context), + compilation.compiler.root + ), + performance: NORMAL_ON, + hash: OFF_FOR_TO_STRING, + env: NORMAL_OFF, + version: NORMAL_ON, + timings: NORMAL_ON, + builtAt: OFF_FOR_TO_STRING, + assets: NORMAL_ON, + entrypoints: AUTO_FOR_TO_STRING, + chunkGroups: OFF_FOR_TO_STRING, + chunkGroupAuxiliary: OFF_FOR_TO_STRING, + chunkGroupChildren: OFF_FOR_TO_STRING, + chunkGroupMaxAssets: (o, { forToString }) => (forToString ? 5 : Infinity), + chunks: OFF_FOR_TO_STRING, + chunkRelations: OFF_FOR_TO_STRING, + chunkModules: ({ all, modules }) => { + if (all === false) return false; + if (all === true) return true; + if (modules) return false; + return true; + }, + dependentModules: OFF_FOR_TO_STRING, + chunkOrigins: OFF_FOR_TO_STRING, + ids: OFF_FOR_TO_STRING, + modules: ({ all, chunks, chunkModules }, { forToString }) => { + if (all === false) return false; + if (all === true) return true; + if (forToString && chunks && chunkModules) return false; + return true; + }, + nestedModules: OFF_FOR_TO_STRING, + groupModulesByType: ON_FOR_TO_STRING, + groupModulesByCacheStatus: ON_FOR_TO_STRING, + groupModulesByLayer: ON_FOR_TO_STRING, + groupModulesByAttributes: ON_FOR_TO_STRING, + groupModulesByPath: ON_FOR_TO_STRING, + groupModulesByExtension: ON_FOR_TO_STRING, + modulesSpace: (o, { forToString }) => (forToString ? 15 : Infinity), + chunkModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), + nestedModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), + relatedAssets: OFF_FOR_TO_STRING, + groupAssetsByEmitStatus: ON_FOR_TO_STRING, + groupAssetsByInfo: ON_FOR_TO_STRING, + groupAssetsByPath: ON_FOR_TO_STRING, + groupAssetsByExtension: ON_FOR_TO_STRING, + groupAssetsByChunk: ON_FOR_TO_STRING, + assetsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), + orphanModules: OFF_FOR_TO_STRING, + runtimeModules: ({ all, runtime }, { forToString }) => + runtime !== undefined + ? runtime + : forToString + ? all === true + : all !== false, + cachedModules: ({ all, cached }, { forToString }) => + cached !== undefined ? cached : forToString ? all === true : all !== false, + moduleAssets: OFF_FOR_TO_STRING, + depth: OFF_FOR_TO_STRING, + cachedAssets: OFF_FOR_TO_STRING, + reasons: OFF_FOR_TO_STRING, + reasonsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), + groupReasonsByOrigin: ON_FOR_TO_STRING, + usedExports: OFF_FOR_TO_STRING, + providedExports: OFF_FOR_TO_STRING, + optimizationBailout: OFF_FOR_TO_STRING, + children: OFF_FOR_TO_STRING, + source: NORMAL_OFF, + moduleTrace: NORMAL_ON, + errors: NORMAL_ON, + errorsCount: NORMAL_ON, + errorDetails: AUTO_FOR_TO_STRING, + errorStack: OFF_FOR_TO_STRING, + errorCause: AUTO_FOR_TO_STRING, + errorErrors: AUTO_FOR_TO_STRING, + warnings: NORMAL_ON, + warningsCount: NORMAL_ON, + publicPath: OFF_FOR_TO_STRING, + logging: ({ all }, { forToString }) => + forToString && all !== false ? "info" : false, + loggingDebug: () => [], + loggingTrace: OFF_FOR_TO_STRING, + excludeModules: () => [], + excludeAssets: () => [], + modulesSort: () => "depth", + chunkModulesSort: () => "name", + nestedModulesSort: () => false, + chunksSort: () => false, + assetsSort: () => "!size", + outputPath: OFF_FOR_TO_STRING, + colors: () => false +}; + +/** + * @template {string} T + * @param {string | ({ test: (value: T) => boolean }) | ((value: T, ...args: EXPECTED_ANY[]) => boolean) | boolean} item item to normalize + * @returns {(value: T, ...args: EXPECTED_ANY[]) => boolean} normalize fn + */ +const normalizeFilter = (item) => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace(/[-[\]{}()*+?.\\^$|]/g, "\\$&")}([\\\\/]|$|!|\\?)` + ); + return (ident) => regExp.test(/** @type {T} */ (ident)); + } + if (item && typeof item === "object" && typeof item.test === "function") { + return (ident) => item.test(ident); + } + if (typeof item === "boolean") { + return () => item; + } + + return /** @type {(value: T, ...args: EXPECTED_ANY[]) => boolean} */ (item); +}; + +/** @typedef {keyof (KnownNormalizedStatsOptions | StatsOptions)} NormalizerKeys */ +/** @typedef {{ [Key in NormalizerKeys]?: (value: StatsOptions[Key]) => KnownNormalizedStatsOptions[Key] }} Normalizers */ + +/** @type {Normalizers} */ +const NORMALIZER = { + excludeModules: (value) => { + if (!Array.isArray(value)) { + value = value + ? /** @type {KnownNormalizedStatsOptions["excludeModules"]} */ ([value]) + : []; + } + return value.map(normalizeFilter); + }, + excludeAssets: (value) => { + if (!Array.isArray(value)) { + value = value ? [value] : []; + } + return value.map(normalizeFilter); + }, + warningsFilter: (value) => { + if (!Array.isArray(value)) { + value = value ? [value] : []; + } + /** + * @callback WarningFilterFn + * @param {StatsError} warning warning + * @param {string} warningString warning string + * @returns {boolean} result + */ + return value.map( + /** + * @param {StatsOptions["warningsFilter"]} filter a warning filter + * @returns {WarningFilterFn} result + */ + (filter) => { + if (typeof filter === "string") { + return (warning, warningString) => warningString.includes(filter); + } + if (filter instanceof RegExp) { + return (warning, warningString) => filter.test(warningString); + } + if (typeof filter === "function") { + return filter; + } + throw new Error( + `Can only filter warnings with Strings or RegExps. (Given: ${filter})` + ); + } + ); + }, + logging: (value) => { + if (value === true) value = "log"; + return /** @type {KnownNormalizedStatsOptions["logging"]} */ (value); + }, + loggingDebug: (value) => { + if (!Array.isArray(value)) { + value = value + ? /** @type {KnownNormalizedStatsOptions["loggingDebug"]} */ ([value]) + : []; + } + return value.map(normalizeFilter); + } +}; + +const PLUGIN_NAME = "DefaultStatsPresetPlugin"; + +class DefaultStatsPresetPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + for (const key of Object.keys(NAMED_PRESETS)) { + const defaults = NAMED_PRESETS[/** @type {keyof NamedPresets} */ (key)]; + compilation.hooks.statsPreset + .for(key) + .tap(PLUGIN_NAME, (options, _context) => { + applyDefaults(options, defaults); + }); + } + compilation.hooks.statsNormalize.tap(PLUGIN_NAME, (options, context) => { + for (const key of Object.keys(DEFAULTS)) { + if (options[key] === undefined) { + options[key] = DEFAULTS[/** @type {DefaultsKeys} */ (key)]( + options, + context, + compilation + ); + } + } + for (const key of Object.keys(NORMALIZER)) { + options[key] = + /** @type {NonNullable} */ + (NORMALIZER[/** @type {NormalizerKeys} */ (key)])(options[key]); + } + }); + }); + } +} + +module.exports = DefaultStatsPresetPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/DefaultStatsPrinterPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/DefaultStatsPrinterPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..86c5c45deee9a986f4951d5d3de7e32f487d6e84 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/DefaultStatsPrinterPlugin.js @@ -0,0 +1,1895 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../logging/Logger").LogTypeEnum} LogTypeEnum */ +/** @typedef {import("./DefaultStatsFactoryPlugin").ChunkId} ChunkId */ +/** @typedef {import("./DefaultStatsFactoryPlugin").ChunkName} ChunkName */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsAsset} KnownStatsAsset */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsAssetChunk} KnownStatsAssetChunk */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsAssetChunkIdHint} KnownStatsAssetChunkIdHint */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsAssetChunkName} KnownStatsAssetChunkName */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsChunk} KnownStatsChunk */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsChunkGroup} KnownStatsChunkGroup */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsChunkOrigin} KnownStatsChunkOrigin */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsCompilation} KnownStatsCompilation */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsError} KnownStatsError */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsLogging} KnownStatsLogging */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsLoggingEntry} KnownStatsLoggingEntry */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsModule} KnownStatsModule */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsModuleIssuer} KnownStatsModuleIssuer */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsModuleReason} KnownStatsModuleReason */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsModuleTraceDependency} KnownStatsModuleTraceDependency */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsModuleTraceItem} KnownStatsModuleTraceItem */ +/** @typedef {import("./DefaultStatsFactoryPlugin").KnownStatsProfile} KnownStatsProfile */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ +/** @typedef {import("./StatsPrinter")} StatsPrinter */ +/** @typedef {import("./StatsPrinter").ColorFunction} ColorFunction */ +/** @typedef {import("./StatsPrinter").KnownStatsPrinterColorFunctions} KnownStatsPrinterColorFunctions */ +/** @typedef {import("./StatsPrinter").KnownStatsPrinterContext} KnownStatsPrinterContext */ +/** @typedef {import("./StatsPrinter").KnownStatsPrinterFormatters} KnownStatsPrinterFormatters */ +/** @typedef {import("./StatsPrinter").StatsPrinterContext} StatsPrinterContext */ +/** @typedef {import("./StatsPrinter").StatsPrinterContextWithExtra} StatsPrinterContextWithExtra */ + +const DATA_URI_CONTENT_LENGTH = 16; +const MAX_MODULE_IDENTIFIER_LENGTH = 80; + +/** + * @param {number} n a number + * @param {string} singular singular + * @param {string} plural plural + * @returns {string} if n is 1, singular, else plural + */ +const plural = (n, singular, plural) => (n === 1 ? singular : plural); + +/** + * @param {Record} sizes sizes by source type + * @param {StatsPrinterContext} options options + * @returns {string | undefined} text + */ +const printSizes = (sizes, { formatSize = (n) => `${n}` }) => { + const keys = Object.keys(sizes); + if (keys.length > 1) { + return keys.map((key) => `${formatSize(sizes[key])} (${key})`).join(" "); + } else if (keys.length === 1) { + return formatSize(sizes[keys[0]]); + } +}; + +/** + * @param {string | null} resource resource + * @returns {string} resource name for display + */ +const getResourceName = (resource) => { + if (!resource) return ""; + const dataUrl = /^data:[^,]+,/.exec(resource); + if (!dataUrl) return resource; + + const len = dataUrl[0].length + DATA_URI_CONTENT_LENGTH; + if (resource.length < len) return resource; + return `${resource.slice( + 0, + Math.min(resource.length - /* '..'.length */ 2, len) + )}..`; +}; + +/** + * @param {string} name module name + * @returns {[string,string]} prefix and module name + */ +const getModuleName = (name) => { + const [, prefix, resource] = + /** @type {[string, string, string]} */ + (/** @type {unknown} */ (/^(.*!)?([^!]*)$/.exec(name))); + + if (resource.length > MAX_MODULE_IDENTIFIER_LENGTH) { + const truncatedResource = `${resource.slice( + 0, + Math.min( + resource.length - /* '...(truncated)'.length */ 14, + MAX_MODULE_IDENTIFIER_LENGTH + ) + )}...(truncated)`; + + return [prefix, getResourceName(truncatedResource)]; + } + + return [prefix, getResourceName(resource)]; +}; + +/** + * @param {string} str string + * @param {(item: string) => string} fn function to apply to each line + * @returns {string} joined string + */ +const mapLines = (str, fn) => str.split("\n").map(fn).join("\n"); + +/** + * @param {number} n a number + * @returns {string} number as two digit string, leading 0 + */ +const twoDigit = (n) => (n >= 10 ? `${n}` : `0${n}`); + +/** + * @param {string | number | null} id an id + * @returns {id is string | number} is i + */ +const isValidId = (id) => { + if (typeof id === "number" || id) { + return true; + } + + return false; +}; + +/** + * @template T + * @param {Array | undefined} list of items + * @param {number} count number of items to show + * @returns {string} string representation of list + */ +const moreCount = (list, count) => + list && list.length > 0 ? `+ ${count}` : `${count}`; + +/** + * @template T + * @template {keyof T} K + * @typedef {{ [P in K]-?: T[P] }} WithRequired + */ + +/** + * @template {keyof StatsPrinterContext} RequiredStatsPrinterContextKeys + * @typedef {StatsPrinterContextWithExtra & WithRequired} DefineStatsPrinterContext + */ + +/** + * @template T + * @template {keyof StatsPrinterContext} RequiredStatsPrinterContextKeys + * @typedef {(thing: Exclude, context: DefineStatsPrinterContext, printer: StatsPrinter) => string | undefined} SimplePrinter + */ + +/** + * @template T + * @typedef {T extends (infer U)[] ? U : T} Unpacked + */ + +/** + * @template {object} O + * @template {keyof O} K + * @template {string} B + * @typedef {K extends string ? Exclude extends EXPECTED_ANY[] ? never : `${B}.${K}` : never} PropertyName + */ + +/** + * @template {object} O + * @template {keyof O} K + * @template {string} B + * @typedef {K extends string ? NonNullable extends EXPECTED_ANY[] ? `${B}.${K}[]` : never : never} ArrayPropertyName + */ + +/** + * @template {object} O + * @template {keyof O} K + * @template {string} B + * @typedef {K extends string ? Exclude extends EXPECTED_ANY[] ? `${B}.${K}` : never : never} MultiplePropertyName + */ + +/** + * @template {object} O + * @template {string} K + * @template {string} E + * @typedef {{ [property in `${K}!`]?: SimplePrinter }} Exclamation + */ + +/** + * @template {object} O + * @template {string} B + * @template {string} [R=B] + * @typedef {{ [K in keyof O as PropertyName]?: SimplePrinter } & + * { [K in keyof O as ArrayPropertyName]?: Exclude extends (infer I)[] ? SimplePrinter : never } & + * { [K in keyof O as MultiplePropertyName]?: SimplePrinter } + * } Printers + */ + +/** + * @typedef {Printers & + * { ["compilation.summary!"]?: SimplePrinter } & + * { ["compilation.errorsInChildren!"]?: SimplePrinter } & + * { ["compilation.warningsInChildren!"]?: SimplePrinter }} CompilationSimplePrinters + */ + +/** + * @type {CompilationSimplePrinters} + */ +const COMPILATION_SIMPLE_PRINTERS = { + "compilation.summary!": ( + _, + { + type, + bold, + green, + red, + yellow, + formatDateTime, + formatTime, + compilation: { + name, + hash, + version, + time, + builtAt, + errorsCount, + warningsCount + } + } + ) => { + const root = type === "compilation.summary!"; + const warningsMessage = + /** @type {number} */ (warningsCount) > 0 + ? yellow( + `${warningsCount} ${plural(/** @type {number} */ (warningsCount), "warning", "warnings")}` + ) + : ""; + const errorsMessage = + /** @type {number} */ (errorsCount) > 0 + ? red( + `${errorsCount} ${plural(/** @type {number} */ (errorsCount), "error", "errors")}` + ) + : ""; + const timeMessage = root && time ? ` in ${formatTime(time)}` : ""; + const hashMessage = hash ? ` (${hash})` : ""; + const builtAtMessage = + root && builtAt ? `${formatDateTime(builtAt)}: ` : ""; + const versionMessage = root && version ? `webpack ${version}` : ""; + const nameMessage = + root && name + ? bold(name) + : name + ? `Child ${bold(name)}` + : root + ? "" + : "Child"; + const subjectMessage = + nameMessage && versionMessage + ? `${nameMessage} (${versionMessage})` + : versionMessage || nameMessage || "webpack"; + let statusMessage; + if (errorsMessage && warningsMessage) { + statusMessage = `compiled with ${errorsMessage} and ${warningsMessage}`; + } else if (errorsMessage) { + statusMessage = `compiled with ${errorsMessage}`; + } else if (warningsMessage) { + statusMessage = `compiled with ${warningsMessage}`; + } else if (errorsCount === 0 && warningsCount === 0) { + statusMessage = `compiled ${green("successfully")}`; + } else { + statusMessage = "compiled"; + } + if ( + builtAtMessage || + versionMessage || + errorsMessage || + warningsMessage || + (errorsCount === 0 && warningsCount === 0) || + timeMessage || + hashMessage + ) { + return `${builtAtMessage}${subjectMessage} ${statusMessage}${timeMessage}${hashMessage}`; + } + }, + "compilation.filteredWarningDetailsCount": (count) => + count + ? `${count} ${plural( + count, + "warning has", + "warnings have" + )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` + : undefined, + "compilation.filteredErrorDetailsCount": (count, { yellow }) => + count + ? yellow( + `${count} ${plural( + count, + "error has", + "errors have" + )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` + ) + : undefined, + "compilation.env": (env, { bold }) => + env + ? `Environment (--env): ${bold(JSON.stringify(env, null, 2))}` + : undefined, + "compilation.publicPath": (publicPath, { bold }) => + `PublicPath: ${bold(publicPath || "(none)")}`, + "compilation.entrypoints": (entrypoints, context, printer) => + Array.isArray(entrypoints) + ? undefined + : printer.print(context.type, Object.values(entrypoints), { + ...context, + chunkGroupKind: "Entrypoint" + }), + "compilation.namedChunkGroups": (namedChunkGroups, context, printer) => { + if (!Array.isArray(namedChunkGroups)) { + const { + compilation: { entrypoints } + } = context; + let chunkGroups = Object.values(namedChunkGroups); + if (entrypoints) { + chunkGroups = chunkGroups.filter( + (group) => + !Object.prototype.hasOwnProperty.call( + entrypoints, + /** @type {string} */ + (group.name) + ) + ); + } + return printer.print(context.type, chunkGroups, { + ...context, + chunkGroupKind: "Chunk Group" + }); + } + }, + "compilation.assetsByChunkName": () => "", + + "compilation.filteredModules": ( + filteredModules, + { compilation: { modules } } + ) => + filteredModules > 0 + ? `${moreCount(modules, filteredModules)} ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "compilation.filteredAssets": ( + filteredAssets, + { compilation: { assets } } + ) => + filteredAssets > 0 + ? `${moreCount(assets, filteredAssets)} ${plural( + filteredAssets, + "asset", + "assets" + )}` + : undefined, + "compilation.logging": (logging, context, printer) => + Array.isArray(logging) + ? undefined + : printer.print( + context.type, + Object.entries(logging).map(([name, value]) => ({ ...value, name })), + context + ), + "compilation.warningsInChildren!": (_, { yellow, compilation }) => { + if ( + !compilation.children && + /** @type {number} */ (compilation.warningsCount) > 0 && + compilation.warnings + ) { + const childWarnings = + /** @type {number} */ (compilation.warningsCount) - + compilation.warnings.length; + if (childWarnings > 0) { + return yellow( + `${childWarnings} ${plural( + childWarnings, + "WARNING", + "WARNINGS" + )} in child compilations${ + compilation.children + ? "" + : " (Use 'stats.children: true' resp. '--stats-children' for more details)" + }` + ); + } + } + }, + "compilation.errorsInChildren!": (_, { red, compilation }) => { + if ( + !compilation.children && + /** @type {number} */ (compilation.errorsCount) > 0 && + compilation.errors + ) { + const childErrors = + /** @type {number} */ (compilation.errorsCount) - + compilation.errors.length; + if (childErrors > 0) { + return red( + `${childErrors} ${plural( + childErrors, + "ERROR", + "ERRORS" + )} in child compilations${ + compilation.children + ? "" + : " (Use 'stats.children: true' resp. '--stats-children' for more details)" + }` + ); + } + } + } +}; + +/** + * @typedef {Printers & + * Printers & + * Exclamation & + * { ["asset.filteredChildren"]?: SimplePrinter } & + * { assetChunk?: SimplePrinter } & + * { assetChunkName?: SimplePrinter } & + * { assetChunkIdHint?: SimplePrinter }} AssetSimplePrinters + */ + +/** @type {AssetSimplePrinters} */ +const ASSET_SIMPLE_PRINTERS = { + "asset.type": (type) => type, + "asset.name": (name, { formatFilename, asset: { isOverSizeLimit } }) => + formatFilename(name, isOverSizeLimit), + "asset.size": (size, { asset: { isOverSizeLimit }, yellow, formatSize }) => + isOverSizeLimit ? yellow(formatSize(size)) : formatSize(size), + "asset.emitted": (emitted, { green, formatFlag }) => + emitted ? green(formatFlag("emitted")) : undefined, + "asset.comparedForEmit": (comparedForEmit, { yellow, formatFlag }) => + comparedForEmit ? yellow(formatFlag("compared for emit")) : undefined, + "asset.cached": (cached, { green, formatFlag }) => + cached ? green(formatFlag("cached")) : undefined, + "asset.isOverSizeLimit": (isOverSizeLimit, { yellow, formatFlag }) => + isOverSizeLimit ? yellow(formatFlag("big")) : undefined, + + "asset.info.immutable": (immutable, { green, formatFlag }) => + immutable ? green(formatFlag("immutable")) : undefined, + "asset.info.javascriptModule": (javascriptModule, { formatFlag }) => + javascriptModule ? formatFlag("javascript module") : undefined, + "asset.info.sourceFilename": (sourceFilename, { formatFlag }) => + sourceFilename ? formatFlag(`from: ${sourceFilename}`) : undefined, + "asset.info.development": (development, { green, formatFlag }) => + development ? green(formatFlag("dev")) : undefined, + "asset.info.hotModuleReplacement": ( + hotModuleReplacement, + { green, formatFlag } + ) => (hotModuleReplacement ? green(formatFlag("hmr")) : undefined), + "asset.separator!": () => "\n", + "asset.filteredRelated": (filteredRelated, { asset: { related } }) => + filteredRelated > 0 + ? `${moreCount(related, filteredRelated)} related ${plural( + filteredRelated, + "asset", + "assets" + )}` + : undefined, + "asset.filteredChildren": (filteredChildren, { asset: { children } }) => + filteredChildren > 0 + ? `${moreCount(children, filteredChildren)} ${plural( + filteredChildren, + "asset", + "assets" + )}` + : undefined, + + assetChunk: (id, { formatChunkId }) => formatChunkId(id), + + assetChunkName: (name) => name || undefined, + assetChunkIdHint: (name) => name || undefined +}; + +/** + * @typedef {Printers & + * Exclamation & + * { ["module.filteredChildren"]?: SimplePrinter } & + * { ["module.filteredReasons"]?: SimplePrinter }} ModuleSimplePrinters + */ + +/** @type {ModuleSimplePrinters} */ +const MODULE_SIMPLE_PRINTERS = { + "module.type": (type) => (type !== "module" ? type : undefined), + "module.id": (id, { formatModuleId }) => + isValidId(id) ? formatModuleId(id) : undefined, + "module.name": (name, { bold }) => { + const [prefix, resource] = getModuleName(name); + return `${prefix || ""}${bold(resource || "")}`; + }, + "module.identifier": (_identifier) => undefined, + "module.layer": (layer, { formatLayer }) => + layer ? formatLayer(layer) : undefined, + "module.sizes": printSizes, + "module.chunks[]": (id, { formatChunkId }) => formatChunkId(id), + "module.depth": (depth, { formatFlag }) => + depth !== null ? formatFlag(`depth ${depth}`) : undefined, + "module.cacheable": (cacheable, { formatFlag, red }) => + cacheable === false ? red(formatFlag("not cacheable")) : undefined, + "module.orphan": (orphan, { formatFlag, yellow }) => + orphan ? yellow(formatFlag("orphan")) : undefined, + // "module.runtime": (runtime, { formatFlag, yellow }) => + // runtime ? yellow(formatFlag("runtime")) : undefined, + "module.optional": (optional, { formatFlag, yellow }) => + optional ? yellow(formatFlag("optional")) : undefined, + "module.dependent": (dependent, { formatFlag, cyan }) => + dependent ? cyan(formatFlag("dependent")) : undefined, + "module.built": (built, { formatFlag, yellow }) => + built ? yellow(formatFlag("built")) : undefined, + "module.codeGenerated": (codeGenerated, { formatFlag, yellow }) => + codeGenerated ? yellow(formatFlag("code generated")) : undefined, + "module.buildTimeExecuted": (buildTimeExecuted, { formatFlag, green }) => + buildTimeExecuted ? green(formatFlag("build time executed")) : undefined, + "module.cached": (cached, { formatFlag, green }) => + cached ? green(formatFlag("cached")) : undefined, + "module.assets": (assets, { formatFlag, magenta }) => + assets && assets.length + ? magenta( + formatFlag( + `${assets.length} ${plural(assets.length, "asset", "assets")}` + ) + ) + : undefined, + "module.warnings": (warnings, { formatFlag, yellow }) => + warnings + ? yellow( + formatFlag(`${warnings} ${plural(warnings, "warning", "warnings")}`) + ) + : undefined, + "module.errors": (errors, { formatFlag, red }) => + errors + ? red(formatFlag(`${errors} ${plural(errors, "error", "errors")}`)) + : undefined, + "module.providedExports": (providedExports, { formatFlag, cyan }) => { + if (Array.isArray(providedExports)) { + if (providedExports.length === 0) return cyan(formatFlag("no exports")); + return cyan(formatFlag(`exports: ${providedExports.join(", ")}`)); + } + }, + "module.usedExports": (usedExports, { formatFlag, cyan, module }) => { + if (usedExports !== true) { + if (usedExports === null) return cyan(formatFlag("used exports unknown")); + if (usedExports === false) return cyan(formatFlag("module unused")); + if (Array.isArray(usedExports)) { + if (usedExports.length === 0) { + return cyan(formatFlag("no exports used")); + } + const providedExportsCount = Array.isArray(module.providedExports) + ? module.providedExports.length + : null; + if ( + providedExportsCount !== null && + providedExportsCount === usedExports.length + ) { + return cyan(formatFlag("all exports used")); + } + + return cyan( + formatFlag(`only some exports used: ${usedExports.join(", ")}`) + ); + } + } + }, + "module.optimizationBailout[]": (optimizationBailout, { yellow }) => + yellow(optimizationBailout), + "module.issuerPath": (issuerPath, { module }) => + module.profile ? undefined : "", + "module.profile": (_profile) => undefined, + "module.filteredModules": (filteredModules, { module: { modules } }) => + filteredModules > 0 + ? `${moreCount(modules, filteredModules)} nested ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "module.filteredReasons": (filteredReasons, { module: { reasons } }) => + filteredReasons > 0 + ? `${moreCount(reasons, filteredReasons)} ${plural( + filteredReasons, + "reason", + "reasons" + )}` + : undefined, + "module.filteredChildren": (filteredChildren, { module: { children } }) => + filteredChildren > 0 + ? `${moreCount(children, filteredChildren)} ${plural( + filteredChildren, + "module", + "modules" + )}` + : undefined, + "module.separator!": () => "\n" +}; + +/** + * @typedef {Printers & + * Printers} ModuleIssuerPrinters + */ + +/** @type {ModuleIssuerPrinters} */ +const MODULE_ISSUER_PRINTERS = { + "moduleIssuer.id": (id, { formatModuleId }) => formatModuleId(id), + "moduleIssuer.profile.total": (value, { formatTime }) => formatTime(value) +}; + +/** + * @typedef {Printers & + * { ["moduleReason.filteredChildren"]?: SimplePrinter }} ModuleReasonsPrinters + */ + +/** @type {ModuleReasonsPrinters} */ +const MODULE_REASON_PRINTERS = { + "moduleReason.type": (type) => type || undefined, + "moduleReason.userRequest": (userRequest, { cyan }) => + cyan(getResourceName(userRequest)), + "moduleReason.moduleId": (moduleId, { formatModuleId }) => + isValidId(moduleId) ? formatModuleId(moduleId) : undefined, + "moduleReason.module": (module, { magenta }) => + module ? magenta(module) : undefined, + "moduleReason.loc": (loc) => loc || undefined, + "moduleReason.explanation": (explanation, { cyan }) => + explanation ? cyan(explanation) : undefined, + "moduleReason.active": (active, { formatFlag }) => + active ? undefined : formatFlag("inactive"), + "moduleReason.resolvedModule": (module, { magenta }) => + module ? magenta(module) : undefined, + "moduleReason.filteredChildren": ( + filteredChildren, + { moduleReason: { children } } + ) => + filteredChildren > 0 + ? `${moreCount(children, filteredChildren)} ${plural( + filteredChildren, + "reason", + "reasons" + )}` + : undefined +}; + +/** @typedef {Printers} ModuleProfilePrinters */ + +/** @type {ModuleProfilePrinters} */ +const MODULE_PROFILE_PRINTERS = { + "module.profile.total": (value, { formatTime }) => formatTime(value), + "module.profile.resolving": (value, { formatTime }) => + `resolving: ${formatTime(value)}`, + "module.profile.restoring": (value, { formatTime }) => + `restoring: ${formatTime(value)}`, + "module.profile.integration": (value, { formatTime }) => + `integration: ${formatTime(value)}`, + "module.profile.building": (value, { formatTime }) => + `building: ${formatTime(value)}`, + "module.profile.storing": (value, { formatTime }) => + `storing: ${formatTime(value)}`, + "module.profile.additionalResolving": (value, { formatTime }) => + value ? `additional resolving: ${formatTime(value)}` : undefined, + "module.profile.additionalIntegration": (value, { formatTime }) => + value ? `additional integration: ${formatTime(value)}` : undefined +}; + +/** + * @typedef {Exclamation & + * Exclamation & + * Printers & + * Exclamation & + * Printers[number], "chunkGroupAsset" | "chunkGroup"> & + * { ['chunkGroupChildGroup.type']?: SimplePrinter } & + * { ['chunkGroupChild.assets[]']?: SimplePrinter } & + * { ['chunkGroupChild.chunks[]']?: SimplePrinter } & + * { ['chunkGroupChild.name']?: SimplePrinter }} ChunkGroupPrinters + */ + +/** @type {ChunkGroupPrinters} */ +const CHUNK_GROUP_PRINTERS = { + "chunkGroup.kind!": (_, { chunkGroupKind }) => chunkGroupKind, + "chunkGroup.separator!": () => "\n", + "chunkGroup.name": (name, { bold }) => (name ? bold(name) : undefined), + "chunkGroup.isOverSizeLimit": (isOverSizeLimit, { formatFlag, yellow }) => + isOverSizeLimit ? yellow(formatFlag("big")) : undefined, + "chunkGroup.assetsSize": (size, { formatSize }) => + size ? formatSize(size) : undefined, + "chunkGroup.auxiliaryAssetsSize": (size, { formatSize }) => + size ? `(${formatSize(size)})` : undefined, + "chunkGroup.filteredAssets": (n, { chunkGroup: { assets } }) => + n > 0 + ? `${moreCount(assets, n)} ${plural(n, "asset", "assets")}` + : undefined, + "chunkGroup.filteredAuxiliaryAssets": ( + n, + { chunkGroup: { auxiliaryAssets } } + ) => + n > 0 + ? `${moreCount(auxiliaryAssets, n)} auxiliary ${plural( + n, + "asset", + "assets" + )}` + : undefined, + "chunkGroup.is!": () => "=", + "chunkGroupAsset.name": (asset, { green }) => green(asset), + "chunkGroupAsset.size": (size, { formatSize, chunkGroup }) => + chunkGroup.assets && + (chunkGroup.assets.length > 1 || + (chunkGroup.auxiliaryAssets && chunkGroup.auxiliaryAssets.length > 0) + ? formatSize(size) + : undefined), + "chunkGroup.children": (children, context, printer) => + Array.isArray(children) + ? undefined + : printer.print( + context.type, + Object.keys(children).map((key) => ({ + type: key, + children: children[key] + })), + context + ), + "chunkGroupChildGroup.type": (type) => `${type}:`, + "chunkGroupChild.assets[]": (file, { formatFilename }) => + formatFilename(file), + "chunkGroupChild.chunks[]": (id, { formatChunkId }) => formatChunkId(id), + "chunkGroupChild.name": (name) => (name ? `(name: ${name})` : undefined) +}; + +/** + * @typedef {Printers & + * { ["chunk.childrenByOrder[].type"]: SimplePrinter } & + * { ["chunk.childrenByOrder[].children[]"]: SimplePrinter } & + * Exclamation & + * Printers} ChunkPrinters + */ + +/** @type {ChunkPrinters} */ +const CHUNK_PRINTERS = { + "chunk.id": (id, { formatChunkId }) => formatChunkId(id), + "chunk.files[]": (file, { formatFilename }) => formatFilename(file), + "chunk.names[]": (name) => name, + "chunk.idHints[]": (name) => name, + "chunk.runtime[]": (name) => name, + "chunk.sizes": (sizes, context) => printSizes(sizes, context), + "chunk.parents[]": (parents, context) => + context.formatChunkId(parents, "parent"), + "chunk.siblings[]": (siblings, context) => + context.formatChunkId(siblings, "sibling"), + "chunk.children[]": (children, context) => + context.formatChunkId(children, "child"), + "chunk.childrenByOrder": (childrenByOrder, context, printer) => + Array.isArray(childrenByOrder) + ? undefined + : printer.print( + context.type, + Object.keys(childrenByOrder).map((key) => ({ + type: key, + children: childrenByOrder[key] + })), + context + ), + "chunk.childrenByOrder[].type": (type) => `${type}:`, + "chunk.childrenByOrder[].children[]": (id, { formatChunkId }) => + isValidId(id) ? formatChunkId(id) : undefined, + "chunk.entry": (entry, { formatFlag, yellow }) => + entry ? yellow(formatFlag("entry")) : undefined, + "chunk.initial": (initial, { formatFlag, yellow }) => + initial ? yellow(formatFlag("initial")) : undefined, + "chunk.rendered": (rendered, { formatFlag, green }) => + rendered ? green(formatFlag("rendered")) : undefined, + "chunk.recorded": (recorded, { formatFlag, green }) => + recorded ? green(formatFlag("recorded")) : undefined, + "chunk.reason": (reason, { yellow }) => (reason ? yellow(reason) : undefined), + "chunk.filteredModules": (filteredModules, { chunk: { modules } }) => + filteredModules > 0 + ? `${moreCount(modules, filteredModules)} chunk ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "chunk.separator!": () => "\n", + + "chunkOrigin.request": (request) => request, + "chunkOrigin.moduleId": (moduleId, { formatModuleId }) => + isValidId(moduleId) ? formatModuleId(moduleId) : undefined, + "chunkOrigin.moduleName": (moduleName, { bold }) => bold(moduleName), + "chunkOrigin.loc": (loc) => loc +}; + +/** + * @typedef {Printers & + * { ["error.filteredDetails"]?: SimplePrinter } & + * Exclamation} ErrorPrinters + */ + +/** + * @type {ErrorPrinters} + */ +const ERROR_PRINTERS = { + "error.compilerPath": (compilerPath, { bold }) => + compilerPath ? bold(`(${compilerPath})`) : undefined, + "error.chunkId": (chunkId, { formatChunkId }) => + isValidId(chunkId) ? formatChunkId(chunkId) : undefined, + "error.chunkEntry": (chunkEntry, { formatFlag }) => + chunkEntry ? formatFlag("entry") : undefined, + "error.chunkInitial": (chunkInitial, { formatFlag }) => + chunkInitial ? formatFlag("initial") : undefined, + "error.file": (file, { bold }) => bold(file), + "error.moduleName": (moduleName, { bold }) => + moduleName.includes("!") + ? `${bold(moduleName.replace(/^(\s|\S)*!/, ""))} (${moduleName})` + : `${bold(moduleName)}`, + "error.loc": (loc, { green }) => green(loc), + "error.message": (message, { bold, formatError }) => + message.includes("\u001B[") ? message : bold(formatError(message)), + "error.details": (details, { formatError }) => formatError(details), + "error.filteredDetails": (filteredDetails) => + filteredDetails ? `+ ${filteredDetails} hidden lines` : undefined, + "error.stack": (stack) => stack, + "error.cause": (cause, context, printer) => + cause + ? indent( + `[cause]: ${ + /** @type {string} */ + (printer.print(`${context.type}.error`, cause, context)) + }`, + " " + ) + : undefined, + "error.moduleTrace": (_moduleTrace) => undefined, + "error.separator!": () => "\n" +}; + +/** + * @typedef {Printers & + * { ["loggingEntry(clear).loggingEntry"]?: SimplePrinter } & + * { ["loggingEntry.trace[]"]?: SimplePrinter[number], "logging"> } & + * { loggingGroup?: SimplePrinter } & + * Printers & + * Exclamation} LogEntryPrinters + */ + +/** @type {LogEntryPrinters} */ +const LOG_ENTRY_PRINTERS = { + "loggingEntry(error).loggingEntry.message": (message, { red }) => + mapLines(message, (x) => ` ${red(x)}`), + "loggingEntry(warn).loggingEntry.message": (message, { yellow }) => + mapLines(message, (x) => ` ${yellow(x)}`), + "loggingEntry(info).loggingEntry.message": (message, { green }) => + mapLines(message, (x) => ` ${green(x)}`), + "loggingEntry(log).loggingEntry.message": (message, { bold }) => + mapLines(message, (x) => ` ${bold(x)}`), + "loggingEntry(debug).loggingEntry.message": (message) => + mapLines(message, (x) => ` ${x}`), + "loggingEntry(trace).loggingEntry.message": (message) => + mapLines(message, (x) => ` ${x}`), + "loggingEntry(status).loggingEntry.message": (message, { magenta }) => + mapLines(message, (x) => ` ${magenta(x)}`), + "loggingEntry(profile).loggingEntry.message": (message, { magenta }) => + mapLines(message, (x) => `

${magenta(x)}`), + "loggingEntry(profileEnd).loggingEntry.message": (message, { magenta }) => + mapLines(message, (x) => `

${magenta(x)}`), + "loggingEntry(time).loggingEntry.message": (message, { magenta }) => + mapLines(message, (x) => ` ${magenta(x)}`), + "loggingEntry(group).loggingEntry.message": (message, { cyan }) => + mapLines(message, (x) => `<-> ${cyan(x)}`), + "loggingEntry(groupCollapsed).loggingEntry.message": (message, { cyan }) => + mapLines(message, (x) => `<+> ${cyan(x)}`), + "loggingEntry(clear).loggingEntry": () => " -------", + "loggingEntry(groupCollapsed).loggingEntry.children": () => "", + "loggingEntry.trace[]": (trace) => + trace ? mapLines(trace, (x) => `| ${x}`) : undefined, + + loggingGroup: (loggingGroup) => + loggingGroup.entries.length === 0 ? "" : undefined, + "loggingGroup.debug": (flag, { red }) => (flag ? red("DEBUG") : undefined), + "loggingGroup.name": (name, { bold }) => bold(`LOG from ${name}`), + "loggingGroup.separator!": () => "\n", + "loggingGroup.filteredEntries": (filteredEntries) => + filteredEntries > 0 ? `+ ${filteredEntries} hidden lines` : undefined +}; + +/** @typedef {Printers} ModuleTraceItemPrinters */ + +/** @type {ModuleTraceItemPrinters} */ +const MODULE_TRACE_ITEM_PRINTERS = { + "moduleTraceItem.originName": (originName) => originName +}; + +/** @typedef {Printers} ModuleTraceDependencyPrinters */ + +/** @type {ModuleTraceDependencyPrinters} */ +const MODULE_TRACE_DEPENDENCY_PRINTERS = { + "moduleTraceDependency.loc": (loc) => loc +}; + +/** + * @type {Record string)>} + */ +const ITEM_NAMES = { + "compilation.assets[]": "asset", + "compilation.modules[]": "module", + "compilation.chunks[]": "chunk", + "compilation.entrypoints[]": "chunkGroup", + "compilation.namedChunkGroups[]": "chunkGroup", + "compilation.errors[]": "error", + "compilation.warnings[]": "error", + "compilation.logging[]": "loggingGroup", + "compilation.children[]": "compilation", + "asset.related[]": "asset", + "asset.children[]": "asset", + "asset.chunks[]": "assetChunk", + "asset.auxiliaryChunks[]": "assetChunk", + "asset.chunkNames[]": "assetChunkName", + "asset.chunkIdHints[]": "assetChunkIdHint", + "asset.auxiliaryChunkNames[]": "assetChunkName", + "asset.auxiliaryChunkIdHints[]": "assetChunkIdHint", + "chunkGroup.assets[]": "chunkGroupAsset", + "chunkGroup.auxiliaryAssets[]": "chunkGroupAsset", + "chunkGroupChild.assets[]": "chunkGroupAsset", + "chunkGroupChild.auxiliaryAssets[]": "chunkGroupAsset", + "chunkGroup.children[]": "chunkGroupChildGroup", + "chunkGroupChildGroup.children[]": "chunkGroupChild", + "module.modules[]": "module", + "module.children[]": "module", + "module.reasons[]": "moduleReason", + "moduleReason.children[]": "moduleReason", + "module.issuerPath[]": "moduleIssuer", + "chunk.origins[]": "chunkOrigin", + "chunk.modules[]": "module", + "loggingGroup.entries[]": (logEntry) => + `loggingEntry(${logEntry.type}).loggingEntry`, + "loggingEntry.children[]": (logEntry) => + `loggingEntry(${logEntry.type}).loggingEntry`, + "error.moduleTrace[]": "moduleTraceItem", + "error.errors[]": "error", + "moduleTraceItem.dependencies[]": "moduleTraceDependency" +}; + +const ERROR_PREFERRED_ORDER = [ + "compilerPath", + "chunkId", + "chunkEntry", + "chunkInitial", + "file", + "separator!", + "moduleName", + "loc", + "separator!", + "message", + "separator!", + "details", + "separator!", + "filteredDetails", + "separator!", + "stack", + "separator!", + "cause", + "separator!", + "missing", + "separator!", + "moduleTrace" +]; + +/** @type {Record} */ +const PREFERRED_ORDERS = { + compilation: [ + "name", + "hash", + "version", + "time", + "builtAt", + "env", + "publicPath", + "assets", + "filteredAssets", + "entrypoints", + "namedChunkGroups", + "chunks", + "modules", + "filteredModules", + "children", + "logging", + "warnings", + "warningsInChildren!", + "filteredWarningDetailsCount", + "errors", + "errorsInChildren!", + "filteredErrorDetailsCount", + "summary!", + "needAdditionalPass" + ], + asset: [ + "type", + "name", + "size", + "chunks", + "auxiliaryChunks", + "emitted", + "comparedForEmit", + "cached", + "info", + "isOverSizeLimit", + "chunkNames", + "auxiliaryChunkNames", + "chunkIdHints", + "auxiliaryChunkIdHints", + "related", + "filteredRelated", + "children", + "filteredChildren" + ], + "asset.info": [ + "immutable", + "sourceFilename", + "javascriptModule", + "development", + "hotModuleReplacement" + ], + chunkGroup: [ + "kind!", + "name", + "isOverSizeLimit", + "assetsSize", + "auxiliaryAssetsSize", + "is!", + "assets", + "filteredAssets", + "auxiliaryAssets", + "filteredAuxiliaryAssets", + "separator!", + "children" + ], + chunkGroupAsset: ["name", "size"], + chunkGroupChildGroup: ["type", "children"], + chunkGroupChild: ["assets", "chunks", "name"], + module: [ + "type", + "name", + "identifier", + "id", + "layer", + "sizes", + "chunks", + "depth", + "cacheable", + "orphan", + "runtime", + "optional", + "dependent", + "built", + "codeGenerated", + "cached", + "assets", + "failed", + "warnings", + "errors", + "children", + "filteredChildren", + "providedExports", + "usedExports", + "optimizationBailout", + "reasons", + "filteredReasons", + "issuerPath", + "profile", + "modules", + "filteredModules" + ], + moduleReason: [ + "active", + "type", + "userRequest", + "moduleId", + "module", + "resolvedModule", + "loc", + "explanation", + "children", + "filteredChildren" + ], + "module.profile": [ + "total", + "separator!", + "resolving", + "restoring", + "integration", + "building", + "storing", + "additionalResolving", + "additionalIntegration" + ], + chunk: [ + "id", + "runtime", + "files", + "names", + "idHints", + "sizes", + "parents", + "siblings", + "children", + "childrenByOrder", + "entry", + "initial", + "rendered", + "recorded", + "reason", + "separator!", + "origins", + "separator!", + "modules", + "separator!", + "filteredModules" + ], + chunkOrigin: ["request", "moduleId", "moduleName", "loc"], + error: ERROR_PREFERRED_ORDER, + warning: ERROR_PREFERRED_ORDER, + "chunk.childrenByOrder[]": ["type", "children"], + loggingGroup: [ + "debug", + "name", + "separator!", + "entries", + "separator!", + "filteredEntries" + ], + loggingEntry: ["message", "trace", "children"] +}; + +/** @typedef {(items: string[]) => string | undefined} SimpleItemsJoiner */ + +/** @type {SimpleItemsJoiner} */ +const itemsJoinOneLine = (items) => items.filter(Boolean).join(" "); +/** @type {SimpleItemsJoiner} */ +const itemsJoinOneLineBrackets = (items) => + items.length > 0 ? `(${items.filter(Boolean).join(" ")})` : undefined; +/** @type {SimpleItemsJoiner} */ +const itemsJoinMoreSpacing = (items) => items.filter(Boolean).join("\n\n"); +/** @type {SimpleItemsJoiner} */ +const itemsJoinComma = (items) => items.filter(Boolean).join(", "); +/** @type {SimpleItemsJoiner} */ +const itemsJoinCommaBrackets = (items) => + items.length > 0 ? `(${items.filter(Boolean).join(", ")})` : undefined; +/** @type {(item: string) => SimpleItemsJoiner} */ +const itemsJoinCommaBracketsWithName = (name) => (items) => + items.length > 0 + ? `(${name}: ${items.filter(Boolean).join(", ")})` + : undefined; + +/** @type {Record} */ +const SIMPLE_ITEMS_JOINER = { + "chunk.parents": itemsJoinOneLine, + "chunk.siblings": itemsJoinOneLine, + "chunk.children": itemsJoinOneLine, + "chunk.names": itemsJoinCommaBrackets, + "chunk.idHints": itemsJoinCommaBracketsWithName("id hint"), + "chunk.runtime": itemsJoinCommaBracketsWithName("runtime"), + "chunk.files": itemsJoinComma, + "chunk.childrenByOrder": itemsJoinOneLine, + "chunk.childrenByOrder[].children": itemsJoinOneLine, + "chunkGroup.assets": itemsJoinOneLine, + "chunkGroup.auxiliaryAssets": itemsJoinOneLineBrackets, + "chunkGroupChildGroup.children": itemsJoinComma, + "chunkGroupChild.assets": itemsJoinOneLine, + "chunkGroupChild.auxiliaryAssets": itemsJoinOneLineBrackets, + "asset.chunks": itemsJoinComma, + "asset.auxiliaryChunks": itemsJoinCommaBrackets, + "asset.chunkNames": itemsJoinCommaBracketsWithName("name"), + "asset.auxiliaryChunkNames": itemsJoinCommaBracketsWithName("auxiliary name"), + "asset.chunkIdHints": itemsJoinCommaBracketsWithName("id hint"), + "asset.auxiliaryChunkIdHints": + itemsJoinCommaBracketsWithName("auxiliary id hint"), + "module.chunks": itemsJoinOneLine, + "module.issuerPath": (items) => + items + .filter(Boolean) + .map((item) => `${item} ->`) + .join(" "), + "compilation.errors": itemsJoinMoreSpacing, + "compilation.warnings": itemsJoinMoreSpacing, + "compilation.logging": itemsJoinMoreSpacing, + "compilation.children": (items) => + indent(/** @type {string} */ (itemsJoinMoreSpacing(items)), " "), + "moduleTraceItem.dependencies": itemsJoinOneLine, + "loggingEntry.children": (items) => + indent(items.filter(Boolean).join("\n"), " ", false) +}; + +/** + * @param {Item[]} items items + * @returns {string} result + */ +const joinOneLine = (items) => + items + .map((item) => item.content) + .filter(Boolean) + .join(" "); + +/** + * @param {Item[]} items items + * @returns {string} result + */ +const joinInBrackets = (items) => { + const res = []; + let mode = 0; + for (const item of items) { + if (item.element === "separator!") { + switch (mode) { + case 0: + case 1: + mode += 2; + break; + case 4: + res.push(")"); + mode = 3; + break; + } + } + if (!item.content) continue; + switch (mode) { + case 0: + mode = 1; + break; + case 1: + res.push(" "); + break; + case 2: + res.push("("); + mode = 4; + break; + case 3: + res.push(" ("); + mode = 4; + break; + case 4: + res.push(", "); + break; + } + res.push(item.content); + } + if (mode === 4) res.push(")"); + return res.join(""); +}; + +/** + * @param {string} str a string + * @param {string} prefix prefix + * @param {boolean=} noPrefixInFirstLine need prefix in the first line? + * @returns {string} result + */ +const indent = (str, prefix, noPrefixInFirstLine) => { + const rem = str.replace(/\n([^\n])/g, `\n${prefix}$1`); + if (noPrefixInFirstLine) return rem; + const ind = str[0] === "\n" ? "" : prefix; + return ind + rem; +}; + +/** + * @param {(false | Item)[]} items items + * @param {string} indenter indenter + * @returns {string} result + */ +const joinExplicitNewLine = (items, indenter) => { + let firstInLine = true; + let first = true; + return items + .map((item) => { + if (!item || !item.content) return; + let content = indent(item.content, first ? "" : indenter, !firstInLine); + if (firstInLine) { + content = content.replace(/^\n+/, ""); + } + if (!content) return; + first = false; + const noJoiner = firstInLine || content.startsWith("\n"); + firstInLine = content.endsWith("\n"); + return noJoiner ? content : ` ${content}`; + }) + .filter(Boolean) + .join("") + .trim(); +}; + +/** + * @param {boolean} error is an error + * @returns {SimpleElementJoiner} joiner + */ +const joinError = + (error) => + /** + * @param {Item[]} items items + * @param {StatsPrinterContextWithExtra} ctx context + * @returns {string} result + */ + (items, { red, yellow }) => + `${error ? red("ERROR") : yellow("WARNING")} in ${joinExplicitNewLine( + items, + "" + )}`; + +/** @typedef {{ element: string, content: string | undefined }} Item */ +/** @typedef {(items: Item[], context: StatsPrinterContextWithExtra & Required) => string} SimpleElementJoiner */ + +/** @type {Record} */ +const SIMPLE_ELEMENT_JOINERS = { + compilation: (items) => { + const result = []; + let lastNeedMore = false; + for (const item of items) { + if (!item.content) continue; + const needMoreSpace = + item.element === "warnings" || + item.element === "filteredWarningDetailsCount" || + item.element === "errors" || + item.element === "filteredErrorDetailsCount" || + item.element === "logging"; + if (result.length !== 0) { + result.push(needMoreSpace || lastNeedMore ? "\n\n" : "\n"); + } + result.push(item.content); + lastNeedMore = needMoreSpace; + } + if (lastNeedMore) result.push("\n"); + return result.join(""); + }, + asset: (items) => + joinExplicitNewLine( + items.map((item) => { + if ( + (item.element === "related" || item.element === "children") && + item.content + ) { + return { + ...item, + content: `\n${item.content}\n` + }; + } + return item; + }), + " " + ), + "asset.info": joinOneLine, + module: (items, { module }) => { + let hasName = false; + return joinExplicitNewLine( + items.map((item) => { + switch (item.element) { + case "id": + if (module.id === module.name) { + if (hasName) return false; + if (item.content) hasName = true; + } + break; + case "name": + if (hasName) return false; + if (item.content) hasName = true; + break; + case "providedExports": + case "usedExports": + case "optimizationBailout": + case "reasons": + case "issuerPath": + case "profile": + case "children": + case "modules": + if (item.content) { + return { + ...item, + content: `\n${item.content}\n` + }; + } + break; + } + return item; + }), + " " + ); + }, + chunk: (items) => { + let hasEntry = false; + return `chunk ${joinExplicitNewLine( + items.filter((item) => { + switch (item.element) { + case "entry": + if (item.content) hasEntry = true; + break; + case "initial": + if (hasEntry) return false; + break; + } + return true; + }), + " " + )}`; + }, + "chunk.childrenByOrder[]": (items) => `(${joinOneLine(items)})`, + chunkGroup: (items) => joinExplicitNewLine(items, " "), + chunkGroupAsset: joinOneLine, + chunkGroupChildGroup: joinOneLine, + chunkGroupChild: joinOneLine, + moduleReason: (items, { moduleReason }) => { + let hasName = false; + return joinExplicitNewLine( + items.map((item) => { + switch (item.element) { + case "moduleId": + if (moduleReason.moduleId === moduleReason.module && item.content) { + hasName = true; + } + break; + case "module": + if (hasName) return false; + break; + case "resolvedModule": + if (moduleReason.module === moduleReason.resolvedModule) { + return false; + } + break; + case "children": + if (item.content) { + return { + ...item, + content: `\n${item.content}\n` + }; + } + break; + } + return item; + }), + " " + ); + }, + "module.profile": joinInBrackets, + moduleIssuer: joinOneLine, + chunkOrigin: (items) => `> ${joinOneLine(items)}`, + "errors[].error": joinError(true), + "warnings[].error": joinError(false), + error: (items) => joinExplicitNewLine(items, ""), + "error.errors[].error": (items) => + indent(`[errors]: ${joinExplicitNewLine(items, "")}`, " "), + loggingGroup: (items) => joinExplicitNewLine(items, "").trimEnd(), + moduleTraceItem: (items) => ` @ ${joinOneLine(items)}`, + moduleTraceDependency: joinOneLine +}; + +/** @type {Record} */ +const AVAILABLE_COLORS = { + bold: "\u001B[1m", + yellow: "\u001B[1m\u001B[33m", + red: "\u001B[1m\u001B[31m", + green: "\u001B[1m\u001B[32m", + cyan: "\u001B[1m\u001B[36m", + magenta: "\u001B[1m\u001B[35m" +}; + +/** + * @template T + * @typedef {T extends [infer Head, ...infer Tail] ? Tail : undefined} Tail + */ + +/** @typedef {Required<{ [Key in keyof KnownStatsPrinterFormatters]: (value: Parameters>[0], options: Required & StatsPrinterContextWithExtra, ...args: Tail>>) => string }>} AvailableFormats */ + +/** @type {AvailableFormats} */ +const AVAILABLE_FORMATS = { + formatChunkId: (id, { yellow }, direction) => { + switch (direction) { + case "parent": + return `<{${yellow(id)}}>`; + case "sibling": + return `={${yellow(id)}}=`; + case "child": + return `>{${yellow(id)}}<`; + default: + return `{${yellow(id)}}`; + } + }, + formatModuleId: (id) => `[${id}]`, + formatFilename: (filename, { green, yellow }, oversize) => + (oversize ? yellow : green)(filename), + formatFlag: (flag) => `[${flag}]`, + formatLayer: (layer) => `(in ${layer})`, + formatSize: require("../SizeFormatHelpers").formatSize, + formatDateTime: (dateTime, { bold }) => { + const d = new Date(dateTime); + const x = twoDigit; + const date = `${d.getFullYear()}-${x(d.getMonth() + 1)}-${x(d.getDate())}`; + const time = `${x(d.getHours())}:${x(d.getMinutes())}:${x(d.getSeconds())}`; + return `${date} ${bold(time)}`; + }, + formatTime: ( + time, + { timeReference, bold, green, yellow, red }, + boldQuantity + ) => { + const unit = " ms"; + if (timeReference && time !== timeReference) { + const times = [ + timeReference / 2, + timeReference / 4, + timeReference / 8, + timeReference / 16 + ]; + if (time < times[3]) return `${time}${unit}`; + else if (time < times[2]) return bold(`${time}${unit}`); + else if (time < times[1]) return green(`${time}${unit}`); + else if (time < times[0]) return yellow(`${time}${unit}`); + return red(`${time}${unit}`); + } + return `${boldQuantity ? bold(time) : time}${unit}`; + }, + formatError: (message, { green, yellow, red }) => { + if (message.includes("\u001B[")) return message; + const highlights = [ + { regExp: /(Did you mean .+)/g, format: green }, + { + regExp: /(Set 'mode' option to 'development' or 'production')/g, + format: green + }, + { regExp: /(\(module has no exports\))/g, format: red }, + { regExp: /\(possible exports: (.+)\)/g, format: green }, + { regExp: /(?:^|\n)(.* doesn't exist)/g, format: red }, + { regExp: /('\w+' option has not been set)/g, format: red }, + { + regExp: /(Emitted value instead of an instance of Error)/g, + format: yellow + }, + { regExp: /(Used? .+ instead)/gi, format: yellow }, + { regExp: /\b(deprecated|must|required)\b/g, format: yellow }, + { + regExp: /\b(BREAKING CHANGE)\b/gi, + format: red + }, + { + regExp: + /\b(error|failed|unexpected|invalid|not found|not supported|not available|not possible|not implemented|doesn't support|conflict|conflicting|not existing|duplicate)\b/gi, + format: red + } + ]; + for (const { regExp, format } of highlights) { + message = message.replace( + regExp, + /** + * @param {string} match match + * @param {string} content content + * @returns {string} result + */ + (match, content) => match.replace(content, format(content)) + ); + } + return message; + } +}; + +/** @typedef {(result: string) => string} ResultModifierFn */ +/** @type {Record} */ +const RESULT_MODIFIER = { + "module.modules": (result) => indent(result, "| ") +}; + +/** + * @param {string[]} array array + * @param {string[]} preferredOrder preferred order + * @returns {string[]} result + */ +const createOrder = (array, preferredOrder) => { + const originalArray = [...array]; + /** @type {Set} */ + const set = new Set(array); + /** @type {Set} */ + const usedSet = new Set(); + array.length = 0; + for (const element of preferredOrder) { + if (element.endsWith("!") || set.has(element)) { + array.push(element); + usedSet.add(element); + } + } + for (const element of originalArray) { + if (!usedSet.has(element)) { + array.push(element); + } + } + return array; +}; + +const PLUGIN_NAME = "DefaultStatsPrinterPlugin"; + +class DefaultStatsPrinterPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.statsPrinter.tap(PLUGIN_NAME, (stats, options) => { + // Put colors into context + stats.hooks.print + .for("compilation") + .tap(PLUGIN_NAME, (compilation, context) => { + for (const color of Object.keys(AVAILABLE_COLORS)) { + const name = + /** @type {keyof KnownStatsPrinterColorFunctions} */ + (color); + /** @type {string | undefined} */ + let start; + if (options.colors) { + if ( + typeof options.colors === "object" && + typeof options.colors[name] === "string" + ) { + start = options.colors[name]; + } else { + start = AVAILABLE_COLORS[name]; + } + } + if (start) { + /** @type {ColorFunction} */ + context[color] = (str) => + `${start}${ + typeof str === "string" + ? str.replace( + // eslint-disable-next-line no-control-regex + /((\u001B\[39m|\u001B\[22m|\u001B\[0m)+)/g, + `$1${start}` + ) + : str + }\u001B[39m\u001B[22m`; + } else { + /** + * @param {string} str string + * @returns {string} str string + */ + context[color] = (str) => str; + } + } + for (const _format of Object.keys(AVAILABLE_FORMATS)) { + const format = + /** @type {keyof KnownStatsPrinterFormatters} */ + (_format); + + context[format] = + /** @type {(content: Parameters>[0], ...args: Tail>>) => string} */ + (content, ...args) => + /** @type {TODO} */ + (AVAILABLE_FORMATS)[format]( + content, + /** @type {StatsPrinterContext & Required} */ + (context), + ...args + ); + } + context.timeReference = compilation.time; + }); + + for (const key of Object.keys(COMPILATION_SIMPLE_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {TODO} */ + ( + COMPILATION_SIMPLE_PRINTERS[ + /** @type {keyof CompilationSimplePrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"compilation">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(ASSET_SIMPLE_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {NonNullable} */ + ( + ASSET_SIMPLE_PRINTERS[ + /** @type {keyof AssetSimplePrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"asset" | "asset.info">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(MODULE_SIMPLE_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {TODO} */ + ( + MODULE_SIMPLE_PRINTERS[ + /** @type {keyof ModuleSimplePrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"module">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(MODULE_ISSUER_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {NonNullable} */ + ( + MODULE_ISSUER_PRINTERS[ + /** @type {keyof ModuleIssuerPrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"moduleIssuer">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(MODULE_REASON_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {TODO} */ + ( + MODULE_REASON_PRINTERS[ + /** @type {keyof ModuleReasonsPrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"moduleReason">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(MODULE_PROFILE_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {NonNullable} */ + ( + MODULE_PROFILE_PRINTERS[ + /** @type {keyof ModuleProfilePrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"profile">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(CHUNK_GROUP_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {TODO} */ + ( + CHUNK_GROUP_PRINTERS[ + /** @type {keyof ChunkGroupPrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"chunkGroupKind" | "chunkGroup">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(CHUNK_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {TODO} */ + (CHUNK_PRINTERS[/** @type {keyof ChunkPrinters} */ (key)])( + obj, + /** @type {DefineStatsPrinterContext<"chunk">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(ERROR_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {TODO} */ + (ERROR_PRINTERS[/** @type {keyof ErrorPrinters} */ (key)])( + obj, + /** @type {DefineStatsPrinterContext<"error">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(LOG_ENTRY_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {TODO} */ + ( + LOG_ENTRY_PRINTERS[ + /** @type {keyof LogEntryPrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"logging">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(MODULE_TRACE_DEPENDENCY_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {NonNullable} */ + ( + MODULE_TRACE_DEPENDENCY_PRINTERS[ + /** @type {keyof ModuleTraceDependencyPrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"moduleTraceDependency">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(MODULE_TRACE_ITEM_PRINTERS)) { + stats.hooks.print.for(key).tap(PLUGIN_NAME, (obj, ctx) => + /** @type {NonNullable} */ + ( + MODULE_TRACE_ITEM_PRINTERS[ + /** @type {keyof ModuleTraceItemPrinters} */ + (key) + ] + )( + obj, + /** @type {DefineStatsPrinterContext<"moduleTraceItem">} */ + (ctx), + stats + ) + ); + } + + for (const key of Object.keys(PREFERRED_ORDERS)) { + const preferredOrder = PREFERRED_ORDERS[key]; + stats.hooks.sortElements + .for(key) + .tap(PLUGIN_NAME, (elements, _context) => { + createOrder(elements, preferredOrder); + }); + } + + for (const key of Object.keys(ITEM_NAMES)) { + const itemName = ITEM_NAMES[key]; + stats.hooks.getItemName + .for(key) + .tap( + PLUGIN_NAME, + typeof itemName === "string" ? () => itemName : itemName + ); + } + + for (const key of Object.keys(SIMPLE_ITEMS_JOINER)) { + const joiner = SIMPLE_ITEMS_JOINER[key]; + stats.hooks.printItems.for(key).tap(PLUGIN_NAME, joiner); + } + + for (const key of Object.keys(SIMPLE_ELEMENT_JOINERS)) { + const joiner = SIMPLE_ELEMENT_JOINERS[key]; + stats.hooks.printElements + .for(key) + .tap(PLUGIN_NAME, /** @type {TODO} */ (joiner)); + } + + for (const key of Object.keys(RESULT_MODIFIER)) { + const modifier = RESULT_MODIFIER[key]; + stats.hooks.result.for(key).tap(PLUGIN_NAME, modifier); + } + }); + }); + } +} + +module.exports = DefaultStatsPrinterPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/StatsFactory.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/StatsFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..4a3ada223d6763d9649d72a283f11b359b921f4c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/StatsFactory.js @@ -0,0 +1,403 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { HookMap, SyncBailHook, SyncWaterfallHook } = require("tapable"); +const { concatComparators, keepOriginalOrder } = require("../util/comparators"); +const smartGrouping = require("../util/smartGrouping"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").Asset} Asset */ +/** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph").ModuleProfile} ModuleProfile */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/comparators").Comparator} Comparator */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig */ +/** @typedef {import("./DefaultStatsFactoryPlugin").ChunkGroupInfoWithName} ChunkGroupInfoWithName */ +/** @typedef {import("./DefaultStatsFactoryPlugin").ModuleIssuerPath} ModuleIssuerPath */ +/** @typedef {import("./DefaultStatsFactoryPlugin").ModuleTrace} ModuleTrace */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunkOrigin} StatsChunkOrigin */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsError} StatsError */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleIssuer} StatsModuleIssuer */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleTraceDependency} StatsModuleTraceDependency */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleTraceItem} StatsModuleTraceItem */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsProfile} StatsProfile */ + +/** + * @typedef {object} KnownStatsFactoryContext + * @property {string} type + * @property {(path: string) => string} makePathsRelative + * @property {Compilation} compilation + * @property {Set} rootModules + * @property {Map} compilationFileToChunks + * @property {Map} compilationAuxiliaryFileToChunks + * @property {RuntimeSpec} runtime + * @property {(compilation: Compilation) => WebpackError[]} cachedGetErrors + * @property {(compilation: Compilation) => WebpackError[]} cachedGetWarnings + */ + +/** @typedef {KnownStatsFactoryContext & Record} StatsFactoryContext */ + +// StatsLogging StatsLoggingEntry + +/** + * @template T + * @template F + * @typedef {T extends Compilation ? StatsCompilation : T extends ChunkGroupInfoWithName ? StatsChunkGroup : T extends Chunk ? StatsChunk : T extends OriginRecord ? StatsChunkOrigin : T extends Module ? StatsModule : T extends ModuleGraphConnection ? StatsModuleReason : T extends Asset ? StatsAsset : T extends ModuleTrace ? StatsModuleTraceItem : T extends Dependency ? StatsModuleTraceDependency : T extends Error ? StatsError : T extends ModuleProfile ? StatsProfile : F} StatsObject + */ + +/** + * @template T + * @template F + * @typedef {T extends ChunkGroupInfoWithName[] ? Record> : T extends (infer V)[] ? StatsObject[] : StatsObject} CreatedObject + */ + +/** @typedef {TODO} FactoryData */ +/** @typedef {TODO} FactoryDataItem */ +/** @typedef {TODO} Result */ +/** @typedef {Record} ObjectForExtract */ + +/** + * @typedef {object} StatsFactoryHooks + * @property {HookMap>} extract + * @property {HookMap>} filter + * @property {HookMap>} sort + * @property {HookMap>} filterSorted + * @property {HookMap>} groupResults + * @property {HookMap>} sortResults + * @property {HookMap>} filterResults + * @property {HookMap>} merge + * @property {HookMap>} result + * @property {HookMap>} getItemName + * @property {HookMap>} getItemFactory + */ + +/** + * @template T + * @typedef {Map} Caches + */ + +class StatsFactory { + constructor() { + /** @type {StatsFactoryHooks} */ + this.hooks = Object.freeze({ + extract: new HookMap( + () => new SyncBailHook(["object", "data", "context"]) + ), + filter: new HookMap( + () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) + ), + sort: new HookMap(() => new SyncBailHook(["comparators", "context"])), + filterSorted: new HookMap( + () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) + ), + groupResults: new HookMap( + () => new SyncBailHook(["groupConfigs", "context"]) + ), + sortResults: new HookMap( + () => new SyncBailHook(["comparators", "context"]) + ), + filterResults: new HookMap( + () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) + ), + merge: new HookMap(() => new SyncBailHook(["items", "context"])), + result: new HookMap(() => new SyncWaterfallHook(["result", "context"])), + getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), + getItemFactory: new HookMap(() => new SyncBailHook(["item", "context"])) + }); + const hooks = this.hooks; + this._caches = + /** @type {{ [Key in keyof StatsFactoryHooks]: Map[]> }} */ ({}); + for (const key of Object.keys(hooks)) { + this._caches[/** @type {keyof StatsFactoryHooks} */ (key)] = new Map(); + } + this._inCreate = false; + } + + /** + * @template {StatsFactoryHooks[keyof StatsFactoryHooks]} HM + * @template {HM extends HookMap ? H : never} H + * @param {HM} hookMap hook map + * @param {Caches} cache cache + * @param {string} type type + * @returns {H[]} hooks + * @private + */ + _getAllLevelHooks(hookMap, cache, type) { + const cacheEntry = cache.get(type); + if (cacheEntry !== undefined) { + return cacheEntry; + } + const hooks = /** @type {H[]} */ ([]); + const typeParts = type.split("."); + for (let i = 0; i < typeParts.length; i++) { + const hook = /** @type {H} */ (hookMap.get(typeParts.slice(i).join("."))); + if (hook) { + hooks.push(hook); + } + } + cache.set(type, hooks); + return hooks; + } + + /** + * @template {StatsFactoryHooks[keyof StatsFactoryHooks]} HM + * @template {HM extends HookMap ? H : never} H + * @template {H extends import("tapable").Hook ? R : never} R + * @param {HM} hookMap hook map + * @param {Caches} cache cache + * @param {string} type type + * @param {(hook: H) => R | void} fn fn + * @returns {R | void} hook + * @private + */ + _forEachLevel(hookMap, cache, type, fn) { + for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { + const result = fn(/** @type {H} */ (hook)); + if (result !== undefined) return result; + } + } + + /** + * @template {StatsFactoryHooks[keyof StatsFactoryHooks]} HM + * @template {HM extends HookMap ? H : never} H + * @param {HM} hookMap hook map + * @param {Caches} cache cache + * @param {string} type type + * @param {FactoryData} data data + * @param {(hook: H, factoryData: FactoryData) => FactoryData} fn fn + * @returns {FactoryData} data + * @private + */ + _forEachLevelWaterfall(hookMap, cache, type, data, fn) { + for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { + data = fn(/** @type {H} */ (hook), data); + } + return data; + } + + /** + * @template {StatsFactoryHooks[keyof StatsFactoryHooks]} T + * @template {T extends HookMap ? H : never} H + * @template {H extends import("tapable").Hook ? R : never} R + * @param {T} hookMap hook map + * @param {Caches} cache cache + * @param {string} type type + * @param {Array} items items + * @param {(hook: H, item: R, idx: number, i: number) => R | undefined} fn fn + * @param {boolean} forceClone force clone + * @returns {R[]} result for each level + * @private + */ + _forEachLevelFilter(hookMap, cache, type, items, fn, forceClone) { + const hooks = this._getAllLevelHooks(hookMap, cache, type); + if (hooks.length === 0) return forceClone ? [...items] : items; + let i = 0; + return items.filter((item, idx) => { + for (const hook of hooks) { + const r = fn(/** @type {H} */ (hook), item, idx, i); + if (r !== undefined) { + if (r) i++; + return r; + } + } + i++; + return true; + }); + } + + /** + * @template FactoryData + * @template FallbackCreatedObject + * @param {string} type type + * @param {FactoryData} data factory data + * @param {Omit} baseContext context used as base + * @returns {CreatedObject} created object + */ + create(type, data, baseContext) { + if (this._inCreate) { + return this._create(type, data, baseContext); + } + try { + this._inCreate = true; + return this._create(type, data, baseContext); + } finally { + for (const key of Object.keys(this._caches)) { + this._caches[/** @type {keyof StatsFactoryHooks} */ (key)].clear(); + } + this._inCreate = false; + } + } + + /** + * @private + * @template FactoryData + * @template FallbackCreatedObject + * @param {string} type type + * @param {FactoryData} data factory data + * @param {Omit} baseContext context used as base + * @returns {CreatedObject} created object + */ + _create(type, data, baseContext) { + const context = /** @type {StatsFactoryContext} */ ({ + ...baseContext, + type, + [type]: data + }); + if (Array.isArray(data)) { + // run filter on unsorted items + const items = this._forEachLevelFilter( + this.hooks.filter, + this._caches.filter, + type, + data, + (h, r, idx, i) => h.call(r, context, idx, i), + true + ); + + // sort items + /** @type {Comparator[]} */ + const comparators = []; + this._forEachLevel(this.hooks.sort, this._caches.sort, type, (h) => + h.call(comparators, context) + ); + if (comparators.length > 0) { + items.sort( + // @ts-expect-error number of arguments is correct + concatComparators(...comparators, keepOriginalOrder(items)) + ); + } + + // run filter on sorted items + const items2 = this._forEachLevelFilter( + this.hooks.filterSorted, + this._caches.filterSorted, + type, + items, + (h, r, idx, i) => h.call(r, context, idx, i), + false + ); + + // for each item + let resultItems = items2.map((item, i) => { + /** @type {StatsFactoryContext} */ + const itemContext = { + ...context, + _index: i + }; + + // run getItemName + const itemName = this._forEachLevel( + this.hooks.getItemName, + this._caches.getItemName, + `${type}[]`, + (h) => h.call(item, itemContext) + ); + if (itemName) itemContext[itemName] = item; + const innerType = itemName ? `${type}[].${itemName}` : `${type}[]`; + + // run getItemFactory + const itemFactory = + this._forEachLevel( + this.hooks.getItemFactory, + this._caches.getItemFactory, + innerType, + (h) => h.call(item, itemContext) + ) || this; + + // run item factory + return itemFactory.create(innerType, item, itemContext); + }); + + // sort result items + /** @type {Comparator[]} */ + const comparators2 = []; + this._forEachLevel( + this.hooks.sortResults, + this._caches.sortResults, + type, + (h) => h.call(comparators2, context) + ); + if (comparators2.length > 0) { + resultItems.sort( + // @ts-expect-error number of arguments is correct + concatComparators(...comparators2, keepOriginalOrder(resultItems)) + ); + } + + // group result items + /** @type {GroupConfig[]} */ + const groupConfigs = []; + this._forEachLevel( + this.hooks.groupResults, + this._caches.groupResults, + type, + (h) => h.call(groupConfigs, context) + ); + if (groupConfigs.length > 0) { + resultItems = smartGrouping(resultItems, groupConfigs); + } + + // run filter on sorted result items + const finalResultItems = this._forEachLevelFilter( + this.hooks.filterResults, + this._caches.filterResults, + type, + resultItems, + (h, r, idx, i) => h.call(r, context, idx, i), + false + ); + + // run merge on mapped items + let result = this._forEachLevel( + this.hooks.merge, + this._caches.merge, + type, + (h) => h.call(finalResultItems, context) + ); + if (result === undefined) result = finalResultItems; + + // run result on merged items + return this._forEachLevelWaterfall( + this.hooks.result, + this._caches.result, + type, + result, + (h, r) => h.call(r, context) + ); + } + /** @type {ObjectForExtract} */ + const object = {}; + + // run extract on value + this._forEachLevel(this.hooks.extract, this._caches.extract, type, (h) => + h.call(object, data, context) + ); + + // run result on extracted object + return this._forEachLevelWaterfall( + this.hooks.result, + this._caches.result, + type, + object, + (h, r) => h.call(r, context) + ); + } +} + +module.exports = StatsFactory; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/StatsPrinter.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/StatsPrinter.js new file mode 100644 index 0000000000000000000000000000000000000000..621dd9a2d77b3db57e74dc7c9cc04d76db5a6e6b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/stats/StatsPrinter.js @@ -0,0 +1,300 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { HookMap, SyncBailHook, SyncWaterfallHook } = require("tapable"); + +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsError} StatsError */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsLogging} StatsLogging */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleIssuer} StatsModuleIssuer */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleTraceDependency} StatsModuleTraceDependency */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleTraceItem} StatsModuleTraceItem */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsProfile} StatsProfile */ + +/** + * @typedef {object} PrintedElement + * @property {string} element + * @property {string | undefined} content + */ + +/** + * @typedef {object} KnownStatsPrinterContext + * @property {string=} type + * @property {StatsCompilation=} compilation + * @property {StatsChunkGroup=} chunkGroup + * @property {string=} chunkGroupKind + * @property {StatsAsset=} asset + * @property {StatsModule=} module + * @property {StatsChunk=} chunk + * @property {StatsModuleReason=} moduleReason + * @property {StatsModuleIssuer=} moduleIssuer + * @property {StatsError=} error + * @property {StatsProfile=} profile + * @property {StatsLogging=} logging + * @property {StatsModuleTraceItem=} moduleTraceItem + * @property {StatsModuleTraceDependency=} moduleTraceDependency + */ + +/** @typedef {(value: string | number) => string} ColorFunction */ + +/** + * @typedef {object} KnownStatsPrinterColorFunctions + * @property {ColorFunction=} bold + * @property {ColorFunction=} yellow + * @property {ColorFunction=} red + * @property {ColorFunction=} green + * @property {ColorFunction=} magenta + * @property {ColorFunction=} cyan + */ + +/** + * @typedef {object} KnownStatsPrinterFormatters + * @property {(file: string, oversize?: boolean) => string=} formatFilename + * @property {(id: string | number) => string=} formatModuleId + * @property {(id: string | number, direction?: "parent" | "child" | "sibling") => string=} formatChunkId + * @property {(size: number) => string=} formatSize + * @property {(size: string) => string=} formatLayer + * @property {(dateTime: number) => string=} formatDateTime + * @property {(flag: string) => string=} formatFlag + * @property {(time: number, boldQuantity?: boolean) => string=} formatTime + * @property {(message: string) => string=} formatError + */ + +/** @typedef {KnownStatsPrinterColorFunctions & KnownStatsPrinterFormatters & KnownStatsPrinterContext & Record} StatsPrinterContext */ +/** @typedef {StatsPrinterContext & Required & Required & { type: string }} StatsPrinterContextWithExtra */ +/** @typedef {EXPECTED_ANY} PrintObject */ + +/** + * @typedef {object} StatsPrintHooks + * @property {HookMap>} sortElements + * @property {HookMap>} printElements + * @property {HookMap>} sortItems + * @property {HookMap>} getItemName + * @property {HookMap>} printItems + * @property {HookMap>} print + * @property {HookMap>} result + */ + +class StatsPrinter { + constructor() { + /** @type {StatsPrintHooks} */ + this.hooks = Object.freeze({ + sortElements: new HookMap( + () => new SyncBailHook(["elements", "context"]) + ), + printElements: new HookMap( + () => new SyncBailHook(["printedElements", "context"]) + ), + sortItems: new HookMap(() => new SyncBailHook(["items", "context"])), + getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), + printItems: new HookMap( + () => new SyncBailHook(["printedItems", "context"]) + ), + print: new HookMap(() => new SyncBailHook(["object", "context"])), + result: new HookMap(() => new SyncWaterfallHook(["result", "context"])) + }); + /** @type {Map[]>>} */ + this._levelHookCache = new Map(); + this._inPrint = false; + } + + /** + * get all level hooks + * @private + * @template {StatsPrintHooks[keyof StatsPrintHooks]} HM + * @template {HM extends HookMap ? H : never} H + * @param {HM} hookMap hook map + * @param {string} type type + * @returns {H[]} hooks + */ + _getAllLevelHooks(hookMap, type) { + let cache = this._levelHookCache.get(hookMap); + if (cache === undefined) { + cache = new Map(); + this._levelHookCache.set(hookMap, cache); + } + const cacheEntry = cache.get(type); + if (cacheEntry !== undefined) { + return /** @type {H[]} */ (cacheEntry); + } + /** @type {H[]} */ + const hooks = []; + const typeParts = type.split("."); + for (let i = 0; i < typeParts.length; i++) { + const hook = /** @type {H} */ (hookMap.get(typeParts.slice(i).join("."))); + if (hook) { + hooks.push(hook); + } + } + cache.set(type, hooks); + return hooks; + } + + /** + * Run `fn` for each level + * @private + * @template {StatsPrintHooks[keyof StatsPrintHooks]} HM + * @template {HM extends HookMap ? H : never} H + * @template {H extends import("tapable").Hook ? R : never} R + * @param {HM} hookMap hook map + * @param {string} type type + * @param {(hooK: H) => R | undefined | void} fn fn + * @returns {R | undefined} hook + */ + _forEachLevel(hookMap, type, fn) { + for (const hook of this._getAllLevelHooks(hookMap, type)) { + const result = fn(/** @type {H} */ (hook)); + if (result !== undefined) return /** @type {R} */ (result); + } + } + + /** + * Run `fn` for each level + * @private + * @template {StatsPrintHooks[keyof StatsPrintHooks]} HM + * @template {HM extends HookMap ? H : never} H + * @param {HM} hookMap hook map + * @param {string} type type + * @param {string} data data + * @param {(hook: H, data: string) => string} fn fn + * @returns {string | undefined} result of `fn` + */ + _forEachLevelWaterfall(hookMap, type, data, fn) { + for (const hook of this._getAllLevelHooks(hookMap, type)) { + data = fn(/** @type {H} */ (hook), data); + } + return data; + } + + /** + * @param {string} type The type + * @param {PrintObject} object Object to print + * @param {StatsPrinterContext=} baseContext The base context + * @returns {string | undefined} printed result + */ + print(type, object, baseContext) { + if (this._inPrint) { + return this._print(type, object, baseContext); + } + try { + this._inPrint = true; + return this._print(type, object, baseContext); + } finally { + this._levelHookCache.clear(); + this._inPrint = false; + } + } + + /** + * @private + * @param {string} type type + * @param {PrintObject} object object + * @param {StatsPrinterContext=} baseContext context + * @returns {string | undefined} printed result + */ + _print(type, object, baseContext) { + /** @type {StatsPrinterContext} */ + const context = { + ...baseContext, + type, + [type]: object + }; + + /** @type {string | undefined} */ + let printResult = this._forEachLevel(this.hooks.print, type, (hook) => + hook.call(object, context) + ); + if (printResult === undefined) { + if (Array.isArray(object)) { + const sortedItems = [...object]; + this._forEachLevel(this.hooks.sortItems, type, (h) => + h.call( + sortedItems, + /** @type {StatsPrinterContextWithExtra} */ + (context) + ) + ); + const printedItems = sortedItems.map((item, i) => { + const itemContext = + /** @type {StatsPrinterContextWithExtra} */ + ({ + ...context, + _index: i + }); + const itemName = this._forEachLevel( + this.hooks.getItemName, + `${type}[]`, + (h) => h.call(item, itemContext) + ); + if (itemName) itemContext[itemName] = item; + return this.print( + itemName ? `${type}[].${itemName}` : `${type}[]`, + item, + itemContext + ); + }); + printResult = this._forEachLevel(this.hooks.printItems, type, (h) => + h.call( + /** @type {string[]} */ (printedItems), + /** @type {StatsPrinterContextWithExtra} */ + (context) + ) + ); + if (printResult === undefined) { + const result = printedItems.filter(Boolean); + if (result.length > 0) printResult = result.join("\n"); + } + } else if (object !== null && typeof object === "object") { + const elements = Object.keys(object).filter( + (key) => object[key] !== undefined + ); + this._forEachLevel(this.hooks.sortElements, type, (h) => + h.call( + elements, + /** @type {StatsPrinterContextWithExtra} */ + (context) + ) + ); + const printedElements = elements.map((element) => { + const content = this.print(`${type}.${element}`, object[element], { + ...context, + _parent: object, + _element: element, + [element]: object[element] + }); + return { element, content }; + }); + printResult = this._forEachLevel(this.hooks.printElements, type, (h) => + h.call( + printedElements, + /** @type {StatsPrinterContextWithExtra} */ + (context) + ) + ); + if (printResult === undefined) { + const result = printedElements.map((e) => e.content).filter(Boolean); + if (result.length > 0) printResult = result.join("\n"); + } + } + } + + return this._forEachLevelWaterfall( + this.hooks.result, + type, + /** @type {string} */ + (printResult), + (h, r) => h.call(r, /** @type {StatsPrinterContextWithExtra} */ (context)) + ); + } +} + +module.exports = StatsPrinter; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/url/URLParserPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/url/URLParserPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..7a864134edb7240e12c6a9a906cfaea479eb7197 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/url/URLParserPlugin.js @@ -0,0 +1,266 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Haijie Xie @hai-x +*/ + +"use strict"; + +const { pathToFileURL } = require("url"); +const CommentCompilationWarning = require("../CommentCompilationWarning"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); +const ConstDependency = require("../dependencies/ConstDependency"); +const ContextDependencyHelpers = require("../dependencies/ContextDependencyHelpers"); +const URLContextDependency = require("../dependencies/URLContextDependency"); +const URLDependency = require("../dependencies/URLDependency"); +const BasicEvaluatedExpression = require("../javascript/BasicEvaluatedExpression"); +const { approve } = require("../javascript/JavascriptParserHelpers"); +const InnerGraph = require("../optimize/InnerGraph"); + +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("estree").NewExpression} NewExpressionNode */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../ContextModule").ContextMode} ContextMode */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +const PLUGIN_NAME = "URLParserPlugin"; + +/** + * @param {NormalModule} module module + * @returns {URL} file url + */ +const getUrl = (module) => pathToFileURL(module.resource); + +/** + * @param {Parser} parser parser parser + * @param {MemberExpression} arg arg + * @returns {boolean} true when it is `meta.url`, otherwise false + */ +const isMetaUrl = (parser, arg) => { + const chain = parser.extractMemberExpressionChain(arg); + + if ( + chain.members.length !== 1 || + chain.object.type !== "MetaProperty" || + chain.object.meta.name !== "import" || + chain.object.property.name !== "meta" || + chain.members[0] !== "url" + ) { + return false; + } + + return true; +}; + +/** + * @type {WeakMap} + */ +const getEvaluatedExprCache = new WeakMap(); + +/** + * @param {NewExpressionNode} expr expression + * @param {Parser} parser parser parser + * @returns {BasicEvaluatedExpression | undefined} basic evaluated expression + */ +const getEvaluatedExpr = (expr, parser) => { + let result = getEvaluatedExprCache.get(expr); + if (result !== undefined) return result; + + /** + * @returns {BasicEvaluatedExpression | undefined} basic evaluated expression + */ + const evaluate = () => { + if (expr.arguments.length !== 2) return; + + const [arg1, arg2] = expr.arguments; + + if (arg2.type !== "MemberExpression" || arg1.type === "SpreadElement") { + return; + } + if (!isMetaUrl(parser, arg2)) return; + + return parser.evaluateExpression(arg1); + }; + + result = evaluate(); + getEvaluatedExprCache.set(expr, result); + + return result; +}; + +class URLParserPlugin { + /** + * @param {JavascriptParserOptions} options options + */ + constructor(options) { + this.options = options; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + const relative = this.options.url === "relative"; + + parser.hooks.canRename.for("URL").tap(PLUGIN_NAME, approve); + parser.hooks.evaluateNewExpression.for("URL").tap(PLUGIN_NAME, (expr) => { + const evaluatedExpr = getEvaluatedExpr(expr, parser); + const request = evaluatedExpr && evaluatedExpr.asString(); + + if (!request) return; + const url = new URL(request, getUrl(parser.state.module)); + + return new BasicEvaluatedExpression() + .setString(url.toString()) + .setRange(/** @type {Range} */ (expr.range)); + }); + parser.hooks.new.for("URL").tap(PLUGIN_NAME, (_expr) => { + const expr = /** @type {NewExpressionNode} */ (_expr); + const { options: importOptions, errors: commentErrors } = + parser.parseCommentOptions(/** @type {Range} */ (expr.range)); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + /** @type {DependencyLocation} */ (comment.loc) + ) + ); + } + } + + if (importOptions && importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + return; + } else if (importOptions.webpackIgnore) { + if (expr.arguments.length !== 2) return; + + const [, arg2] = expr.arguments; + + if (arg2.type !== "MemberExpression" || !isMetaUrl(parser, arg2)) { + return; + } + + const dep = new ConstDependency( + RuntimeGlobals.baseURI, + /** @type {Range} */ (arg2.range), + [RuntimeGlobals.baseURI] + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.module.addPresentationalDependency(dep); + + return true; + } + } + + const evaluatedExpr = getEvaluatedExpr(expr, parser); + if (!evaluatedExpr) return; + + let request; + + // static URL + if ((request = evaluatedExpr.asString())) { + const [arg1, arg2] = expr.arguments; + const dep = new URLDependency( + request, + [ + /** @type {Range} */ (arg1.range)[0], + /** @type {Range} */ (arg2.range)[1] + ], + /** @type {Range} */ (expr.range), + relative + ); + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + parser.state.current.addDependency(dep); + InnerGraph.onUsage(parser.state, (e) => (dep.usedByExports = e)); + return true; + } + + if (this.options.dynamicUrl === false) return; + + // context URL + let include; + let exclude; + + if (importOptions) { + if (importOptions.webpackInclude !== undefined) { + if ( + !importOptions.webpackInclude || + !(importOptions.webpackInclude instanceof RegExp) + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackInclude\` expected a regular expression, but received: ${importOptions.webpackInclude}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else { + include = importOptions.webpackInclude; + } + } + if (importOptions.webpackExclude !== undefined) { + if ( + !importOptions.webpackExclude || + !(importOptions.webpackExclude instanceof RegExp) + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackExclude\` expected a regular expression, but received: ${importOptions.webpackExclude}.`, + /** @type {DependencyLocation} */ (expr.loc) + ) + ); + } else { + exclude = importOptions.webpackExclude; + } + } + } + const dep = ContextDependencyHelpers.create( + URLContextDependency, + /** @type {Range} */ (expr.range), + evaluatedExpr, + expr, + this.options, + { + include, + exclude, + mode: "sync", + typePrefix: "new URL with import.meta.url", + category: "url" + }, + parser + ); + if (!dep) return; + dep.loc = /** @type {DependencyLocation} */ (expr.loc); + dep.optional = Boolean(parser.scope.inTry); + parser.state.current.addDependency(dep); + return true; + }); + parser.hooks.isPure.for("NewExpression").tap(PLUGIN_NAME, (_expr) => { + const expr = /** @type {NewExpressionNode} */ (_expr); + const { callee } = expr; + if (callee.type !== "Identifier") return; + const calleeInfo = parser.getFreeInfoFromVariable(callee.name); + if (!calleeInfo || calleeInfo.name !== "URL") return; + + const evaluatedExpr = getEvaluatedExpr(expr, parser); + const request = evaluatedExpr && evaluatedExpr.asString(); + + if (request) return true; + }); + } +} + +module.exports = URLParserPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/ArrayHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/ArrayHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..af9ac2df457a6aaf8dc030c1cc8d0a513bda10ce --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/ArrayHelpers.js @@ -0,0 +1,46 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * Compare two arrays or strings by performing strict equality check for each value. + * @template T + * @param {ArrayLike} a Array of values to be compared + * @param {ArrayLike} b Array of values to be compared + * @returns {boolean} returns true if all the elements of passed arrays are strictly equal. + */ +module.exports.equals = (a, b) => { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; +}; + +/** + * Partition an array by calling a predicate function on each value. + * @template T + * @param {Array} arr Array of values to be partitioned + * @param {(value: T) => boolean} fn Partition function which partitions based on truthiness of result. + * @returns {[Array, Array]} returns the values of `arr` partitioned into two new arrays based on fn predicate. + */ +module.exports.groupBy = ( + // eslint-disable-next-line default-param-last + arr = [], + fn +) => + arr.reduce( + /** + * @param {[Array, Array]} groups An accumulator storing already partitioned values returned from previous call. + * @param {T} value The value of the current element + * @returns {[Array, Array]} returns an array of partitioned groups accumulator resulting from calling a predicate on the current value. + */ + (groups, value) => { + groups[fn(value) ? 0 : 1].push(value); + return groups; + }, + [[], []] + ); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/ArrayQueue.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/ArrayQueue.js new file mode 100644 index 0000000000000000000000000000000000000000..f877ca1fee901a62505124a80c2c8d69d95ee7cc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/ArrayQueue.js @@ -0,0 +1,104 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @template T + */ +class ArrayQueue { + /** + * @param {Iterable=} items The initial elements. + */ + constructor(items) { + /** + * @private + * @type {T[]} + */ + this._list = items ? [...items] : []; + /** + * @private + * @type {T[]} + */ + this._listReversed = []; + } + + /** + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this._list.length + this._listReversed.length; + } + + /** + * Empties the queue. + */ + clear() { + this._list.length = 0; + this._listReversed.length = 0; + } + + /** + * Appends the specified element to this queue. + * @param {T} item The element to add. + * @returns {void} + */ + enqueue(item) { + this._list.push(item); + } + + /** + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + if (this._listReversed.length === 0) { + if (this._list.length === 0) return; + if (this._list.length === 1) return this._list.pop(); + if (this._list.length < 16) return this._list.shift(); + const temp = this._listReversed; + this._listReversed = this._list; + this._listReversed.reverse(); + this._list = temp; + } + return this._listReversed.pop(); + } + + /** + * Finds and removes an item + * @param {T} item the item + * @returns {void} + */ + delete(item) { + const i = this._list.indexOf(item); + if (i >= 0) { + this._list.splice(i, 1); + } else { + const i = this._listReversed.indexOf(item); + if (i >= 0) this._listReversed.splice(i, 1); + } + } + + [Symbol.iterator]() { + return { + next: () => { + const item = this.dequeue(); + if (item) { + return { + done: false, + value: item + }; + } + return { + done: true, + value: undefined + }; + } + }; + } +} + +module.exports = ArrayQueue; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/AsyncQueue.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/AsyncQueue.js new file mode 100644 index 0000000000000000000000000000000000000000..1bbdc8a52dacc6772a23f7c220af090a14081f36 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/AsyncQueue.js @@ -0,0 +1,410 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { AsyncSeriesHook, SyncHook } = require("tapable"); +const { makeWebpackError } = require("../HookWebpackError"); +const WebpackError = require("../WebpackError"); +const ArrayQueue = require("./ArrayQueue"); + +const QUEUED_STATE = 0; +const PROCESSING_STATE = 1; +const DONE_STATE = 2; + +let inHandleResult = 0; + +/** + * @template T + * @callback Callback + * @param {(WebpackError | null)=} err + * @param {(T | null)=} result + */ + +/** + * @template T + * @template K + * @template R + */ +class AsyncQueueEntry { + /** + * @param {T} item the item + * @param {Callback} callback the callback + */ + constructor(item, callback) { + this.item = item; + /** @type {typeof QUEUED_STATE | typeof PROCESSING_STATE | typeof DONE_STATE} */ + this.state = QUEUED_STATE; + /** @type {Callback | undefined} */ + this.callback = callback; + /** @type {Callback[] | undefined} */ + this.callbacks = undefined; + /** @type {R | null | undefined} */ + this.result = undefined; + /** @type {WebpackError | null | undefined} */ + this.error = undefined; + } +} + +/** + * @template T, K + * @typedef {(item: T) => K} getKey + */ + +/** + * @template T, R + * @typedef {(item: T, callback: Callback) => void} Processor + */ + +/** + * @template T + * @template K + * @template R + */ +class AsyncQueue { + /** + * @param {object} options options object + * @param {string=} options.name name of the queue + * @param {number=} options.parallelism how many items should be processed at once + * @param {string=} options.context context of execution + * @param {AsyncQueue=} options.parent parent queue, which will have priority over this queue and with shared parallelism + * @param {getKey=} options.getKey extract key from item + * @param {Processor} options.processor async function to process items + */ + constructor({ name, context, parallelism, parent, processor, getKey }) { + this._name = name; + this._context = context || "normal"; + this._parallelism = parallelism || 1; + this._processor = processor; + this._getKey = + getKey || + /** @type {getKey} */ ((item) => /** @type {T & K} */ (item)); + /** @type {Map>} */ + this._entries = new Map(); + /** @type {ArrayQueue>} */ + this._queued = new ArrayQueue(); + /** @type {AsyncQueue[] | undefined} */ + this._children = undefined; + this._activeTasks = 0; + this._willEnsureProcessing = false; + this._needProcessing = false; + this._stopped = false; + /** @type {AsyncQueue} */ + this._root = parent ? parent._root : this; + if (parent) { + if (this._root._children === undefined) { + this._root._children = [this]; + } else { + this._root._children.push(this); + } + } + + this.hooks = { + /** @type {AsyncSeriesHook<[T]>} */ + beforeAdd: new AsyncSeriesHook(["item"]), + /** @type {SyncHook<[T]>} */ + added: new SyncHook(["item"]), + /** @type {AsyncSeriesHook<[T]>} */ + beforeStart: new AsyncSeriesHook(["item"]), + /** @type {SyncHook<[T]>} */ + started: new SyncHook(["item"]), + /** @type {SyncHook<[T, WebpackError | null | undefined, R | null | undefined]>} */ + result: new SyncHook(["item", "error", "result"]) + }; + + this._ensureProcessing = this._ensureProcessing.bind(this); + } + + /** + * @returns {string} context of execution + */ + getContext() { + return this._context; + } + + /** + * @param {string} value context of execution + */ + setContext(value) { + this._context = value; + } + + /** + * @param {T} item an item + * @param {Callback} callback callback function + * @returns {void} + */ + add(item, callback) { + if (this._stopped) return callback(new WebpackError("Queue was stopped")); + this.hooks.beforeAdd.callAsync(item, (err) => { + if (err) { + callback( + makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeAdd`) + ); + return; + } + const key = this._getKey(item); + const entry = this._entries.get(key); + if (entry !== undefined) { + if (entry.state === DONE_STATE) { + if (inHandleResult++ > 3) { + process.nextTick(() => callback(entry.error, entry.result)); + } else { + callback(entry.error, entry.result); + } + inHandleResult--; + } else if (entry.callbacks === undefined) { + entry.callbacks = [callback]; + } else { + entry.callbacks.push(callback); + } + return; + } + const newEntry = new AsyncQueueEntry(item, callback); + if (this._stopped) { + this.hooks.added.call(item); + this._root._activeTasks++; + process.nextTick(() => + this._handleResult(newEntry, new WebpackError("Queue was stopped")) + ); + } else { + this._entries.set(key, newEntry); + this._queued.enqueue(newEntry); + const root = this._root; + root._needProcessing = true; + if (root._willEnsureProcessing === false) { + root._willEnsureProcessing = true; + setImmediate(root._ensureProcessing); + } + this.hooks.added.call(item); + } + }); + } + + /** + * @param {T} item an item + * @returns {void} + */ + invalidate(item) { + const key = this._getKey(item); + const entry = + /** @type {AsyncQueueEntry} */ + (this._entries.get(key)); + this._entries.delete(key); + if (entry.state === QUEUED_STATE) { + this._queued.delete(entry); + } + } + + /** + * Waits for an already started item + * @param {T} item an item + * @param {Callback} callback callback function + * @returns {void} + */ + waitFor(item, callback) { + const key = this._getKey(item); + const entry = this._entries.get(key); + if (entry === undefined) { + return callback( + new WebpackError( + "waitFor can only be called for an already started item" + ) + ); + } + if (entry.state === DONE_STATE) { + process.nextTick(() => callback(entry.error, entry.result)); + } else if (entry.callbacks === undefined) { + entry.callbacks = [callback]; + } else { + entry.callbacks.push(callback); + } + } + + /** + * @returns {void} + */ + stop() { + this._stopped = true; + const queue = this._queued; + this._queued = new ArrayQueue(); + const root = this._root; + for (const entry of queue) { + this._entries.delete( + this._getKey(/** @type {AsyncQueueEntry} */ (entry).item) + ); + root._activeTasks++; + this._handleResult( + /** @type {AsyncQueueEntry} */ (entry), + new WebpackError("Queue was stopped") + ); + } + } + + /** + * @returns {void} + */ + increaseParallelism() { + const root = this._root; + root._parallelism++; + /* istanbul ignore next */ + if (root._willEnsureProcessing === false && root._needProcessing) { + root._willEnsureProcessing = true; + setImmediate(root._ensureProcessing); + } + } + + /** + * @returns {void} + */ + decreaseParallelism() { + const root = this._root; + root._parallelism--; + } + + /** + * @param {T} item an item + * @returns {boolean} true, if the item is currently being processed + */ + isProcessing(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + return entry !== undefined && entry.state === PROCESSING_STATE; + } + + /** + * @param {T} item an item + * @returns {boolean} true, if the item is currently queued + */ + isQueued(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + return entry !== undefined && entry.state === QUEUED_STATE; + } + + /** + * @param {T} item an item + * @returns {boolean} true, if the item is currently queued + */ + isDone(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + return entry !== undefined && entry.state === DONE_STATE; + } + + /** + * @returns {void} + */ + _ensureProcessing() { + while (this._activeTasks < this._parallelism) { + const entry = this._queued.dequeue(); + if (entry === undefined) break; + this._activeTasks++; + entry.state = PROCESSING_STATE; + this._startProcessing(entry); + } + this._willEnsureProcessing = false; + if (this._queued.length > 0) return; + if (this._children !== undefined) { + for (const child of this._children) { + while (this._activeTasks < this._parallelism) { + const entry = child._queued.dequeue(); + if (entry === undefined) break; + this._activeTasks++; + entry.state = PROCESSING_STATE; + child._startProcessing(entry); + } + if (child._queued.length > 0) return; + } + } + if (!this._willEnsureProcessing) this._needProcessing = false; + } + + /** + * @param {AsyncQueueEntry} entry the entry + * @returns {void} + */ + _startProcessing(entry) { + this.hooks.beforeStart.callAsync(entry.item, (err) => { + if (err) { + this._handleResult( + entry, + makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeStart`) + ); + return; + } + let inCallback = false; + try { + this._processor(entry.item, (e, r) => { + inCallback = true; + this._handleResult(entry, e, r); + }); + } catch (err) { + if (inCallback) throw err; + this._handleResult(entry, /** @type {WebpackError} */ (err), null); + } + this.hooks.started.call(entry.item); + }); + } + + /** + * @param {AsyncQueueEntry} entry the entry + * @param {(WebpackError | null)=} err error, if any + * @param {(R | null)=} result result, if any + * @returns {void} + */ + _handleResult(entry, err, result) { + this.hooks.result.callAsync(entry.item, err, result, (hookError) => { + const error = hookError + ? makeWebpackError(hookError, `AsyncQueue(${this._name}).hooks.result`) + : err; + + const callback = /** @type {Callback} */ (entry.callback); + const callbacks = entry.callbacks; + entry.state = DONE_STATE; + entry.callback = undefined; + entry.callbacks = undefined; + entry.result = result; + entry.error = error; + + const root = this._root; + root._activeTasks--; + if (root._willEnsureProcessing === false && root._needProcessing) { + root._willEnsureProcessing = true; + setImmediate(root._ensureProcessing); + } + + if (inHandleResult++ > 3) { + process.nextTick(() => { + callback(error, result); + if (callbacks !== undefined) { + for (const callback of callbacks) { + callback(error, result); + } + } + }); + } else { + callback(error, result); + if (callbacks !== undefined) { + for (const callback of callbacks) { + callback(error, result); + } + } + } + inHandleResult--; + }); + } + + clear() { + this._entries.clear(); + this._queued.clear(); + this._activeTasks = 0; + this._willEnsureProcessing = false; + this._needProcessing = false; + this._stopped = false; + } +} + +module.exports = AsyncQueue; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/Hash.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/Hash.js new file mode 100644 index 0000000000000000000000000000000000000000..667add22380d112e534ac3886cad89df589b1d44 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/Hash.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +class Hash { + /* istanbul ignore next */ + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @abstract + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + const AbstractMethodError = require("../AbstractMethodError"); + + throw new AbstractMethodError(); + } + + /* istanbul ignore next */ + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @abstract + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + const AbstractMethodError = require("../AbstractMethodError"); + + throw new AbstractMethodError(); + } +} + +module.exports = Hash; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/IterableHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/IterableHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..ef56089fb6afba9aa368302068e0e7e199ceca77 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/IterableHelpers.js @@ -0,0 +1,45 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @template T + * @param {Iterable} set a set + * @returns {T | undefined} last item + */ +const last = (set) => { + let last; + for (const item of set) last = item; + return last; +}; + +/** + * @template T + * @param {Iterable} iterable iterable + * @param {(value: T) => boolean | null | undefined} filter predicate + * @returns {boolean} true, if some items match the filter predicate + */ +const someInIterable = (iterable, filter) => { + for (const item of iterable) { + if (filter(item)) return true; + } + return false; +}; + +/** + * @template T + * @param {Iterable} iterable an iterable + * @returns {number} count of items + */ +const countIterable = (iterable) => { + let i = 0; + for (const _ of iterable) i++; + return i; +}; + +module.exports.countIterable = countIterable; +module.exports.last = last; +module.exports.someInIterable = someInIterable; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/LazyBucketSortedSet.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/LazyBucketSortedSet.js new file mode 100644 index 0000000000000000000000000000000000000000..26188756a1656b441abc868d33b3b493dfcece76 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/LazyBucketSortedSet.js @@ -0,0 +1,271 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { first } = require("./SetHelpers"); +const SortableSet = require("./SortableSet"); + +/** + * @template T + * @template K + * @typedef {(item: T) => K} GetKey + */ + +/** + * @template T + * @typedef {(a: T, n: T) => number} Comparator + */ + +/** + * @template T + * @template K + * @typedef {LazyBucketSortedSet | SortableSet} Entry + */ + +/** + * @template T + * @template K + * @typedef {GetKey | Comparator | Comparator} Arg + */ + +/** + * Multi layer bucket sorted set: + * Supports adding non-existing items (DO NOT ADD ITEM TWICE), + * Supports removing exiting items (DO NOT REMOVE ITEM NOT IN SET), + * Supports popping the first items according to defined order, + * Supports iterating all items without order, + * Supports updating an item in an efficient way, + * Supports size property, which is the number of items, + * Items are lazy partially sorted when needed + * @template T + * @template K + */ +class LazyBucketSortedSet { + /** + * @param {GetKey} getKey function to get key from item + * @param {Comparator=} comparator comparator to sort keys + * @param {...Arg} args more pairs of getKey and comparator plus optional final comparator for the last layer + */ + constructor(getKey, comparator, ...args) { + this._getKey = getKey; + this._innerArgs = args; + this._leaf = args.length <= 1; + this._keys = new SortableSet(undefined, comparator); + /** @type {Map>} */ + this._map = new Map(); + this._unsortedItems = new Set(); + this.size = 0; + } + + /** + * @param {T} item an item + * @returns {void} + */ + add(item) { + this.size++; + this._unsortedItems.add(item); + } + + /** + * @param {K} key key of item + * @param {T} item the item + * @returns {void} + */ + _addInternal(key, item) { + let entry = this._map.get(key); + if (entry === undefined) { + entry = this._leaf + ? new SortableSet( + undefined, + /** @type {Comparator} */ + (this._innerArgs[0]) + ) + : new LazyBucketSortedSet( + .../** @type {[GetKey, Comparator]} */ + (this._innerArgs) + ); + this._keys.add(key); + this._map.set(key, entry); + } + entry.add(item); + } + + /** + * @param {T} item an item + * @returns {void} + */ + delete(item) { + this.size--; + if (this._unsortedItems.has(item)) { + this._unsortedItems.delete(item); + return; + } + const key = this._getKey(item); + const entry = /** @type {Entry} */ (this._map.get(key)); + entry.delete(item); + if (entry.size === 0) { + this._deleteKey(key); + } + } + + /** + * @param {K} key key to be removed + * @returns {void} + */ + _deleteKey(key) { + this._keys.delete(key); + this._map.delete(key); + } + + /** + * @returns {T | undefined} an item + */ + popFirst() { + if (this.size === 0) return; + this.size--; + if (this._unsortedItems.size > 0) { + for (const item of this._unsortedItems) { + const key = this._getKey(item); + this._addInternal(key, item); + } + this._unsortedItems.clear(); + } + this._keys.sort(); + const key = /** @type {K} */ (first(this._keys)); + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + leafEntry.sort(); + const item = /** @type {T} */ (first(leafEntry)); + leafEntry.delete(item); + if (leafEntry.size === 0) { + this._deleteKey(key); + } + return item; + } + const nodeEntry = + /** @type {LazyBucketSortedSet} */ + (entry); + const item = nodeEntry.popFirst(); + if (nodeEntry.size === 0) { + this._deleteKey(key); + } + return item; + } + + /** + * @param {T} item to be updated item + * @returns {(remove?: true) => void} finish update + */ + startUpdate(item) { + if (this._unsortedItems.has(item)) { + return (remove) => { + if (remove) { + this._unsortedItems.delete(item); + this.size--; + } + }; + } + const key = this._getKey(item); + if (this._leaf) { + const oldEntry = /** @type {SortableSet} */ (this._map.get(key)); + return (remove) => { + if (remove) { + this.size--; + oldEntry.delete(item); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + return; + } + const newKey = this._getKey(item); + if (key === newKey) { + // This flags the sortable set as unordered + oldEntry.add(item); + } else { + oldEntry.delete(item); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + this._addInternal(newKey, item); + } + }; + } + const oldEntry = + /** @type {LazyBucketSortedSet} */ + (this._map.get(key)); + const finishUpdate = oldEntry.startUpdate(item); + return (remove) => { + if (remove) { + this.size--; + finishUpdate(true); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + return; + } + const newKey = this._getKey(item); + if (key === newKey) { + finishUpdate(); + } else { + finishUpdate(true); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + this._addInternal(newKey, item); + } + }; + } + + /** + * @param {Iterator[]} iterators list of iterators to append to + * @returns {void} + */ + _appendIterators(iterators) { + if (this._unsortedItems.size > 0) { + iterators.push(this._unsortedItems[Symbol.iterator]()); + } + for (const key of this._keys) { + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + const iterator = leafEntry[Symbol.iterator](); + iterators.push(iterator); + } else { + const nodeEntry = + /** @type {LazyBucketSortedSet} */ + (entry); + nodeEntry._appendIterators(iterators); + } + } + } + + /** + * @returns {Iterator} the iterator + */ + [Symbol.iterator]() { + /** @type {Iterator[]} */ + const iterators = []; + this._appendIterators(iterators); + iterators.reverse(); + let currentIterator = + /** @type {Iterator} */ + (iterators.pop()); + return { + next: () => { + const res = currentIterator.next(); + if (res.done) { + if (iterators.length === 0) return res; + currentIterator = /** @type {Iterator} */ (iterators.pop()); + return currentIterator.next(); + } + return res; + } + }; + } +} + +module.exports = LazyBucketSortedSet; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/LazySet.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/LazySet.js new file mode 100644 index 0000000000000000000000000000000000000000..cfcc6691a66ef45473a9009a829f7f7a2e1c8066 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/LazySet.js @@ -0,0 +1,235 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const makeSerializable = require("./makeSerializable"); + +/** + * @template T + * @param {Set} targetSet set where items should be added + * @param {Set>} toMerge iterables to be merged + * @returns {void} + */ +const merge = (targetSet, toMerge) => { + for (const set of toMerge) { + for (const item of set) { + targetSet.add(item); + } + } +}; + +/** + * @template T + * @param {Set>} targetSet set where iterables should be added + * @param {Array>} toDeepMerge lazy sets to be flattened + * @returns {void} + */ +const flatten = (targetSet, toDeepMerge) => { + for (const set of toDeepMerge) { + if (set._set.size > 0) targetSet.add(set._set); + if (set._needMerge) { + for (const mergedSet of set._toMerge) { + targetSet.add(mergedSet); + } + flatten(targetSet, set._toDeepMerge); + } + } +}; + +/** + * @template T + * @typedef {import("typescript-iterable").SetIterator} SetIterator + */ + +/** + * Like Set but with an addAll method to eventually add items from another iterable. + * Access methods make sure that all delayed operations are executed. + * Iteration methods deopts to normal Set performance until clear is called again (because of the chance of modifications during iteration). + * @template T + */ +class LazySet { + /** + * @param {Iterable=} iterable init iterable + */ + constructor(iterable) { + /** @type {Set} */ + this._set = new Set(iterable); + /** @type {Set>} */ + this._toMerge = new Set(); + /** @type {Array>} */ + this._toDeepMerge = []; + this._needMerge = false; + this._deopt = false; + } + + _flatten() { + flatten(this._toMerge, this._toDeepMerge); + this._toDeepMerge.length = 0; + } + + _merge() { + this._flatten(); + merge(this._set, this._toMerge); + this._toMerge.clear(); + this._needMerge = false; + } + + _isEmpty() { + return ( + this._set.size === 0 && + this._toMerge.size === 0 && + this._toDeepMerge.length === 0 + ); + } + + get size() { + if (this._needMerge) this._merge(); + return this._set.size; + } + + /** + * @param {T} item an item + * @returns {LazySet} itself + */ + add(item) { + this._set.add(item); + return this; + } + + /** + * @param {Iterable | LazySet} iterable a immutable iterable or another immutable LazySet which will eventually be merged into the Set + * @returns {LazySet} itself + */ + addAll(iterable) { + if (this._deopt) { + const _set = this._set; + for (const item of iterable) { + _set.add(item); + } + } else { + if (iterable instanceof LazySet) { + if (iterable._isEmpty()) return this; + this._toDeepMerge.push(iterable); + this._needMerge = true; + if (this._toDeepMerge.length > 100000) { + this._flatten(); + } + } else { + this._toMerge.add(iterable); + this._needMerge = true; + } + if (this._toMerge.size > 100000) this._merge(); + } + return this; + } + + clear() { + this._set.clear(); + this._toMerge.clear(); + this._toDeepMerge.length = 0; + this._needMerge = false; + this._deopt = false; + } + + /** + * @param {T} value an item + * @returns {boolean} true, if the value was in the Set before + */ + delete(value) { + if (this._needMerge) this._merge(); + return this._set.delete(value); + } + + /** + * @returns {SetIterator<[T, T]>} entries + */ + entries() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set.entries(); + } + + /** + * @template K + * @param {(value: T, value2: T, set: Set) => void} callbackFn function called for each entry + * @param {K} thisArg this argument for the callbackFn + * @returns {void} + */ + forEach(callbackFn, thisArg) { + this._deopt = true; + if (this._needMerge) this._merge(); + // eslint-disable-next-line unicorn/no-array-for-each, unicorn/no-array-method-this-argument + this._set.forEach(callbackFn, thisArg); + } + + /** + * @param {T} item an item + * @returns {boolean} true, when the item is in the Set + */ + has(item) { + if (this._needMerge) this._merge(); + return this._set.has(item); + } + + /** + * @returns {SetIterator} keys + */ + keys() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set.keys(); + } + + /** + * @returns {SetIterator} values + */ + values() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set.values(); + } + + /** + * @returns {SetIterator} iterable iterator + */ + [Symbol.iterator]() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set[Symbol.iterator](); + } + + /* istanbul ignore next */ + get [Symbol.toStringTag]() { + return "LazySet"; + } + + /** + * @param {import("../serialization/ObjectMiddleware").ObjectSerializerContext} context context + */ + serialize({ write }) { + if (this._needMerge) this._merge(); + write(this._set.size); + for (const item of this._set) write(item); + } + + /** + * @template T + * @param {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} context context + * @returns {LazySet} lazy set + */ + static deserialize({ read }) { + const count = read(); + const items = []; + for (let i = 0; i < count; i++) { + items.push(read()); + } + return new LazySet(items); + } +} + +makeSerializable(LazySet, "webpack/lib/util/LazySet"); + +module.exports = LazySet; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/MapHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/MapHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..533436e2384103c2058dfe4858cb659b8418b448 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/MapHelpers.js @@ -0,0 +1,34 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * getOrInsert is a helper function for maps that allows you to get a value + * from a map if it exists, or insert a new value if it doesn't. If it value doesn't + * exist, it will be computed by the provided function. + * @template K + * @template V + * @param {Map} map The map object to check + * @param {K} key The key to check + * @param {() => V} computer function which will compute the value if it doesn't exist + * @returns {V} The value from the map, or the computed value + * @example + * ```js + * const map = new Map(); + * const value = getOrInsert(map, "key", () => "value"); + * console.log(value); // "value" + * ``` + */ +module.exports.getOrInsert = (map, key, computer) => { + // Grab key from map + const value = map.get(key); + // If the value already exists, return it + if (value !== undefined) return value; + // Otherwise compute the value, set it in the map, and return it + const newValue = computer(); + map.set(key, newValue); + return newValue; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/ParallelismFactorCalculator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/ParallelismFactorCalculator.js new file mode 100644 index 0000000000000000000000000000000000000000..4651a53886bf42b01c351cffe56d55c375e0f044 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/ParallelismFactorCalculator.js @@ -0,0 +1,69 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const binarySearchBounds = require("./binarySearchBounds"); + +/** @typedef {(value: number) => void} Callback */ + +class ParallelismFactorCalculator { + constructor() { + /** @type {number[]} */ + this._rangePoints = []; + /** @type {Callback[]} */ + this._rangeCallbacks = []; + } + + /** + * @param {number} start range start + * @param {number} end range end + * @param {Callback} callback callback + * @returns {void} + */ + range(start, end, callback) { + if (start === end) return callback(1); + this._rangePoints.push(start); + this._rangePoints.push(end); + this._rangeCallbacks.push(callback); + } + + calculate() { + const segments = [...new Set(this._rangePoints)].sort((a, b) => + a < b ? -1 : 1 + ); + const parallelism = segments.map(() => 0); + const rangeStartIndices = []; + for (let i = 0; i < this._rangePoints.length; i += 2) { + const start = this._rangePoints[i]; + const end = this._rangePoints[i + 1]; + let idx = binarySearchBounds.eq(segments, start); + rangeStartIndices.push(idx); + do { + parallelism[idx]++; + idx++; + } while (segments[idx] < end); + } + for (let i = 0; i < this._rangeCallbacks.length; i++) { + const start = this._rangePoints[i * 2]; + const end = this._rangePoints[i * 2 + 1]; + let idx = rangeStartIndices[i]; + let sum = 0; + let totalDuration = 0; + let current = start; + do { + const p = parallelism[idx]; + idx++; + const duration = segments[idx] - current; + totalDuration += duration; + current = segments[idx]; + sum += p * duration; + } while (current < end); + this._rangeCallbacks[i](sum / totalDuration); + } + } +} + +module.exports = ParallelismFactorCalculator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/Queue.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/Queue.js new file mode 100644 index 0000000000000000000000000000000000000000..3820770655a0ca603c08c288361347755514f76c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/Queue.js @@ -0,0 +1,52 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @template T + */ +class Queue { + /** + * @param {Iterable=} items The initial elements. + */ + constructor(items) { + /** + * @private + * @type {Set} + */ + this._set = new Set(items); + } + + /** + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this._set.size; + } + + /** + * Appends the specified element to this queue. + * @param {T} item The element to add. + * @returns {void} + */ + enqueue(item) { + this._set.add(item); + } + + /** + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + const result = this._set[Symbol.iterator]().next(); + if (result.done) return; + this._set.delete(result.value); + return result.value; + } +} + +module.exports = Queue; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/Semaphore.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/Semaphore.js new file mode 100644 index 0000000000000000000000000000000000000000..66b9ad938e06b42a278c54d24f89b223189c32e8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/Semaphore.js @@ -0,0 +1,51 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +class Semaphore { + /** + * Creates an instance of Semaphore. + * @param {number} available the amount available number of "tasks" + * in the Semaphore + */ + constructor(available) { + this.available = available; + /** @type {(() => void)[]} */ + this.waiters = []; + /** @private */ + this._continue = this._continue.bind(this); + } + + /** + * @param {() => void} callback function block to capture and run + * @returns {void} + */ + acquire(callback) { + if (this.available > 0) { + this.available--; + callback(); + } else { + this.waiters.push(callback); + } + } + + release() { + this.available++; + if (this.waiters.length > 0) { + process.nextTick(this._continue); + } + } + + _continue() { + if (this.available > 0 && this.waiters.length > 0) { + this.available--; + const callback = /** @type {(() => void)} */ (this.waiters.pop()); + callback(); + } + } +} + +module.exports = Semaphore; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/SetHelpers.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/SetHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..9691d9ab7a1b2f9a1eb943800851ab9d2cf88e2b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/SetHelpers.js @@ -0,0 +1,94 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * intersect creates Set containing the intersection of elements between all sets + * @template T + * @param {Set[]} sets an array of sets being checked for shared elements + * @returns {Set} returns a new Set containing the intersecting items + */ +const intersect = (sets) => { + if (sets.length === 0) return new Set(); + if (sets.length === 1) return new Set(sets[0]); + let minSize = Infinity; + let minIndex = -1; + for (let i = 0; i < sets.length; i++) { + const size = sets[i].size; + if (size < minSize) { + minIndex = i; + minSize = size; + } + } + const current = new Set(sets[minIndex]); + for (let i = 0; i < sets.length; i++) { + if (i === minIndex) continue; + const set = sets[i]; + for (const item of current) { + if (!set.has(item)) { + current.delete(item); + } + } + } + return current; +}; + +/** + * Checks if a set is the subset of another set + * @template T + * @param {Set} bigSet a Set which contains the original elements to compare against + * @param {Set} smallSet the set whose elements might be contained inside of bigSet + * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet + */ +const isSubset = (bigSet, smallSet) => { + if (bigSet.size < smallSet.size) return false; + for (const item of smallSet) { + if (!bigSet.has(item)) return false; + } + return true; +}; + +/** + * @template T + * @param {Set} set a set + * @param {(set: T) => boolean} fn selector function + * @returns {T | undefined} found item + */ +const find = (set, fn) => { + for (const item of set) { + if (fn(item)) return item; + } +}; + +/** + * @template T + * @param {Set | ReadonlySet} set a set + * @returns {T | undefined} first item + */ +const first = (set) => { + const entry = set.values().next(); + return entry.done ? undefined : entry.value; +}; + +/** + * @template T + * @param {Set} a first + * @param {Set} b second + * @returns {Set} combined set, may be identical to a or b + */ +const combine = (a, b) => { + if (b.size === 0) return a; + if (a.size === 0) return b; + const set = new Set(a); + for (const item of b) set.add(item); + return set; +}; + +module.exports.combine = combine; +module.exports.find = find; +module.exports.first = first; +module.exports.intersect = intersect; +module.exports.isSubset = isSubset; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/SortableSet.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/SortableSet.js new file mode 100644 index 0000000000000000000000000000000000000000..18ad2ca7d1d8fdfccc05a55ec0122a176fdab0e3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/SortableSet.js @@ -0,0 +1,175 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const NONE = Symbol("not sorted"); + +/** + * A subset of Set that offers sorting functionality + * @template T item type in set + * @extends {Set} + */ +class SortableSet extends Set { + /** + * Create a new sortable set + * @template T + * @typedef {(a: T, b: T) => number} SortFunction + * @param {Iterable=} initialIterable The initial iterable value + * @param {SortFunction=} defaultSort Default sorting function + */ + constructor(initialIterable, defaultSort) { + super(initialIterable); + /** + * @private + * @type {undefined | SortFunction} + */ + this._sortFn = defaultSort; + /** + * @private + * @type {typeof NONE | undefined | ((a: T, b: T) => number)}} + */ + this._lastActiveSortFn = NONE; + /** + * @private + * @template R + * @type {Map<(set: SortableSet) => EXPECTED_ANY, EXPECTED_ANY> | undefined} + */ + this._cache = undefined; + /** + * @private + * @template R + * @type {Map<(set: SortableSet) => EXPECTED_ANY, EXPECTED_ANY> | undefined} + */ + this._cacheOrderIndependent = undefined; + } + + /** + * @param {T} value value to add to set + * @returns {this} returns itself + */ + add(value) { + this._lastActiveSortFn = NONE; + this._invalidateCache(); + this._invalidateOrderedCache(); + super.add(value); + return this; + } + + /** + * @param {T} value value to delete + * @returns {boolean} true if value existed in set, false otherwise + */ + delete(value) { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.delete(value); + } + + /** + * @returns {void} + */ + clear() { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.clear(); + } + + /** + * Sort with a comparer function + * @param {SortFunction | undefined} sortFn Sorting comparer function + * @returns {void} + */ + sortWith(sortFn) { + if (this.size <= 1 || sortFn === this._lastActiveSortFn) { + // already sorted - nothing to do + return; + } + + const sortedArray = [...this].sort(sortFn); + super.clear(); + for (let i = 0; i < sortedArray.length; i += 1) { + super.add(sortedArray[i]); + } + this._lastActiveSortFn = sortFn; + this._invalidateCache(); + } + + sort() { + this.sortWith(this._sortFn); + return this; + } + + /** + * Get data from cache + * @template {EXPECTED_ANY} R + * @param {(set: SortableSet) => R} fn function to calculate value + * @returns {R} returns result of fn(this), cached until set changes + */ + getFromCache(fn) { + if (this._cache === undefined) { + this._cache = new Map(); + } else { + const result = this._cache.get(fn); + const data = /** @type {R} */ (result); + if (data !== undefined) { + return data; + } + } + const newData = fn(this); + this._cache.set(fn, newData); + return newData; + } + + /** + * Get data from cache (ignoring sorting) + * @template R + * @param {(set: SortableSet) => R} fn function to calculate value + * @returns {R} returns result of fn(this), cached until set changes + */ + getFromUnorderedCache(fn) { + if (this._cacheOrderIndependent === undefined) { + this._cacheOrderIndependent = new Map(); + } else { + const result = this._cacheOrderIndependent.get(fn); + const data = /** @type {R} */ (result); + if (data !== undefined) { + return data; + } + } + const newData = fn(this); + this._cacheOrderIndependent.set(fn, newData); + return newData; + } + + /** + * @private + * @returns {void} + */ + _invalidateCache() { + if (this._cache !== undefined) { + this._cache.clear(); + } + } + + /** + * @private + * @returns {void} + */ + _invalidateOrderedCache() { + if (this._cacheOrderIndependent !== undefined) { + this._cacheOrderIndependent.clear(); + } + } + + /** + * @returns {T[]} the raw array + */ + toJSON() { + return [...this]; + } +} + +module.exports = SortableSet; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/StackedCacheMap.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/StackedCacheMap.js new file mode 100644 index 0000000000000000000000000000000000000000..781aa86d6946d26c34a7d816ad5b0dd6e63e2029 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/StackedCacheMap.js @@ -0,0 +1,142 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +new Map().entries(); + +/** + * The StackedCacheMap is a data structure designed as an alternative to a Map + * in situations where you need to handle multiple item additions and + * frequently access the largest map. + * + * It is particularly optimized for efficiently adding multiple items + * at once, which can be achieved using the `addAll` method. + * + * It has a fallback Map that is used when the map to be added is mutable. + * + * Note: `delete` and `has` are not supported for performance reasons. + * @example + * ```js + * const map = new StackedCacheMap(); + * map.addAll(new Map([["a", 1], ["b", 2]]), true); + * map.addAll(new Map([["c", 3], ["d", 4]]), true); + * map.get("a"); // 1 + * map.get("d"); // 4 + * for (const [key, value] of map) { + * console.log(key, value); + * } + * ``` + * @template K + * @template V + */ +class StackedCacheMap { + constructor() { + /** @type {Map} */ + this.map = new Map(); + /** @type {ReadonlyMap[]} */ + this.stack = []; + } + + /** + * If `immutable` is true, the map can be referenced by the StackedCacheMap + * and should not be changed afterwards. If the map is mutable, all items + * are copied into a fallback Map. + * @param {ReadonlyMap} map map to add + * @param {boolean=} immutable if 'map' is immutable and StackedCacheMap can keep referencing it + */ + addAll(map, immutable) { + if (immutable) { + this.stack.push(map); + + // largest map should go first + for (let i = this.stack.length - 1; i > 0; i--) { + const beforeLast = this.stack[i - 1]; + if (beforeLast.size >= map.size) break; + this.stack[i] = beforeLast; + this.stack[i - 1] = map; + } + } else { + for (const [key, value] of map) { + this.map.set(key, value); + } + } + } + + /** + * @param {K} item the key of the element to add + * @param {V} value the value of the element to add + * @returns {void} + */ + set(item, value) { + this.map.set(item, value); + } + + /** + * @param {K} item the item to delete + * @returns {void} + */ + delete(item) { + throw new Error("Items can't be deleted from a StackedCacheMap"); + } + + /** + * @param {K} item the item to test + * @returns {boolean} true if the item exists in this set + */ + has(item) { + throw new Error( + "Checking StackedCacheMap.has before reading is inefficient, use StackedCacheMap.get and check for undefined" + ); + } + + /** + * @param {K} item the key of the element to return + * @returns {V | undefined} the value of the element + */ + get(item) { + for (const map of this.stack) { + const value = map.get(item); + if (value !== undefined) return value; + } + return this.map.get(item); + } + + clear() { + this.stack.length = 0; + this.map.clear(); + } + + /** + * @returns {number} size of the map + */ + get size() { + let size = this.map.size; + for (const map of this.stack) { + size += map.size; + } + return size; + } + + /** + * @returns {Iterator<[K, V]>} iterator + */ + [Symbol.iterator]() { + const iterators = this.stack.map((map) => map[Symbol.iterator]()); + let current = this.map[Symbol.iterator](); + return { + next() { + let result = current.next(); + while (result.done && iterators.length > 0) { + current = /** @type {MapIterator<[K, V]>} */ (iterators.pop()); + result = current.next(); + } + return result; + } + }; + } +} + +module.exports = StackedCacheMap; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/StackedMap.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/StackedMap.js new file mode 100644 index 0000000000000000000000000000000000000000..d515db21712f88d3aca6b82724109187002c82c5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/StackedMap.js @@ -0,0 +1,164 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const TOMBSTONE = Symbol("tombstone"); +const UNDEFINED_MARKER = Symbol("undefined"); + +/** + * @template T + * @typedef {T | undefined} Cell + */ + +/** + * @template T + * @typedef {T | typeof TOMBSTONE | typeof UNDEFINED_MARKER} InternalCell + */ + +/** + * @template K + * @template V + * @param {[K, InternalCell]} pair the internal cell + * @returns {[K, Cell]} its “safe” representation + */ +const extractPair = (pair) => { + const key = pair[0]; + const val = pair[1]; + if (val === UNDEFINED_MARKER || val === TOMBSTONE) { + return [key, undefined]; + } + return /** @type {[K, Cell]} */ (pair); +}; + +/** + * @template K + * @template V + */ +class StackedMap { + /** + * @param {Map>[]=} parentStack an optional parent + */ + constructor(parentStack) { + /** @type {Map>} */ + this.map = new Map(); + /** @type {Map>[]} */ + this.stack = parentStack === undefined ? [] : [...parentStack]; + this.stack.push(this.map); + } + + /** + * @param {K} item the key of the element to add + * @param {V} value the value of the element to add + * @returns {void} + */ + set(item, value) { + this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); + } + + /** + * @param {K} item the item to delete + * @returns {void} + */ + delete(item) { + if (this.stack.length > 1) { + this.map.set(item, TOMBSTONE); + } else { + this.map.delete(item); + } + } + + /** + * @param {K} item the item to test + * @returns {boolean} true if the item exists in this set + */ + has(item) { + const topValue = this.map.get(item); + if (topValue !== undefined) { + return topValue !== TOMBSTONE; + } + if (this.stack.length > 1) { + for (let i = this.stack.length - 2; i >= 0; i--) { + const value = this.stack[i].get(item); + if (value !== undefined) { + this.map.set(item, value); + return value !== TOMBSTONE; + } + } + this.map.set(item, TOMBSTONE); + } + return false; + } + + /** + * @param {K} item the key of the element to return + * @returns {Cell} the value of the element + */ + get(item) { + const topValue = this.map.get(item); + if (topValue !== undefined) { + return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER + ? undefined + : topValue; + } + if (this.stack.length > 1) { + for (let i = this.stack.length - 2; i >= 0; i--) { + const value = this.stack[i].get(item); + if (value !== undefined) { + this.map.set(item, value); + return value === TOMBSTONE || value === UNDEFINED_MARKER + ? undefined + : value; + } + } + this.map.set(item, TOMBSTONE); + } + } + + _compress() { + if (this.stack.length === 1) return; + this.map = new Map(); + for (const data of this.stack) { + for (const pair of data) { + if (pair[1] === TOMBSTONE) { + this.map.delete(pair[0]); + } else { + this.map.set(pair[0], pair[1]); + } + } + } + this.stack = [this.map]; + } + + asArray() { + this._compress(); + return [...this.map.keys()]; + } + + asSet() { + this._compress(); + return new Set(this.map.keys()); + } + + asPairArray() { + this._compress(); + return Array.from(this.map.entries(), extractPair); + } + + asMap() { + return new Map(this.asPairArray()); + } + + get size() { + this._compress(); + return this.map.size; + } + + createChild() { + return new StackedMap(this.stack); + } +} + +module.exports = StackedMap; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/StringXor.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/StringXor.js new file mode 100644 index 0000000000000000000000000000000000000000..785af5f610b3af2816b5e3dc66d1c2b2da0cce2b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/StringXor.js @@ -0,0 +1,102 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../util/Hash")} Hash */ + +/** + * StringXor class provides methods for performing + * [XOR operations](https://en.wikipedia.org/wiki/Exclusive_or) on strings. In this context + * we operating on the character codes of two strings, which are represented as + * [Buffer](https://nodejs.org/api/buffer.html) objects. + * + * We use [StringXor in webpack](https://github.com/webpack/webpack/commit/41a8e2ea483a544c4ccd3e6217bdfb80daffca39) + * to create a hash of the current state of the compilation. By XOR'ing the Module hashes, it + * doesn't matter if the Module hashes are sorted or not. This is useful because it allows us to avoid sorting the + * Module hashes. + * @example + * ```js + * const xor = new StringXor(); + * xor.add('hello'); + * xor.add('world'); + * console.log(xor.toString()); + * ``` + * @example + * ```js + * const xor = new StringXor(); + * xor.add('foo'); + * xor.add('bar'); + * const hash = createHash('sha256'); + * hash.update(xor.toString()); + * console.log(hash.digest('hex')); + * ``` + */ +class StringXor { + constructor() { + /** @type {Buffer|undefined} */ + this._value = undefined; + } + + /** + * Adds a string to the current StringXor object. + * @param {string} str string + * @returns {void} + */ + add(str) { + const len = str.length; + const value = this._value; + if (value === undefined) { + /** + * We are choosing to use Buffer.allocUnsafe() because it is often faster than Buffer.alloc() because + * it allocates a new buffer of the specified size without initializing the memory. + */ + const newValue = (this._value = Buffer.allocUnsafe(len)); + for (let i = 0; i < len; i++) { + newValue[i] = str.charCodeAt(i); + } + return; + } + const valueLen = value.length; + if (valueLen < len) { + const newValue = (this._value = Buffer.allocUnsafe(len)); + let i; + for (i = 0; i < valueLen; i++) { + newValue[i] = value[i] ^ str.charCodeAt(i); + } + for (; i < len; i++) { + newValue[i] = str.charCodeAt(i); + } + } else { + for (let i = 0; i < len; i++) { + // eslint-disable-next-line operator-assignment + value[i] = value[i] ^ str.charCodeAt(i); + } + } + } + + /** + * Returns a string that represents the current state of the StringXor object. We chose to use "latin1" encoding + * here because "latin1" encoding is a single-byte encoding that can represent all characters in the + * [ISO-8859-1 character set](https://en.wikipedia.org/wiki/ISO/IEC_8859-1). This is useful when working + * with binary data that needs to be represented as a string. + * @returns {string} Returns a string that represents the current state of the StringXor object. + */ + toString() { + const value = this._value; + return value === undefined ? "" : value.toString("latin1"); + } + + /** + * Updates the hash with the current state of the StringXor object. + * @param {Hash} hash Hash instance + */ + updateHash(hash) { + const value = this._value; + if (value !== undefined) hash.update(value); + } +} + +module.exports = StringXor; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/TupleQueue.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/TupleQueue.js new file mode 100644 index 0000000000000000000000000000000000000000..e446582a37038c44c13fbb36b20c2172b0d24d10 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/TupleQueue.js @@ -0,0 +1,70 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const TupleSet = require("./TupleSet"); + +/** + * @template T + * @template V + */ +class TupleQueue { + /** + * @param {Iterable<[T, V, ...EXPECTED_ANY]>=} items The initial elements. + */ + constructor(items) { + /** + * @private + * @type {TupleSet} + */ + this._set = new TupleSet(items); + /** + * @private + * @type {Iterator<[T, V, ...EXPECTED_ANY]>} + */ + this._iterator = this._set[Symbol.iterator](); + } + + /** + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this._set.size; + } + + /** + * Appends the specified element to this queue. + * @param {[T, V, ...EXPECTED_ANY]} item The element to add. + * @returns {void} + */ + enqueue(...item) { + this._set.add(...item); + } + + /** + * Retrieves and removes the head of this queue. + * @returns {[T, V, ...EXPECTED_ANY] | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + const result = this._iterator.next(); + if (result.done) { + if (this._set.size > 0) { + this._iterator = this._set[Symbol.iterator](); + const value = + /** @type {[T, V, ...EXPECTED_ANY]} */ + (this._iterator.next().value); + this._set.delete(...value); + return value; + } + return; + } + this._set.delete(.../** @type {[T, V, ...EXPECTED_ANY]} */ (result.value)); + return result.value; + } +} + +module.exports = TupleQueue; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/TupleSet.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/TupleSet.js new file mode 100644 index 0000000000000000000000000000000000000000..1916ff4d914254ad04de9d3411fb130b12092f13 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/TupleSet.js @@ -0,0 +1,180 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @template K + * @template V + * @typedef {Map | Set>} InnerMap + */ + +/** + * @template T + * @template V + */ +class TupleSet { + /** + * @param {Iterable<[T, V, ...EXPECTED_ANY]>=} init init + */ + constructor(init) { + /** @type {InnerMap} */ + this._map = new Map(); + this.size = 0; + if (init) { + for (const tuple of init) { + this.add(...tuple); + } + } + } + + /** + * @param {[T, V, ...EXPECTED_ANY]} args tuple + * @returns {void} + */ + add(...args) { + let map = this._map; + for (let i = 0; i < args.length - 2; i++) { + const arg = args[i]; + const innerMap = map.get(arg); + if (innerMap === undefined) { + map.set(arg, (map = new Map())); + } else { + map = /** @type {InnerMap} */ (innerMap); + } + } + + const beforeLast = args[args.length - 2]; + let set = /** @type {Set} */ (map.get(beforeLast)); + if (set === undefined) { + map.set(beforeLast, (set = new Set())); + } + + const last = args[args.length - 1]; + this.size -= set.size; + set.add(last); + this.size += set.size; + } + + /** + * @param {[T, V, ...EXPECTED_ANY]} args tuple + * @returns {boolean} true, if the tuple is in the Set + */ + has(...args) { + let map = this._map; + for (let i = 0; i < args.length - 2; i++) { + const arg = args[i]; + map = /** @type {InnerMap} */ (map.get(arg)); + if (map === undefined) { + return false; + } + } + + const beforeLast = args[args.length - 2]; + const set = map.get(beforeLast); + if (set === undefined) { + return false; + } + + const last = args[args.length - 1]; + return set.has(last); + } + + /** + * @param {[T, V, ...EXPECTED_ANY]} args tuple + * @returns {void} + */ + delete(...args) { + let map = this._map; + for (let i = 0; i < args.length - 2; i++) { + const arg = args[i]; + map = /** @type {InnerMap} */ (map.get(arg)); + if (map === undefined) { + return; + } + } + + const beforeLast = args[args.length - 2]; + const set = map.get(beforeLast); + if (set === undefined) { + return; + } + + const last = args[args.length - 1]; + this.size -= set.size; + set.delete(last); + this.size += set.size; + } + + /** + * @returns {Iterator<[T, V, ...EXPECTED_ANY]>} iterator + */ + [Symbol.iterator]() { + // This is difficult to type because we can have a map inside a map inside a map, etc. where the end is a set (each key is an argument) + // But in basic use we only have 2 arguments in our methods, so we have `Map>` + /** @type {MapIterator<[T, InnerMap | Set]>[]} */ + const iteratorStack = []; + /** @type {[T?, V?, ...EXPECTED_ANY]} */ + const tuple = []; + /** @type {SetIterator | undefined} */ + let currentSetIterator; + + /** + * @param {MapIterator<[T, InnerMap | Set]>} it iterator + * @returns {boolean} result + */ + const next = (it) => { + const result = it.next(); + if (result.done) { + if (iteratorStack.length === 0) return false; + tuple.pop(); + return next( + /** @type {MapIterator<[T, InnerMap | Set]>} */ + (iteratorStack.pop()) + ); + } + const [key, value] = result.value; + iteratorStack.push(it); + tuple.push(key); + if (value instanceof Set) { + currentSetIterator = value[Symbol.iterator](); + return true; + } + return next(value[Symbol.iterator]()); + }; + + next(this._map[Symbol.iterator]()); + + return { + next() { + while (currentSetIterator) { + const result = currentSetIterator.next(); + if (result.done) { + tuple.pop(); + if ( + !next( + /** @type {MapIterator<[T, InnerMap | Set]>} */ + (iteratorStack.pop()) + ) + ) { + currentSetIterator = undefined; + } + } else { + return { + done: false, + value: + /* eslint-disable unicorn/prefer-spread */ + /** @type {[T, V, ...EXPECTED_ANY]} */ + (tuple.concat(result.value)) + }; + } + } + return { done: true, value: undefined }; + } + }; + } +} + +module.exports = TupleSet; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/URLAbsoluteSpecifier.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/URLAbsoluteSpecifier.js new file mode 100644 index 0000000000000000000000000000000000000000..1538249334824a0bdeb08e35c0fa6bbfd26eb2ea --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/URLAbsoluteSpecifier.js @@ -0,0 +1,87 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +/** @typedef {import("./fs").InputFileSystem} InputFileSystem */ +/** @typedef {(error: Error|null, result?: Buffer) => void} ErrorFirstCallback */ + +const backSlashCharCode = "\\".charCodeAt(0); +const slashCharCode = "/".charCodeAt(0); +const aLowerCaseCharCode = "a".charCodeAt(0); +const zLowerCaseCharCode = "z".charCodeAt(0); +const aUpperCaseCharCode = "A".charCodeAt(0); +const zUpperCaseCharCode = "Z".charCodeAt(0); +const _0CharCode = "0".charCodeAt(0); +const _9CharCode = "9".charCodeAt(0); +const plusCharCode = "+".charCodeAt(0); +const hyphenCharCode = "-".charCodeAt(0); +const colonCharCode = ":".charCodeAt(0); +const hashCharCode = "#".charCodeAt(0); +const queryCharCode = "?".charCodeAt(0); +/** + * Get scheme if specifier is an absolute URL specifier + * e.g. Absolute specifiers like 'file:///user/webpack/index.js' + * https://tools.ietf.org/html/rfc3986#section-3.1 + * @param {string} specifier specifier + * @returns {string|undefined} scheme if absolute URL specifier provided + */ +function getScheme(specifier) { + const start = specifier.charCodeAt(0); + + // First char maybe only a letter + if ( + (start < aLowerCaseCharCode || start > zLowerCaseCharCode) && + (start < aUpperCaseCharCode || start > zUpperCaseCharCode) + ) { + return; + } + + let i = 1; + let ch = specifier.charCodeAt(i); + + while ( + (ch >= aLowerCaseCharCode && ch <= zLowerCaseCharCode) || + (ch >= aUpperCaseCharCode && ch <= zUpperCaseCharCode) || + (ch >= _0CharCode && ch <= _9CharCode) || + ch === plusCharCode || + ch === hyphenCharCode + ) { + if (++i === specifier.length) return; + ch = specifier.charCodeAt(i); + } + + // Scheme must end with colon + if (ch !== colonCharCode) return; + + // Check for Windows absolute path + // https://url.spec.whatwg.org/#url-miscellaneous + if (i === 1) { + const nextChar = i + 1 < specifier.length ? specifier.charCodeAt(i + 1) : 0; + if ( + nextChar === 0 || + nextChar === backSlashCharCode || + nextChar === slashCharCode || + nextChar === hashCharCode || + nextChar === queryCharCode + ) { + return; + } + } + + return specifier.slice(0, i).toLowerCase(); +} + +/** + * @param {string} specifier specifier + * @returns {string | null | undefined} protocol if absolute URL specifier provided + */ +function getProtocol(specifier) { + const scheme = getScheme(specifier); + return scheme === undefined ? undefined : `${scheme}:`; +} + +module.exports.getProtocol = getProtocol; +module.exports.getScheme = getScheme; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/WeakTupleMap.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/WeakTupleMap.js new file mode 100644 index 0000000000000000000000000000000000000000..563a8dd7016f8b4e68e6fbf4a4fa6a25a26a22e9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/WeakTupleMap.js @@ -0,0 +1,227 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @template {EXPECTED_ANY[]} T + * @template V + * @typedef {Map>} M + */ + +/** + * @template {EXPECTED_ANY[]} T + * @template V + * @typedef {WeakMap>} W + */ + +/** + * @param {EXPECTED_ANY} thing thing + * @returns {boolean} true if is weak + */ +const isWeakKey = (thing) => typeof thing === "object" && thing !== null; + +/** + * @template {unknown[]} T + * @typedef {T extends readonly (infer ElementType)[] ? ElementType : never} ArrayElement + */ + +/** + * @template {EXPECTED_ANY[]} K + * @template V + */ +class WeakTupleMap { + constructor() { + /** @private */ + this.f = 0; + /** + * @private + * @type {V | undefined} + */ + this.v = undefined; + /** + * @private + * @type {M | undefined} + */ + this.m = undefined; + /** + * @private + * @type {W | undefined} + */ + this.w = undefined; + } + + /** + * @param {[...K, V]} args tuple + * @returns {void} + */ + set(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length - 1; i++) { + node = node._get(/** @type {ArrayElement} */ (args[i])); + } + node._setValue(/** @type {V} */ (args[args.length - 1])); + } + + /** + * @param {K} args tuple + * @returns {boolean} true, if the tuple is in the Set + */ + has(...args) { + /** @type {WeakTupleMap | undefined} */ + let node = this; + for (let i = 0; i < args.length; i++) { + node = node._peek(/** @type {ArrayElement} */ (args[i])); + if (node === undefined) return false; + } + return node._hasValue(); + } + + /** + * @param {K} args tuple + * @returns {V | undefined} the value + */ + get(...args) { + /** @type {WeakTupleMap | undefined} */ + let node = this; + for (let i = 0; i < args.length; i++) { + node = node._peek(/** @type {ArrayElement} */ (args[i])); + if (node === undefined) return; + } + return node._getValue(); + } + + /** + * @param {[...K, (...args: K) => V]} args tuple + * @returns {V} the value + */ + provide(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length - 1; i++) { + node = node._get(/** @type {ArrayElement} */ (args[i])); + } + if (node._hasValue()) return /** @type {V} */ (node._getValue()); + const fn = /** @type {(...args: K) => V} */ (args[args.length - 1]); + const newValue = fn(.../** @type {K} */ (args.slice(0, -1))); + node._setValue(newValue); + return newValue; + } + + /** + * @param {K} args tuple + * @returns {void} + */ + delete(...args) { + /** @type {WeakTupleMap | undefined} */ + let node = this; + for (let i = 0; i < args.length; i++) { + node = node._peek(/** @type {ArrayElement} */ (args[i])); + if (node === undefined) return; + } + node._deleteValue(); + } + + /** + * @returns {void} + */ + clear() { + this.f = 0; + this.v = undefined; + this.w = undefined; + this.m = undefined; + } + + _getValue() { + return this.v; + } + + _hasValue() { + return (this.f & 1) === 1; + } + + /** + * @param {V} v value + * @private + */ + _setValue(v) { + this.f |= 1; + this.v = v; + } + + _deleteValue() { + this.f &= 6; + this.v = undefined; + } + + /** + * @param {ArrayElement} thing thing + * @returns {WeakTupleMap | undefined} thing + * @private + */ + _peek(thing) { + if (isWeakKey(thing)) { + if ((this.f & 4) !== 4) return; + return /** @type {WeakMap, WeakTupleMap>} */ ( + this.w + ).get(thing); + } + if ((this.f & 2) !== 2) return; + return /** @type {Map, WeakTupleMap>} */ (this.m).get( + thing + ); + } + + /** + * @private + * @param {ArrayElement} thing thing + * @returns {WeakTupleMap} value + */ + _get(thing) { + if (isWeakKey(thing)) { + if ((this.f & 4) !== 4) { + /** @type {W} */ + const newMap = new WeakMap(); + this.f |= 4; + /** @type {WeakTupleMap} */ + const newNode = new WeakTupleMap(); + (this.w = newMap).set(thing, newNode); + return newNode; + } + const entry = /** @type {W} */ (this.w).get(thing); + if (entry !== undefined) { + return entry; + } + /** @type {WeakTupleMap} */ + const newNode = new WeakTupleMap(); + /** @type {W} */ + (this.w).set(thing, newNode); + return newNode; + } + if ((this.f & 2) !== 2) { + /** @type {M} */ + const newMap = new Map(); + this.f |= 2; + /** @type {WeakTupleMap} */ + const newNode = new WeakTupleMap(); + (this.m = newMap).set(thing, newNode); + return newNode; + } + const entry = + /** @type {M} */ + (this.m).get(thing); + if (entry !== undefined) { + return entry; + } + /** @type {WeakTupleMap} */ + const newNode = new WeakTupleMap(); + /** @type {M} */ + (this.m).set(thing, newNode); + return newNode; + } +} + +module.exports = WeakTupleMap; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/binarySearchBounds.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/binarySearchBounds.js new file mode 100644 index 0000000000000000000000000000000000000000..040e9bcfc291ad32fa5724839e7d42b0a00c9e11 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/binarySearchBounds.js @@ -0,0 +1,129 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Mikola Lysenko @mikolalysenko +*/ + +"use strict"; + +/* cspell:disable-next-line */ +// Refactor: Peter Somogyvari @petermetz + +/** @typedef {">=" | "<=" | "<" | ">" | "-" } BinarySearchPredicate */ +/** @typedef {"GE" | "GT" | "LT" | "LE" | "EQ" } SearchPredicateSuffix */ + +/** + * Helper function for compiling binary search functions. + * + * The generated code uses a while loop to repeatedly divide the search interval + * in half until the desired element is found, or the search interval is empty. + * + * The following is an example of a generated function for calling `compileSearch("P", "c(x,y)<=0", true, ["y", "c"], false)`: + * + * ```js + * function P(a,l,h,y,c){var i=l-1;while(l<=h){var m=(l+h)>>>1,x=a[m];if(c(x,y)<=0){i=m;l=m+1}else{h=m-1}}return i}; + * ``` + * @param {string} funcName The name of the function to be compiled. + * @param {string} predicate The predicate / comparison operator to be used in the binary search. + * @param {boolean} reversed Whether the search should be reversed. + * @param {string[]} extraArgs Extra arguments to be passed to the function. + * @param {boolean=} earlyOut Whether the search should return as soon as a match is found. + * @returns {string} The compiled binary search function. + */ +const compileSearch = (funcName, predicate, reversed, extraArgs, earlyOut) => { + const code = [ + "function ", + funcName, + "(a,l,h,", + extraArgs.join(","), + "){", + earlyOut ? "" : "var i=", + reversed ? "l-1" : "h+1", + ";while(l<=h){var m=(l+h)>>>1,x=a[m]" + ]; + + if (earlyOut) { + if (!predicate.includes("c")) { + code.push(";if(x===y){return m}else if(x<=y){"); + } else { + code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"); + } + } else { + code.push(";if(", predicate, "){i=m;"); + } + if (reversed) { + code.push("l=m+1}else{h=m-1}"); + } else { + code.push("h=m-1}else{l=m+1}"); + } + code.push("}"); + if (earlyOut) { + code.push("return -1};"); + } else { + code.push("return i};"); + } + return code.join(""); +}; + +/** + * This helper functions generate code for two binary search functions: + * A(): Performs a binary search on an array using the comparison operator specified. + * P(): Performs a binary search on an array using a _custom comparison function_ + * `c(x,y)` **and** comparison operator specified by `predicate`. + * @template T + * @param {BinarySearchPredicate} predicate The predicate / comparison operator to be used in the binary search. + * @param {boolean} reversed Whether the search should be reversed. + * @param {SearchPredicateSuffix} suffix The suffix to be used in the function name. + * @param {boolean=} earlyOut Whether the search should return as soon as a match is found. + * @returns {(items: T[], start: number, compareFn?: number | ((item: T, needle: number) => number), l?: number, h?: number) => number} The compiled binary search function. + */ +const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => { + const arg1 = compileSearch("A", `x${predicate}y`, reversed, ["y"], earlyOut); + + const arg2 = compileSearch( + "P", + `c(x,y)${predicate}0`, + reversed, + ["y", "c"], + earlyOut + ); + + const fnHeader = "function dispatchBinarySearch"; + + const fnBody = + // eslint-disable-next-line no-multi-str + "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBinarySearch"; + + const fnArgList = [arg1, arg2, fnHeader, suffix, fnBody, suffix]; + const fnSource = fnArgList.join(""); + // eslint-disable-next-line no-new-func + const result = new Function(fnSource); + return result(); +}; + +/** + * These functions are used to perform binary searches on arrays. + * @example + * ```js + * const { gt, le} = require("./binarySearchBounds"); + * const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + * + * // Find the index of the first element greater than 5 + * const index1 = gt(arr, 5); // index1 === 3 + * + * // Find the index of the first element less than or equal to 5 + * const index2 = le(arr, 5); // index2 === 4 + * ``` + */ +module.exports = { + ge: compileBoundsSearch(">=", false, "GE"), + gt: compileBoundsSearch(">", false, "GT"), + lt: compileBoundsSearch("<", true, "LT"), + le: compileBoundsSearch("<=", true, "LE"), + eq: compileBoundsSearch("-", true, "EQ", true) +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/chainedImports.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/chainedImports.js new file mode 100644 index 0000000000000000000000000000000000000000..295233b7d1cbf0de608ff919fd3360f9ad39ee01 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/chainedImports.js @@ -0,0 +1,97 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ + +/** + * @summary Get the subset of ids and their corresponding range in an id chain that should be re-rendered by webpack. + * Only those in the chain that are actually referring to namespaces or imports should be re-rendered. + * Deeper member accessors on the imported object should not be re-rendered. If deeper member accessors are re-rendered, + * there is a potential loss of meaning with rendering a quoted accessor as an unquoted accessor, or vice versa, + * because minifiers treat quoted accessors differently. e.g. import { a } from "./module"; a["b"] vs a.b + * @param {string[]} untrimmedIds chained ids + * @param {Range} untrimmedRange range encompassing allIds + * @param {Range[] | undefined} ranges cumulative range of ids for each of allIds + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {Dependency} dependency dependency + * @returns {{trimmedIds: string[], trimmedRange: Range}} computed trimmed ids and cumulative range of those ids + */ +module.exports.getTrimmedIdsAndRange = ( + untrimmedIds, + untrimmedRange, + ranges, + moduleGraph, + dependency +) => { + let trimmedIds = trimIdsToThoseImported( + untrimmedIds, + moduleGraph, + dependency + ); + let trimmedRange = untrimmedRange; + if (trimmedIds.length !== untrimmedIds.length) { + // The array returned from dep.idRanges is right-aligned with the array returned from dep.names. + // Meaning, the two arrays may not always have the same number of elements, but the last element of + // dep.idRanges corresponds to [the expression fragment to the left of] the last element of dep.names. + // Use this to find the correct replacement range based on the number of ids that were trimmed. + const idx = + ranges === undefined + ? -1 /* trigger failure case below */ + : ranges.length + (trimmedIds.length - untrimmedIds.length); + if (idx < 0 || idx >= /** @type {Range[]} */ (ranges).length) { + // cspell:ignore minifiers + // Should not happen but we can't throw an error here because of backward compatibility with + // external plugins in wp5. Instead, we just disable trimming for now. This may break some minifiers. + trimmedIds = untrimmedIds; + // TODO webpack 6 remove the "trimmedIds = ids" above and uncomment the following line instead. + // throw new Error("Missing range starts data for id replacement trimming."); + } else { + trimmedRange = /** @type {Range[]} */ (ranges)[idx]; + } + } + + return { trimmedIds, trimmedRange }; +}; + +/** + * @summary Determine which IDs in the id chain are actually referring to namespaces or imports, + * and which are deeper member accessors on the imported object. + * @param {string[]} ids untrimmed ids + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {Dependency} dependency dependency + * @returns {string[]} trimmed ids + */ +function trimIdsToThoseImported(ids, moduleGraph, dependency) { + /** @type {string[]} */ + let trimmedIds = []; + let currentExportsInfo = moduleGraph.getExportsInfo( + /** @type {Module} */ (moduleGraph.getModule(dependency)) + ); + for (let i = 0; i < ids.length; i++) { + if (i === 0 && ids[i] === "default") { + continue; // ExportInfo for the next level under default is still at the root ExportsInfo, so don't advance currentExportsInfo + } + const exportInfo = currentExportsInfo.getExportInfo(ids[i]); + if (exportInfo.provided === false) { + // json imports have nested ExportInfo for elements that things that are not actually exported, so check .provided + trimmedIds = ids.slice(0, i); + break; + } + const nestedInfo = exportInfo.getNestedExportsInfo(); + if (!nestedInfo) { + // once all nested exports are traversed, the next item is the actual import so stop there + trimmedIds = ids.slice(0, i + 1); + break; + } + currentExportsInfo = nestedInfo; + } + // Never trim to nothing. This can happen for invalid imports (e.g. import { notThere } from "./module", or import { anything } from "./missingModule") + return trimmedIds.length ? trimmedIds : ids; +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/cleverMerge.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/cleverMerge.js new file mode 100644 index 0000000000000000000000000000000000000000..7e3fbbb71ae132b8241046371c1689d930e662be --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/cleverMerge.js @@ -0,0 +1,674 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @type {WeakMap>} */ +const mergeCache = new WeakMap(); +/** @type {WeakMap>>} */ +const setPropertyCache = new WeakMap(); +const DELETE = Symbol("DELETE"); +const DYNAMIC_INFO = Symbol("cleverMerge dynamic info"); + +/** + * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. + * @template T + * @template O + * @example + * // performs cleverMerge(first, second), stores the result in WeakMap and returns result + * cachedCleverMerge({a: 1}, {a: 2}) + * {a: 2} + * // when same arguments passed, gets the result from WeakMap and returns it. + * cachedCleverMerge({a: 1}, {a: 2}) + * {a: 2} + * @param {T | null | undefined} first first object + * @param {O | null | undefined} second second object + * @returns {T & O | T | O} merged object of first and second object + */ +const cachedCleverMerge = (first, second) => { + if (second === undefined) return /** @type {T} */ (first); + if (first === undefined) return /** @type {O} */ (second); + if (typeof second !== "object" || second === null) { + return /** @type {O} */ (second); + } + if (typeof first !== "object" || first === null) { + return /** @type {T} */ (first); + } + + let innerCache = mergeCache.get(first); + if (innerCache === undefined) { + innerCache = new WeakMap(); + mergeCache.set(first, innerCache); + } + const prevMerge = /** @type {T & O} */ (innerCache.get(second)); + if (prevMerge !== undefined) return prevMerge; + const newMerge = _cleverMerge(first, second, true); + innerCache.set(second, newMerge); + return newMerge; +}; + +/** + * @template T + * @param {Partial} obj object + * @param {string} property property + * @param {string | number | boolean} value assignment value + * @returns {T} new object + */ +const cachedSetProperty = (obj, property, value) => { + let mapByProperty = setPropertyCache.get(obj); + + if (mapByProperty === undefined) { + mapByProperty = new Map(); + setPropertyCache.set(obj, mapByProperty); + } + + let mapByValue = mapByProperty.get(property); + + if (mapByValue === undefined) { + mapByValue = new Map(); + mapByProperty.set(property, mapByValue); + } + + let result = mapByValue.get(value); + + if (result) return /** @type {T} */ (result); + + result = { + ...obj, + [property]: value + }; + mapByValue.set(value, result); + + return /** @type {T} */ (result); +}; + +/** + * @typedef {Map} ByValues + */ + +/** + * @template T + * @typedef {object} ObjectParsedPropertyEntry + * @property {T[keyof T] | undefined} base base value + * @property {string | undefined} byProperty the name of the selector property + * @property {ByValues | undefined} byValues value depending on selector property, merged with base + */ + +/** @typedef {(function(...EXPECTED_ANY): object) & { [DYNAMIC_INFO]: [DynamicFunction, object] }} DynamicFunction */ + +/** + * @template {object} T + * @typedef {Map>} ParsedObjectStatic + */ + +/** + * @template {object} T + * @typedef {{ byProperty: string, fn: DynamicFunction }} ParsedObjectDynamic + */ + +/** + * @template {object} T + * @typedef {object} ParsedObject + * @property {ParsedObjectStatic} static static properties (key is property name) + * @property {ParsedObjectDynamic | undefined} dynamic dynamic part + */ + +/** @type {WeakMap>} */ +const parseCache = new WeakMap(); + +/** + * @template {object} T + * @param {T} obj the object + * @returns {ParsedObject} parsed object + */ +const cachedParseObject = (obj) => { + const entry = parseCache.get(/** @type {EXPECTED_OBJECT} */ (obj)); + if (entry !== undefined) return entry; + const result = parseObject(obj); + parseCache.set(/** @type {EXPECTED_OBJECT} */ (obj), result); + return result; +}; + +/** @typedef {{ [p: string]: { [p: string]: EXPECTED_ANY } } | DynamicFunction} ByObject */ + +/** + * @template {object} T + * @param {T} obj the object + * @returns {ParsedObject} parsed object + */ +const parseObject = (obj) => { + /** @type {ParsedObjectStatic} */ + const info = new Map(); + /** @type {ParsedObjectDynamic | undefined} */ + let dynamicInfo; + /** + * @param {keyof T} p path + * @returns {Partial>} object parsed property entry + */ + const getInfo = (p) => { + const entry = info.get(p); + if (entry !== undefined) return entry; + const newEntry = { + base: undefined, + byProperty: undefined, + byValues: undefined + }; + info.set(p, newEntry); + return newEntry; + }; + for (const key_ of Object.keys(obj)) { + const key = /** @type {keyof T} */ (key_); + if (typeof key === "string" && key.startsWith("by")) { + const byProperty = key; + const byObj = /** @type {ByObject} */ (obj[byProperty]); + if (typeof byObj === "object") { + for (const byValue of Object.keys(byObj)) { + const obj = byObj[/** @type {keyof (keyof T)} */ (byValue)]; + for (const key of Object.keys(obj)) { + const entry = getInfo(/** @type {keyof T} */ (key)); + if (entry.byProperty === undefined) { + entry.byProperty = byProperty; + entry.byValues = new Map(); + } else if (entry.byProperty !== byProperty) { + throw new Error( + `${/** @type {string} */ (byProperty)} and ${entry.byProperty} for a single property is not supported` + ); + } + /** @type {ByValues} */ + (entry.byValues).set(byValue, obj[key]); + if (byValue === "default") { + for (const otherByValue of Object.keys(byObj)) { + if ( + !( + /** @type {ByValues} */ + (entry.byValues).has(otherByValue) + ) + ) { + /** @type {ByValues} */ + (entry.byValues).set(otherByValue, undefined); + } + } + } + } + } + } else if (typeof byObj === "function") { + if (dynamicInfo === undefined) { + dynamicInfo = { + byProperty: key, + fn: byObj + }; + } else { + throw new Error( + `${key} and ${dynamicInfo.byProperty} when both are functions is not supported` + ); + } + } else { + const entry = getInfo(key); + entry.base = obj[key]; + } + } else { + const entry = getInfo(key); + entry.base = obj[key]; + } + } + return { + static: info, + dynamic: dynamicInfo + }; +}; + +/** + * @template {object} T + * @param {ParsedObjectStatic} info static properties (key is property name) + * @param {{ byProperty: string, fn: DynamicFunction } | undefined} dynamicInfo dynamic part + * @returns {T} the object + */ +const serializeObject = (info, dynamicInfo) => { + const obj = /** @type {T} */ ({}); + // Setup byProperty structure + for (const entry of info.values()) { + if (entry.byProperty !== undefined) { + const byProperty = /** @type {keyof T} */ (entry.byProperty); + const byObj = (obj[byProperty] = + obj[byProperty] || /** @type {TODO} */ ({})); + for (const byValue of /** @type {ByValues} */ (entry.byValues).keys()) { + byObj[byValue] = byObj[byValue] || {}; + } + } + } + for (const [key, entry] of info) { + if (entry.base !== undefined) { + obj[/** @type {keyof T} */ (key)] = entry.base; + } + // Fill byProperty structure + if (entry.byProperty !== undefined) { + const byProperty = /** @type {keyof T} */ (entry.byProperty); + const byObj = (obj[byProperty] = + obj[byProperty] || /** @type {TODO} */ ({})); + for (const byValue of Object.keys(byObj)) { + const value = getFromByValues( + /** @type {ByValues} */ + (entry.byValues), + byValue + ); + if (value !== undefined) byObj[byValue][key] = value; + } + } + } + if (dynamicInfo !== undefined) { + /** @type {TODO} */ + (obj)[dynamicInfo.byProperty] = dynamicInfo.fn; + } + return obj; +}; + +const VALUE_TYPE_UNDEFINED = 0; +const VALUE_TYPE_ATOM = 1; +const VALUE_TYPE_ARRAY_EXTEND = 2; +const VALUE_TYPE_OBJECT = 3; +const VALUE_TYPE_DELETE = 4; + +/** + * @template T + * @param {T} value a single value + * @returns {VALUE_TYPE_UNDEFINED | VALUE_TYPE_ATOM | VALUE_TYPE_ARRAY_EXTEND | VALUE_TYPE_OBJECT | VALUE_TYPE_DELETE} value type + */ +const getValueType = (value) => { + if (value === undefined) { + return VALUE_TYPE_UNDEFINED; + } else if (value === DELETE) { + return VALUE_TYPE_DELETE; + } else if (Array.isArray(value)) { + if (value.includes("...")) return VALUE_TYPE_ARRAY_EXTEND; + return VALUE_TYPE_ATOM; + } else if ( + typeof value === "object" && + value !== null && + (!value.constructor || value.constructor === Object) + ) { + return VALUE_TYPE_OBJECT; + } + return VALUE_TYPE_ATOM; +}; + +/** + * Merges two objects. Objects are deeply clever merged. + * Arrays might reference the old value with "...". + * Non-object values take preference over object values. + * @template T + * @template O + * @param {T} first first object + * @param {O} second second object + * @returns {T & O | T | O} merged object of first and second object + */ +const cleverMerge = (first, second) => { + if (second === undefined) return first; + if (first === undefined) return second; + if (typeof second !== "object" || second === null) return second; + if (typeof first !== "object" || first === null) return first; + + return /** @type {T & O} */ (_cleverMerge(first, second, false)); +}; + +/** + * @template {object} T + * @template {object} O + * Merges two objects. Objects are deeply clever merged. + * @param {T} first first + * @param {O} second second + * @param {boolean} internalCaching should parsing of objects and nested merges be cached + * @returns {T & O} merged object of first and second object + */ +const _cleverMerge = (first, second, internalCaching = false) => { + const firstObject = internalCaching + ? cachedParseObject(first) + : parseObject(first); + const { static: firstInfo, dynamic: firstDynamicInfo } = firstObject; + + // If the first argument has a dynamic part we modify the dynamic part to merge the second argument + if (firstDynamicInfo !== undefined) { + let { byProperty, fn } = firstDynamicInfo; + const fnInfo = fn[DYNAMIC_INFO]; + if (fnInfo) { + second = + /** @type {O} */ + ( + internalCaching + ? cachedCleverMerge(fnInfo[1], second) + : cleverMerge(fnInfo[1], second) + ); + fn = fnInfo[0]; + } + /** @type {DynamicFunction} */ + const newFn = (...args) => { + const fnResult = fn(...args); + return internalCaching + ? cachedCleverMerge(fnResult, second) + : cleverMerge(fnResult, second); + }; + newFn[DYNAMIC_INFO] = [fn, second]; + return /** @type {T & O} */ ( + serializeObject(firstObject.static, { byProperty, fn: newFn }) + ); + } + + // If the first part is static only, we merge the static parts and keep the dynamic part of the second argument + const secondObject = internalCaching + ? cachedParseObject(second) + : parseObject(second); + const { static: secondInfo, dynamic: secondDynamicInfo } = secondObject; + const resultInfo = new Map(); + for (const [key, firstEntry] of firstInfo) { + const secondEntry = secondInfo.get( + /** @type {keyof (T | O)} */ + (key) + ); + const entry = + secondEntry !== undefined + ? mergeEntries(firstEntry, secondEntry, internalCaching) + : firstEntry; + resultInfo.set(key, entry); + } + for (const [key, secondEntry] of secondInfo) { + if (!firstInfo.has(/** @type {keyof (T | O)} */ (key))) { + resultInfo.set(key, secondEntry); + } + } + return /** @type {T & O} */ (serializeObject(resultInfo, secondDynamicInfo)); +}; + +/** + * @template T, O + * @param {ObjectParsedPropertyEntry} firstEntry a + * @param {ObjectParsedPropertyEntry} secondEntry b + * @param {boolean} internalCaching should parsing of objects and nested merges be cached + * @returns {ObjectParsedPropertyEntry} new entry + */ +const mergeEntries = (firstEntry, secondEntry, internalCaching) => { + switch (getValueType(secondEntry.base)) { + case VALUE_TYPE_ATOM: + case VALUE_TYPE_DELETE: + // No need to consider firstEntry at all + // second value override everything + // = second.base + second.byProperty + return secondEntry; + case VALUE_TYPE_UNDEFINED: + if (!firstEntry.byProperty) { + // = first.base + second.byProperty + return { + base: firstEntry.base, + byProperty: secondEntry.byProperty, + byValues: secondEntry.byValues + }; + } else if (firstEntry.byProperty !== secondEntry.byProperty) { + throw new Error( + `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` + ); + } else { + // = first.base + (first.byProperty + second.byProperty) + // need to merge first and second byValues + const newByValues = new Map(firstEntry.byValues); + for (const [key, value] of /** @type {ByValues} */ ( + secondEntry.byValues + )) { + const firstValue = getFromByValues( + /** @type {ByValues} */ + (firstEntry.byValues), + key + ); + newByValues.set( + key, + mergeSingleValue(firstValue, value, internalCaching) + ); + } + return { + base: firstEntry.base, + byProperty: firstEntry.byProperty, + byValues: newByValues + }; + } + default: { + if (!firstEntry.byProperty) { + // The simple case + // = (first.base + second.base) + second.byProperty + return { + base: + /** @type {T[keyof T] & O[keyof O]} */ + ( + mergeSingleValue( + firstEntry.base, + secondEntry.base, + internalCaching + ) + ), + byProperty: secondEntry.byProperty, + byValues: secondEntry.byValues + }; + } + let newBase; + const intermediateByValues = new Map(firstEntry.byValues); + for (const [key, value] of intermediateByValues) { + intermediateByValues.set( + key, + mergeSingleValue(value, secondEntry.base, internalCaching) + ); + } + if ( + [.../** @type {ByValues} */ (firstEntry.byValues).values()].every( + (value) => { + const type = getValueType(value); + return type === VALUE_TYPE_ATOM || type === VALUE_TYPE_DELETE; + } + ) + ) { + // = (first.base + second.base) + ((first.byProperty + second.base) + second.byProperty) + newBase = mergeSingleValue( + firstEntry.base, + secondEntry.base, + internalCaching + ); + } else { + // = first.base + ((first.byProperty (+default) + second.base) + second.byProperty) + newBase = firstEntry.base; + if (!intermediateByValues.has("default")) { + intermediateByValues.set("default", secondEntry.base); + } + } + if (!secondEntry.byProperty) { + // = first.base + (first.byProperty + second.base) + return { + base: newBase, + byProperty: firstEntry.byProperty, + byValues: intermediateByValues + }; + } else if (firstEntry.byProperty !== secondEntry.byProperty) { + throw new Error( + `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` + ); + } + const newByValues = new Map(intermediateByValues); + for (const [key, value] of /** @type {ByValues} */ ( + secondEntry.byValues + )) { + const firstValue = getFromByValues(intermediateByValues, key); + newByValues.set( + key, + mergeSingleValue(firstValue, value, internalCaching) + ); + } + return { + base: newBase, + byProperty: firstEntry.byProperty, + byValues: newByValues + }; + } + } +}; + +/** + * @template V + * @param {ByValues} byValues all values + * @param {string} key value of the selector + * @returns {V | undefined} value + */ +const getFromByValues = (byValues, key) => { + if (key !== "default" && byValues.has(key)) { + return byValues.get(key); + } + return byValues.get("default"); +}; + +/** + * @template A + * @template B + * @param {A | A[]} a value + * @param {B | B[]} b value + * @param {boolean} internalCaching should parsing of objects and nested merges be cached + * @returns {A & B | (A | B)[] | A | A[] | B | B[]} value + */ +const mergeSingleValue = (a, b, internalCaching) => { + const bType = getValueType(b); + const aType = getValueType(a); + switch (bType) { + case VALUE_TYPE_DELETE: + case VALUE_TYPE_ATOM: + return b; + case VALUE_TYPE_OBJECT: { + return aType !== VALUE_TYPE_OBJECT + ? b + : internalCaching + ? cachedCleverMerge(a, b) + : cleverMerge(a, b); + } + case VALUE_TYPE_UNDEFINED: + return a; + case VALUE_TYPE_ARRAY_EXTEND: + switch ( + aType !== VALUE_TYPE_ATOM + ? aType + : Array.isArray(a) + ? VALUE_TYPE_ARRAY_EXTEND + : VALUE_TYPE_OBJECT + ) { + case VALUE_TYPE_UNDEFINED: + return b; + case VALUE_TYPE_DELETE: + return /** @type {B[]} */ (b).filter((item) => item !== "..."); + case VALUE_TYPE_ARRAY_EXTEND: { + /** @type {(A | B)[]} */ + const newArray = []; + for (const item of /** @type {B[]} */ (b)) { + if (item === "...") { + for (const item of /** @type {A[]} */ (a)) { + newArray.push(item); + } + } else { + newArray.push(item); + } + } + return newArray; + } + case VALUE_TYPE_OBJECT: + return /** @type {(A | B)[]} */ (b).map((item) => + item === "..." ? /** @type {A} */ (a) : item + ); + default: + throw new Error("Not implemented"); + } + default: + throw new Error("Not implemented"); + } +}; + +/** + * @template {object} T + * @param {T} obj the object + * @param {(keyof T)[]=} keysToKeepOriginalValue keys to keep original value + * @returns {T} the object without operations like "..." or DELETE + */ +const removeOperations = (obj, keysToKeepOriginalValue = []) => { + const newObj = /** @type {T} */ ({}); + for (const _key of Object.keys(obj)) { + const key = /** @type {keyof T} */ (_key); + const value = obj[key]; + const type = getValueType(value); + if (type === VALUE_TYPE_OBJECT && keysToKeepOriginalValue.includes(key)) { + newObj[key] = value; + continue; + } + switch (type) { + case VALUE_TYPE_UNDEFINED: + case VALUE_TYPE_DELETE: + break; + case VALUE_TYPE_OBJECT: + newObj[key] = + /** @type {T[keyof T]} */ + ( + removeOperations( + /** @type {T} */ + (value), + keysToKeepOriginalValue + ) + ); + break; + case VALUE_TYPE_ARRAY_EXTEND: + newObj[key] = + /** @type {T[keyof T]} */ + ( + /** @type {EXPECTED_ANY[]} */ + (value).filter((i) => i !== "...") + ); + break; + default: + newObj[key] = value; + break; + } + } + return newObj; +}; + +/** + * @template T + * @template {keyof T} P + * @template V + * @param {T} obj the object + * @param {P} byProperty the by description + * @param {...V} values values + * @returns {Omit} object with merged byProperty + */ +const resolveByProperty = (obj, byProperty, ...values) => { + if (typeof obj !== "object" || obj === null || !(byProperty in obj)) { + return obj; + } + const { [byProperty]: _byValue, ..._remaining } = obj; + const remaining = /** @type {T} */ (_remaining); + const byValue = + /** @type {Record | ((...args: V[]) => T)} */ + (_byValue); + if (typeof byValue === "object") { + const key = /** @type {string} */ (values[0]); + if (key in byValue) { + return cachedCleverMerge(remaining, byValue[key]); + } else if ("default" in byValue) { + return cachedCleverMerge(remaining, byValue.default); + } + return remaining; + } else if (typeof byValue === "function") { + // eslint-disable-next-line prefer-spread + const result = byValue.apply(null, values); + return cachedCleverMerge( + remaining, + resolveByProperty(result, byProperty, ...values) + ); + } + return obj; +}; + +module.exports.DELETE = DELETE; +module.exports.cachedCleverMerge = cachedCleverMerge; +module.exports.cachedSetProperty = cachedSetProperty; +module.exports.cleverMerge = cleverMerge; +module.exports.removeOperations = removeOperations; +module.exports.resolveByProperty = resolveByProperty; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/comparators.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/comparators.js new file mode 100644 index 0000000000000000000000000000000000000000..5e8004c83dd794ecfa1edac8802c5d36ae1f8280 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/comparators.js @@ -0,0 +1,649 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { compareRuntime } = require("./runtime"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Chunk").ChunkId} ChunkId */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../dependencies/HarmonyImportSideEffectDependency")} HarmonyImportSideEffectDependency */ +/** @typedef {import("../dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ + +/** + * @typedef {object} DependencySourceOrder + * @property {number} main the main source order + * @property {number} sub the sub source order + */ + +/** + * @template T + * @typedef {(a: T, b: T) => -1 | 0 | 1} Comparator + */ +/** + * @template {object} TArg + * @template T + * @typedef {(tArg: TArg, a: T, b: T) => -1 | 0 | 1} RawParameterizedComparator + */ +/** + * @template {object} TArg + * @template T + * @typedef {(tArg: TArg) => Comparator} ParameterizedComparator + */ + +/** + * @template {object} TArg + * @template {object} T + * @param {RawParameterizedComparator} fn comparator with argument + * @returns {ParameterizedComparator} comparator + */ +const createCachedParameterizedComparator = (fn) => { + /** @type {WeakMap>} */ + const map = new WeakMap(); + return (arg) => { + const cachedResult = map.get(/** @type {EXPECTED_OBJECT} */ (arg)); + if (cachedResult !== undefined) return cachedResult; + /** + * @param {T} a first item + * @param {T} b second item + * @returns {-1|0|1} compare result + */ + const result = fn.bind(null, arg); + map.set(/** @type {EXPECTED_OBJECT} */ (arg), result); + return result; + }; +}; + +/** + * @param {string | number} a first id + * @param {string | number} b second id + * @returns {-1 | 0 | 1} compare result + */ +const compareIds = (a, b) => { + if (typeof a !== typeof b) { + return typeof a < typeof b ? -1 : 1; + } + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; + +/** + * @template T + * @param {Comparator} elementComparator comparator for elements + * @returns {Comparator>} comparator for iterables of elements + */ +const compareIterables = (elementComparator) => { + const cacheEntry = compareIteratorsCache.get(elementComparator); + if (cacheEntry !== undefined) return cacheEntry; + /** + * @param {Iterable} a first value + * @param {Iterable} b second value + * @returns {-1|0|1} compare result + */ + const result = (a, b) => { + const aI = a[Symbol.iterator](); + const bI = b[Symbol.iterator](); + while (true) { + const aItem = aI.next(); + const bItem = bI.next(); + if (aItem.done) { + return bItem.done ? 0 : -1; + } else if (bItem.done) { + return 1; + } + const res = elementComparator(aItem.value, bItem.value); + if (res !== 0) return res; + } + }; + compareIteratorsCache.set(elementComparator, result); + return result; +}; + +/** + * Compare two locations + * @param {DependencyLocation} a A location node + * @param {DependencyLocation} b A location node + * @returns {-1|0|1} sorting comparator value + */ +const compareLocations = (a, b) => { + const isObjectA = typeof a === "object" && a !== null; + const isObjectB = typeof b === "object" && b !== null; + if (!isObjectA || !isObjectB) { + if (isObjectA) return 1; + if (isObjectB) return -1; + return 0; + } + if ("start" in a) { + if ("start" in b) { + const ap = a.start; + const bp = b.start; + if (ap.line < bp.line) return -1; + if (ap.line > bp.line) return 1; + if ( + /** @type {number} */ (ap.column) < /** @type {number} */ (bp.column) + ) { + return -1; + } + if ( + /** @type {number} */ (ap.column) > /** @type {number} */ (bp.column) + ) { + return 1; + } + } else { + return -1; + } + } else if ("start" in b) { + return 1; + } + if ("name" in a) { + if ("name" in b) { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + } else { + return -1; + } + } else if ("name" in b) { + return 1; + } + if ("index" in a) { + if ("index" in b) { + if (/** @type {number} */ (a.index) < /** @type {number} */ (b.index)) { + return -1; + } + if (/** @type {number} */ (a.index) > /** @type {number} */ (b.index)) { + return 1; + } + } else { + return -1; + } + } else if ("index" in b) { + return 1; + } + return 0; +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesById = (chunkGraph, a, b) => + compareIds( + /** @type {ModuleId} */ (chunkGraph.getModuleId(a)), + /** @type {ModuleId} */ (chunkGraph.getModuleId(b)) + ); + +/** + * @param {number} a number + * @param {number} b number + * @returns {-1|0|1} compare result + */ +const compareNumbers = (a, b) => { + if (typeof a !== typeof b) { + return typeof a < typeof b ? -1 : 1; + } + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; + +/** + * @param {string} a string + * @param {string} b string + * @returns {-1|0|1} compare result + */ +const compareStringsNumeric = (a, b) => { + const aLength = a.length; + const bLength = b.length; + + let aChar = 0; + let bChar = 0; + + let aIsDigit = false; + let bIsDigit = false; + let i = 0; + let j = 0; + while (i < aLength && j < bLength) { + aChar = a.charCodeAt(i); + bChar = b.charCodeAt(j); + + aIsDigit = aChar >= 48 && aChar <= 57; + bIsDigit = bChar >= 48 && bChar <= 57; + + if (!aIsDigit && !bIsDigit) { + if (aChar < bChar) return -1; + if (aChar > bChar) return 1; + i++; + j++; + } else if (aIsDigit && !bIsDigit) { + // This segment of a is shorter than in b + return 1; + } else if (!aIsDigit && bIsDigit) { + // This segment of b is shorter than in a + return -1; + } else { + let aNumber = aChar - 48; + let bNumber = bChar - 48; + + while (++i < aLength) { + aChar = a.charCodeAt(i); + if (aChar < 48 || aChar > 57) break; + aNumber = aNumber * 10 + aChar - 48; + } + + while (++j < bLength) { + bChar = b.charCodeAt(j); + if (bChar < 48 || bChar > 57) break; + bNumber = bNumber * 10 + bChar - 48; + } + + if (aNumber < bNumber) return -1; + if (aNumber > bNumber) return 1; + } + } + + if (j < bLength) { + // a is shorter than b + bChar = b.charCodeAt(j); + bIsDigit = bChar >= 48 && bChar <= 57; + return bIsDigit ? -1 : 1; + } + if (i < aLength) { + // b is shorter than a + aChar = a.charCodeAt(i); + aIsDigit = aChar >= 48 && aChar <= 57; + return aIsDigit ? 1 : -1; + } + + return 0; +}; + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesByPostOrderIndexOrIdentifier = (moduleGraph, a, b) => { + const cmp = compareNumbers( + /** @type {number} */ (moduleGraph.getPostOrderIndex(a)), + /** @type {number} */ (moduleGraph.getPostOrderIndex(b)) + ); + if (cmp !== 0) return cmp; + return compareIds(a.identifier(), b.identifier()); +}; + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesByPreOrderIndexOrIdentifier = (moduleGraph, a, b) => { + const cmp = compareNumbers( + /** @type {number} */ (moduleGraph.getPreOrderIndex(a)), + /** @type {number} */ (moduleGraph.getPreOrderIndex(b)) + ); + if (cmp !== 0) return cmp; + return compareIds(a.identifier(), b.identifier()); +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesByIdOrIdentifier = (chunkGraph, a, b) => { + const cmp = compareIds( + /** @type {ModuleId} */ (chunkGraph.getModuleId(a)), + /** @type {ModuleId} */ (chunkGraph.getModuleId(b)) + ); + if (cmp !== 0) return cmp; + return compareIds(a.identifier(), b.identifier()); +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {-1 | 0 | 1} compare result + */ +const compareChunks = (chunkGraph, a, b) => chunkGraph.compareChunks(a, b); + +/** + * @param {string} a first string + * @param {string} b second string + * @returns {-1|0|1} compare result + */ +const compareStrings = (a, b) => { + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; + +/** + * @param {ChunkGroup} a first chunk group + * @param {ChunkGroup} b second chunk group + * @returns {-1 | 0 | 1} compare result + */ +const compareChunkGroupsByIndex = (a, b) => + /** @type {number} */ (a.index) < /** @type {number} */ (b.index) ? -1 : 1; + +/** + * @template {EXPECTED_OBJECT} K1 + * @template {EXPECTED_OBJECT} K2 + * @template T + */ +class TwoKeyWeakMap { + constructor() { + /** + * @private + * @type {WeakMap>} + */ + this._map = new WeakMap(); + } + + /** + * @param {K1} key1 first key + * @param {K2} key2 second key + * @returns {T | undefined} value + */ + get(key1, key2) { + const childMap = this._map.get(key1); + if (childMap === undefined) { + return; + } + return childMap.get(key2); + } + + /** + * @param {K1} key1 first key + * @param {K2} key2 second key + * @param {T | undefined} value new value + * @returns {void} + */ + set(key1, key2, value) { + let childMap = this._map.get(key1); + if (childMap === undefined) { + childMap = new WeakMap(); + this._map.set(key1, childMap); + } + childMap.set(key2, value); + } +} + +/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ +const concatComparatorsCache = new TwoKeyWeakMap(); + +/** + * @template T + * @param {Comparator} c1 comparator + * @param {Comparator} c2 comparator + * @param {Comparator[]} cRest comparators + * @returns {Comparator} comparator + */ +const concatComparators = (c1, c2, ...cRest) => { + if (cRest.length > 0) { + const [c3, ...cRest2] = cRest; + return concatComparators(c1, concatComparators(c2, c3, ...cRest2)); + } + const cacheEntry = /** @type {Comparator} */ ( + concatComparatorsCache.get(c1, c2) + ); + if (cacheEntry !== undefined) return cacheEntry; + /** + * @param {T} a first value + * @param {T} b second value + * @returns {-1|0|1} compare result + */ + const result = (a, b) => { + const res = c1(a, b); + if (res !== 0) return res; + return c2(a, b); + }; + concatComparatorsCache.set(c1, c2, result); + return result; +}; + +/** + * @template A, B + * @typedef {(input: A) => B | undefined | null} Selector + */ + +/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ +const compareSelectCache = new TwoKeyWeakMap(); + +/** + * @template T + * @template R + * @param {Selector} getter getter for value + * @param {Comparator} comparator comparator + * @returns {Comparator} comparator + */ +const compareSelect = (getter, comparator) => { + const cacheEntry = compareSelectCache.get(getter, comparator); + if (cacheEntry !== undefined) return cacheEntry; + /** + * @param {T} a first value + * @param {T} b second value + * @returns {-1|0|1} compare result + */ + const result = (a, b) => { + const aValue = getter(a); + const bValue = getter(b); + if (aValue !== undefined && aValue !== null) { + if (bValue !== undefined && bValue !== null) { + return comparator(aValue, bValue); + } + return -1; + } + if (bValue !== undefined && bValue !== null) { + return 1; + } + return 0; + }; + compareSelectCache.set(getter, comparator, result); + return result; +}; + +/** @type {WeakMap, Comparator>>} */ +const compareIteratorsCache = new WeakMap(); + +// TODO this is no longer needed when minimum node.js version is >= 12 +// since these versions ship with a stable sort function +/** + * @template T + * @param {Iterable} iterable original ordered list + * @returns {Comparator} comparator + */ +const keepOriginalOrder = (iterable) => { + /** @type {Map} */ + const map = new Map(); + let i = 0; + for (const item of iterable) { + map.set(item, i++); + } + return (a, b) => + compareNumbers( + /** @type {number} */ (map.get(a)), + /** @type {number} */ (map.get(b)) + ); +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {Comparator} comparator + */ +const compareChunksNatural = (chunkGraph) => { + const cmpFn = module.exports.compareModulesById(chunkGraph); + const cmpIterableFn = compareIterables(cmpFn); + return concatComparators( + compareSelect( + (chunk) => /** @type {string|number} */ (chunk.name), + compareIds + ), + compareSelect((chunk) => chunk.runtime, compareRuntime), + compareSelect( + /** + * @param {Chunk} chunk a chunk + * @returns {Iterable} modules + */ + (chunk) => chunkGraph.getOrderedChunkModulesIterable(chunk, cmpFn), + cmpIterableFn + ) + ); +}; + +/** + * For HarmonyImportSideEffectDependency and HarmonyImportSpecifierDependency, we should prioritize import order to match the behavior of running modules directly in a JS engine without a bundler. + * For other types like ConstDependency, we can instead prioritize usage order. + * https://github.com/webpack/webpack/pull/19686 + * @param {Dependency[]} dependencies dependencies + * @param {WeakMap} dependencySourceOrderMap dependency source order map + * @returns {void} + */ +const sortWithSourceOrder = (dependencies, dependencySourceOrderMap) => { + /** + * @param {Dependency} dep dependency + * @returns {number} source order + */ + const getSourceOrder = (dep) => { + if (dependencySourceOrderMap.has(dep)) { + const { main } = /** @type {DependencySourceOrder} */ ( + dependencySourceOrderMap.get(dep) + ); + return main; + } + return /** @type { HarmonyImportSideEffectDependency | HarmonyImportSpecifierDependency} */ ( + dep + ).sourceOrder; + }; + + /** + * If the sourceOrder is a number, it means the dependency needs to be sorted. + * @param {number | undefined} sourceOrder sourceOrder + * @returns {boolean} needReSort + */ + const needReSort = (sourceOrder) => { + if (typeof sourceOrder === "number") { + return true; + } + return false; + }; + + // Extract dependencies with sourceOrder and sort them + const withSourceOrder = []; + + // First pass: collect dependencies with sourceOrder + for (let i = 0; i < dependencies.length; i++) { + const dep = dependencies[i]; + const sourceOrder = getSourceOrder(dep); + + if (needReSort(sourceOrder)) { + withSourceOrder.push({ dep, sourceOrder, originalIndex: i }); + } + } + + if (withSourceOrder.length <= 1) { + return; + } + + // Sort dependencies with sourceOrder + withSourceOrder.sort((a, b) => { + // Handle both dependencies in map case + if ( + dependencySourceOrderMap.has(a.dep) && + dependencySourceOrderMap.has(b.dep) + ) { + const { main: mainA, sub: subA } = /** @type {DependencySourceOrder} */ ( + dependencySourceOrderMap.get(a.dep) + ); + const { main: mainB, sub: subB } = /** @type {DependencySourceOrder} */ ( + dependencySourceOrderMap.get(b.dep) + ); + if (mainA === mainB) { + return compareNumbers(subA, subB); + } + return compareNumbers(mainA, mainB); + } + + return compareNumbers(a.sourceOrder, b.sourceOrder); + }); + + // Second pass: build result array + let sortedIndex = 0; + for (let i = 0; i < dependencies.length; i++) { + const dep = dependencies[i]; + const sourceOrder = getSourceOrder(dep); + + if (needReSort(sourceOrder)) { + dependencies[i] = withSourceOrder[sortedIndex].dep; + sortedIndex++; + } + } +}; + +module.exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex; +/** @type {ParameterizedComparator} */ +module.exports.compareChunks = + createCachedParameterizedComparator(compareChunks); +/** + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {-1|0|1} compare result + */ +module.exports.compareChunksById = (a, b) => + compareIds(/** @type {ChunkId} */ (a.id), /** @type {ChunkId} */ (b.id)); +module.exports.compareChunksNatural = compareChunksNatural; + +module.exports.compareIds = compareIds; + +module.exports.compareIterables = compareIterables; + +module.exports.compareLocations = compareLocations; + +/** @type {ParameterizedComparator} */ +module.exports.compareModulesById = + createCachedParameterizedComparator(compareModulesById); +/** @type {ParameterizedComparator} */ +module.exports.compareModulesByIdOrIdentifier = + createCachedParameterizedComparator(compareModulesByIdOrIdentifier); +/** + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +module.exports.compareModulesByIdentifier = (a, b) => + compareIds(a.identifier(), b.identifier()); +/** @type {ParameterizedComparator} */ +module.exports.compareModulesByPostOrderIndexOrIdentifier = + createCachedParameterizedComparator( + compareModulesByPostOrderIndexOrIdentifier + ); +/** @type {ParameterizedComparator} */ +module.exports.compareModulesByPreOrderIndexOrIdentifier = + createCachedParameterizedComparator( + compareModulesByPreOrderIndexOrIdentifier + ); + +module.exports.compareNumbers = compareNumbers; +module.exports.compareSelect = compareSelect; +module.exports.compareStrings = compareStrings; +module.exports.compareStringsNumeric = compareStringsNumeric; + +module.exports.concatComparators = concatComparators; + +module.exports.keepOriginalOrder = keepOriginalOrder; +module.exports.sortWithSourceOrder = sortWithSourceOrder; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/compileBooleanMatcher.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/compileBooleanMatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..551675d764da4848eb12d639083ef806570d9c4e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/compileBooleanMatcher.js @@ -0,0 +1,239 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @param {string} str string + * @returns {string} quoted meta + */ +const quoteMeta = (str) => str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); + +/** + * @param {string} str string + * @returns {string} string + */ +const toSimpleString = (str) => { + if (`${Number(str)}` === str) { + return str; + } + return JSON.stringify(str); +}; + +/** + * @param {Record} map value map + * @returns {boolean | ((value: string) => string)} true/false, when unconditionally true/false, or a template function to determine the value at runtime + */ +const compileBooleanMatcher = (map) => { + const positiveItems = Object.keys(map).filter((i) => map[i]); + const negativeItems = Object.keys(map).filter((i) => !map[i]); + if (positiveItems.length === 0) return false; + if (negativeItems.length === 0) return true; + return compileBooleanMatcherFromLists(positiveItems, negativeItems); +}; + +/** + * @param {string[]} positiveItems positive items + * @param {string[]} negativeItems negative items + * @returns {(value: string) => string} a template function to determine the value at runtime + */ +const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => { + if (positiveItems.length === 0) return () => "false"; + if (negativeItems.length === 0) return () => "true"; + if (positiveItems.length === 1) { + return (value) => `${toSimpleString(positiveItems[0])} == ${value}`; + } + if (negativeItems.length === 1) { + return (value) => `${toSimpleString(negativeItems[0])} != ${value}`; + } + const positiveRegexp = itemsToRegexp(positiveItems); + const negativeRegexp = itemsToRegexp(negativeItems); + if (positiveRegexp.length <= negativeRegexp.length) { + return (value) => `/^${positiveRegexp}$/.test(${value})`; + } + return (value) => `!/^${negativeRegexp}$/.test(${value})`; +}; + +/** + * @param {Set} itemsSet items set + * @param {(str: string) => string | false} getKey get key function + * @param {(str: Array) => boolean} condition condition + * @returns {Array>} list of common items + */ +const popCommonItems = (itemsSet, getKey, condition) => { + /** @type {Map>} */ + const map = new Map(); + for (const item of itemsSet) { + const key = getKey(item); + if (key) { + let list = map.get(key); + if (list === undefined) { + /** @type {Array} */ + list = []; + map.set(key, list); + } + list.push(item); + } + } + /** @type {Array>} */ + const result = []; + for (const list of map.values()) { + if (condition(list)) { + for (const item of list) { + itemsSet.delete(item); + } + result.push(list); + } + } + return result; +}; + +/** + * @param {Array} items items + * @returns {string} common prefix + */ +const getCommonPrefix = (items) => { + let prefix = items[0]; + for (let i = 1; i < items.length; i++) { + const item = items[i]; + for (let p = 0; p < prefix.length; p++) { + if (item[p] !== prefix[p]) { + prefix = prefix.slice(0, p); + break; + } + } + } + return prefix; +}; + +/** + * @param {Array} items items + * @returns {string} common suffix + */ +const getCommonSuffix = (items) => { + let suffix = items[0]; + for (let i = 1; i < items.length; i++) { + const item = items[i]; + for (let p = item.length - 1, s = suffix.length - 1; s >= 0; p--, s--) { + if (item[p] !== suffix[s]) { + suffix = suffix.slice(s + 1); + break; + } + } + } + return suffix; +}; + +/** + * @param {Array} itemsArr array of items + * @returns {string} regexp + */ +const itemsToRegexp = (itemsArr) => { + if (itemsArr.length === 1) { + return quoteMeta(itemsArr[0]); + } + /** @type {Array} */ + const finishedItems = []; + + // merge single char items: (a|b|c|d|ef) => ([abcd]|ef) + let countOfSingleCharItems = 0; + for (const item of itemsArr) { + if (item.length === 1) { + countOfSingleCharItems++; + } + } + // special case for only single char items + if (countOfSingleCharItems === itemsArr.length) { + return `[${quoteMeta(itemsArr.sort().join(""))}]`; + } + /** @type {Set} */ + const items = new Set(itemsArr.sort()); + if (countOfSingleCharItems > 2) { + let singleCharItems = ""; + for (const item of items) { + if (item.length === 1) { + singleCharItems += item; + items.delete(item); + } + } + finishedItems.push(`[${quoteMeta(singleCharItems)}]`); + } + + // special case for 2 items with common prefix/suffix + if (finishedItems.length === 0 && items.size === 2) { + const prefix = getCommonPrefix(itemsArr); + const suffix = getCommonSuffix( + itemsArr.map((item) => item.slice(prefix.length)) + ); + if (prefix.length > 0 || suffix.length > 0) { + return `${quoteMeta(prefix)}${itemsToRegexp( + itemsArr.map((i) => i.slice(prefix.length, -suffix.length || undefined)) + )}${quoteMeta(suffix)}`; + } + } + + // special case for 2 items with common suffix + if (finishedItems.length === 0 && items.size === 2) { + /** @type {Iterator} */ + const it = items[Symbol.iterator](); + const a = it.next().value; + const b = it.next().value; + if (a.length > 0 && b.length > 0 && a.slice(-1) === b.slice(-1)) { + return `${itemsToRegexp([a.slice(0, -1), b.slice(0, -1)])}${quoteMeta( + a.slice(-1) + )}`; + } + } + + // find common prefix: (a1|a2|a3|a4|b5) => (a(1|2|3|4)|b5) + const prefixed = popCommonItems( + items, + (item) => (item.length >= 1 ? item[0] : false), + (list) => { + if (list.length >= 3) return true; + if (list.length <= 1) return false; + return list[0][1] === list[1][1]; + } + ); + for (const prefixedItems of prefixed) { + const prefix = getCommonPrefix(prefixedItems); + finishedItems.push( + `${quoteMeta(prefix)}${itemsToRegexp( + prefixedItems.map((i) => i.slice(prefix.length)) + )}` + ); + } + + // find common suffix: (a1|b1|c1|d1|e2) => ((a|b|c|d)1|e2) + const suffixed = popCommonItems( + items, + (item) => (item.length >= 1 ? item.slice(-1) : false), + (list) => { + if (list.length >= 3) return true; + if (list.length <= 1) return false; + return list[0].slice(-2) === list[1].slice(-2); + } + ); + for (const suffixedItems of suffixed) { + const suffix = getCommonSuffix(suffixedItems); + finishedItems.push( + `${itemsToRegexp( + suffixedItems.map((i) => i.slice(0, -suffix.length)) + )}${quoteMeta(suffix)}` + ); + } + + // TODO further optimize regexp, i. e. + // use ranges: (1|2|3|4|a) => [1-4a] + /** @type {string[]} */ + const conditional = [...finishedItems, ...Array.from(items, quoteMeta)]; + if (conditional.length === 1) return conditional[0]; + return `(${conditional.join("|")})`; +}; + +compileBooleanMatcher.fromLists = compileBooleanMatcherFromLists; +compileBooleanMatcher.itemsToRegexp = itemsToRegexp; + +module.exports = compileBooleanMatcher; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/concatenate.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/concatenate.js new file mode 100644 index 0000000000000000000000000000000000000000..7dc16cf1304adf08d44835fe7ff1ff4f0d24d950 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/concatenate.js @@ -0,0 +1,232 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Template = require("../Template"); + +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("eslint-scope").Reference} Reference */ +/** @typedef {import("eslint-scope").Variable} Variable */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("../javascript/JavascriptParser").Range} Range */ +/** @typedef {import("../javascript/JavascriptParser").Program} Program */ +/** @typedef {Set} UsedNames */ + +const DEFAULT_EXPORT = "__WEBPACK_DEFAULT_EXPORT__"; +const NAMESPACE_OBJECT_EXPORT = "__WEBPACK_NAMESPACE_OBJECT__"; + +/** + * @param {Variable} variable variable + * @returns {Reference[]} references + */ +const getAllReferences = (variable) => { + let set = variable.references; + // Look for inner scope variables too (like in class Foo { t() { Foo } }) + const identifiers = new Set(variable.identifiers); + for (const scope of variable.scope.childScopes) { + for (const innerVar of scope.variables) { + if (innerVar.identifiers.some((id) => identifiers.has(id))) { + set = [...set, ...innerVar.references]; + break; + } + } + } + return set; +}; + +/** + * @param {Node | Node[]} ast ast + * @param {Node} node node + * @returns {undefined | Node[]} result + */ +const getPathInAst = (ast, node) => { + if (ast === node) { + return []; + } + + const nr = /** @type {Range} */ (node.range); + + /** + * @param {Node} n node + * @returns {Node[] | undefined} result + */ + const enterNode = (n) => { + if (!n) return; + const r = n.range; + if (r && r[0] <= nr[0] && r[1] >= nr[1]) { + const path = getPathInAst(n, node); + if (path) { + path.push(n); + return path; + } + } + }; + + if (Array.isArray(ast)) { + for (let i = 0; i < ast.length; i++) { + const enterResult = enterNode(ast[i]); + if (enterResult !== undefined) return enterResult; + } + } else if (ast && typeof ast === "object") { + const keys = + /** @type {Array} */ + (Object.keys(ast)); + for (let i = 0; i < keys.length; i++) { + // We are making the faster check in `enterNode` using `n.range` + const value = + ast[ + /** @type {Exclude} */ + (keys[i]) + ]; + if (Array.isArray(value)) { + const pathResult = getPathInAst(value, node); + if (pathResult !== undefined) return pathResult; + } else if (value && typeof value === "object") { + const enterResult = enterNode(value); + if (enterResult !== undefined) return enterResult; + } + } + } +}; + +/** + * @param {string} oldName old name + * @param {UsedNames} usedNamed1 used named 1 + * @param {UsedNames} usedNamed2 used named 2 + * @param {string} extraInfo extra info + * @returns {string} found new name + */ +function findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { + let name = oldName; + + if (name === DEFAULT_EXPORT) { + name = ""; + } + if (name === NAMESPACE_OBJECT_EXPORT) { + name = "namespaceObject"; + } + + // Remove uncool stuff + extraInfo = extraInfo.replace( + /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, + "" + ); + + const splittedInfo = extraInfo.split("/"); + while (splittedInfo.length) { + name = splittedInfo.pop() + (name ? `_${name}` : ""); + const nameIdent = Template.toIdentifier(name); + if ( + !usedNamed1.has(nameIdent) && + (!usedNamed2 || !usedNamed2.has(nameIdent)) + ) { + return nameIdent; + } + } + + let i = 0; + let nameWithNumber = Template.toIdentifier(`${name}_${i}`); + while ( + usedNamed1.has(nameWithNumber) || + // eslint-disable-next-line no-unmodified-loop-condition + (usedNamed2 && usedNamed2.has(nameWithNumber)) + ) { + i++; + nameWithNumber = Template.toIdentifier(`${name}_${i}`); + } + return nameWithNumber; +} + +/** @typedef {Set} ScopeSet */ + +/** + * @param {Scope | null} s scope + * @param {UsedNames} nameSet name set + * @param {ScopeSet} scopeSet1 scope set 1 + * @param {ScopeSet} scopeSet2 scope set 2 + */ +const addScopeSymbols = (s, nameSet, scopeSet1, scopeSet2) => { + let scope = s; + while (scope) { + if (scopeSet1.has(scope)) break; + if (scopeSet2.has(scope)) break; + scopeSet1.add(scope); + for (const variable of scope.variables) { + nameSet.add(variable.name); + } + scope = scope.upper; + } +}; + +const RESERVED_NAMES = new Set( + [ + // internal names (should always be renamed) + DEFAULT_EXPORT, + NAMESPACE_OBJECT_EXPORT, + + // keywords + "abstract,arguments,async,await,boolean,break,byte,case,catch,char,class,const,continue", + "debugger,default,delete,do,double,else,enum,eval,export,extends,false,final,finally,float", + "for,function,goto,if,implements,import,in,instanceof,int,interface,let,long,native,new,null", + "package,private,protected,public,return,short,static,super,switch,synchronized,this,throw", + "throws,transient,true,try,typeof,var,void,volatile,while,with,yield", + + // commonjs/amd + "module,__dirname,__filename,exports,require,define", + + // js globals + "Array,Date,eval,function,hasOwnProperty,Infinity,isFinite,isNaN,isPrototypeOf,length,Math", + "NaN,name,Number,Object,prototype,String,Symbol,toString,undefined,valueOf", + + // browser globals + "alert,all,anchor,anchors,area,assign,blur,button,checkbox,clearInterval,clearTimeout", + "clientInformation,close,closed,confirm,constructor,crypto,decodeURI,decodeURIComponent", + "defaultStatus,document,element,elements,embed,embeds,encodeURI,encodeURIComponent,escape", + "event,fileUpload,focus,form,forms,frame,innerHeight,innerWidth,layer,layers,link,location", + "mimeTypes,navigate,navigator,frames,frameRate,hidden,history,image,images,offscreenBuffering", + "open,opener,option,outerHeight,outerWidth,packages,pageXOffset,pageYOffset,parent,parseFloat", + "parseInt,password,pkcs11,plugin,prompt,propertyIsEnum,radio,reset,screenX,screenY,scroll", + "secure,select,self,setInterval,setTimeout,status,submit,taint,text,textarea,top,unescape", + "untaint,window", + + // window events + "onblur,onclick,onerror,onfocus,onkeydown,onkeypress,onkeyup,onmouseover,onload,onmouseup,onmousedown,onsubmit" + ] + .join(",") + .split(",") +); + +/** @typedef {{ usedNames: UsedNames, alreadyCheckedScopes: ScopeSet }} ScopeInfo */ + +/** + * @param {Map} usedNamesInScopeInfo used names in scope info + * @param {string} module module identifier + * @param {string} id export id + * @returns {ScopeInfo} info + */ +const getUsedNamesInScopeInfo = (usedNamesInScopeInfo, module, id) => { + const key = `${module}-${id}`; + let info = usedNamesInScopeInfo.get(key); + if (info === undefined) { + info = { + usedNames: new Set(), + alreadyCheckedScopes: new Set() + }; + usedNamesInScopeInfo.set(key, info); + } + return info; +}; + +module.exports = { + DEFAULT_EXPORT, + NAMESPACE_OBJECT_EXPORT, + RESERVED_NAMES, + addScopeSymbols, + findNewName, + getAllReferences, + getPathInAst, + getUsedNamesInScopeInfo +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/conventions.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/conventions.js new file mode 100644 index 0000000000000000000000000000000000000000..f60517870c914dca1d7015d012433330f40398ca --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/conventions.js @@ -0,0 +1,125 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Gengkun He @ahabhgk +*/ + +"use strict"; + +/** @typedef {import("../../declarations/WebpackOptions").CssGeneratorExportsConvention} CssGeneratorExportsConvention */ +// Copy from css-loader +/** + * @param {string} string string + * @returns {string} result + */ +const preserveCamelCase = (string) => { + let result = string; + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < result.length; i++) { + const character = result[i]; + + if (isLastCharLower && /[\p{Lu}]/u.test(character)) { + result = `${result.slice(0, i)}-${result.slice(i)}`; + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i += 1; + } else if ( + isLastCharUpper && + isLastLastCharUpper && + /[\p{Ll}]/u.test(character) + ) { + result = `${result.slice(0, i - 1)}-${result.slice(i - 1)}`; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = + character.toLowerCase() === character && + character.toUpperCase() !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = + character.toUpperCase() === character && + character.toLowerCase() !== character; + } + } + + return result; +}; + +// Copy from css-loader +/** + * @param {string} input input + * @returns {string} result + */ +module.exports.camelCase = (input) => { + let result = input.trim(); + + if (result.length === 0) { + return ""; + } + + if (result.length === 1) { + return result.toLowerCase(); + } + + const hasUpperCase = result !== result.toLowerCase(); + + if (hasUpperCase) { + result = preserveCamelCase(result); + } + + return result + .replace(/^[_.\- ]+/, "") + .toLowerCase() + .replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toUpperCase()) + .replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, (m) => m.toUpperCase()); +}; + +/** + * @param {string} input input + * @param {CssGeneratorExportsConvention | undefined} convention convention + * @returns {string[]} results + */ +module.exports.cssExportConvention = (input, convention) => { + const set = new Set(); + if (typeof convention === "function") { + set.add(convention(input)); + } else { + switch (convention) { + case "camel-case": { + set.add(input); + set.add(module.exports.camelCase(input)); + break; + } + case "camel-case-only": { + set.add(module.exports.camelCase(input)); + break; + } + case "dashes": { + set.add(input); + set.add(module.exports.dashesCamelCase(input)); + break; + } + case "dashes-only": { + set.add(module.exports.dashesCamelCase(input)); + break; + } + case "as-is": { + set.add(input); + break; + } + } + } + return [...set]; +}; + +// Copy from css-loader +/** + * @param {string} input input + * @returns {string} result + */ +module.exports.dashesCamelCase = (input) => + input.replace(/-+(\w)/g, (match, firstLetter) => firstLetter.toUpperCase()); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/create-schema-validation.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/create-schema-validation.js new file mode 100644 index 0000000000000000000000000000000000000000..6364eda65ff79ffe3b29b8eff4d672c8ccfb3e3a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/create-schema-validation.js @@ -0,0 +1,42 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const memoize = require("./memoize"); + +/** @typedef {import("schema-utils").Schema} Schema */ +/** @typedef {import("schema-utils/declarations/validate").ValidationErrorConfiguration} ValidationErrorConfiguration */ +/** @typedef {import("./fs").JsonObject} JsonObject */ + +const getValidate = memoize(() => require("schema-utils").validate); + +/** + * @template {object | object[]} T + * @param {((value: T) => boolean) | undefined} check check + * @param {() => Schema} getSchema get schema fn + * @param {ValidationErrorConfiguration} options options + * @returns {(value?: T) => void} validate + */ +const createSchemaValidation = (check, getSchema, options) => { + getSchema = memoize(getSchema); + return (value) => { + if (check && value && !check(value)) { + getValidate()( + getSchema(), + /** @type {EXPECTED_OBJECT | EXPECTED_OBJECT[]} */ + (value), + options + ); + require("util").deprecate( + () => {}, + "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", + "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" + )(); + } + }; +}; + +module.exports = createSchemaValidation; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/createHash.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/createHash.js new file mode 100644 index 0000000000000000000000000000000000000000..2ff475af8f2a8ac005b5cbfc18c69a40d4d54e01 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/createHash.js @@ -0,0 +1,200 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Hash = require("./Hash"); + +/** @typedef {import("../../declarations/WebpackOptions").HashFunction} HashFunction */ + +const BULK_SIZE = 2000; + +// We are using an object instead of a Map as this will stay static during the runtime +// so access to it can be optimized by v8 +/** @type {{[key: string]: Map}} */ +const digestCaches = {}; + +/** @typedef {() => Hash} HashFactory */ + +class BulkUpdateDecorator extends Hash { + /** + * @param {Hash | HashFactory} hashOrFactory function to create a hash + * @param {string=} hashKey key for caching + */ + constructor(hashOrFactory, hashKey) { + super(); + this.hashKey = hashKey; + if (typeof hashOrFactory === "function") { + this.hashFactory = hashOrFactory; + this.hash = undefined; + } else { + this.hashFactory = undefined; + this.hash = hashOrFactory; + } + this.buffer = ""; + } + + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + if ( + inputEncoding !== undefined || + typeof data !== "string" || + data.length > BULK_SIZE + ) { + if (this.hash === undefined) { + this.hash = /** @type {HashFactory} */ (this.hashFactory)(); + } + if (this.buffer.length > 0) { + this.hash.update(this.buffer); + this.buffer = ""; + } + this.hash.update(data, inputEncoding); + } else { + this.buffer += data; + if (this.buffer.length > BULK_SIZE) { + if (this.hash === undefined) { + this.hash = /** @type {HashFactory} */ (this.hashFactory)(); + } + this.hash.update(this.buffer); + this.buffer = ""; + } + } + return this; + } + + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + let digestCache; + const buffer = this.buffer; + if (this.hash === undefined) { + // short data for hash, we can use caching + const cacheKey = `${this.hashKey}-${encoding}`; + digestCache = digestCaches[cacheKey]; + if (digestCache === undefined) { + digestCache = digestCaches[cacheKey] = new Map(); + } + const cacheEntry = digestCache.get(buffer); + if (cacheEntry !== undefined) return cacheEntry; + this.hash = /** @type {HashFactory} */ (this.hashFactory)(); + } + if (buffer.length > 0) { + this.hash.update(buffer); + } + const digestResult = this.hash.digest(encoding); + const result = + typeof digestResult === "string" ? digestResult : digestResult.toString(); + if (digestCache !== undefined) { + digestCache.set(buffer, result); + } + return result; + } +} + +/* istanbul ignore next */ +class DebugHash extends Hash { + constructor() { + super(); + this.string = ""; + } + + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + if (typeof data !== "string") data = data.toString("utf8"); + const prefix = Buffer.from("@webpack-debug-digest@").toString("hex"); + if (data.startsWith(prefix)) { + data = Buffer.from(data.slice(prefix.length), "hex").toString(); + } + this.string += `[${data}](${ + /** @type {string} */ + ( + // eslint-disable-next-line unicorn/error-message + new Error().stack + ).split("\n", 3)[2] + })\n`; + return this; + } + + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + return Buffer.from(`@webpack-debug-digest@${this.string}`).toString("hex"); + } +} + +/** @type {typeof import("crypto") | undefined} */ +let crypto; +/** @type {typeof import("./hash/xxhash64") | undefined} */ +let createXXHash64; +/** @type {typeof import("./hash/md4") | undefined} */ +let createMd4; +/** @type {typeof import("./hash/BatchedHash") | undefined} */ +let BatchedHash; + +/** + * Creates a hash by name or function + * @param {HashFunction} algorithm the algorithm name or a constructor creating a hash + * @returns {Hash} the hash + */ +module.exports = (algorithm) => { + if (typeof algorithm === "function") { + // eslint-disable-next-line new-cap + return new BulkUpdateDecorator(() => new algorithm()); + } + switch (algorithm) { + // TODO add non-cryptographic algorithm here + case "debug": + return new DebugHash(); + case "xxhash64": + if (createXXHash64 === undefined) { + createXXHash64 = require("./hash/xxhash64"); + if (BatchedHash === undefined) { + BatchedHash = require("./hash/BatchedHash"); + } + } + return new /** @type {typeof import("./hash/BatchedHash")} */ ( + BatchedHash + )(createXXHash64()); + case "md4": + if (createMd4 === undefined) { + createMd4 = require("./hash/md4"); + if (BatchedHash === undefined) { + BatchedHash = require("./hash/BatchedHash"); + } + } + return new /** @type {typeof import("./hash/BatchedHash")} */ ( + BatchedHash + )(createMd4()); + case "native-md4": + if (crypto === undefined) crypto = require("crypto"); + return new BulkUpdateDecorator( + () => /** @type {typeof import("crypto")} */ (crypto).createHash("md4"), + "md4" + ); + default: + if (crypto === undefined) crypto = require("crypto"); + return new BulkUpdateDecorator( + () => + /** @type {typeof import("crypto")} */ (crypto).createHash(algorithm), + algorithm + ); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/deprecation.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/deprecation.js new file mode 100644 index 0000000000000000000000000000000000000000..5d3b61b31d313356be04f07b7c5ab5d09a01e6bd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/deprecation.js @@ -0,0 +1,352 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); + +/** @type {Map void>} */ +const deprecationCache = new Map(); + +/** + * @typedef {object} FakeHookMarker + * @property {true} _fakeHook it's a fake hook + */ + +/** + * @template T + * @typedef {T & FakeHookMarker} FakeHook + */ + +/** + * @param {string} message deprecation message + * @param {string} code deprecation code + * @returns {() => void} function to trigger deprecation + */ +const createDeprecation = (message, code) => { + const cached = deprecationCache.get(message); + if (cached !== undefined) return cached; + const fn = util.deprecate( + () => {}, + message, + `DEP_WEBPACK_DEPRECATION_${code}` + ); + deprecationCache.set(message, fn); + return fn; +}; + +/** @typedef {"concat" | "entry" | "filter" | "find" | "findIndex" | "includes" | "indexOf" | "join" | "lastIndexOf" | "map" | "reduce" | "reduceRight" | "slice" | "some"} COPY_METHODS_NAMES */ + +/** @type {COPY_METHODS_NAMES[]} */ +const COPY_METHODS = [ + "concat", + "entry", + "filter", + "find", + "findIndex", + "includes", + "indexOf", + "join", + "lastIndexOf", + "map", + "reduce", + "reduceRight", + "slice", + "some" +]; + +/** @typedef {"copyWithin" | "entries" | "fill" | "keys" | "pop" | "reverse" | "shift" | "splice" | "sort" | "unshift"} DISABLED_METHODS_NAMES */ + +/** @type {DISABLED_METHODS_NAMES[]} */ +const DISABLED_METHODS = [ + "copyWithin", + "entries", + "fill", + "keys", + "pop", + "reverse", + "shift", + "splice", + "sort", + "unshift" +]; + +/** + * @template T + * @typedef {Set & {[Symbol.isConcatSpreadable]?: boolean} & { push?: (...items: T[]) => void } & { [P in DISABLED_METHODS_NAMES]?: () => void } & { [P in COPY_METHODS_NAMES]?: () => TODO }} SetWithDeprecatedArrayMethods + */ + +/** + * @template T + * @param {SetWithDeprecatedArrayMethods} set new set + * @param {string} name property name + * @returns {void} + */ +module.exports.arrayToSetDeprecation = (set, name) => { + for (const method of COPY_METHODS) { + if (set[method]) continue; + const d = createDeprecation( + `${name} was changed from Array to Set (using Array method '${method}' is deprecated)`, + "ARRAY_TO_SET" + ); + /** + * @deprecated + * @this {Set} + * @returns {number} count + */ + // eslint-disable-next-line func-names + set[method] = function () { + d(); + // eslint-disable-next-line unicorn/prefer-spread + const array = Array.from(this); + return Array.prototype[/** @type {keyof COPY_METHODS} */ (method)].apply( + array, + // eslint-disable-next-line prefer-rest-params + arguments + ); + }; + } + const dPush = createDeprecation( + `${name} was changed from Array to Set (using Array method 'push' is deprecated)`, + "ARRAY_TO_SET_PUSH" + ); + const dLength = createDeprecation( + `${name} was changed from Array to Set (using Array property 'length' is deprecated)`, + "ARRAY_TO_SET_LENGTH" + ); + const dIndexer = createDeprecation( + `${name} was changed from Array to Set (indexing Array is deprecated)`, + "ARRAY_TO_SET_INDEXER" + ); + /** + * @deprecated + * @this {Set} + * @returns {number} count + */ + set.push = function push() { + dPush(); + // eslint-disable-next-line prefer-rest-params, unicorn/prefer-spread + for (const item of Array.from(arguments)) { + this.add(item); + } + return this.size; + }; + for (const method of DISABLED_METHODS) { + if (set[method]) continue; + + set[method] = () => { + throw new Error( + `${name} was changed from Array to Set (using Array method '${method}' is not possible)` + ); + }; + } + /** + * @param {number} index index + * @returns {() => T | undefined} value + */ + const createIndexGetter = (index) => { + /** + * @this {Set} a Set + * @returns {T | undefined} the value at this location + */ + // eslint-disable-next-line func-style + const fn = function () { + dIndexer(); + let i = 0; + for (const item of this) { + if (i++ === index) return item; + } + }; + return fn; + }; + /** + * @param {number} index index + */ + const defineIndexGetter = (index) => { + Object.defineProperty(set, index, { + get: createIndexGetter(index), + set(value) { + throw new Error( + `${name} was changed from Array to Set (indexing Array with write is not possible)` + ); + } + }); + }; + defineIndexGetter(0); + let indexerDefined = 1; + Object.defineProperty(set, "length", { + get() { + dLength(); + const length = this.size; + for (indexerDefined; indexerDefined < length + 1; indexerDefined++) { + defineIndexGetter(indexerDefined); + } + return length; + }, + set(value) { + throw new Error( + `${name} was changed from Array to Set (writing to Array property 'length' is not possible)` + ); + } + }); + set[Symbol.isConcatSpreadable] = true; +}; + +/** + * @template T + * @param {string} name name + * @returns {{ new (values?: readonly T[] | null): SetDeprecatedArray }} SetDeprecatedArray + */ +module.exports.createArrayToSetDeprecationSet = (name) => { + let initialized = false; + + /** + * @template T + */ + class SetDeprecatedArray extends Set { + /** + * @param {readonly T[] | null=} items items + */ + constructor(items) { + super(items); + if (!initialized) { + initialized = true; + module.exports.arrayToSetDeprecation( + SetDeprecatedArray.prototype, + name + ); + } + } + } + return SetDeprecatedArray; +}; + +/** + * @template {object} T + * @param {T} fakeHook fake hook implementation + * @param {string=} message deprecation message (not deprecated when unset) + * @param {string=} code deprecation code (not deprecated when unset) + * @returns {FakeHook} fake hook which redirects + */ +module.exports.createFakeHook = (fakeHook, message, code) => { + if (message && code) { + fakeHook = deprecateAllProperties(fakeHook, message, code); + } + return Object.freeze( + Object.assign(fakeHook, { _fakeHook: /** @type {true} */ (true) }) + ); +}; + +/** + * @template T + * @param {T} obj object + * @param {string} message deprecation message + * @param {string} code deprecation code + * @returns {T} object with property access deprecated + */ +const deprecateAllProperties = (obj, message, code) => { + const newObj = {}; + const descriptors = Object.getOwnPropertyDescriptors(obj); + for (const name of Object.keys(descriptors)) { + const descriptor = descriptors[name]; + if (typeof descriptor.value === "function") { + Object.defineProperty(newObj, name, { + ...descriptor, + value: util.deprecate(descriptor.value, message, code) + }); + } else if (descriptor.get || descriptor.set) { + Object.defineProperty(newObj, name, { + ...descriptor, + get: descriptor.get && util.deprecate(descriptor.get, message, code), + set: descriptor.set && util.deprecate(descriptor.set, message, code) + }); + } else { + let value = descriptor.value; + Object.defineProperty(newObj, name, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + get: util.deprecate(() => value, message, code), + set: descriptor.writable + ? util.deprecate( + /** + * @template T + * @param {T} v value + * @returns {T} result + */ + (v) => (value = v), + message, + code + ) + : undefined + }); + } + } + return /** @type {T} */ (newObj); +}; + +module.exports.deprecateAllProperties = deprecateAllProperties; + +/** + * @template {object} T + * @param {T} obj object + * @param {string} name property name + * @param {string} code deprecation code + * @param {string} note additional note + * @returns {T} frozen object with deprecation when modifying + */ +module.exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { + const message = `${name} will be frozen in future, all modifications are deprecated.${ + note && `\n${note}` + }`; + return /** @type {T} */ ( + new Proxy(obj, { + set: util.deprecate( + /** + * @param {object} target target + * @param {string | symbol} property property + * @param {EXPECTED_ANY} value value + * @param {EXPECTED_ANY} receiver receiver + * @returns {boolean} result + */ + (target, property, value, receiver) => + Reflect.set(target, property, value, receiver), + message, + code + ), + defineProperty: util.deprecate( + /** + * @param {object} target target + * @param {string | symbol} property property + * @param {PropertyDescriptor} descriptor descriptor + * @returns {boolean} result + */ + (target, property, descriptor) => + Reflect.defineProperty(target, property, descriptor), + message, + code + ), + deleteProperty: util.deprecate( + /** + * @param {object} target target + * @param {string | symbol} property property + * @returns {boolean} result + */ + (target, property) => Reflect.deleteProperty(target, property), + message, + code + ), + setPrototypeOf: util.deprecate( + /** + * @param {object} target target + * @param {EXPECTED_OBJECT | null} proto proto + * @returns {boolean} result + */ + (target, proto) => Reflect.setPrototypeOf(target, proto), + message, + code + ) + }) + ); +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/deterministicGrouping.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/deterministicGrouping.js new file mode 100644 index 0000000000000000000000000000000000000000..4331a3e47f4ea9280b41c88874873f7287e438ab --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/deterministicGrouping.js @@ -0,0 +1,542 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +// Simulations show these probabilities for a single change +// 93.1% that one group is invalidated +// 4.8% that two groups are invalidated +// 1.1% that 3 groups are invalidated +// 0.1% that 4 or more groups are invalidated +// +// And these for removing/adding 10 lexically adjacent files +// 64.5% that one group is invalidated +// 24.8% that two groups are invalidated +// 7.8% that 3 groups are invalidated +// 2.7% that 4 or more groups are invalidated +// +// And these for removing/adding 3 random files +// 0% that one group is invalidated +// 3.7% that two groups are invalidated +// 80.8% that 3 groups are invalidated +// 12.3% that 4 groups are invalidated +// 3.2% that 5 or more groups are invalidated + +/** + * @param {string} a key + * @param {string} b key + * @returns {number} the similarity as number + */ +const similarity = (a, b) => { + const l = Math.min(a.length, b.length); + let dist = 0; + for (let i = 0; i < l; i++) { + const ca = a.charCodeAt(i); + const cb = b.charCodeAt(i); + dist += Math.max(0, 10 - Math.abs(ca - cb)); + } + return dist; +}; + +/** + * @param {string} a key + * @param {string} b key + * @param {Set} usedNames set of already used names + * @returns {string} the common part and a single char for the difference + */ +const getName = (a, b, usedNames) => { + const l = Math.min(a.length, b.length); + let i = 0; + while (i < l) { + if (a.charCodeAt(i) !== b.charCodeAt(i)) { + i++; + break; + } + i++; + } + while (i < l) { + const name = a.slice(0, i); + const lowerName = name.toLowerCase(); + if (!usedNames.has(lowerName)) { + usedNames.add(lowerName); + return name; + } + i++; + } + // names always contain a hash, so this is always unique + // we don't need to check usedNames nor add it + return a; +}; + +/** + * @param {Record} total total size + * @param {Record} size single size + * @returns {void} + */ +const addSizeTo = (total, size) => { + for (const key of Object.keys(size)) { + total[key] = (total[key] || 0) + size[key]; + } +}; + +/** + * @param {Record} total total size + * @param {Record} size single size + * @returns {void} + */ +const subtractSizeFrom = (total, size) => { + for (const key of Object.keys(size)) { + total[key] -= size[key]; + } +}; + +/** + * @template T + * @param {Iterable>} nodes some nodes + * @returns {Record} total size + */ +const sumSize = (nodes) => { + const sum = Object.create(null); + for (const node of nodes) { + addSizeTo(sum, node.size); + } + return sum; +}; + +/** + * @param {Record} size size + * @param {Record} maxSize minimum size + * @returns {boolean} true, when size is too big + */ +const isTooBig = (size, maxSize) => { + for (const key of Object.keys(size)) { + const s = size[key]; + if (s === 0) continue; + const maxSizeValue = maxSize[key]; + if (typeof maxSizeValue === "number" && s > maxSizeValue) return true; + } + return false; +}; + +/** + * @param {Record} size size + * @param {Record} minSize minimum size + * @returns {boolean} true, when size is too small + */ +const isTooSmall = (size, minSize) => { + for (const key of Object.keys(size)) { + const s = size[key]; + if (s === 0) continue; + const minSizeValue = minSize[key]; + if (typeof minSizeValue === "number" && s < minSizeValue) return true; + } + return false; +}; + +/** + * @param {Record} size size + * @param {Record} minSize minimum size + * @returns {Set} set of types that are too small + */ +const getTooSmallTypes = (size, minSize) => { + const types = new Set(); + for (const key of Object.keys(size)) { + const s = size[key]; + if (s === 0) continue; + const minSizeValue = minSize[key]; + if (typeof minSizeValue === "number" && s < minSizeValue) types.add(key); + } + return types; +}; + +/** + * @template {object} T + * @param {T} size size + * @param {Set} types types + * @returns {number} number of matching size types + */ +const getNumberOfMatchingSizeTypes = (size, types) => { + let i = 0; + for (const key of Object.keys(size)) { + if (size[/** @type {keyof T} */ (key)] !== 0 && types.has(key)) i++; + } + return i; +}; + +/** + * @param {Record} size size + * @param {Set} types types + * @returns {number} selective size sum + */ +const selectiveSizeSum = (size, types) => { + let sum = 0; + for (const key of Object.keys(size)) { + if (size[key] !== 0 && types.has(key)) sum += size[key]; + } + return sum; +}; + +/** + * @template T + */ +class Node { + /** + * @param {T} item item + * @param {string} key key + * @param {Record} size size + */ + constructor(item, key, size) { + this.item = item; + this.key = key; + this.size = size; + } +} + +/** + * @template T + */ +class Group { + /** + * @param {Node[]} nodes nodes + * @param {number[] | null} similarities similarities between the nodes (length = nodes.length - 1) + * @param {Record=} size size of the group + */ + constructor(nodes, similarities, size) { + this.nodes = nodes; + this.similarities = similarities; + this.size = size || sumSize(nodes); + /** @type {string | undefined} */ + this.key = undefined; + } + + /** + * @param {(node: Node) => boolean} filter filter function + * @returns {Node[] | undefined} removed nodes + */ + popNodes(filter) { + const newNodes = []; + const newSimilarities = []; + const resultNodes = []; + let lastNode; + for (let i = 0; i < this.nodes.length; i++) { + const node = this.nodes[i]; + if (filter(node)) { + resultNodes.push(node); + } else { + if (newNodes.length > 0) { + newSimilarities.push( + lastNode === this.nodes[i - 1] + ? /** @type {number[]} */ (this.similarities)[i - 1] + : similarity(/** @type {Node} */ (lastNode).key, node.key) + ); + } + newNodes.push(node); + lastNode = node; + } + } + if (resultNodes.length === this.nodes.length) return; + this.nodes = newNodes; + this.similarities = newSimilarities; + this.size = sumSize(newNodes); + return resultNodes; + } +} + +/** + * @template T + * @param {Iterable>} nodes nodes + * @returns {number[]} similarities + */ +const getSimilarities = (nodes) => { + // calculate similarities between lexically adjacent nodes + /** @type {number[]} */ + const similarities = []; + let last; + for (const node of nodes) { + if (last !== undefined) { + similarities.push(similarity(last.key, node.key)); + } + last = node; + } + return similarities; +}; + +/** + * @template T + * @typedef {object} GroupedItems + * @property {string} key + * @property {T[]} items + * @property {Record} size + */ + +/** + * @template T + * @typedef {object} Options + * @property {Record} maxSize maximum size of a group + * @property {Record} minSize minimum size of a group (preferred over maximum size) + * @property {Iterable} items a list of items + * @property {(item: T) => Record} getSize function to get size of an item + * @property {(item: T) => string} getKey function to get the key of an item + */ + +/** + * @template T + * @param {Options} options options object + * @returns {GroupedItems[]} grouped items + */ +module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { + /** @type {Group[]} */ + const result = []; + + const nodes = Array.from( + items, + (item) => new Node(item, getKey(item), getSize(item)) + ); + + /** @type {Node[]} */ + const initialNodes = []; + + // lexically ordering of keys + nodes.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); + + // return nodes bigger than maxSize directly as group + // But make sure that minSize is not violated + for (const node of nodes) { + if (isTooBig(node.size, maxSize) && !isTooSmall(node.size, minSize)) { + result.push(new Group([node], [])); + } else { + initialNodes.push(node); + } + } + + if (initialNodes.length > 0) { + const initialGroup = new Group(initialNodes, getSimilarities(initialNodes)); + + /** + * @param {Group} group group + * @param {Record} consideredSize size of the group to consider + * @returns {boolean} true, if the group was modified + */ + const removeProblematicNodes = (group, consideredSize = group.size) => { + const problemTypes = getTooSmallTypes(consideredSize, minSize); + if (problemTypes.size > 0) { + // We hit an edge case where the working set is already smaller than minSize + // We merge problematic nodes with the smallest result node to keep minSize intact + const problemNodes = group.popNodes( + (n) => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 + ); + if (problemNodes === undefined) return false; + // Only merge it with result nodes that have the problematic size type + const possibleResultGroups = result.filter( + (n) => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 + ); + if (possibleResultGroups.length > 0) { + const bestGroup = possibleResultGroups.reduce((min, group) => { + const minMatches = getNumberOfMatchingSizeTypes(min, problemTypes); + const groupMatches = getNumberOfMatchingSizeTypes( + group, + problemTypes + ); + if (minMatches !== groupMatches) { + return minMatches < groupMatches ? group : min; + } + if ( + selectiveSizeSum(min.size, problemTypes) > + selectiveSizeSum(group.size, problemTypes) + ) { + return group; + } + return min; + }); + for (const node of problemNodes) bestGroup.nodes.push(node); + bestGroup.nodes.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); + } else { + // There are no other nodes with the same size types + // We create a new group and have to accept that it's smaller than minSize + result.push(new Group(problemNodes, null)); + } + return true; + } + return false; + }; + + if (initialGroup.nodes.length > 0) { + const queue = [initialGroup]; + + while (queue.length) { + const group = /** @type {Group} */ (queue.pop()); + // only groups bigger than maxSize need to be splitted + if (!isTooBig(group.size, maxSize)) { + result.push(group); + continue; + } + // If the group is already too small + // we try to work only with the unproblematic nodes + if (removeProblematicNodes(group)) { + // This changed something, so we try this group again + queue.push(group); + continue; + } + + // find unsplittable area from left and right + // going minSize from left and right + // at least one node need to be included otherwise we get stuck + let left = 1; + const leftSize = Object.create(null); + addSizeTo(leftSize, group.nodes[0].size); + while (left < group.nodes.length && isTooSmall(leftSize, minSize)) { + addSizeTo(leftSize, group.nodes[left].size); + left++; + } + let right = group.nodes.length - 2; + const rightSize = Object.create(null); + addSizeTo(rightSize, group.nodes[group.nodes.length - 1].size); + while (right >= 0 && isTooSmall(rightSize, minSize)) { + addSizeTo(rightSize, group.nodes[right].size); + right--; + } + + // left v v right + // [ O O O ] O O O [ O O O ] + // ^^^^^^^^^ leftSize + // rightSize ^^^^^^^^^ + // leftSize > minSize + // rightSize > minSize + + // Perfect split: [ O O O ] [ O O O ] + // right === left - 1 + + if (left - 1 > right) { + // We try to remove some problematic nodes to "fix" that + let prevSize; + if (right < group.nodes.length - left) { + subtractSizeFrom(rightSize, group.nodes[right + 1].size); + prevSize = rightSize; + } else { + subtractSizeFrom(leftSize, group.nodes[left - 1].size); + prevSize = leftSize; + } + if (removeProblematicNodes(group, prevSize)) { + // This changed something, so we try this group again + queue.push(group); + continue; + } + // can't split group while holding minSize + // because minSize is preferred of maxSize we return + // the problematic nodes as result here even while it's too big + // To avoid this make sure maxSize > minSize * 3 + result.push(group); + continue; + } + if (left <= right) { + // when there is a area between left and right + // we look for best split point + // we split at the minimum similarity + // here key space is separated the most + // But we also need to make sure to not create too small groups + let best = -1; + let bestSimilarity = Infinity; + let pos = left; + const rightSize = sumSize(group.nodes.slice(pos)); + + // pos v v right + // [ O O O ] O O O [ O O O ] + // ^^^^^^^^^ leftSize + // rightSize ^^^^^^^^^^^^^^^ + + while (pos <= right + 1) { + const similarity = /** @type {number[]} */ (group.similarities)[ + pos - 1 + ]; + if ( + similarity < bestSimilarity && + !isTooSmall(leftSize, minSize) && + !isTooSmall(rightSize, minSize) + ) { + best = pos; + bestSimilarity = similarity; + } + addSizeTo(leftSize, group.nodes[pos].size); + subtractSizeFrom(rightSize, group.nodes[pos].size); + pos++; + } + if (best < 0) { + // This can't happen + // but if that assumption is wrong + // fallback to a big group + result.push(group); + continue; + } + left = best; + right = best - 1; + } + + // create two new groups for left and right area + // and queue them up + const rightNodes = [group.nodes[right + 1]]; + /** @type {number[]} */ + const rightSimilarities = []; + for (let i = right + 2; i < group.nodes.length; i++) { + rightSimilarities.push( + /** @type {number[]} */ (group.similarities)[i - 1] + ); + rightNodes.push(group.nodes[i]); + } + queue.push(new Group(rightNodes, rightSimilarities)); + + const leftNodes = [group.nodes[0]]; + /** @type {number[]} */ + const leftSimilarities = []; + for (let i = 1; i < left; i++) { + leftSimilarities.push( + /** @type {number[]} */ (group.similarities)[i - 1] + ); + leftNodes.push(group.nodes[i]); + } + queue.push(new Group(leftNodes, leftSimilarities)); + } + } + } + + // lexically ordering + result.sort((a, b) => { + if (a.nodes[0].key < b.nodes[0].key) return -1; + if (a.nodes[0].key > b.nodes[0].key) return 1; + return 0; + }); + + // give every group a name + const usedNames = new Set(); + for (let i = 0; i < result.length; i++) { + const group = result[i]; + if (group.nodes.length === 1) { + group.key = group.nodes[0].key; + } else { + const first = group.nodes[0]; + const last = group.nodes[group.nodes.length - 1]; + const name = getName(first.key, last.key, usedNames); + group.key = name; + } + } + + // return the results + return result.map( + (group) => + /** @type {GroupedItems} */ + ({ + key: group.key, + items: group.nodes.map((node) => node.item), + size: group.size + }) + ); +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/extractUrlAndGlobal.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/extractUrlAndGlobal.js new file mode 100644 index 0000000000000000000000000000000000000000..394924a53245ad2c47a0bced02f02d5acd9364fb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/extractUrlAndGlobal.js @@ -0,0 +1,18 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sam Chen @chenxsan +*/ + +"use strict"; + +/** + * @param {string} urlAndGlobal the script request + * @returns {string[]} script url and its global variable + */ +module.exports = function extractUrlAndGlobal(urlAndGlobal) { + const index = urlAndGlobal.indexOf("@"); + if (index <= 0 || index === urlAndGlobal.length - 1) { + throw new Error(`Invalid request "${urlAndGlobal}"`); + } + return [urlAndGlobal.slice(index + 1), urlAndGlobal.slice(0, index)]; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/findGraphRoots.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/findGraphRoots.js new file mode 100644 index 0000000000000000000000000000000000000000..d7d02e49f3b441dc0f0012219bacdc673cb8b2a7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/findGraphRoots.js @@ -0,0 +1,231 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const NO_MARKER = 0; +const IN_PROGRESS_MARKER = 1; +const DONE_MARKER = 2; +const DONE_MAYBE_ROOT_CYCLE_MARKER = 3; +const DONE_AND_ROOT_MARKER = 4; + +/** + * @template T + */ +class Node { + /** + * @param {T} item the value of the node + */ + constructor(item) { + this.item = item; + /** @type {Set>} */ + this.dependencies = new Set(); + this.marker = NO_MARKER; + /** @type {Cycle | undefined} */ + this.cycle = undefined; + this.incoming = 0; + } +} + +/** + * @template T + */ +class Cycle { + constructor() { + /** @type {Set>} */ + this.nodes = new Set(); + } +} + +/** + * @template T + * @typedef {object} StackEntry + * @property {Node} node + * @property {Node[]} openEdges + */ + +/** + * @template T + * @param {Iterable} items list of items + * @param {(item: T) => Iterable} getDependencies function to get dependencies of an item (items that are not in list are ignored) + * @returns {Iterable} graph roots of the items + */ +module.exports = (items, getDependencies) => { + /** @type {Map>} */ + const itemToNode = new Map(); + for (const item of items) { + const node = new Node(item); + itemToNode.set(item, node); + } + + // early exit when there is only a single item + if (itemToNode.size <= 1) return items; + + // grab all the dependencies + for (const node of itemToNode.values()) { + for (const dep of getDependencies(node.item)) { + const depNode = itemToNode.get(dep); + if (depNode !== undefined) { + node.dependencies.add(depNode); + } + } + } + + // Set of current root modules + // items will be removed if a new reference to it has been found + /** @type {Set>} */ + const roots = new Set(); + + // Set of current cycles without references to it + // cycles will be removed if a new reference to it has been found + // that is not part of the cycle + /** @type {Set>} */ + const rootCycles = new Set(); + + // For all non-marked nodes + for (const selectedNode of itemToNode.values()) { + if (selectedNode.marker === NO_MARKER) { + // deep-walk all referenced modules + // in a non-recursive way + + // start by entering the selected node + selectedNode.marker = IN_PROGRESS_MARKER; + + // keep a stack to avoid recursive walk + /** @type {StackEntry[]} */ + const stack = [ + { + node: selectedNode, + openEdges: [...selectedNode.dependencies] + } + ]; + + // process the top item until stack is empty + while (stack.length > 0) { + const topOfStack = stack[stack.length - 1]; + + // Are there still edges unprocessed in the current node? + if (topOfStack.openEdges.length > 0) { + // Process one dependency + const dependency = + /** @type {Node} */ + (topOfStack.openEdges.pop()); + switch (dependency.marker) { + case NO_MARKER: + // dependency has not be visited yet + // mark it as in-progress and recurse + stack.push({ + node: dependency, + openEdges: [...dependency.dependencies] + }); + dependency.marker = IN_PROGRESS_MARKER; + break; + case IN_PROGRESS_MARKER: { + // It's a in-progress cycle + let cycle = dependency.cycle; + if (!cycle) { + cycle = new Cycle(); + cycle.nodes.add(dependency); + dependency.cycle = cycle; + } + // set cycle property for each node in the cycle + // if nodes are already part of a cycle + // we merge the cycles to a shared cycle + for ( + let i = stack.length - 1; + stack[i].node !== dependency; + i-- + ) { + const node = stack[i].node; + if (node.cycle) { + if (node.cycle !== cycle) { + // merge cycles + for (const cycleNode of node.cycle.nodes) { + cycleNode.cycle = cycle; + cycle.nodes.add(cycleNode); + } + } + } else { + node.cycle = cycle; + cycle.nodes.add(node); + } + } + // don't recurse into dependencies + // these are already on the stack + break; + } + case DONE_AND_ROOT_MARKER: + // This node has be visited yet and is currently a root node + // But as this is a new reference to the node + // it's not really a root + // so we have to convert it to a normal node + dependency.marker = DONE_MARKER; + roots.delete(dependency); + break; + case DONE_MAYBE_ROOT_CYCLE_MARKER: + // This node has be visited yet and + // is maybe currently part of a completed root cycle + // we found a new reference to the cycle + // so it's not really a root cycle + // remove the cycle from the root cycles + // and convert it to a normal node + rootCycles.delete(/** @type {Cycle} */ (dependency.cycle)); + dependency.marker = DONE_MARKER; + break; + // DONE_MARKER: nothing to do, don't recurse into dependencies + } + } else { + // All dependencies of the current node has been visited + // we leave the node + stack.pop(); + topOfStack.node.marker = DONE_MARKER; + } + } + const cycle = selectedNode.cycle; + if (cycle) { + for (const node of cycle.nodes) { + node.marker = DONE_MAYBE_ROOT_CYCLE_MARKER; + } + rootCycles.add(cycle); + } else { + selectedNode.marker = DONE_AND_ROOT_MARKER; + roots.add(selectedNode); + } + } + } + + // Extract roots from root cycles + // We take the nodes with most incoming edges + // inside of the cycle + for (const cycle of rootCycles) { + let max = 0; + /** @type {Set>} */ + const cycleRoots = new Set(); + const nodes = cycle.nodes; + for (const node of nodes) { + for (const dep of node.dependencies) { + if (nodes.has(dep)) { + dep.incoming++; + if (dep.incoming < max) continue; + if (dep.incoming > max) { + cycleRoots.clear(); + max = dep.incoming; + } + cycleRoots.add(dep); + } + } + } + for (const cycleRoot of cycleRoots) { + roots.add(cycleRoot); + } + } + + // When roots were found, return them + if (roots.size > 0) { + return Array.from(roots, (r) => r.item); + } + + throw new Error("Implementation of findGraphRoots is broken"); +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/fs.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/fs.js new file mode 100644 index 0000000000000000000000000000000000000000..29ab36d88c26168c6e304d2bf85c024ffa4c6ed9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/fs.js @@ -0,0 +1,658 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const path = require("path"); + +/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ + +/** + * @template T + * @typedef {object} IStatsBase + * @property {() => boolean} isFile + * @property {() => boolean} isDirectory + * @property {() => boolean} isBlockDevice + * @property {() => boolean} isCharacterDevice + * @property {() => boolean} isSymbolicLink + * @property {() => boolean} isFIFO + * @property {() => boolean} isSocket + * @property {T} dev + * @property {T} ino + * @property {T} mode + * @property {T} nlink + * @property {T} uid + * @property {T} gid + * @property {T} rdev + * @property {T} size + * @property {T} blksize + * @property {T} blocks + * @property {T} atimeMs + * @property {T} mtimeMs + * @property {T} ctimeMs + * @property {T} birthtimeMs + * @property {Date} atime + * @property {Date} mtime + * @property {Date} ctime + * @property {Date} birthtime + */ + +/** + * @typedef {IStatsBase} IStats + */ + +/** + * @typedef {IStatsBase & { atimeNs: bigint, mtimeNs: bigint, ctimeNs: bigint, birthtimeNs: bigint }} IBigIntStats + */ + +/** + * @template {string | Buffer} [T=string] + * @typedef {object} Dirent + * @property {() => boolean} isFile true when is file, otherwise false + * @property {() => boolean} isDirectory true when is directory, otherwise false + * @property {() => boolean} isBlockDevice true when is block device, otherwise false + * @property {() => boolean} isCharacterDevice true when is character device, otherwise false + * @property {() => boolean} isSymbolicLink true when is symbolic link, otherwise false + * @property {() => boolean} isFIFO true when is FIFO, otherwise false + * @property {() => boolean} isSocket true when is socket, otherwise false + * @property {T} name name + * @property {string} parentPath path + * @property {string=} path path + */ + +/** @typedef {string | number | boolean | null} JsonPrimitive */ +/** @typedef {JsonValue[]} JsonArray */ +/** @typedef {{ [Key in string]?: JsonValue }} JsonObject */ +/** @typedef {JsonPrimitive | JsonObject | JsonArray} JsonValue */ + +/** @typedef {(err: NodeJS.ErrnoException | null) => void} NoParamCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: string) => void} StringCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: Buffer) => void} BufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: string | Buffer) => void} StringOrBufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: string[]) => void} ReaddirStringCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: Buffer[]) => void} ReaddirBufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: string[] | Buffer[]) => void} ReaddirStringOrBufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: Dirent[]) => void} ReaddirDirentCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: Dirent[]) => void} ReaddirDirentBufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IStats) => void} StatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IBigIntStats) => void} BigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IStats | IBigIntStats) => void} StatsOrBigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: number) => void} NumberCallback */ +/** @typedef {(err: NodeJS.ErrnoException | Error | null, result?: JsonObject) => void} ReadJsonCallback */ + +/** @typedef {Map} TimeInfoEntries */ + +/** + * @typedef {object} WatcherInfo + * @property {Set | null} changes get current aggregated changes that have not yet send to callback + * @property {Set | null} removals get current aggregated removals that have not yet send to callback + * @property {TimeInfoEntries} fileTimeInfoEntries get info about files + * @property {TimeInfoEntries} contextTimeInfoEntries get info about directories + */ + +/** @typedef {Set} Changes */ +/** @typedef {Set} Removals */ + +// TODO webpack 6 deprecate missing getInfo +/** + * @typedef {object} Watcher + * @property {() => void} close closes the watcher and all underlying file watchers + * @property {() => void} pause closes the watcher, but keeps underlying file watchers alive until the next watch call + * @property {(() => Changes | null)=} getAggregatedChanges get current aggregated changes that have not yet send to callback + * @property {(() => Removals | null)=} getAggregatedRemovals get current aggregated removals that have not yet send to callback + * @property {() => TimeInfoEntries} getFileTimeInfoEntries get info about files + * @property {() => TimeInfoEntries} getContextTimeInfoEntries get info about directories + * @property {() => WatcherInfo=} getInfo get info about timestamps and changes + */ + +/** + * @callback WatchMethod + * @param {Iterable} files watched files + * @param {Iterable} directories watched directories + * @param {Iterable} missing watched existence entries + * @param {number} startTime timestamp of start time + * @param {WatchOptions} options options object + * @param {(err: Error | null, timeInfoEntries1?: TimeInfoEntries, timeInfoEntries2?: TimeInfoEntries, changes?: Changes, removals?: Removals) => void} callback aggregated callback + * @param {(value: string, num: number) => void} callbackUndelayed callback when the first change was detected + * @returns {Watcher} a watcher + */ + +// TODO webpack 6 make optional methods required and avoid using non standard methods like `join`, `relative`, `dirname`, move IntermediateFileSystemExtras methods to InputFilesystem or OutputFilesystem + +/** + * @typedef {string | Buffer | URL} PathLike + */ + +/** + * @typedef {PathLike | number} PathOrFileDescriptor + */ + +/** + * @typedef {object} ObjectEncodingOptions + * @property {BufferEncoding | null | undefined=} encoding + */ + +/** + * @typedef {{ + * (path: PathOrFileDescriptor, options: ({ encoding?: null | undefined, flag?: string | undefined } & import("events").Abortable) | undefined | null, callback: BufferCallback): void; + * (path: PathOrFileDescriptor, options: ({ encoding: BufferEncoding, flag?: string | undefined } & import("events").Abortable) | BufferEncoding, callback: StringCallback): void; + * (path: PathOrFileDescriptor, options: (ObjectEncodingOptions & { flag?: string | undefined } & import("events").Abortable) | BufferEncoding | undefined | null, callback: StringOrBufferCallback): void; + * (path: PathOrFileDescriptor, callback: BufferCallback): void; + * }} ReadFile + */ + +/** + * @typedef {{ + * (path: PathOrFileDescriptor, options?: { encoding?: null | undefined, flag?: string | undefined } | null): Buffer; + * (path: PathOrFileDescriptor, options: { encoding: BufferEncoding, flag?: string | undefined } | BufferEncoding): string; + * (path: PathOrFileDescriptor, options?: (ObjectEncodingOptions & { flag?: string | undefined }) | BufferEncoding | null): string | Buffer; + * }} ReadFileSync + */ + +/** + * @typedef {ObjectEncodingOptions | BufferEncoding | undefined | null} EncodingOption + */ + +/** + * @typedef {'buffer'| { encoding: 'buffer' }} BufferEncodingOption + */ + +/** + * @typedef {object} StatOptions + * @property {(boolean | undefined)=} bigint + */ + +/** + * @typedef {object} StatSyncOptions + * @property {(boolean | undefined)=} bigint + * @property {(boolean | undefined)=} throwIfNoEntry + */ + +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void; + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void; + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void; + * (path: PathLike, callback: StringCallback): void; + * }} Readlink + */ + +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string; + * (path: PathLike, options: BufferEncodingOption): Buffer; + * (path: PathLike, options?: EncodingOption): string | Buffer; + * }} ReadlinkSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void; + * (path: PathLike, options: { encoding: 'buffer', withFileTypes?: false | undefined, recursive?: boolean | undefined } | 'buffer', callback: (err: NodeJS.ErrnoException | null, files?: Buffer[]) => void): void; + * (path: PathLike, options: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[] | Buffer[]) => void): void; + * (path: PathLike, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void; + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files?: Dirent[]) => void): void; + * (path: PathLike, options: { encoding: 'buffer', withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; + * }} Readdir + */ + +/** + * @typedef {{ + * (path: PathLike, options?: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined; } | BufferEncoding | null): string[]; + * (path: PathLike, options: { encoding: 'buffer', withFileTypes?: false | undefined, recursive?: boolean | undefined } | 'buffer'): Buffer[]; + * (path: PathLike, options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | null): string[] | Buffer[]; + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }): Dirent[]; + * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }): Dirent[]; + * }} ReaddirSync + */ + +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void; + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void; + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void; + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void; + * }} Stat + */ + +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats; + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined; + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined; + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats; + * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats; + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats; + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined; + * }} StatSync + */ + +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void; + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void; + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void; + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void; + * }} LStat + */ + +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats; + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined; + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined; + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats; + * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats; + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats; + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined; + * }} LStatSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void; + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void; + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void; + * (path: PathLike, callback: StringCallback): void; + * }} RealPath + */ + +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string; + * (path: PathLike, options: BufferEncodingOption): Buffer; + * (path: PathLike, options?: EncodingOption): string | Buffer; + * }} RealPathSync + */ + +/** + * @typedef {(pathOrFileDescriptor: PathOrFileDescriptor, callback: ReadJsonCallback) => void} ReadJson + */ + +/** + * @typedef {(pathOrFileDescriptor: PathOrFileDescriptor) => JsonObject} ReadJsonSync + */ + +/** + * @typedef {(value?: string | string[] | Set) => void} Purge + */ + +/** + * @typedef {object} InputFileSystem + * @property {ReadFile} readFile + * @property {ReadFileSync=} readFileSync + * @property {Readlink} readlink + * @property {ReadlinkSync=} readlinkSync + * @property {Readdir} readdir + * @property {ReaddirSync=} readdirSync + * @property {Stat} stat + * @property {StatSync=} statSync + * @property {LStat=} lstat + * @property {LStatSync=} lstatSync + * @property {RealPath=} realpath + * @property {RealPathSync=} realpathSync + * @property {ReadJson=} readJson + * @property {ReadJsonSync=} readJsonSync + * @property {Purge=} purge + * @property {((path1: string, path2: string) => string)=} join + * @property {((from: string, to: string) => string)=} relative + * @property {((dirname: string) => string)=} dirname + */ + +/** + * @typedef {number | string} Mode + */ + +/** + * @typedef {(ObjectEncodingOptions & import("events").Abortable & { mode?: Mode | undefined, flag?: string | undefined, flush?: boolean | undefined }) | BufferEncoding | null} WriteFileOptions + */ + +/** + * @typedef {{ + * (file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; + * (file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; + * }} WriteFile + */ + +/** + * @typedef {{ recursive?: boolean | undefined, mode?: Mode | undefined }} MakeDirectoryOptions + */ + +/** + * @typedef {{ + * (file: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: StringCallback): void; + * (file: PathLike, options: Mode | (MakeDirectoryOptions & { recursive?: false | undefined; }) | null | undefined, callback: NoParamCallback): void; + * (file: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: StringCallback): void; + * (file: PathLike, callback: NoParamCallback): void; + * }} Mkdir + */ + +/** + * @typedef {{ maxRetries?: number | undefined, recursive?: boolean | undefined, retryDelay?: number | undefined }} RmDirOptions + */ + +/** + * @typedef {{ + * (file: PathLike, callback: NoParamCallback): void; + * (file: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + * }} Rmdir + */ + +/** + * @typedef {(pathLike: PathLike, callback: NoParamCallback) => void} Unlink + */ + +/** + * @typedef {object} OutputFileSystem + * @property {WriteFile} writeFile + * @property {Mkdir} mkdir + * @property {Readdir=} readdir + * @property {Rmdir=} rmdir + * @property {Unlink=} unlink + * @property {Stat} stat + * @property {LStat=} lstat + * @property {ReadFile} readFile + * @property {((path1: string, path2: string) => string)=} join + * @property {((from: string, to: string) => string)=} relative + * @property {((dirname: string) => string)=} dirname + */ + +/** + * @typedef {object} WatchFileSystem + * @property {WatchMethod} watch + */ + +/** + * @typedef {{ + * (path: PathLike, options: MakeDirectoryOptions & { recursive: true }): string | undefined; + * (path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false | undefined }) | null): void; + * (path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + * }} MkdirSync + */ + +/** + * @typedef {object} StreamOptions + * @property {(string | undefined)=} flags + * @property {(BufferEncoding | undefined)} encoding + * @property {(number | EXPECTED_ANY | undefined)=} fd + * @property {(number | undefined)=} mode + * @property {(boolean | undefined)=} autoClose + * @property {(boolean | undefined)=} emitClose + * @property {(number | undefined)=} start + * @property {(AbortSignal | null | undefined)=} signal + */ + +/** + * @typedef {object} FSImplementation + * @property {((...args: EXPECTED_ANY[]) => EXPECTED_ANY)=} open + * @property {((...args: EXPECTED_ANY[]) => EXPECTED_ANY)=} close + */ + +/** + * @typedef {FSImplementation & { write: (...args: EXPECTED_ANY[]) => EXPECTED_ANY; close?: (...args: EXPECTED_ANY[]) => EXPECTED_ANY }} CreateWriteStreamFSImplementation + */ + +/** + * @typedef {StreamOptions & { fs?: CreateWriteStreamFSImplementation | null | undefined }} WriteStreamOptions + */ + +/** + * @typedef {(pathLike: PathLike, result?: BufferEncoding | WriteStreamOptions) => NodeJS.WritableStream} CreateWriteStream + */ + +/** + * @typedef {number | string} OpenMode + */ + +/** + * @typedef {{ + * (file: PathLike, flags: OpenMode | undefined, mode: Mode | undefined | null, callback: NumberCallback): void; + * (file: PathLike, flags: OpenMode | undefined, callback: NumberCallback): void; + * (file: PathLike, callback: NumberCallback): void; + * }} Open + */ + +/** + * @typedef {number | bigint} ReadPosition + */ + +/** + * @typedef {object} ReadSyncOptions + * @property {(number | undefined)=} offset + * @property {(number | undefined)=} length + * @property {(ReadPosition | null | undefined)=} position + */ + +/** + * @template {NodeJS.ArrayBufferView} TBuffer + * @typedef {object} ReadAsyncOptions + * @property {(number | undefined)=} offset + * @property {(number | undefined)=} length + * @property {(ReadPosition | null | undefined)=} position + * @property {TBuffer=} buffer + */ + +/** + * @template {NodeJS.ArrayBufferView} [TBuffer=NodeJS.ArrayBufferView] + * @typedef {{ + * (fd: number, buffer: TBuffer, offset: number, length: number, position: ReadPosition | null, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void): void; + * (fd: number, options: ReadAsyncOptions, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void): void; + * (fd: number, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void): void; + * }} Read + */ + +/** @typedef {(df: number, callback: NoParamCallback) => void} Close */ + +/** @typedef {(a: PathLike, b: PathLike, callback: NoParamCallback) => void} Rename */ + +/** + * @typedef {object} IntermediateFileSystemExtras + * @property {MkdirSync} mkdirSync + * @property {CreateWriteStream} createWriteStream + * @property {Open} open + * @property {Read} read + * @property {Close} close + * @property {Rename} rename + */ + +/** @typedef {InputFileSystem & OutputFileSystem & IntermediateFileSystemExtras} IntermediateFileSystem */ + +/** + * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system + * @param {string} rootPath the root path + * @param {string} targetPath the target path + * @returns {string} location of targetPath relative to rootPath + */ +const relative = (fs, rootPath, targetPath) => { + if (fs && fs.relative) { + return fs.relative(rootPath, targetPath); + } else if (path.posix.isAbsolute(rootPath)) { + return path.posix.relative(rootPath, targetPath); + } else if (path.win32.isAbsolute(rootPath)) { + return path.win32.relative(rootPath, targetPath); + } + throw new Error( + `${rootPath} is neither a posix nor a windows path, and there is no 'relative' method defined in the file system` + ); +}; + +/** + * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system + * @param {string} rootPath a path + * @param {string} filename a filename + * @returns {string} the joined path + */ +const join = (fs, rootPath, filename) => { + if (fs && fs.join) { + return fs.join(rootPath, filename); + } else if (path.posix.isAbsolute(rootPath)) { + return path.posix.join(rootPath, filename); + } else if (path.win32.isAbsolute(rootPath)) { + return path.win32.join(rootPath, filename); + } + throw new Error( + `${rootPath} is neither a posix nor a windows path, and there is no 'join' method defined in the file system` + ); +}; + +/** + * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system + * @param {string} absPath an absolute path + * @returns {string} the parent directory of the absolute path + */ +const dirname = (fs, absPath) => { + if (fs && fs.dirname) { + return fs.dirname(absPath); + } else if (path.posix.isAbsolute(absPath)) { + return path.posix.dirname(absPath); + } else if (path.win32.isAbsolute(absPath)) { + return path.win32.dirname(absPath); + } + throw new Error( + `${absPath} is neither a posix nor a windows path, and there is no 'dirname' method defined in the file system` + ); +}; + +/** + * @param {OutputFileSystem} fs a file system + * @param {string} p an absolute path + * @param {(err?: Error) => void} callback callback function for the error + * @returns {void} + */ +const mkdirp = (fs, p, callback) => { + fs.mkdir(p, (err) => { + if (err) { + if (err.code === "ENOENT") { + const dir = dirname(fs, p); + if (dir === p) { + callback(err); + return; + } + mkdirp(fs, dir, (err) => { + if (err) { + callback(err); + return; + } + fs.mkdir(p, (err) => { + if (err) { + if (err.code === "EEXIST") { + callback(); + return; + } + callback(err); + return; + } + callback(); + }); + }); + return; + } else if (err.code === "EEXIST") { + callback(); + return; + } + callback(err); + return; + } + callback(); + }); +}; + +/** + * @param {IntermediateFileSystem} fs a file system + * @param {string} p an absolute path + * @returns {void} + */ +const mkdirpSync = (fs, p) => { + try { + fs.mkdirSync(p); + } catch (err) { + if (err) { + if (/** @type {NodeJS.ErrnoException} */ (err).code === "ENOENT") { + const dir = dirname(fs, p); + if (dir === p) { + throw err; + } + mkdirpSync(fs, dir); + fs.mkdirSync(p); + return; + } else if (/** @type {NodeJS.ErrnoException} */ (err).code === "EEXIST") { + return; + } + throw err; + } + } +}; + +/** + * @param {InputFileSystem} fs a file system + * @param {string} p an absolute path + * @param {ReadJsonCallback} callback callback + * @returns {void} + */ +const readJson = (fs, p, callback) => { + if ("readJson" in fs) { + return /** @type {NonNullable} */ ( + fs.readJson + )(p, callback); + } + fs.readFile(p, (err, buf) => { + if (err) return callback(err); + let data; + try { + data = JSON.parse(/** @type {Buffer} */ (buf).toString("utf8")); + } catch (err1) { + return callback(/** @type {Error} */ (err1)); + } + return callback(null, data); + }); +}; + +/** + * @param {InputFileSystem} fs a file system + * @param {string} p an absolute path + * @param {(err: NodeJS.ErrnoException | Error | null, stats?: IStats | string) => void} callback callback + * @returns {void} + */ +const lstatReadlinkAbsolute = (fs, p, callback) => { + let i = 3; + const doReadLink = () => { + fs.readlink(p, (err, target) => { + if (err && --i > 0) { + // It might was just changed from symlink to file + // we retry 2 times to catch this case before throwing the error + return doStat(); + } + if (err) return callback(err); + const value = /** @type {string} */ (target).toString(); + callback(null, join(fs, dirname(fs, p), value)); + }); + }; + const doStat = () => { + if ("lstat" in fs) { + return /** @type {NonNullable} */ (fs.lstat)( + p, + (err, stats) => { + if (err) return callback(err); + if (/** @type {IStats} */ (stats).isSymbolicLink()) { + return doReadLink(); + } + callback(null, stats); + } + ); + } + return fs.stat(p, callback); + }; + if ("lstat" in fs) return doStat(); + doReadLink(); +}; + +module.exports.dirname = dirname; +module.exports.join = join; +module.exports.lstatReadlinkAbsolute = lstatReadlinkAbsolute; +module.exports.mkdirp = mkdirp; +module.exports.mkdirpSync = mkdirpSync; +module.exports.readJson = readJson; +module.exports.relative = relative; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/generateDebugId.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/generateDebugId.js new file mode 100644 index 0000000000000000000000000000000000000000..bd501f89a2da918f51eff9c2ce1fb6db8b8ac880 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/generateDebugId.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Alexander Akait @alexander-akait +*/ + +"use strict"; + +const createHash = require("./createHash"); + +/** + * @param {string | Buffer} content content + * @param {string} file file + * @returns {string} generated debug id + */ +module.exports = (content, file) => { + // We need a uuid which is 128 bits so we need 2x 64 bit hashes. + // The first 64 bits is a hash of the source. + const sourceHash = createHash("xxhash64").update(content).digest("hex"); + // The next 64 bits is a hash of the filename and sourceHash + const hash128 = `${sourceHash}${createHash("xxhash64") + .update(file) + .update(sourceHash) + .digest("hex")}`; + + return [ + hash128.slice(0, 8), + hash128.slice(8, 12), + `4${hash128.slice(12, 15)}`, + ((Number.parseInt(hash128.slice(15, 16), 16) & 3) | 8).toString(16) + + hash128.slice(17, 20), + hash128.slice(20, 32) + ].join("-"); +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/BatchedHash.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/BatchedHash.js new file mode 100644 index 0000000000000000000000000000000000000000..cc030f8bd7da2093403bf17262500dbf116e27da --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/BatchedHash.js @@ -0,0 +1,71 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Hash = require("../Hash"); +const MAX_SHORT_STRING = require("./wasm-hash").MAX_SHORT_STRING; + +class BatchedHash extends Hash { + /** + * @param {Hash} hash hash + */ + constructor(hash) { + super(); + this.string = undefined; + this.encoding = undefined; + this.hash = hash; + } + + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + if (this.string !== undefined) { + if ( + typeof data === "string" && + inputEncoding === this.encoding && + this.string.length + data.length < MAX_SHORT_STRING + ) { + this.string += data; + return this; + } + this.hash.update(this.string, this.encoding); + this.string = undefined; + } + if (typeof data === "string") { + if ( + data.length < MAX_SHORT_STRING && + // base64 encoding is not valid since it may contain padding chars + (!inputEncoding || !inputEncoding.startsWith("ba")) + ) { + this.string = data; + this.encoding = inputEncoding; + } else { + this.hash.update(data, inputEncoding); + } + } else { + this.hash.update(data); + } + return this; + } + + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + if (this.string !== undefined) { + this.hash.update(this.string, this.encoding); + } + return this.hash.digest(encoding); + } +} + +module.exports = BatchedHash; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/md4.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/md4.js new file mode 100644 index 0000000000000000000000000000000000000000..eb15298d3e37a0abf3e6ab62a9e203ec9eda2f13 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/md4.js @@ -0,0 +1,20 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const create = require("./wasm-hash"); + +// #region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1 +const md4 = new WebAssembly.Module( + Buffer.from( + // 2150 bytes + "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqFEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvQCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCBCIOIAQgAyABKAIAIg8gBSAEIAIgAyAEc3FzampBA3ciCCACIANzcXNqakEHdyEJIAEoAgwiBiACIAggASgCCCIQIAMgAiAJIAIgCHNxc2pqQQt3IgogCCAJc3FzampBE3chCyABKAIUIgcgCSAKIAEoAhAiESAIIAkgCyAJIApzcXNqakEDdyIMIAogC3Nxc2pqQQd3IQ0gASgCHCIJIAsgDCABKAIYIgggCiALIA0gCyAMc3FzampBC3ciEiAMIA1zcXNqakETdyETIAEoAiQiFCANIBIgASgCICIVIAwgDSATIA0gEnNxc2pqQQN3IgwgEiATc3FzampBB3chDSABKAIsIgsgEyAMIAEoAigiCiASIBMgDSAMIBNzcXNqakELdyISIAwgDXNxc2pqQRN3IRMgASgCNCIWIA0gEiABKAIwIhcgDCANIBMgDSASc3FzampBA3ciGCASIBNzcXNqakEHdyEZIBggASgCPCINIBMgGCABKAI4IgwgEiATIBkgEyAYc3FzampBC3ciEiAYIBlzcXNqakETdyITIBIgGXJxIBIgGXFyaiAPakGZ84nUBWpBA3ciGCATIBIgGSAYIBIgE3JxIBIgE3FyaiARakGZ84nUBWpBBXciEiATIBhycSATIBhxcmogFWpBmfOJ1AVqQQl3IhMgEiAYcnEgEiAYcXJqIBdqQZnzidQFakENdyIYIBIgE3JxIBIgE3FyaiAOakGZ84nUBWpBA3ciGSAYIBMgEiAZIBMgGHJxIBMgGHFyaiAHakGZ84nUBWpBBXciEiAYIBlycSAYIBlxcmogFGpBmfOJ1AVqQQl3IhMgEiAZcnEgEiAZcXJqIBZqQZnzidQFakENdyIYIBIgE3JxIBIgE3FyaiAQakGZ84nUBWpBA3ciGSAYIBMgEiAZIBMgGHJxIBMgGHFyaiAIakGZ84nUBWpBBXciEiAYIBlycSAYIBlxcmogCmpBmfOJ1AVqQQl3IhMgEiAZcnEgEiAZcXJqIAxqQZnzidQFakENdyIYIBIgE3JxIBIgE3FyaiAGakGZ84nUBWpBA3ciGSAYIBMgEiAZIBMgGHJxIBMgGHFyaiAJakGZ84nUBWpBBXciEiAYIBlycSAYIBlxcmogC2pBmfOJ1AVqQQl3IhMgEiAZcnEgEiAZcXJqIA1qQZnzidQFakENdyIYIBNzIBJzaiAPakGh1+f2BmpBA3ciDyAYIBMgEiAPIBhzIBNzaiAVakGh1+f2BmpBCXciEiAPcyAYc2ogEWpBodfn9gZqQQt3IhEgEnMgD3NqIBdqQaHX5/YGakEPdyIPIBFzIBJzaiAQakGh1+f2BmpBA3ciECAPIBEgEiAPIBBzIBFzaiAKakGh1+f2BmpBCXciCiAQcyAPc2ogCGpBodfn9gZqQQt3IgggCnMgEHNqIAxqQaHX5/YGakEPdyIMIAhzIApzaiAOakGh1+f2BmpBA3ciDiAMIAggCiAMIA5zIAhzaiAUakGh1+f2BmpBCXciCCAOcyAMc2ogB2pBodfn9gZqQQt3IgcgCHMgDnNqIBZqQaHX5/YGakEPdyIKIAdzIAhzaiAGakGh1+f2BmpBA3ciBiAFaiEFIAIgCiAHIAggBiAKcyAHc2ogC2pBodfn9gZqQQl3IgcgBnMgCnNqIAlqQaHX5/YGakELdyIIIAdzIAZzaiANakGh1+f2BmpBD3dqIQIgAyAIaiEDIAQgB2ohBCABQUBrIQEMAQsLIAUkASACJAIgAyQDIAQkBAsNACAAEAEjACAAaiQAC/sEAgN/AX4jACAAaq1CA4YhBCAAQcgAakFAcSICQQhrIAAiAUEBaiEAIAFBgAE6AAADQCAAIAJJQQAgAEEHcRsEQCAAQQA6AAAgAEEBaiEADAELCwNAIAAgAkkEQCAAQgA3AwAgAEEIaiEADAELCyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", + "base64" + ) +); +// #endregion + +module.exports = create.bind(null, md4, [], 64, 32); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/wasm-hash.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/wasm-hash.js new file mode 100644 index 0000000000000000000000000000000000000000..fbc3f3909f06ed745b6bd8808a46d10c48d6d5b0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/wasm-hash.js @@ -0,0 +1,176 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +// 65536 is the size of a wasm memory page +// 64 is the maximum chunk size for every possible wasm hash implementation +// 4 is the maximum number of bytes per char for string encoding (max is utf-8) +// ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64 +const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3; + +class WasmHash { + /** + * @param {WebAssembly.Instance} instance wasm instance + * @param {WebAssembly.Instance[]} instancesPool pool of instances + * @param {number} chunkSize size of data chunks passed to wasm + * @param {number} digestSize size of digest returned by wasm + */ + constructor(instance, instancesPool, chunkSize, digestSize) { + const exports = /** @type {EXPECTED_ANY} */ (instance.exports); + exports.init(); + this.exports = exports; + this.mem = Buffer.from(exports.memory.buffer, 0, 65536); + this.buffered = 0; + this.instancesPool = instancesPool; + this.chunkSize = chunkSize; + this.digestSize = digestSize; + } + + reset() { + this.buffered = 0; + this.exports.init(); + } + + /** + * @param {Buffer | string} data data + * @param {BufferEncoding=} encoding encoding + * @returns {this} itself + */ + update(data, encoding) { + if (typeof data === "string") { + while (data.length > MAX_SHORT_STRING) { + this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding); + data = data.slice(MAX_SHORT_STRING); + } + this._updateWithShortString(data, encoding); + return this; + } + this._updateWithBuffer(data); + return this; + } + + /** + * @param {string} data data + * @param {BufferEncoding=} encoding encoding + * @returns {void} + */ + _updateWithShortString(data, encoding) { + const { exports, buffered, mem, chunkSize } = this; + let endPos; + if (data.length < 70) { + // eslint-disable-next-line unicorn/text-encoding-identifier-case + if (!encoding || encoding === "utf-8" || encoding === "utf8") { + endPos = buffered; + for (let i = 0; i < data.length; i++) { + const cc = data.charCodeAt(i); + if (cc < 0x80) { + mem[endPos++] = cc; + } else if (cc < 0x800) { + mem[endPos] = (cc >> 6) | 0xc0; + mem[endPos + 1] = (cc & 0x3f) | 0x80; + endPos += 2; + } else { + // bail-out for weird chars + endPos += mem.write(data.slice(i), endPos, encoding); + break; + } + } + } else if (encoding === "latin1") { + endPos = buffered; + for (let i = 0; i < data.length; i++) { + const cc = data.charCodeAt(i); + mem[endPos++] = cc; + } + } else { + endPos = buffered + mem.write(data, buffered, encoding); + } + } else { + endPos = buffered + mem.write(data, buffered, encoding); + } + if (endPos < chunkSize) { + this.buffered = endPos; + } else { + const l = endPos & ~(this.chunkSize - 1); + exports.update(l); + const newBuffered = endPos - l; + this.buffered = newBuffered; + if (newBuffered > 0) mem.copyWithin(0, l, endPos); + } + } + + /** + * @param {Buffer} data data + * @returns {void} + */ + _updateWithBuffer(data) { + const { exports, buffered, mem } = this; + const length = data.length; + if (buffered + length < this.chunkSize) { + data.copy(mem, buffered, 0, length); + this.buffered += length; + } else { + const l = (buffered + length) & ~(this.chunkSize - 1); + if (l > 65536) { + let i = 65536 - buffered; + data.copy(mem, buffered, 0, i); + exports.update(65536); + const stop = l - buffered - 65536; + while (i < stop) { + data.copy(mem, 0, i, i + 65536); + exports.update(65536); + i += 65536; + } + data.copy(mem, 0, i, l - buffered); + exports.update(l - buffered - i); + } else { + data.copy(mem, buffered, 0, l - buffered); + exports.update(l); + } + const newBuffered = length + buffered - l; + this.buffered = newBuffered; + if (newBuffered > 0) data.copy(mem, 0, length - newBuffered, length); + } + } + + /** + * @param {BufferEncoding} type type + * @returns {Buffer | string} digest + */ + digest(type) { + const { exports, buffered, mem, digestSize } = this; + exports.final(buffered); + this.instancesPool.push(this); + const hex = mem.toString("latin1", 0, digestSize); + if (type === "hex") return hex; + if (type === "binary" || !type) return Buffer.from(hex, "hex"); + return Buffer.from(hex, "hex").toString(type); + } +} + +/** + * @param {WebAssembly.Module} wasmModule wasm module + * @param {WasmHash[]} instancesPool pool of instances + * @param {number} chunkSize size of data chunks passed to wasm + * @param {number} digestSize size of digest returned by wasm + * @returns {WasmHash} wasm hash + */ +const create = (wasmModule, instancesPool, chunkSize, digestSize) => { + if (instancesPool.length > 0) { + const old = /** @type {WasmHash} */ (instancesPool.pop()); + old.reset(); + return old; + } + + return new WasmHash( + new WebAssembly.Instance(wasmModule), + instancesPool, + chunkSize, + digestSize + ); +}; + +module.exports = create; +module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/xxhash64.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/xxhash64.js new file mode 100644 index 0000000000000000000000000000000000000000..b9262b8753ceec6b80f56f37101d15fa79058b4f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/hash/xxhash64.js @@ -0,0 +1,20 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const create = require("./wasm-hash"); + +// #region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1 +const xxhash64 = new WebAssembly.Module( + Buffer.from( + // 1160 bytes + "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACqgIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAFBIGoiASAASQ0ACyACJAAgAyQBIAQkAiAFJAMLngYCAn8CfiMEQgBSBH4jAEIBiSMBQgeJfCMCQgyJfCMDQhKJfCMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IwFCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0jAkLP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSMDQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9BULFz9my8eW66icLIwQgAK18fCEDA0AgAUEIaiICIABNBEAgAyABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQMgAiEBDAELCyABQQRqIgIgAE0EQCADIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCEDIAIhAQsDQCAAIAFHBEAgAyABMQAAQsXP2bLx5brqJ36FQguJQoeVr6+Ytt6bnn9+IQMgAUEBaiEBDAELC0EAIAMgA0IhiIVCz9bTvtLHq9lCfiIDQh2IIAOFQvnz3fGZ9pmrFn4iA0IgiCADhSIDQiCIIgRC//8Dg0IghiAEQoCA/P8Pg0IQiIQiBEL/gYCA8B+DQhCGIARCgP6DgIDgP4NCCIiEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIANC/////w+DIgNC//8Dg0IghiADQoCA/P8Pg0IQiIQiA0L/gYCA8B+DQhCGIANCgP6DgIDgP4NCCIiEIgNCj4C8gPCBwAeDQgiGIANC8IHAh4CegPgAg0IEiIQiA0KGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gA0Kw4MCBg4aMmDCEfDcDAAs=", + "base64" + ) +); +// #endregion + +module.exports = create.bind(null, xxhash64, [], 32, 16); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/identifier.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/identifier.js new file mode 100644 index 0000000000000000000000000000000000000000..1bcdc51a077c7a38075bd43041b3db45c965e55a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/identifier.js @@ -0,0 +1,401 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const path = require("path"); + +const WINDOWS_ABS_PATH_REGEXP = /^[a-zA-Z]:[\\/]/; +const SEGMENTS_SPLIT_REGEXP = /([|!])/; +const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g; + +/** + * @param {string} relativePath relative path + * @returns {string} request + */ +const relativePathToRequest = (relativePath) => { + if (relativePath === "") return "./."; + if (relativePath === "..") return "../."; + if (relativePath.startsWith("../")) return relativePath; + return `./${relativePath}`; +}; + +/** + * @param {string} context context for relative path + * @param {string} maybeAbsolutePath path to make relative + * @returns {string} relative path in request style + */ +const absoluteToRequest = (context, maybeAbsolutePath) => { + if (maybeAbsolutePath[0] === "/") { + if ( + maybeAbsolutePath.length > 1 && + maybeAbsolutePath[maybeAbsolutePath.length - 1] === "/" + ) { + // this 'path' is actually a regexp generated by dynamic requires. + // Don't treat it as an absolute path. + return maybeAbsolutePath; + } + + const querySplitPos = maybeAbsolutePath.indexOf("?"); + let resource = + querySplitPos === -1 + ? maybeAbsolutePath + : maybeAbsolutePath.slice(0, querySplitPos); + resource = relativePathToRequest(path.posix.relative(context, resource)); + return querySplitPos === -1 + ? resource + : resource + maybeAbsolutePath.slice(querySplitPos); + } + + if (WINDOWS_ABS_PATH_REGEXP.test(maybeAbsolutePath)) { + const querySplitPos = maybeAbsolutePath.indexOf("?"); + let resource = + querySplitPos === -1 + ? maybeAbsolutePath + : maybeAbsolutePath.slice(0, querySplitPos); + resource = path.win32.relative(context, resource); + if (!WINDOWS_ABS_PATH_REGEXP.test(resource)) { + resource = relativePathToRequest( + resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/") + ); + } + return querySplitPos === -1 + ? resource + : resource + maybeAbsolutePath.slice(querySplitPos); + } + + // not an absolute path + return maybeAbsolutePath; +}; + +/** + * @param {string} context context for relative path + * @param {string} relativePath path + * @returns {string} absolute path + */ +const requestToAbsolute = (context, relativePath) => { + if (relativePath.startsWith("./") || relativePath.startsWith("../")) { + return path.join(context, relativePath); + } + return relativePath; +}; + +/** @typedef {EXPECTED_OBJECT} AssociatedObjectForCache */ + +/** + * @template T + * @typedef {(value: string, cache?: AssociatedObjectForCache) => T} MakeCacheableResult + */ + +/** + * @template T + * @typedef {(value: string) => T} BindCacheResultFn + */ + +/** + * @template T + * @typedef {(cache: AssociatedObjectForCache) => BindCacheResultFn} BindCache + */ + +/** + * @template T + * @param {((value: string) => T)} realFn real function + * @returns {MakeCacheableResult & { bindCache: BindCache }} cacheable function + */ +const makeCacheable = (realFn) => { + /** + * @template T + * @typedef {Map} CacheItem + */ + /** @type {WeakMap>} */ + const cache = new WeakMap(); + + /** + * @param {AssociatedObjectForCache} associatedObjectForCache an object to which the cache will be attached + * @returns {CacheItem} cache item + */ + const getCache = (associatedObjectForCache) => { + const entry = cache.get(associatedObjectForCache); + if (entry !== undefined) return entry; + /** @type {Map} */ + const map = new Map(); + cache.set(associatedObjectForCache, map); + return map; + }; + + /** @type {MakeCacheableResult & { bindCache: BindCache }} */ + const fn = (str, associatedObjectForCache) => { + if (!associatedObjectForCache) return realFn(str); + const cache = getCache(associatedObjectForCache); + const entry = cache.get(str); + if (entry !== undefined) return entry; + const result = realFn(str); + cache.set(str, result); + return result; + }; + + /** @type {BindCache} */ + fn.bindCache = (associatedObjectForCache) => { + const cache = getCache(associatedObjectForCache); + /** + * @param {string} str string + * @returns {T} value + */ + return (str) => { + const entry = cache.get(str); + if (entry !== undefined) return entry; + const result = realFn(str); + cache.set(str, result); + return result; + }; + }; + + return fn; +}; + +/** @typedef {(context: string, value: string, associatedObjectForCache?: AssociatedObjectForCache) => string} MakeCacheableWithContextResult */ +/** @typedef {(context: string, value: string) => string} BindCacheForContextResultFn */ +/** @typedef {(value: string) => string} BindContextCacheForContextResultFn */ +/** @typedef {(associatedObjectForCache?: AssociatedObjectForCache) => BindCacheForContextResultFn} BindCacheForContext */ +/** @typedef {(value: string, associatedObjectForCache?: AssociatedObjectForCache) => BindContextCacheForContextResultFn} BindContextCacheForContext */ + +/** + * @param {(context: string, identifier: string) => string} fn function + * @returns {MakeCacheableWithContextResult & { bindCache: BindCacheForContext, bindContextCache: BindContextCacheForContext }} cacheable function with context + */ +const makeCacheableWithContext = (fn) => { + /** @type {WeakMap>>} */ + const cache = new WeakMap(); + + /** @type {MakeCacheableWithContextResult & { bindCache: BindCacheForContext, bindContextCache: BindContextCacheForContext }} */ + const cachedFn = (context, identifier, associatedObjectForCache) => { + if (!associatedObjectForCache) return fn(context, identifier); + + let innerCache = cache.get(associatedObjectForCache); + if (innerCache === undefined) { + innerCache = new Map(); + cache.set(associatedObjectForCache, innerCache); + } + + let cachedResult; + let innerSubCache = innerCache.get(context); + if (innerSubCache === undefined) { + innerCache.set(context, (innerSubCache = new Map())); + } else { + cachedResult = innerSubCache.get(identifier); + } + + if (cachedResult !== undefined) { + return cachedResult; + } + const result = fn(context, identifier); + innerSubCache.set(identifier, result); + return result; + }; + + /** @type {BindCacheForContext} */ + cachedFn.bindCache = (associatedObjectForCache) => { + let innerCache; + if (associatedObjectForCache) { + innerCache = cache.get(associatedObjectForCache); + if (innerCache === undefined) { + innerCache = new Map(); + cache.set(associatedObjectForCache, innerCache); + } + } else { + innerCache = new Map(); + } + + /** + * @param {string} context context used to create relative path + * @param {string} identifier identifier used to create relative path + * @returns {string} the returned relative path + */ + const boundFn = (context, identifier) => { + let cachedResult; + let innerSubCache = innerCache.get(context); + if (innerSubCache === undefined) { + innerCache.set(context, (innerSubCache = new Map())); + } else { + cachedResult = innerSubCache.get(identifier); + } + + if (cachedResult !== undefined) { + return cachedResult; + } + const result = fn(context, identifier); + innerSubCache.set(identifier, result); + return result; + }; + + return boundFn; + }; + + /** @type {BindContextCacheForContext} */ + cachedFn.bindContextCache = (context, associatedObjectForCache) => { + let innerSubCache; + if (associatedObjectForCache) { + let innerCache = cache.get(associatedObjectForCache); + if (innerCache === undefined) { + innerCache = new Map(); + cache.set(associatedObjectForCache, innerCache); + } + + innerSubCache = innerCache.get(context); + if (innerSubCache === undefined) { + innerCache.set(context, (innerSubCache = new Map())); + } + } else { + innerSubCache = new Map(); + } + + /** + * @param {string} identifier identifier used to create relative path + * @returns {string} the returned relative path + */ + const boundFn = (identifier) => { + const cachedResult = innerSubCache.get(identifier); + if (cachedResult !== undefined) { + return cachedResult; + } + const result = fn(context, identifier); + innerSubCache.set(identifier, result); + return result; + }; + + return boundFn; + }; + + return cachedFn; +}; + +/** + * @param {string} context context for relative path + * @param {string} identifier identifier for path + * @returns {string} a converted relative path + */ +const _makePathsRelative = (context, identifier) => + identifier + .split(SEGMENTS_SPLIT_REGEXP) + .map((str) => absoluteToRequest(context, str)) + .join(""); + +/** + * @param {string} context context for relative path + * @param {string} identifier identifier for path + * @returns {string} a converted relative path + */ +const _makePathsAbsolute = (context, identifier) => + identifier + .split(SEGMENTS_SPLIT_REGEXP) + .map((str) => requestToAbsolute(context, str)) + .join(""); + +/** + * @param {string} context absolute context path + * @param {string} request any request string may containing absolute paths, query string, etc. + * @returns {string} a new request string avoiding absolute paths when possible + */ +const _contextify = (context, request) => + request + .split("!") + .map((r) => absoluteToRequest(context, r)) + .join("!"); + +const contextify = makeCacheableWithContext(_contextify); + +/** + * @param {string} context absolute context path + * @param {string} request any request string + * @returns {string} a new request string using absolute paths when possible + */ +const _absolutify = (context, request) => + request + .split("!") + .map((r) => requestToAbsolute(context, r)) + .join("!"); + +const absolutify = makeCacheableWithContext(_absolutify); + +const PATH_QUERY_FRAGMENT_REGEXP = + /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; +const PATH_QUERY_REGEXP = /^((?:\0.|[^?\0])*)(\?.*)?$/; + +/** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */ +/** @typedef {{ resource: string, path: string, query: string }} ParsedResourceWithoutFragment */ + +/** + * @param {string} str the path with query and fragment + * @returns {ParsedResource} parsed parts + */ +const _parseResource = (str) => { + const match = + /** @type {[string, string, string | undefined, string | undefined]} */ + (/** @type {unknown} */ (PATH_QUERY_FRAGMENT_REGEXP.exec(str))); + return { + resource: str, + path: match[1].replace(/\0(.)/g, "$1"), + query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", + fragment: match[3] || "" + }; +}; + +/** + * Parse resource, skips fragment part + * @param {string} str the path with query and fragment + * @returns {ParsedResourceWithoutFragment} parsed parts + */ +const _parseResourceWithoutFragment = (str) => { + const match = + /** @type {[string, string, string | undefined]} */ + (/** @type {unknown} */ (PATH_QUERY_REGEXP.exec(str))); + return { + resource: str, + path: match[1].replace(/\0(.)/g, "$1"), + query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "" + }; +}; + +/** + * @param {string} filename the filename which should be undone + * @param {string} outputPath the output path that is restored (only relevant when filename contains "..") + * @param {boolean} enforceRelative true returns ./ for empty paths + * @returns {string} repeated ../ to leave the directory of the provided filename to be back on output dir + */ +const getUndoPath = (filename, outputPath, enforceRelative) => { + let depth = -1; + let append = ""; + outputPath = outputPath.replace(/[\\/]$/, ""); + for (const part of filename.split(/[/\\]+/)) { + if (part === "..") { + if (depth > -1) { + depth--; + } else { + const i = outputPath.lastIndexOf("/"); + const j = outputPath.lastIndexOf("\\"); + const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j); + if (pos < 0) return `${outputPath}/`; + append = `${outputPath.slice(pos + 1)}/${append}`; + outputPath = outputPath.slice(0, pos); + } + } else if (part !== ".") { + depth++; + } + } + return depth > 0 + ? `${"../".repeat(depth)}${append}` + : enforceRelative + ? `./${append}` + : append; +}; + +module.exports.absolutify = absolutify; +module.exports.contextify = contextify; +module.exports.getUndoPath = getUndoPath; +module.exports.makePathsAbsolute = makeCacheableWithContext(_makePathsAbsolute); +module.exports.makePathsRelative = makeCacheableWithContext(_makePathsRelative); +module.exports.parseResource = makeCacheable(_parseResource); +module.exports.parseResourceWithoutFragment = makeCacheable( + _parseResourceWithoutFragment +); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/internalSerializables.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/internalSerializables.js new file mode 100644 index 0000000000000000000000000000000000000000..964a5c2657053098b613f2884f9d2075a223b594 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/internalSerializables.js @@ -0,0 +1,226 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +// We need to include a list of requires here +// to allow webpack to be bundled with only static requires +// We could use a dynamic require(`../${request}`) but this +// would include too many modules and not every tool is able +// to process this +module.exports = { + AsyncDependenciesBlock: () => require("../AsyncDependenciesBlock"), + CommentCompilationWarning: () => require("../CommentCompilationWarning"), + ContextModule: () => require("../ContextModule"), + "cache/PackFileCacheStrategy": () => + require("../cache/PackFileCacheStrategy"), + "cache/ResolverCachePlugin": () => require("../cache/ResolverCachePlugin"), + "container/ContainerEntryDependency": () => + require("../container/ContainerEntryDependency"), + "container/ContainerEntryModule": () => + require("../container/ContainerEntryModule"), + "container/ContainerExposedDependency": () => + require("../container/ContainerExposedDependency"), + "container/FallbackDependency": () => + require("../container/FallbackDependency"), + "container/FallbackItemDependency": () => + require("../container/FallbackItemDependency"), + "container/FallbackModule": () => require("../container/FallbackModule"), + "container/RemoteModule": () => require("../container/RemoteModule"), + "container/RemoteToExternalDependency": () => + require("../container/RemoteToExternalDependency"), + "dependencies/AMDDefineDependency": () => + require("../dependencies/AMDDefineDependency"), + "dependencies/AMDRequireArrayDependency": () => + require("../dependencies/AMDRequireArrayDependency"), + "dependencies/AMDRequireContextDependency": () => + require("../dependencies/AMDRequireContextDependency"), + "dependencies/AMDRequireDependenciesBlock": () => + require("../dependencies/AMDRequireDependenciesBlock"), + "dependencies/AMDRequireDependency": () => + require("../dependencies/AMDRequireDependency"), + "dependencies/AMDRequireItemDependency": () => + require("../dependencies/AMDRequireItemDependency"), + "dependencies/CachedConstDependency": () => + require("../dependencies/CachedConstDependency"), + "dependencies/ExternalModuleDependency": () => + require("../dependencies/ExternalModuleDependency"), + "dependencies/ExternalModuleInitFragment": () => + require("../dependencies/ExternalModuleInitFragment"), + "dependencies/CreateScriptUrlDependency": () => + require("../dependencies/CreateScriptUrlDependency"), + "dependencies/CommonJsRequireContextDependency": () => + require("../dependencies/CommonJsRequireContextDependency"), + "dependencies/CommonJsExportRequireDependency": () => + require("../dependencies/CommonJsExportRequireDependency"), + "dependencies/CommonJsExportsDependency": () => + require("../dependencies/CommonJsExportsDependency"), + "dependencies/CommonJsFullRequireDependency": () => + require("../dependencies/CommonJsFullRequireDependency"), + "dependencies/CommonJsRequireDependency": () => + require("../dependencies/CommonJsRequireDependency"), + "dependencies/CommonJsSelfReferenceDependency": () => + require("../dependencies/CommonJsSelfReferenceDependency"), + "dependencies/ConstDependency": () => + require("../dependencies/ConstDependency"), + "dependencies/ContextDependency": () => + require("../dependencies/ContextDependency"), + "dependencies/ContextElementDependency": () => + require("../dependencies/ContextElementDependency"), + "dependencies/CriticalDependencyWarning": () => + require("../dependencies/CriticalDependencyWarning"), + "dependencies/CssImportDependency": () => + require("../dependencies/CssImportDependency"), + "dependencies/CssLocalIdentifierDependency": () => + require("../dependencies/CssLocalIdentifierDependency"), + "dependencies/CssSelfLocalIdentifierDependency": () => + require("../dependencies/CssSelfLocalIdentifierDependency"), + "dependencies/CssIcssImportDependency": () => + require("../dependencies/CssIcssImportDependency"), + "dependencies/CssIcssExportDependency": () => + require("../dependencies/CssIcssExportDependency"), + "dependencies/CssUrlDependency": () => + require("../dependencies/CssUrlDependency"), + "dependencies/CssIcssSymbolDependency": () => + require("../dependencies/CssIcssSymbolDependency"), + "dependencies/DelegatedSourceDependency": () => + require("../dependencies/DelegatedSourceDependency"), + "dependencies/DllEntryDependency": () => + require("../dependencies/DllEntryDependency"), + "dependencies/EntryDependency": () => + require("../dependencies/EntryDependency"), + "dependencies/ExportsInfoDependency": () => + require("../dependencies/ExportsInfoDependency"), + "dependencies/HarmonyAcceptDependency": () => + require("../dependencies/HarmonyAcceptDependency"), + "dependencies/HarmonyAcceptImportDependency": () => + require("../dependencies/HarmonyAcceptImportDependency"), + "dependencies/HarmonyCompatibilityDependency": () => + require("../dependencies/HarmonyCompatibilityDependency"), + "dependencies/HarmonyExportExpressionDependency": () => + require("../dependencies/HarmonyExportExpressionDependency"), + "dependencies/HarmonyExportHeaderDependency": () => + require("../dependencies/HarmonyExportHeaderDependency"), + "dependencies/HarmonyExportImportedSpecifierDependency": () => + require("../dependencies/HarmonyExportImportedSpecifierDependency"), + "dependencies/HarmonyExportSpecifierDependency": () => + require("../dependencies/HarmonyExportSpecifierDependency"), + "dependencies/HarmonyImportSideEffectDependency": () => + require("../dependencies/HarmonyImportSideEffectDependency"), + "dependencies/HarmonyImportSpecifierDependency": () => + require("../dependencies/HarmonyImportSpecifierDependency"), + "dependencies/HarmonyEvaluatedImportSpecifierDependency": () => + require("../dependencies/HarmonyEvaluatedImportSpecifierDependency"), + "dependencies/ImportContextDependency": () => + require("../dependencies/ImportContextDependency"), + "dependencies/ImportDependency": () => + require("../dependencies/ImportDependency"), + "dependencies/ImportEagerDependency": () => + require("../dependencies/ImportEagerDependency"), + "dependencies/ImportWeakDependency": () => + require("../dependencies/ImportWeakDependency"), + "dependencies/JsonExportsDependency": () => + require("../dependencies/JsonExportsDependency"), + "dependencies/LocalModule": () => require("../dependencies/LocalModule"), + "dependencies/LocalModuleDependency": () => + require("../dependencies/LocalModuleDependency"), + "dependencies/ModuleDecoratorDependency": () => + require("../dependencies/ModuleDecoratorDependency"), + "dependencies/ModuleHotAcceptDependency": () => + require("../dependencies/ModuleHotAcceptDependency"), + "dependencies/ModuleHotDeclineDependency": () => + require("../dependencies/ModuleHotDeclineDependency"), + "dependencies/ImportMetaHotAcceptDependency": () => + require("../dependencies/ImportMetaHotAcceptDependency"), + "dependencies/ImportMetaHotDeclineDependency": () => + require("../dependencies/ImportMetaHotDeclineDependency"), + "dependencies/ImportMetaContextDependency": () => + require("../dependencies/ImportMetaContextDependency"), + "dependencies/ProvidedDependency": () => + require("../dependencies/ProvidedDependency"), + "dependencies/PureExpressionDependency": () => + require("../dependencies/PureExpressionDependency"), + "dependencies/RequireContextDependency": () => + require("../dependencies/RequireContextDependency"), + "dependencies/RequireEnsureDependenciesBlock": () => + require("../dependencies/RequireEnsureDependenciesBlock"), + "dependencies/RequireEnsureDependency": () => + require("../dependencies/RequireEnsureDependency"), + "dependencies/RequireEnsureItemDependency": () => + require("../dependencies/RequireEnsureItemDependency"), + "dependencies/RequireHeaderDependency": () => + require("../dependencies/RequireHeaderDependency"), + "dependencies/RequireIncludeDependency": () => + require("../dependencies/RequireIncludeDependency"), + "dependencies/RequireIncludeDependencyParserPlugin": () => + require("../dependencies/RequireIncludeDependencyParserPlugin"), + "dependencies/RequireResolveContextDependency": () => + require("../dependencies/RequireResolveContextDependency"), + "dependencies/RequireResolveDependency": () => + require("../dependencies/RequireResolveDependency"), + "dependencies/RequireResolveHeaderDependency": () => + require("../dependencies/RequireResolveHeaderDependency"), + "dependencies/RuntimeRequirementsDependency": () => + require("../dependencies/RuntimeRequirementsDependency"), + "dependencies/StaticExportsDependency": () => + require("../dependencies/StaticExportsDependency"), + "dependencies/SystemPlugin": () => require("../dependencies/SystemPlugin"), + "dependencies/UnsupportedDependency": () => + require("../dependencies/UnsupportedDependency"), + "dependencies/URLDependency": () => require("../dependencies/URLDependency"), + "dependencies/URLContextDependency": () => + require("../dependencies/URLContextDependency"), + "dependencies/WebAssemblyExportImportedDependency": () => + require("../dependencies/WebAssemblyExportImportedDependency"), + "dependencies/WebAssemblyImportDependency": () => + require("../dependencies/WebAssemblyImportDependency"), + "dependencies/WebpackIsIncludedDependency": () => + require("../dependencies/WebpackIsIncludedDependency"), + "dependencies/WorkerDependency": () => + require("../dependencies/WorkerDependency"), + "json/JsonData": () => require("../json/JsonData"), + "optimize/ConcatenatedModule": () => + require("../optimize/ConcatenatedModule"), + DelegatedModule: () => require("../DelegatedModule"), + DependenciesBlock: () => require("../DependenciesBlock"), + DllModule: () => require("../DllModule"), + ExternalModule: () => require("../ExternalModule"), + FileSystemInfo: () => require("../FileSystemInfo"), + InitFragment: () => require("../InitFragment"), + InvalidDependenciesModuleWarning: () => + require("../InvalidDependenciesModuleWarning"), + Module: () => require("../Module"), + ModuleBuildError: () => require("../ModuleBuildError"), + ModuleDependencyWarning: () => require("../ModuleDependencyWarning"), + ModuleError: () => require("../ModuleError"), + ModuleGraph: () => require("../ModuleGraph"), + ModuleParseError: () => require("../ModuleParseError"), + ModuleWarning: () => require("../ModuleWarning"), + NormalModule: () => require("../NormalModule"), + CssModule: () => require("../CssModule"), + RawDataUrlModule: () => require("../asset/RawDataUrlModule"), + RawModule: () => require("../RawModule"), + "sharing/ConsumeSharedModule": () => + require("../sharing/ConsumeSharedModule"), + "sharing/ConsumeSharedFallbackDependency": () => + require("../sharing/ConsumeSharedFallbackDependency"), + "sharing/ProvideSharedModule": () => + require("../sharing/ProvideSharedModule"), + "sharing/ProvideSharedDependency": () => + require("../sharing/ProvideSharedDependency"), + "sharing/ProvideForSharedDependency": () => + require("../sharing/ProvideForSharedDependency"), + UnsupportedFeatureWarning: () => require("../UnsupportedFeatureWarning"), + "util/LazySet": () => require("../util/LazySet"), + UnhandledSchemeError: () => require("../UnhandledSchemeError"), + NodeStuffInWebError: () => require("../NodeStuffInWebError"), + EnvironmentNotSupportAsyncWarning: () => + require("../EnvironmentNotSupportAsyncWarning"), + WebpackError: () => require("../WebpackError"), + + "util/registerExternalSerializer": () => { + // already registered + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/magicComment.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/magicComment.js new file mode 100644 index 0000000000000000000000000000000000000000..173dfe53f8600a6c3996117d7cc1f1e85ae27944 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/magicComment.js @@ -0,0 +1,25 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Alexander Akait @alexander-akait +*/ + +"use strict"; + +const memoize = require("./memoize"); + +const getVm = memoize(() => require("vm")); + +// regexp to match at least one "magic comment" +module.exports.createMagicCommentContext = () => + getVm().createContext(undefined, { + name: "Webpack Magic Comment Parser", + codeGeneration: { strings: false, wasm: false } + }); +module.exports.webpackCommentRegExp = new RegExp( + /(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/ +); + +// regexp to match at least one "magic comment" +/** + * @returns {import("vm").Context} magic comment context + */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/makeSerializable.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/makeSerializable.js new file mode 100644 index 0000000000000000000000000000000000000000..c5f08c113a67b99b8739d4a7bdba6ef06d783645 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/makeSerializable.js @@ -0,0 +1,60 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const { register } = require("./serialization"); + +/** @typedef {import("../serialization/ObjectMiddleware").Constructor} Constructor */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +/** @typedef {{ serialize: (context: ObjectSerializerContext) => void, deserialize: (context: ObjectDeserializerContext) => void }} SerializableClass */ +/** + * @template {SerializableClass} T + * @typedef {(new (...params: EXPECTED_ANY[]) => T) & { deserialize?: (context: ObjectDeserializerContext) => T }} SerializableClassConstructor + */ + +/** + * @template {SerializableClass} T + */ +class ClassSerializer { + /** + * @param {SerializableClassConstructor} Constructor constructor + */ + constructor(Constructor) { + this.Constructor = Constructor; + } + + /** + * @param {T} obj obj + * @param {ObjectSerializerContext} context context + */ + serialize(obj, context) { + obj.serialize(context); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {T} obj + */ + deserialize(context) { + if (typeof this.Constructor.deserialize === "function") { + return this.Constructor.deserialize(context); + } + const obj = new this.Constructor(); + obj.deserialize(context); + return obj; + } +} + +/** + * @template {Constructor} T + * @param {T} Constructor the constructor + * @param {string} request the request which will be required when deserializing + * @param {string | null=} name the name to make multiple serializer unique when sharing a request + */ +module.exports = (Constructor, request, name = null) => { + register(Constructor, request, name, new ClassSerializer(Constructor)); +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/memoize.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/memoize.js new file mode 100644 index 0000000000000000000000000000000000000000..478d670965184eeb4bf1c02a304ac3032463d6bb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/memoize.js @@ -0,0 +1,36 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** + * @template T + * @typedef {() => T} FunctionReturning + */ + +/** + * @template T + * @param {FunctionReturning} fn memorized function + * @returns {FunctionReturning} new function + */ +const memoize = (fn) => { + let cache = false; + /** @type {T | undefined} */ + let result; + return () => { + if (cache) { + return /** @type {T} */ (result); + } + + result = fn(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + /** @type {FunctionReturning | undefined} */ + (fn) = undefined; + return /** @type {T} */ (result); + }; +}; + +module.exports = memoize; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/nonNumericOnlyHash.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/nonNumericOnlyHash.js new file mode 100644 index 0000000000000000000000000000000000000000..ec8ca745ffc6e3d8554db18339b4221767625dc9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/nonNumericOnlyHash.js @@ -0,0 +1,22 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const A_CODE = "a".charCodeAt(0); + +/** + * @param {string} hash hash + * @param {number} hashLength hash length + * @returns {string} returns hash that has at least one non numeric char + */ +module.exports = (hash, hashLength) => { + if (hashLength < 1) return ""; + const slice = hash.slice(0, hashLength); + if (/[^\d]/.test(slice)) return slice; + return `${String.fromCharCode( + A_CODE + (Number.parseInt(hash[0], 10) % 6) + )}${slice.slice(1)}`; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/numberHash.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/numberHash.js new file mode 100644 index 0000000000000000000000000000000000000000..950d14bf8bb2e4a70678a001f9562b87ecbb5174 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/numberHash.js @@ -0,0 +1,95 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * Threshold for switching from 32-bit to 64-bit hashing. This is selected to ensure that the bias towards lower modulo results when using 32-bit hashing is <0.5%. + * @type {number} + */ +const FNV_64_THRESHOLD = 1 << 24; + +/** + * The FNV-1a offset basis for 32-bit hash values. + * @type {number} + */ +const FNV_OFFSET_32 = 2166136261; +/** + * The FNV-1a prime for 32-bit hash values. + * @type {number} + */ +const FNV_PRIME_32 = 16777619; +/** + * The mask for a positive 32-bit signed integer. + * @type {number} + */ +const MASK_31 = 0x7fffffff; + +/** + * The FNV-1a offset basis for 64-bit hash values. + * @type {bigint} + */ +const FNV_OFFSET_64 = BigInt("0xCBF29CE484222325"); +/** + * The FNV-1a prime for 64-bit hash values. + * @type {bigint} + */ +const FNV_PRIME_64 = BigInt("0x100000001B3"); + +/** + * Computes a 32-bit FNV-1a hash value for the given string. + * See https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function + * @param {string} str The input string to hash + * @returns {number} - The computed hash value. + */ +function fnv1a32(str) { + let hash = FNV_OFFSET_32; + for (let i = 0, len = str.length; i < len; i++) { + hash ^= str.charCodeAt(i); + // Use Math.imul to do c-style 32-bit multiplication and keep only the 32 least significant bits + hash = Math.imul(hash, FNV_PRIME_32); + } + // Force the result to be positive + return hash & MASK_31; +} + +/** + * Computes a 64-bit FNV-1a hash value for the given string. + * See https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function + * @param {string} str The input string to hash + * @returns {bigint} - The computed hash value. + */ +function fnv1a64(str) { + let hash = FNV_OFFSET_64; + for (let i = 0, len = str.length; i < len; i++) { + hash ^= BigInt(str.charCodeAt(i)); + hash = BigInt.asUintN(64, hash * FNV_PRIME_64); + } + return hash; +} + +/** + * Computes a hash value for the given string and range. This hashing algorithm is a modified + * version of the [FNV-1a algorithm](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function). + * It is optimized for speed and does **not** generate a cryptographic hash value. + * + * We use `numberHash` in `lib/ids/IdHelpers.js` to generate hash values for the module identifier. The generated + * hash is used as a prefix for the module id's to avoid collisions with other modules. + * @param {string} str The input string to hash. + * @param {number} range The range of the hash value (0 to range-1). + * @returns {number} - The computed hash value. + * @example + * ```js + * const numberHash = require("webpack/lib/util/numberHash"); + * numberHash("hello", 1000); // 73 + * numberHash("hello world"); // 72 + * ``` + */ +module.exports = (str, range) => { + if (range < FNV_64_THRESHOLD) { + return fnv1a32(str) % range; + } + return Number(fnv1a64(str) % BigInt(range)); +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/objectToMap.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/objectToMap.js new file mode 100644 index 0000000000000000000000000000000000000000..bb8c870eac3b39b0da381e007511035514d82d9f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/objectToMap.js @@ -0,0 +1,15 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +/** + * Convert an object into an ES6 map + * @template {object} T + * @param {T} obj any object type that works with Object.entries() + * @returns {Map} an ES6 Map of KV pairs + */ +module.exports = function objectToMap(obj) { + return new Map(Object.entries(obj)); +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/processAsyncTree.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/processAsyncTree.js new file mode 100644 index 0000000000000000000000000000000000000000..de3cf2aee84afae72930924887cbe0cf457d4e9f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/processAsyncTree.js @@ -0,0 +1,68 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @template T + * @template {Error} E + * @param {Iterable} items initial items + * @param {number} concurrency number of items running in parallel + * @param {(item: T, push: (item: T) => void, callback: (err?: E) => void) => void} processor worker which pushes more items + * @param {(err?: E) => void} callback all items processed + * @returns {void} + */ +const processAsyncTree = (items, concurrency, processor, callback) => { + const queue = [...items]; + if (queue.length === 0) return callback(); + let processing = 0; + let finished = false; + let processScheduled = true; + + /** + * @param {T} item item + */ + const push = (item) => { + queue.push(item); + if (!processScheduled && processing < concurrency) { + processScheduled = true; + process.nextTick(processQueue); + } + }; + + /** + * @param {E | null | undefined} err error + */ + const processorCallback = (err) => { + processing--; + if (err && !finished) { + finished = true; + callback(err); + return; + } + if (!processScheduled) { + processScheduled = true; + process.nextTick(processQueue); + } + }; + + const processQueue = () => { + if (finished) return; + while (processing < concurrency && queue.length > 0) { + processing++; + const item = /** @type {T} */ (queue.pop()); + processor(item, push, processorCallback); + } + processScheduled = false; + if (queue.length === 0 && processing === 0 && !finished) { + finished = true; + callback(); + } + }; + + processQueue(); +}; + +module.exports = processAsyncTree; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/propertyAccess.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/propertyAccess.js new file mode 100644 index 0000000000000000000000000000000000000000..10cdc5240ef0bee10de1d3c62d137877457d84a9 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/propertyAccess.js @@ -0,0 +1,30 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RESERVED_IDENTIFIER, SAFE_IDENTIFIER } = require("./propertyName"); + +/** + * @param {ArrayLike} properties properties + * @param {number} start start index + * @returns {string} chain of property accesses + */ +const propertyAccess = (properties, start = 0) => { + let str = ""; + for (let i = start; i < properties.length; i++) { + const p = properties[i]; + if (`${Number(p)}` === p) { + str += `[${p}]`; + } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFIER.has(p)) { + str += `.${p}`; + } else { + str += `[${JSON.stringify(p)}]`; + } + } + return str; +}; + +module.exports = propertyAccess; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/propertyName.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/propertyName.js new file mode 100644 index 0000000000000000000000000000000000000000..b2d8a8f72eb37df525c9f0c1676007cfcfe4ba5a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/propertyName.js @@ -0,0 +1,76 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/; +const RESERVED_IDENTIFIER = new Set([ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "export", + "extends", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "return", + "super", + "switch", + "this", + "throw", + "try", + "typeof", + "var", + "void", + "while", + "with", + "enum", + // strict mode + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "yield", + // module code + "await", + // skip future reserved keywords defined under ES1 till ES3 + // additional + "null", + "true", + "false" +]); + +/** + * @summary Returns a valid JS property name for the given property. + * Certain strings like "default", "null", and names with whitespace are not + * valid JS property names, so they are returned as strings. + * @param {string} prop property name to analyze + * @returns {string} valid JS property name + */ +const propertyName = (prop) => { + if (SAFE_IDENTIFIER.test(prop) && !RESERVED_IDENTIFIER.has(prop)) { + return prop; + } + return JSON.stringify(prop); +}; + +module.exports = { RESERVED_IDENTIFIER, SAFE_IDENTIFIER, propertyName }; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/registerExternalSerializer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/registerExternalSerializer.js new file mode 100644 index 0000000000000000000000000000000000000000..7b7d747bc0b7b34f57872c56d6ac00fdc07a9f3c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/registerExternalSerializer.js @@ -0,0 +1,333 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Position = require("acorn").Position; +const SourceLocation = require("acorn").SourceLocation; +const ValidationError = require("schema-utils").ValidationError; +const { + CachedSource, + ConcatSource, + OriginalSource, + PrefixSource, + RawSource, + ReplaceSource, + SourceMapSource +} = require("webpack-sources"); +const { register } = require("./serialization"); + +/** @typedef {import("acorn").Position} Position */ +/** @typedef {import("../Dependency").RealDependencyLocation} RealDependencyLocation */ +/** @typedef {import("../Dependency").SourcePosition} SourcePosition */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ + +const CURRENT_MODULE = "webpack/lib/util/registerExternalSerializer"; + +register( + CachedSource, + CURRENT_MODULE, + "webpack-sources/CachedSource", + new (class CachedSourceSerializer { + /** + * @param {CachedSource} source the cached source to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write, writeLazy }) { + if (writeLazy) { + writeLazy(source.originalLazy()); + } else { + write(source.original()); + } + write(source.getCachedData()); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {CachedSource} cached source + */ + deserialize({ read }) { + const source = read(); + const cachedData = read(); + return new CachedSource(source, cachedData); + } + })() +); + +register( + RawSource, + CURRENT_MODULE, + "webpack-sources/RawSource", + new (class RawSourceSerializer { + /** + * @param {RawSource} source the raw source to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.buffer()); + write(!source.isBuffer()); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {RawSource} raw source + */ + deserialize({ read }) { + const source = read(); + const convertToString = read(); + return new RawSource(source, convertToString); + } + })() +); + +register( + ConcatSource, + CURRENT_MODULE, + "webpack-sources/ConcatSource", + new (class ConcatSourceSerializer { + /** + * @param {ConcatSource} source the concat source to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.getChildren()); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {ConcatSource} concat source + */ + deserialize({ read }) { + const source = new ConcatSource(); + source.addAllSkipOptimizing(read()); + return source; + } + })() +); + +register( + PrefixSource, + CURRENT_MODULE, + "webpack-sources/PrefixSource", + new (class PrefixSourceSerializer { + /** + * @param {PrefixSource} source the prefix source to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.getPrefix()); + write(source.original()); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {PrefixSource} prefix source + */ + deserialize({ read }) { + return new PrefixSource(read(), read()); + } + })() +); + +register( + ReplaceSource, + CURRENT_MODULE, + "webpack-sources/ReplaceSource", + new (class ReplaceSourceSerializer { + /** + * @param {ReplaceSource} source the replace source to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.original()); + write(source.getName()); + const replacements = source.getReplacements(); + write(replacements.length); + for (const repl of replacements) { + write(repl.start); + write(repl.end); + } + for (const repl of replacements) { + write(repl.content); + write(repl.name); + } + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {ReplaceSource} replace source + */ + deserialize({ read }) { + const source = new ReplaceSource(read(), read()); + const len = read(); + const startEndBuffer = []; + for (let i = 0; i < len; i++) { + startEndBuffer.push(read(), read()); + } + let j = 0; + for (let i = 0; i < len; i++) { + source.replace( + startEndBuffer[j++], + startEndBuffer[j++], + read(), + read() + ); + } + return source; + } + })() +); + +register( + OriginalSource, + CURRENT_MODULE, + "webpack-sources/OriginalSource", + new (class OriginalSourceSerializer { + /** + * @param {OriginalSource} source the original source to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.buffer()); + write(source.getName()); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {OriginalSource} original source + */ + deserialize({ read }) { + const buffer = read(); + const name = read(); + return new OriginalSource(buffer, name); + } + })() +); + +register( + SourceLocation, + CURRENT_MODULE, + "acorn/SourceLocation", + new (class SourceLocationSerializer { + /** + * @param {SourceLocation} loc the location to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(loc, { write }) { + write(loc.start.line); + write(loc.start.column); + write(loc.end.line); + write(loc.end.column); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {RealDependencyLocation} location + */ + deserialize({ read }) { + return { + start: { + line: read(), + column: read() + }, + end: { + line: read(), + column: read() + } + }; + } + })() +); + +register( + Position, + CURRENT_MODULE, + "acorn/Position", + new (class PositionSerializer { + /** + * @param {Position} pos the position to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(pos, { write }) { + write(pos.line); + write(pos.column); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {SourcePosition} position + */ + deserialize({ read }) { + return { + line: read(), + column: read() + }; + } + })() +); + +register( + SourceMapSource, + CURRENT_MODULE, + "webpack-sources/SourceMapSource", + new (class SourceMapSourceSerializer { + /** + * @param {SourceMapSource} source the source map source to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.getArgsAsBuffers()); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {SourceMapSource} source source map source + */ + deserialize({ read }) { + // @ts-expect-error + return new SourceMapSource(...read()); + } + })() +); + +register( + ValidationError, + CURRENT_MODULE, + "schema-utils/ValidationError", + new (class ValidationErrorSerializer { + /** + * @param {ValidationError} error the source map source to be serialized + * @param {ObjectSerializerContext} context context + * @returns {void} + */ + serialize(error, { write }) { + write(error.errors); + write(error.schema); + write({ + name: error.headerName, + baseDataPath: error.baseDataPath, + postFormatter: error.postFormatter + }); + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {ValidationError} error + */ + deserialize({ read }) { + return new ValidationError(read(), read(), read()); + } + })() +); diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/removeBOM.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/removeBOM.js new file mode 100644 index 0000000000000000000000000000000000000000..55cd64aac1041af10abca6a2de8c2fe25d6b5f54 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/removeBOM.js @@ -0,0 +1,25 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Alexander Akait @alexander-akait +*/ + +"use strict"; + +/** + * @param {string | Buffer} strOrBuffer string or buffer + * @returns {string | Buffer} result without BOM + */ +module.exports = (strOrBuffer) => { + if (typeof strOrBuffer === "string" && strOrBuffer.charCodeAt(0) === 0xfeff) { + return strOrBuffer.slice(1); + } else if ( + Buffer.isBuffer(strOrBuffer) && + strOrBuffer[0] === 0xef && + strOrBuffer[1] === 0xbb && + strOrBuffer[2] === 0xbf + ) { + return strOrBuffer.subarray(3); + } + + return strOrBuffer; +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/runtime.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..5a0a5078f6ebd63b9bc1c31a46e3e06c4ae3be94 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/runtime.js @@ -0,0 +1,703 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const SortableSet = require("./SortableSet"); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ + +/** @typedef {string | SortableSet | undefined} RuntimeSpec */ +/** @typedef {RuntimeSpec | boolean} RuntimeCondition */ + +/** + * @param {Compilation} compilation the compilation + * @param {string} name name of the entry + * @param {EntryOptions=} options optionally already received entry options + * @returns {RuntimeSpec} runtime + */ +const getEntryRuntime = (compilation, name, options) => { + let dependOn; + let runtime; + if (options) { + ({ dependOn, runtime } = options); + } else { + const entry = compilation.entries.get(name); + if (!entry) return name; + ({ dependOn, runtime } = entry.options); + } + if (dependOn) { + /** @type {RuntimeSpec} */ + let result; + const queue = new Set(dependOn); + for (const name of queue) { + const dep = compilation.entries.get(name); + if (!dep) continue; + const { dependOn, runtime } = dep.options; + if (dependOn) { + for (const name of dependOn) { + queue.add(name); + } + } else { + result = mergeRuntimeOwned(result, runtime || name); + } + } + return result || name; + } + return runtime || name; +}; + +/** + * @param {RuntimeSpec} runtime runtime + * @param {(runtime: string | undefined) => void} fn functor + * @param {boolean} deterministicOrder enforce a deterministic order + * @returns {void} + */ +const forEachRuntime = (runtime, fn, deterministicOrder = false) => { + if (runtime === undefined) { + fn(undefined); + } else if (typeof runtime === "string") { + fn(runtime); + } else { + if (deterministicOrder) runtime.sort(); + for (const r of runtime) { + fn(r); + } + } +}; + +/** + * @template T + * @param {SortableSet} set set + * @returns {string} runtime key + */ +const getRuntimesKey = (set) => { + set.sort(); + return [...set].join("\n"); +}; + +/** + * @param {RuntimeSpec} runtime runtime(s) + * @returns {string} key of runtimes + */ +const getRuntimeKey = (runtime) => { + if (runtime === undefined) return "*"; + if (typeof runtime === "string") return runtime; + return runtime.getFromUnorderedCache(getRuntimesKey); +}; + +/** + * @param {string} key key of runtimes + * @returns {RuntimeSpec} runtime(s) + */ +const keyToRuntime = (key) => { + if (key === "*") return; + const items = key.split("\n"); + if (items.length === 1) return items[0]; + return new SortableSet(items); +}; + +/** + * @template T + * @param {SortableSet} set set + * @returns {string} runtime string + */ +const getRuntimesString = (set) => { + set.sort(); + return [...set].join("+"); +}; + +/** + * @param {RuntimeSpec} runtime runtime(s) + * @returns {string} readable version + */ +const runtimeToString = (runtime) => { + if (runtime === undefined) return "*"; + if (typeof runtime === "string") return runtime; + return runtime.getFromUnorderedCache(getRuntimesString); +}; + +/** + * @param {RuntimeCondition} runtimeCondition runtime condition + * @returns {string} readable version + */ +const runtimeConditionToString = (runtimeCondition) => { + if (runtimeCondition === true) return "true"; + if (runtimeCondition === false) return "false"; + return runtimeToString(runtimeCondition); +}; + +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {boolean} true, when they are equal + */ +const runtimeEqual = (a, b) => { + if (a === b) { + return true; + } else if ( + a === undefined || + b === undefined || + typeof a === "string" || + typeof b === "string" + ) { + return false; + } else if (a.size !== b.size) { + return false; + } + a.sort(); + b.sort(); + const aIt = a[Symbol.iterator](); + const bIt = b[Symbol.iterator](); + for (;;) { + const aV = aIt.next(); + if (aV.done) return true; + const bV = bIt.next(); + if (aV.value !== bV.value) return false; + } +}; + +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {-1|0|1} compare + */ +const compareRuntime = (a, b) => { + if (a === b) { + return 0; + } else if (a === undefined) { + return -1; + } else if (b === undefined) { + return 1; + } + const aKey = getRuntimeKey(a); + const bKey = getRuntimeKey(b); + if (aKey < bKey) return -1; + if (aKey > bKey) return 1; + return 0; +}; + +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} merged + */ +const mergeRuntime = (a, b) => { + if (a === undefined) { + return b; + } else if (b === undefined) { + return a; + } else if (a === b) { + return a; + } else if (typeof a === "string") { + if (typeof b === "string") { + const set = new SortableSet(); + set.add(a); + set.add(b); + return set; + } else if (b.has(a)) { + return b; + } + const set = new SortableSet(b); + set.add(a); + return set; + } + if (typeof b === "string") { + if (a.has(b)) return a; + const set = new SortableSet(a); + set.add(b); + return set; + } + const set = new SortableSet(a); + for (const item of b) set.add(item); + if (set.size === a.size) return a; + return set; +}; + +/** + * @param {RuntimeCondition} a first + * @param {RuntimeCondition} b second + * @param {RuntimeSpec} runtime full runtime + * @returns {RuntimeCondition} result + */ +const mergeRuntimeCondition = (a, b, runtime) => { + if (a === false) return b; + if (b === false) return a; + if (a === true || b === true) return true; + const merged = mergeRuntime(a, b); + if (merged === undefined) return; + if (typeof merged === "string") { + if (typeof runtime === "string" && merged === runtime) return true; + return merged; + } + if (typeof runtime === "string" || runtime === undefined) return merged; + if (merged.size === runtime.size) return true; + return merged; +}; + +/** + * @param {RuntimeSpec | true} a first + * @param {RuntimeSpec | true} b second + * @param {RuntimeSpec} runtime full runtime + * @returns {RuntimeSpec | true} result + */ +const mergeRuntimeConditionNonFalse = (a, b, runtime) => { + if (a === true || b === true) return true; + const merged = mergeRuntime(a, b); + if (merged === undefined) return; + if (typeof merged === "string") { + if (typeof runtime === "string" && merged === runtime) return true; + return merged; + } + if (typeof runtime === "string" || runtime === undefined) return merged; + if (merged.size === runtime.size) return true; + return merged; +}; + +/** + * @param {RuntimeSpec} a first (may be modified) + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} merged + */ +const mergeRuntimeOwned = (a, b) => { + if (b === undefined) { + return a; + } else if (a === b) { + return a; + } else if (a === undefined) { + if (typeof b === "string") { + return b; + } + return new SortableSet(b); + } else if (typeof a === "string") { + if (typeof b === "string") { + const set = new SortableSet(); + set.add(a); + set.add(b); + return set; + } + const set = new SortableSet(b); + set.add(a); + return set; + } + if (typeof b === "string") { + a.add(b); + return a; + } + for (const item of b) a.add(item); + return a; +}; + +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} merged + */ +const intersectRuntime = (a, b) => { + if (a === undefined) { + return b; + } else if (b === undefined) { + return a; + } else if (a === b) { + return a; + } else if (typeof a === "string") { + if (typeof b === "string") { + return; + } else if (b.has(a)) { + return a; + } + return; + } + if (typeof b === "string") { + if (a.has(b)) return b; + return; + } + const set = new SortableSet(); + for (const item of b) { + if (a.has(item)) set.add(item); + } + if (set.size === 0) return; + if (set.size === 1) { + const [item] = set; + return item; + } + return set; +}; + +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} result + */ +const subtractRuntime = (a, b) => { + if (a === undefined) { + return; + } else if (b === undefined) { + return a; + } else if (a === b) { + return; + } else if (typeof a === "string") { + if (typeof b === "string") { + return a; + } else if (b.has(a)) { + return; + } + return a; + } + if (typeof b === "string") { + if (!a.has(b)) return a; + if (a.size === 2) { + for (const item of a) { + if (item !== b) return item; + } + } + const set = new SortableSet(a); + set.delete(b); + return set; + } + const set = new SortableSet(); + for (const item of a) { + if (!b.has(item)) set.add(item); + } + if (set.size === 0) return; + if (set.size === 1) { + const [item] = set; + return item; + } + return set; +}; + +/** + * @param {RuntimeCondition} a first + * @param {RuntimeCondition} b second + * @param {RuntimeSpec} runtime runtime + * @returns {RuntimeCondition} result + */ +const subtractRuntimeCondition = (a, b, runtime) => { + if (b === true) return false; + if (b === false) return a; + if (a === false) return false; + const result = subtractRuntime(a === true ? runtime : a, b); + return result === undefined ? false : result; +}; + +/** + * @param {RuntimeSpec} runtime runtime + * @param {(runtime?: RuntimeSpec) => boolean} filter filter function + * @returns {boolean | RuntimeSpec} true/false if filter is constant for all runtimes, otherwise runtimes that are active + */ +const filterRuntime = (runtime, filter) => { + if (runtime === undefined) return filter(); + if (typeof runtime === "string") return filter(runtime); + let some = false; + let every = true; + let result; + for (const r of runtime) { + const v = filter(r); + if (v) { + some = true; + result = mergeRuntimeOwned(result, r); + } else { + every = false; + } + } + if (!some) return false; + if (every) return true; + return result; +}; + +/** + * @template T + * @typedef {Map} RuntimeSpecMapInnerMap + */ + +/** + * @template T + * @template [R=T] + */ +class RuntimeSpecMap { + /** + * @param {RuntimeSpecMap=} clone copy form this + */ + constructor(clone) { + /** @type {0 | 1 | 2} */ + this._mode = clone ? clone._mode : 0; // 0 = empty, 1 = single entry, 2 = map + /** @type {RuntimeSpec} */ + this._singleRuntime = clone ? clone._singleRuntime : undefined; + /** @type {R | undefined} */ + this._singleValue = clone ? clone._singleValue : undefined; + /** @type {RuntimeSpecMapInnerMap | undefined} */ + this._map = clone && clone._map ? new Map(clone._map) : undefined; + } + + /** + * @param {RuntimeSpec} runtime the runtimes + * @returns {R | undefined} value + */ + get(runtime) { + switch (this._mode) { + case 0: + return; + case 1: + return runtimeEqual(this._singleRuntime, runtime) + ? this._singleValue + : undefined; + default: + return /** @type {RuntimeSpecMapInnerMap} */ (this._map).get( + getRuntimeKey(runtime) + ); + } + } + + /** + * @param {RuntimeSpec} runtime the runtimes + * @returns {boolean} true, when the runtime is stored + */ + has(runtime) { + switch (this._mode) { + case 0: + return false; + case 1: + return runtimeEqual(this._singleRuntime, runtime); + default: + return /** @type {RuntimeSpecMapInnerMap} */ (this._map).has( + getRuntimeKey(runtime) + ); + } + } + + /** + * @param {RuntimeSpec} runtime the runtimes + * @param {R} value the value + */ + set(runtime, value) { + switch (this._mode) { + case 0: + this._mode = 1; + this._singleRuntime = runtime; + this._singleValue = value; + break; + case 1: + if (runtimeEqual(this._singleRuntime, runtime)) { + this._singleValue = value; + break; + } + this._mode = 2; + this._map = new Map(); + this._map.set( + getRuntimeKey(this._singleRuntime), + /** @type {R} */ (this._singleValue) + ); + this._singleRuntime = undefined; + this._singleValue = undefined; + /* falls through */ + default: + /** @type {RuntimeSpecMapInnerMap} */ + (this._map).set(getRuntimeKey(runtime), value); + } + } + + /** + * @param {RuntimeSpec} runtime the runtimes + * @param {() => R} computer function to compute the value + * @returns {R} the new value + */ + provide(runtime, computer) { + switch (this._mode) { + case 0: + this._mode = 1; + this._singleRuntime = runtime; + return (this._singleValue = computer()); + case 1: { + if (runtimeEqual(this._singleRuntime, runtime)) { + return /** @type {R} */ (this._singleValue); + } + this._mode = 2; + this._map = new Map(); + this._map.set( + getRuntimeKey(this._singleRuntime), + /** @type {R} */ + (this._singleValue) + ); + this._singleRuntime = undefined; + this._singleValue = undefined; + const newValue = computer(); + this._map.set(getRuntimeKey(runtime), newValue); + return newValue; + } + default: { + const key = getRuntimeKey(runtime); + const value = + /** @type {RuntimeSpecMapInnerMap} */ + (this._map).get(key); + if (value !== undefined) return value; + const newValue = computer(); + /** @type {RuntimeSpecMapInnerMap} */ + (this._map).set(key, newValue); + return newValue; + } + } + } + + /** + * @param {RuntimeSpec} runtime the runtimes + */ + delete(runtime) { + switch (this._mode) { + case 0: + return; + case 1: + if (runtimeEqual(this._singleRuntime, runtime)) { + this._mode = 0; + this._singleRuntime = undefined; + this._singleValue = undefined; + } + return; + default: + /** @type {RuntimeSpecMapInnerMap} */ + (this._map).delete(getRuntimeKey(runtime)); + } + } + + /** + * @param {RuntimeSpec} runtime the runtimes + * @param {(value: R | undefined) => R} fn function to update the value + */ + update(runtime, fn) { + switch (this._mode) { + case 0: + throw new Error("runtime passed to update must exist"); + case 1: { + if (runtimeEqual(this._singleRuntime, runtime)) { + this._singleValue = fn(this._singleValue); + break; + } + const newValue = fn(undefined); + if (newValue !== undefined) { + this._mode = 2; + this._map = new Map(); + this._map.set( + getRuntimeKey(this._singleRuntime), + /** @type {R} */ + (this._singleValue) + ); + this._singleRuntime = undefined; + this._singleValue = undefined; + this._map.set(getRuntimeKey(runtime), newValue); + } + break; + } + default: { + const key = getRuntimeKey(runtime); + const oldValue = + /** @type {RuntimeSpecMapInnerMap} */ + (this._map).get(key); + const newValue = fn(oldValue); + if (newValue !== oldValue) { + /** @type {RuntimeSpecMapInnerMap} */ + (this._map).set(key, newValue); + } + } + } + } + + keys() { + switch (this._mode) { + case 0: + return []; + case 1: + return [this._singleRuntime]; + default: + return Array.from( + /** @type {RuntimeSpecMapInnerMap} */ + (this._map).keys(), + keyToRuntime + ); + } + } + + /** + * @returns {IterableIterator} values + */ + values() { + switch (this._mode) { + case 0: + return [][Symbol.iterator](); + case 1: + return [/** @type {R} */ (this._singleValue)][Symbol.iterator](); + default: + return /** @type {RuntimeSpecMapInnerMap} */ (this._map).values(); + } + } + + get size() { + if (/** @type {number} */ (this._mode) <= 1) { + return /** @type {number} */ (this._mode); + } + + return /** @type {RuntimeSpecMapInnerMap} */ (this._map).size; + } +} + +class RuntimeSpecSet { + /** + * @param {Iterable=} iterable iterable + */ + constructor(iterable) { + /** @type {Map} */ + this._map = new Map(); + if (iterable) { + for (const item of iterable) { + this.add(item); + } + } + } + + /** + * @param {RuntimeSpec} runtime runtime + */ + add(runtime) { + this._map.set(getRuntimeKey(runtime), runtime); + } + + /** + * @param {RuntimeSpec} runtime runtime + * @returns {boolean} true, when the runtime exists + */ + has(runtime) { + return this._map.has(getRuntimeKey(runtime)); + } + + /** + * @returns {IterableIterator} iterable iterator + */ + [Symbol.iterator]() { + return this._map.values(); + } + + get size() { + return this._map.size; + } +} + +module.exports.RuntimeSpecMap = RuntimeSpecMap; +module.exports.RuntimeSpecSet = RuntimeSpecSet; +module.exports.compareRuntime = compareRuntime; +module.exports.filterRuntime = filterRuntime; +module.exports.forEachRuntime = forEachRuntime; +module.exports.getEntryRuntime = getEntryRuntime; +module.exports.getRuntimeKey = getRuntimeKey; +module.exports.intersectRuntime = intersectRuntime; +module.exports.keyToRuntime = keyToRuntime; +module.exports.mergeRuntime = mergeRuntime; +module.exports.mergeRuntimeCondition = mergeRuntimeCondition; +module.exports.mergeRuntimeConditionNonFalse = mergeRuntimeConditionNonFalse; +module.exports.mergeRuntimeOwned = mergeRuntimeOwned; +module.exports.runtimeConditionToString = runtimeConditionToString; +module.exports.runtimeEqual = runtimeEqual; +module.exports.runtimeToString = runtimeToString; +module.exports.subtractRuntime = subtractRuntime; +module.exports.subtractRuntimeCondition = subtractRuntimeCondition; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/semver.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/semver.js new file mode 100644 index 0000000000000000000000000000000000000000..f64af49fa429794441dc5c8f7abbb2dc317c8162 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/semver.js @@ -0,0 +1,602 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {string | number | undefined} SemVerRangeItem */ +/** @typedef {(SemVerRangeItem | SemVerRangeItem[])[]} SemVerRange */ + +/** + * @param {string} str version string + * @returns {SemVerRange} parsed version + */ +const parseVersion = (str) => { + /** + * @param {str} str str + * @returns {(string | number)[]} result + */ + var splitAndConvert = function (str) { + return str.split(".").map(function (item) { + // eslint-disable-next-line eqeqeq + return +item == /** @type {EXPECTED_ANY} */ (item) ? +item : item; + }); + }; + + var match = + /** @type {RegExpExecArray} */ + (/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str)); + + /** @type {(string | number | undefined | [])[]} */ + var ver = match[1] ? splitAndConvert(match[1]) : []; + + if (match[2]) { + ver.length++; + ver.push.apply(ver, splitAndConvert(match[2])); + } + + if (match[3]) { + ver.push([]); + ver.push.apply(ver, splitAndConvert(match[3])); + } + + return ver; +}; +module.exports.parseVersion = parseVersion; + +/* eslint-disable eqeqeq */ +/** + * @param {string} a version + * @param {string} b version + * @returns {boolean} true, iff a < b + */ +const versionLt = (a, b) => { + // @ts-expect-error + a = parseVersion(a); + // @ts-expect-error + b = parseVersion(b); + var i = 0; + for (;;) { + // a b EOA object undefined number string + // EOA a == b a < b b < a a < b a < b + // object b < a (0) b < a a < b a < b + // undefined a < b a < b (0) a < b a < b + // number b < a b < a b < a (1) a < b + // string b < a b < a b < a b < a (1) + // EOA end of array + // (0) continue on + // (1) compare them via "<" + + // Handles first row in table + if (i >= a.length) return i < b.length && (typeof b[i])[0] != "u"; + + var aValue = a[i]; + var aType = (typeof aValue)[0]; + + // Handles first column in table + if (i >= b.length) return aType == "u"; + + var bValue = b[i]; + var bType = (typeof bValue)[0]; + + if (aType == bType) { + if (aType != "o" && aType != "u" && aValue != bValue) { + return aValue < bValue; + } + i++; + } else { + // Handles remaining cases + if (aType == "o" && bType == "n") return true; + return bType == "s" || aType == "u"; + } + } +}; +/* eslint-enable eqeqeq */ +module.exports.versionLt = versionLt; + +/** + * @param {string} str range string + * @returns {SemVerRange} parsed range + */ +module.exports.parseRange = (str) => { + /** + * @param {string} str str + * @returns {(string | number)[]} result + */ + const splitAndConvert = (str) => { + return str + .split(".") + .map((item) => (item !== "NaN" && `${+item}` === item ? +item : item)); + }; + + // see https://docs.npmjs.com/misc/semver#range-grammar for grammar + /** + * @param {string} str str + * @returns {SemVerRangeItem[]} + */ + const parsePartial = (str) => { + const match = + /** @type {RegExpExecArray} */ + (/^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str)); + /** @type {SemVerRangeItem[]} */ + const ver = match[1] ? [0, ...splitAndConvert(match[1])] : [0]; + + if (match[2]) { + ver.length++; + ver.push.apply(ver, splitAndConvert(match[2])); + } + + // remove trailing any matchers + let last = ver[ver.length - 1]; + while ( + ver.length && + (last === undefined || /^[*xX]$/.test(/** @type {string} */ (last))) + ) { + ver.pop(); + last = ver[ver.length - 1]; + } + + return ver; + }; + + /** + * + * @param {SemVerRangeItem[]} range range + * @returns {SemVerRangeItem[]} + */ + const toFixed = (range) => { + if (range.length === 1) { + // Special case for "*" is "x.x.x" instead of "=" + return [0]; + } else if (range.length === 2) { + // Special case for "1" is "1.x.x" instead of "=1" + return [1, ...range.slice(1)]; + } else if (range.length === 3) { + // Special case for "1.2" is "1.2.x" instead of "=1.2" + return [2, ...range.slice(1)]; + } + + return [range.length, ...range.slice(1)]; + }; + + /** + * + * @param {SemVerRangeItem[]} range + * @returns {SemVerRangeItem[]} result + */ + const negate = (range) => { + return [-(/** @type { [number]} */ (range)[0]) - 1, ...range.slice(1)]; + }; + + /** + * @param {string} str str + * @returns {SemVerRange} + */ + const parseSimple = (str) => { + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | '!' ) ( ' ' ) * partial + // tilde ::= '~' ( ' ' ) * partial + // caret ::= '^' ( ' ' ) * partial + const match = /^(\^|~|<=|<|>=|>|=|v|!)/.exec(str); + const start = match ? match[0] : ""; + const remainder = parsePartial( + start.length ? str.slice(start.length).trim() : str.trim() + ); + + switch (start) { + case "^": + if (remainder.length > 1 && remainder[1] === 0) { + if (remainder.length > 2 && remainder[2] === 0) { + return [3, ...remainder.slice(1)]; + } + return [2, ...remainder.slice(1)]; + } + return [1, ...remainder.slice(1)]; + case "~": + if (remainder.length === 2 && remainder[0] === 0) { + return [1, ...remainder.slice(1)]; + } + return [2, ...remainder.slice(1)]; + case ">=": + return remainder; + case "=": + case "v": + case "": + return toFixed(remainder); + case "<": + return negate(remainder); + case ">": { + // and( >=, not( = ) ) => >=, =, not, and + const fixed = toFixed(remainder); + // eslint-disable-next-line no-sparse-arrays + return [, fixed, 0, remainder, 2]; + } + case "<=": + // or( <, = ) => <, =, or + // eslint-disable-next-line no-sparse-arrays + return [, toFixed(remainder), negate(remainder), 1]; + case "!": { + // not = + const fixed = toFixed(remainder); + // eslint-disable-next-line no-sparse-arrays + return [, fixed, 0]; + } + default: + throw new Error("Unexpected start value"); + } + }; + + /** + * + * @param {SemVerRangeItem[][]} items items + * @param {number} fn fn + * @returns {SemVerRange} result + */ + const combine = (items, fn) => { + if (items.length === 1) return items[0]; + const arr = []; + for (const item of items.slice().reverse()) { + if (0 in item) { + arr.push(item); + } else { + arr.push(...item.slice(1)); + } + } + + // eslint-disable-next-line no-sparse-arrays + return [, ...arr, ...items.slice(1).map(() => fn)]; + }; + + /** + * @param {string} str str + * @returns {SemVerRange} + */ + const parseRange = (str) => { + // range ::= hyphen | simple ( ' ' ( ' ' ) * simple ) * | '' + // hyphen ::= partial ( ' ' ) * ' - ' ( ' ' ) * partial + const items = str.split(/\s+-\s+/); + + if (items.length === 1) { + str = str.trim(); + + /** @type {SemVerRangeItem[][]} */ + const items = []; + const r = /[-0-9A-Za-z]\s+/g; + var start = 0; + var match; + while ((match = r.exec(str))) { + const end = match.index + 1; + items.push( + /** @type {SemVerRangeItem[]} */ + (parseSimple(str.slice(start, end).trim())) + ); + start = end; + } + items.push( + /** @type {SemVerRangeItem[]} */ + (parseSimple(str.slice(start).trim())) + ); + return combine(items, 2); + } + + const a = parsePartial(items[0]); + const b = parsePartial(items[1]); + // >=a <=b => and( >=a, or( >=a, { + // range-set ::= range ( logical-or range ) * + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + const items = + /** @type {SemVerRangeItem[][]} */ + (str.split(/\s*\|\|\s*/).map(parseRange)); + + return combine(items, 1); + }; + + return parseLogicalOr(str); +}; + +/* eslint-disable eqeqeq */ +/** + * @param {SemVerRange} range + * @returns {string} + */ +const rangeToString = (range) => { + var fixCount = /** @type {number} */ (range[0]); + var str = ""; + if (range.length === 1) { + return "*"; + } else if (fixCount + 0.5) { + str += + fixCount == 0 + ? ">=" + : fixCount == -1 + ? "<" + : fixCount == 1 + ? "^" + : fixCount == 2 + ? "~" + : fixCount > 0 + ? "=" + : "!="; + var needDot = 1; + for (var i = 1; i < range.length; i++) { + var item = range[i]; + var t = (typeof item)[0]; + needDot--; + str += + t == "u" + ? // undefined: prerelease marker, add an "-" + "-" + : // number or string: add the item, set flag to add an "." between two of them + (needDot > 0 ? "." : "") + ((needDot = 2), item); + } + return str; + } + /** @type {string[]} */ + var stack = []; + // eslint-disable-next-line no-redeclare + for (var i = 1; i < range.length; i++) { + // eslint-disable-next-line no-redeclare + var item = range[i]; + stack.push( + item === 0 + ? "not(" + pop() + ")" + : item === 1 + ? "(" + pop() + " || " + pop() + ")" + : item === 2 + ? stack.pop() + " " + stack.pop() + : rangeToString(/** @type {SemVerRange} */ (item)) + ); + } + return pop(); + + function pop() { + return /** @type {string} */ (stack.pop()).replace(/^\((.+)\)$/, "$1"); + } +}; + +module.exports.rangeToString = rangeToString; + +/** + * @param {SemVerRange} range version range + * @param {string} version the version + * @returns {boolean} if version satisfy the range + */ +const satisfy = (range, version) => { + if (0 in range) { + // @ts-expect-error + version = parseVersion(version); + var fixCount = /** @type {number} */ (range[0]); + // when negated is set it swill set for < instead of >= + var negated = fixCount < 0; + if (negated) fixCount = -fixCount - 1; + for (var i = 0, j = 1, isEqual = true; ; j++, i++) { + // cspell:word nequal nequ + + // when isEqual = true: + // range version: EOA/object undefined number string + // EOA equal block big-ver big-ver + // undefined bigger next big-ver big-ver + // number smaller block cmp big-cmp + // fixed number smaller block cmp-fix differ + // string smaller block differ cmp + // fixed string smaller block small-cmp cmp-fix + + // when isEqual = false: + // range version: EOA/object undefined number string + // EOA nequal block next-ver next-ver + // undefined nequal block next-ver next-ver + // number nequal block next next + // fixed number nequal block next next (this never happens) + // string nequal block next next + // fixed string nequal block next next (this never happens) + + // EOA end of array + // equal (version is equal range): + // when !negated: return true, + // when negated: return false + // bigger (version is bigger as range): + // when fixed: return false, + // when !negated: return true, + // when negated: return false, + // smaller (version is smaller as range): + // when !negated: return false, + // when negated: return true + // nequal (version is not equal range (> resp <)): return true + // block (version is in different prerelease area): return false + // differ (version is different from fixed range (string vs. number)): return false + // next: continues to the next items + // next-ver: when fixed: return false, continues to the next item only for the version, sets isEqual=false + // big-ver: when fixed || negated: return false, continues to the next item only for the version, sets isEqual=false + // next-nequ: continues to the next items, sets isEqual=false + // cmp (negated === false): version < range => return false, version > range => next-nequ, else => next + // cmp (negated === true): version > range => return false, version < range => next-nequ, else => next + // cmp-fix: version == range => next, else => return false + // big-cmp: when negated => return false, else => next-nequ + // small-cmp: when negated => next-nequ, else => return false + + var rangeType = + /** @type {"s" | "n" | "u" | ""} */ + (j < range.length ? (typeof range[j])[0] : ""); + + /** @type {number | string | undefined} */ + var versionValue; + /** @type {"n" | "s" | "u" | "o" | undefined} */ + var versionType; + + // Handles first column in both tables (end of version or object) + if ( + i >= version.length || + ((versionValue = version[i]), + (versionType = /** @type {"n" | "s" | "u" | "o"} */ ( + (typeof versionValue)[0] + )) == "o") + ) { + // Handles nequal + if (!isEqual) return true; + // Handles bigger + if (rangeType == "u") return j > fixCount && !negated; + // Handles equal and smaller: (range === EOA) XOR negated + return (rangeType == "") != negated; // equal + smaller + } + + // Handles second column in both tables (version = undefined) + if (versionType == "u") { + if (!isEqual || rangeType != "u") { + return false; + } + } + + // switch between first and second table + else if (isEqual) { + // Handle diagonal + if (rangeType == versionType) { + if (j <= fixCount) { + // Handles "cmp-fix" cases + if (versionValue != range[j]) { + return false; + } + } else { + // Handles "cmp" cases + if ( + negated + ? versionValue > /** @type {(number | string)[]} */ (range)[j] + : versionValue < /** @type {(number | string)[]} */ (range)[j] + ) { + return false; + } + if (versionValue != range[j]) isEqual = false; + } + } + + // Handle big-ver + else if (rangeType != "s" && rangeType != "n") { + if (negated || j <= fixCount) return false; + isEqual = false; + j--; + } + + // Handle differ, big-cmp and small-cmp + else if (j <= fixCount || versionType < rangeType != negated) { + return false; + } else { + isEqual = false; + } + } else { + // Handles all "next-ver" cases in the second table + // eslint-disable-next-line no-lonely-if + if (rangeType != "s" && rangeType != "n") { + isEqual = false; + j--; + } + + // next is applied by default + } + } + } + + /** @type {(boolean | number)[]} */ + var stack = []; + var p = stack.pop.bind(stack); + // eslint-disable-next-line no-redeclare + for (var i = 1; i < range.length; i++) { + var item = /** @type {SemVerRangeItem[] | 0 | 1 | 2} */ (range[i]); + + stack.push( + item == 1 + ? /** @type {() => number} */ (p)() | /** @type {() => number} */ (p)() + : item == 2 + ? /** @type {() => number} */ (p)() & + /** @type {() => number} */ (p)() + : item + ? satisfy(item, version) + : !p() + ); + } + return !!p(); +}; +/* eslint-enable eqeqeq */ +module.exports.satisfy = satisfy; + +/** + * @param {SemVerRange | string | number | false | undefined} json + * @returns {string} + */ +module.exports.stringifyHoley = (json) => { + switch (typeof json) { + case "undefined": + return ""; + case "object": + if (Array.isArray(json)) { + let str = "["; + for (let i = 0; i < json.length; i++) { + if (i !== 0) str += ","; + str += this.stringifyHoley(json[i]); + } + str += "]"; + return str; + } + + return JSON.stringify(json); + default: + return JSON.stringify(json); + } +}; + +//#region runtime code: parseVersion +/** + * @param {RuntimeTemplate} runtimeTemplate + * @returns {string} + */ +exports.parseVersionRuntimeCode = (runtimeTemplate) => + `var parseVersion = ${runtimeTemplate.basicFunction("str", [ + "// see webpack/lib/util/semver.js for original code", + `var p=${runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)"}{return p.split(".").map(${runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)"}{return+p==p?+p:p})},n=/^([^-+]+)?(?:-([^+]+))?(?:\\+(.+))?$/.exec(str),r=n[1]?p(n[1]):[];return n[2]&&(r.length++,r.push.apply(r,p(n[2]))),n[3]&&(r.push([]),r.push.apply(r,p(n[3]))),r;` + ])}`; +//#endregion + +//#region runtime code: versionLt +/** + * @param {RuntimeTemplate} runtimeTemplate + * @returns {string} + */ +exports.versionLtRuntimeCode = (runtimeTemplate) => + `var versionLt = ${runtimeTemplate.basicFunction("a, b", [ + "// see webpack/lib/util/semver.js for original code", + 'a=parseVersion(a),b=parseVersion(b);for(var r=0;;){if(r>=a.length)return r=b.length)return"u"==n;var t=b[r],f=(typeof t)[0];if(n!=f)return"o"==n&&"n"==f||("s"==f||"u"==n);if("o"!=n&&"u"!=n&&e!=t)return e + `var rangeToString = ${runtimeTemplate.basicFunction("range", [ + "// see webpack/lib/util/semver.js for original code", + 'var r=range[0],n="";if(1===range.length)return"*";if(r+.5){n+=0==r?">=":-1==r?"<":1==r?"^":2==r?"~":r>0?"=":"!=";for(var e=1,a=1;a0?".":"")+(e=2,t)}return n}var g=[];for(a=1;a + `var satisfy = ${runtimeTemplate.basicFunction("range, version", [ + "// see webpack/lib/util/semver.js for original code", + 'if(0 in range){version=parseVersion(version);var e=range[0],r=e<0;r&&(e=-e-1);for(var n=0,i=1,a=!0;;i++,n++){var f,s,g=i=version.length||"o"==(s=(typeof(f=version[n]))[0]))return!a||("u"==g?i>e&&!r:""==g!=r);if("u"==s){if(!a||"u"!=g)return!1}else if(a)if(g==s)if(i<=e){if(f!=range[i])return!1}else{if(r?f>range[i]:f} Serializer + */ + +const getBinaryMiddleware = memoize(() => + require("../serialization/BinaryMiddleware") +); +const getObjectMiddleware = memoize(() => + require("../serialization/ObjectMiddleware") +); +const getSingleItemMiddleware = memoize(() => + require("../serialization/SingleItemMiddleware") +); +const getSerializer = memoize(() => require("../serialization/Serializer")); +const getSerializerMiddleware = memoize(() => + require("../serialization/SerializerMiddleware") +); + +const getBinaryMiddlewareInstance = memoize( + () => new (getBinaryMiddleware())() +); + +const registerSerializers = memoize(() => { + require("./registerExternalSerializer"); + + // Load internal paths with a relative require + // This allows bundling all internal serializers + const internalSerializables = require("./internalSerializables"); + + getObjectMiddleware().registerLoader(/^webpack\/lib\//, (req) => { + const loader = + internalSerializables[ + /** @type {keyof import("./internalSerializables")} */ + (req.slice("webpack/lib/".length)) + ]; + if (loader) { + loader(); + } else { + // eslint-disable-next-line no-console + console.warn(`${req} not found in internalSerializables`); + } + return true; + }); +}); + +/** + * @type {Serializer} + */ +let buffersSerializer; + +// Expose serialization API +module.exports = { + get register() { + return getObjectMiddleware().register; + }, + get registerLoader() { + return getObjectMiddleware().registerLoader; + }, + get registerNotSerializable() { + return getObjectMiddleware().registerNotSerializable; + }, + get NOT_SERIALIZABLE() { + return getObjectMiddleware().NOT_SERIALIZABLE; + }, + /** @type {MEASURE_START_OPERATION} */ + get MEASURE_START_OPERATION() { + return getBinaryMiddleware().MEASURE_START_OPERATION; + }, + /** @type {MEASURE_END_OPERATION} */ + get MEASURE_END_OPERATION() { + return getBinaryMiddleware().MEASURE_END_OPERATION; + }, + get buffersSerializer() { + if (buffersSerializer !== undefined) return buffersSerializer; + registerSerializers(); + const Serializer = getSerializer(); + const binaryMiddleware = getBinaryMiddlewareInstance(); + const SerializerMiddleware = getSerializerMiddleware(); + const SingleItemMiddleware = getSingleItemMiddleware(); + return /** @type {Serializer} */ ( + buffersSerializer = new Serializer([ + new SingleItemMiddleware(), + new (getObjectMiddleware())((context) => { + if ("write" in context) { + context.writeLazy = (value) => { + context.write( + SerializerMiddleware.createLazy(value, binaryMiddleware) + ); + }; + } + }, DEFAULTS.HASH_FUNCTION), + binaryMiddleware + ]) + ); + }, + /** + * @template D, S, C + * @param {IntermediateFileSystem} fs filesystem + * @param {string | Hash} hashFunction hash function to use + * @returns {Serializer} file serializer + */ + createFileSerializer: (fs, hashFunction) => { + registerSerializers(); + const Serializer = getSerializer(); + + const FileMiddleware = require("../serialization/FileMiddleware"); + + const fileMiddleware = new FileMiddleware(fs, hashFunction); + const binaryMiddleware = getBinaryMiddlewareInstance(); + const SerializerMiddleware = getSerializerMiddleware(); + const SingleItemMiddleware = getSingleItemMiddleware(); + return /** @type {Serializer} */ ( + new Serializer([ + new SingleItemMiddleware(), + new (getObjectMiddleware())((context) => { + if ("write" in context) { + context.writeLazy = (value) => { + context.write( + SerializerMiddleware.createLazy(value, binaryMiddleware) + ); + }; + context.writeSeparate = (value, options) => { + const lazy = SerializerMiddleware.createLazy( + value, + fileMiddleware, + options + ); + context.write(lazy); + return lazy; + }; + } + }, hashFunction), + binaryMiddleware, + fileMiddleware + ]) + ); + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/smartGrouping.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/smartGrouping.js new file mode 100644 index 0000000000000000000000000000000000000000..7b6360a7f85104e67eddfe00b9169a0571887cc8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/smartGrouping.js @@ -0,0 +1,206 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @typedef {object} GroupOptions + * @property {boolean=} groupChildren + * @property {boolean=} force + * @property {number=} targetGroupCount + */ + +/** + * @template T + * @template R + * @typedef {object} GroupConfig + * @property {(item: T) => string[] | undefined} getKeys + * @property {(key: string, children: (R | T)[], items: T[]) => R} createGroup + * @property {(name: string, items: T[]) => GroupOptions=} getOptions + */ + +/** + * @template T + * @template R + * @typedef {object} ItemWithGroups + * @property {T} item + * @property {Set>} groups + */ + +/** + * @template T + * @template R + * @typedef {{ config: GroupConfig, name: string, alreadyGrouped: boolean, items: Set> | undefined }} Group + */ + +/** + * @template T + * @template R + * @param {T[]} items the list of items + * @param {GroupConfig[]} groupConfigs configuration + * @returns {(R | T)[]} grouped items + */ +const smartGrouping = (items, groupConfigs) => { + /** @type {Set>} */ + const itemsWithGroups = new Set(); + /** @type {Map>} */ + const allGroups = new Map(); + for (const item of items) { + /** @type {Set>} */ + const groups = new Set(); + for (let i = 0; i < groupConfigs.length; i++) { + const groupConfig = groupConfigs[i]; + const keys = groupConfig.getKeys(item); + if (keys) { + for (const name of keys) { + const key = `${i}:${name}`; + let group = allGroups.get(key); + if (group === undefined) { + allGroups.set( + key, + (group = { + config: groupConfig, + name, + alreadyGrouped: false, + items: undefined + }) + ); + } + groups.add(group); + } + } + } + itemsWithGroups.add({ + item, + groups + }); + } + /** + * @param {Set>} itemsWithGroups input items with groups + * @returns {(T | R)[]} groups items + */ + const runGrouping = (itemsWithGroups) => { + const totalSize = itemsWithGroups.size; + for (const entry of itemsWithGroups) { + for (const group of entry.groups) { + if (group.alreadyGrouped) continue; + const items = group.items; + if (items === undefined) { + group.items = new Set([entry]); + } else { + items.add(entry); + } + } + } + /** @type {Map, { items: Set>, options: GroupOptions | false | undefined, used: boolean }>} */ + const groupMap = new Map(); + for (const group of allGroups.values()) { + if (group.items) { + const items = group.items; + group.items = undefined; + groupMap.set(group, { + items, + options: undefined, + used: false + }); + } + } + /** @type {(T | R)[]} */ + const results = []; + for (;;) { + /** @type {Group | undefined} */ + let bestGroup; + let bestGroupSize = -1; + let bestGroupItems; + let bestGroupOptions; + for (const [group, state] of groupMap) { + const { items, used } = state; + let options = state.options; + if (options === undefined) { + const groupConfig = group.config; + state.options = options = + (groupConfig.getOptions && + groupConfig.getOptions( + group.name, + Array.from(items, ({ item }) => item) + )) || + false; + } + + const force = options && options.force; + if (!force) { + if (bestGroupOptions && bestGroupOptions.force) continue; + if (used) continue; + if (items.size <= 1 || totalSize - items.size <= 1) { + continue; + } + } + const targetGroupCount = (options && options.targetGroupCount) || 4; + const sizeValue = force + ? items.size + : Math.min( + items.size, + (totalSize * 2) / targetGroupCount + + itemsWithGroups.size - + items.size + ); + if ( + sizeValue > bestGroupSize || + (force && (!bestGroupOptions || !bestGroupOptions.force)) + ) { + bestGroup = group; + bestGroupSize = sizeValue; + bestGroupItems = items; + bestGroupOptions = options; + } + } + if (bestGroup === undefined) { + break; + } + const items = new Set(bestGroupItems); + const options = bestGroupOptions; + + const groupChildren = !options || options.groupChildren !== false; + + for (const item of items) { + itemsWithGroups.delete(item); + // Remove all groups that items have from the map to not select them again + for (const group of item.groups) { + const state = groupMap.get(group); + if (state !== undefined) { + state.items.delete(item); + if (state.items.size === 0) { + groupMap.delete(group); + } else { + state.options = undefined; + if (groupChildren) { + state.used = true; + } + } + } + } + } + groupMap.delete(bestGroup); + + const key = bestGroup.name; + const groupConfig = bestGroup.config; + + const allItems = Array.from(items, ({ item }) => item); + + bestGroup.alreadyGrouped = true; + const children = groupChildren ? runGrouping(items) : allItems; + bestGroup.alreadyGrouped = false; + + results.push(groupConfig.createGroup(key, children, allItems)); + } + for (const { item } of itemsWithGroups) { + results.push(item); + } + return results; + }; + return runGrouping(itemsWithGroups); +}; + +module.exports = smartGrouping; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/source.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/source.js new file mode 100644 index 0000000000000000000000000000000000000000..065c7a605bf6df282b6830a3b2790760eb35ac69 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/util/source.js @@ -0,0 +1,62 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("webpack-sources").Source} Source */ + +/** @type {WeakMap>} */ +const equalityCache = new WeakMap(); + +/** + * @param {Source} a a source + * @param {Source} b another source + * @returns {boolean} true, when both sources are equal + */ +const _isSourceEqual = (a, b) => { + // prefer .buffer(), it's called anyway during emit + /** @type {Buffer|string} */ + let aSource = typeof a.buffer === "function" ? a.buffer() : a.source(); + /** @type {Buffer|string} */ + let bSource = typeof b.buffer === "function" ? b.buffer() : b.source(); + if (aSource === bSource) return true; + if (typeof aSource === "string" && typeof bSource === "string") return false; + if (!Buffer.isBuffer(aSource)) aSource = Buffer.from(aSource, "utf8"); + if (!Buffer.isBuffer(bSource)) bSource = Buffer.from(bSource, "utf8"); + return aSource.equals(bSource); +}; + +/** + * @param {Source} a a source + * @param {Source} b another source + * @returns {boolean} true, when both sources are equal + */ +const isSourceEqual = (a, b) => { + if (a === b) return true; + const cache1 = equalityCache.get(a); + if (cache1 !== undefined) { + const result = cache1.get(b); + if (result !== undefined) return result; + } + const result = _isSourceEqual(a, b); + if (cache1 !== undefined) { + cache1.set(b, result); + } else { + const map = new WeakMap(); + map.set(b, result); + equalityCache.set(a, map); + } + const cache2 = equalityCache.get(b); + if (cache2 !== undefined) { + cache2.set(a, result); + } else { + const map = new WeakMap(); + map.set(a, result); + equalityCache.set(b, map); + } + return result; +}; + +module.exports.isSourceEqual = isSourceEqual; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/validateSchema.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/validateSchema.js new file mode 100644 index 0000000000000000000000000000000000000000..7091887e9a8520253203b592b2b988f1e8cee1b6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/validateSchema.js @@ -0,0 +1,177 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { validate } = require("schema-utils"); + +/* cSpell:disable */ +const DID_YOU_MEAN = { + rules: "module.rules", + loaders: "module.rules or module.rules.*.use", + query: "module.rules.*.options (BREAKING CHANGE since webpack 5)", + noParse: "module.noParse", + filename: "output.filename or module.rules.*.generator.filename", + file: "output.filename", + chunkFilename: "output.chunkFilename", + chunkfilename: "output.chunkFilename", + ecmaVersion: + "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", + ecmaversion: + "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", + ecma: "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", + path: "output.path", + pathinfo: "output.pathinfo", + pathInfo: "output.pathinfo", + jsonpFunction: "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", + chunkCallbackName: + "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", + jsonpScriptType: "output.scriptType (BREAKING CHANGE since webpack 5)", + hotUpdateFunction: "output.hotUpdateGlobal (BREAKING CHANGE since webpack 5)", + splitChunks: "optimization.splitChunks", + immutablePaths: "snapshot.immutablePaths", + managedPaths: "snapshot.managedPaths", + maxModules: "stats.modulesSpace (BREAKING CHANGE since webpack 5)", + hashedModuleIds: + 'optimization.moduleIds: "hashed" (BREAKING CHANGE since webpack 5)', + namedChunks: + 'optimization.chunkIds: "named" (BREAKING CHANGE since webpack 5)', + namedModules: + 'optimization.moduleIds: "named" (BREAKING CHANGE since webpack 5)', + occurrenceOrder: + 'optimization.chunkIds: "size" and optimization.moduleIds: "size" (BREAKING CHANGE since webpack 5)', + automaticNamePrefix: + "optimization.splitChunks.[cacheGroups.*].idHint (BREAKING CHANGE since webpack 5)", + noEmitOnErrors: + "optimization.emitOnErrors (BREAKING CHANGE since webpack 5: logic is inverted to avoid negative flags)", + Buffer: + "to use the ProvidePlugin to process the Buffer variable to modules as polyfill\n" + + "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + + "Note: if you are using 'node.Buffer: false', you can just remove that as this is the default behavior now.\n" + + "To provide a polyfill to modules use:\n" + + 'new ProvidePlugin({ Buffer: ["buffer", "Buffer"] }) and npm install buffer.', + process: + "to use the ProvidePlugin to process the process variable to modules as polyfill\n" + + "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + + "Note: if you are using 'node.process: false', you can just remove that as this is the default behavior now.\n" + + "To provide a polyfill to modules use:\n" + + 'new ProvidePlugin({ process: "process" }) and npm install buffer.' +}; + +const REMOVED = { + concord: + "BREAKING CHANGE: resolve.concord has been removed and is no longer available.", + devtoolLineToLine: + "BREAKING CHANGE: output.devtoolLineToLine has been removed and is no longer available." +}; +/* cSpell:enable */ + +/** + * @param {Parameters[0]} schema a json schema + * @param {Parameters[1]} options the options that should be validated + * @param {Parameters[2]=} validationConfiguration configuration for generating errors + * @returns {void} + */ +const validateSchema = (schema, options, validationConfiguration) => { + validate( + schema, + options, + validationConfiguration || { + name: "Webpack", + postFormatter: (formattedError, error) => { + const children = error.children; + if ( + children && + children.some( + (child) => + child.keyword === "absolutePath" && + child.instancePath === "/output/filename" + ) + ) { + return `${formattedError}\nPlease use output.path to specify absolute path and output.filename for the file name.`; + } + + if ( + children && + children.some( + (child) => + child.keyword === "pattern" && child.instancePath === "/devtool" + ) + ) { + return ( + `${formattedError}\n` + + "BREAKING CHANGE since webpack 5: The devtool option is more strict.\n" + + "Please strictly follow the order of the keywords in the pattern." + ); + } + + if (error.keyword === "additionalProperties") { + const params = error.params; + if ( + Object.prototype.hasOwnProperty.call( + DID_YOU_MEAN, + params.additionalProperty + ) + ) { + return `${formattedError}\nDid you mean ${ + DID_YOU_MEAN[ + /** @type {keyof DID_YOU_MEAN} */ (params.additionalProperty) + ] + }?`; + } + + if ( + Object.prototype.hasOwnProperty.call( + REMOVED, + params.additionalProperty + ) + ) { + return `${formattedError}\n${ + REMOVED[/** @type {keyof REMOVED} */ (params.additionalProperty)] + }?`; + } + + if (!error.instancePath) { + if (params.additionalProperty === "debug") { + return ( + `${formattedError}\n` + + "The 'debug' property was removed in webpack 2.0.0.\n" + + "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + + "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + + "plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " debug: true\n" + + " })\n" + + "]" + ); + } + + if (params.additionalProperty) { + return ( + `${formattedError}\n` + + "For typos: please correct them.\n" + + "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + + " Loaders should be updated to allow passing options via loader options in module.rules.\n" + + " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + + " plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " // test: /\\.xxx$/, // may apply this only for some modules\n" + + " options: {\n" + + ` ${params.additionalProperty}: …\n` + + " }\n" + + " })\n" + + " ]" + ); + } + } + } + + return formattedError; + } + } + ); +}; + +module.exports = validateSchema; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..20a65973ebca9c17cdbadddd6aecbca1b12999f2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js @@ -0,0 +1,142 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ + +/** + * @typedef {object} AsyncWasmLoadingRuntimeModuleOptions + * @property {((wasmModuleSrcPath: string) => string)=} generateBeforeLoadBinaryCode + * @property {(wasmModuleSrcPath: string) => string} generateLoadBinaryCode + * @property {(() => string)=} generateBeforeInstantiateStreaming + * @property {boolean} supportsStreaming + */ + +class AsyncWasmLoadingRuntimeModule extends RuntimeModule { + /** + * @param {AsyncWasmLoadingRuntimeModuleOptions} options options + */ + constructor({ + generateLoadBinaryCode, + generateBeforeLoadBinaryCode, + generateBeforeInstantiateStreaming, + supportsStreaming + }) { + super("wasm loading", RuntimeModule.STAGE_NORMAL); + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.generateBeforeLoadBinaryCode = generateBeforeLoadBinaryCode; + this.generateBeforeInstantiateStreaming = + generateBeforeInstantiateStreaming; + this.supportsStreaming = supportsStreaming; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const chunk = /** @type {Chunk} */ (this.chunk); + const { outputOptions, runtimeTemplate } = compilation; + const fn = RuntimeGlobals.instantiateWasm; + const wasmModuleSrcPath = compilation.getPath( + JSON.stringify(outputOptions.webassemblyModuleFilename), + { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: (length) => + `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, + module: { + id: '" + wasmModuleId + "', + hash: '" + wasmModuleHash + "', + hashWithLength(length) { + return `" + wasmModuleHash.slice(0, ${length}) + "`; + } + }, + runtime: chunk.runtime + } + ); + + const loader = this.generateLoadBinaryCode(wasmModuleSrcPath); + const fallback = [ + `.then(${runtimeTemplate.returningFunction("x.arrayBuffer()", "x")})`, + `.then(${runtimeTemplate.returningFunction( + "WebAssembly.instantiate(bytes, importsObj)", + "bytes" + )})`, + `.then(${runtimeTemplate.returningFunction( + "Object.assign(exports, res.instance.exports)", + "res" + )})` + ]; + const getStreaming = () => { + const concat = (/** @type {string[]} */ ...text) => text.join(""); + return [ + this.generateBeforeLoadBinaryCode + ? this.generateBeforeLoadBinaryCode(wasmModuleSrcPath) + : "", + `var req = ${loader};`, + `var fallback = ${runtimeTemplate.returningFunction( + Template.asString(["req", Template.indent(fallback)]) + )};`, + concat( + "return req.then(", + runtimeTemplate.basicFunction("res", [ + 'if (typeof WebAssembly.instantiateStreaming === "function") {', + Template.indent( + this.generateBeforeInstantiateStreaming + ? this.generateBeforeInstantiateStreaming() + : "" + ), + Template.indent([ + "return WebAssembly.instantiateStreaming(res, importsObj)", + Template.indent([ + ".then(", + Template.indent([ + `${runtimeTemplate.returningFunction( + "Object.assign(exports, res.instance.exports)", + "res" + )},`, + runtimeTemplate.basicFunction("e", [ + 'if(res.headers.get("Content-Type") !== "application/wasm") {', + Template.indent([ + 'console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n", e);', + "return fallback();" + ]), + "}", + "throw e;" + ]) + ]), + ");" + ]) + ]), + "}", + "return fallback();" + ]), + ");" + ) + ]; + }; + + return `${fn} = ${runtimeTemplate.basicFunction( + "exports, wasmModuleId, wasmModuleHash, importsObj", + this.supportsStreaming + ? getStreaming() + : [ + this.generateBeforeLoadBinaryCode + ? this.generateBeforeLoadBinaryCode(wasmModuleSrcPath) + : "", + `return ${loader}`, + `${Template.indent(fallback)};` + ] + )};`; + } +} + +module.exports = AsyncWasmLoadingRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyGenerator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..f66d5e6d6a5b7669d1b809c3b8c66a821a54127d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyGenerator.js @@ -0,0 +1,72 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const Generator = require("../Generator"); +const { WEBASSEMBLY_TYPES } = require("../ModuleSourceTypesConstants"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../NormalModule")} NormalModule */ + +/** + * @typedef {object} AsyncWebAssemblyGeneratorOptions + * @property {boolean=} mangleImports mangle imports + */ + +class AsyncWebAssemblyGenerator extends Generator { + /** + * @param {AsyncWebAssemblyGeneratorOptions} options options + */ + constructor(options) { + super(); + this.options = options; + } + + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + return WEBASSEMBLY_TYPES; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + const originalSource = module.originalSource(); + if (!originalSource) { + return 0; + } + return originalSource.size(); + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate(module, generateContext) { + return /** @type {Source} */ (module.originalSource()); + } + + /** + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generateError(error, module, generateContext) { + return new RawSource(error.message); + } +} + +module.exports = AsyncWebAssemblyGenerator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..ab15a20ec23554c67a8cd8ea6cc4a32a6d912106 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js @@ -0,0 +1,219 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const Generator = require("../Generator"); +const InitFragment = require("../InitFragment"); +const { WEBASSEMBLY_TYPES } = require("../ModuleSourceTypesConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +/** + * @typedef {{ request: string, importVar: string }} ImportObjRequestItem + */ + +class AsyncWebAssemblyJavascriptGenerator extends Generator { + /** + * @param {OutputOptions["webassemblyModuleFilename"]} filenameTemplate template for the WebAssembly module filename + */ + constructor(filenameTemplate) { + super(); + this.filenameTemplate = filenameTemplate; + } + + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + return WEBASSEMBLY_TYPES; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + return 40 + module.dependencies.length * 10; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate(module, generateContext) { + const { + runtimeTemplate, + chunkGraph, + moduleGraph, + runtimeRequirements, + runtime + } = generateContext; + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.moduleId); + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.instantiateWasm); + /** @type {InitFragment>[]} */ + const initFragments = []; + /** @type {Map} */ + const depModules = new Map(); + /** @type {Map} */ + const wasmDepsByRequest = new Map(); + for (const dep of module.dependencies) { + if (dep instanceof WebAssemblyImportDependency) { + const module = /** @type {Module} */ (moduleGraph.getModule(dep)); + if (!depModules.has(module)) { + depModules.set(module, { + request: dep.request, + importVar: `WEBPACK_IMPORTED_MODULE_${depModules.size}` + }); + } + let list = wasmDepsByRequest.get(dep.request); + if (list === undefined) { + list = []; + wasmDepsByRequest.set(dep.request, list); + } + list.push(dep); + } + } + + /** @type {Array} */ + const promises = []; + + const importStatements = Array.from( + depModules, + ([importedModule, { request, importVar }]) => { + if (moduleGraph.isAsync(importedModule)) { + promises.push(importVar); + } + return runtimeTemplate.importStatement({ + update: false, + module: importedModule, + moduleGraph, + chunkGraph, + request, + originModule: module, + importVar, + runtimeRequirements + }); + } + ); + const importsCode = importStatements.map(([x]) => x).join(""); + const importsCompatCode = importStatements.map(([_, x]) => x).join(""); + + const importObjRequestItems = Array.from( + wasmDepsByRequest, + ([request, deps]) => { + const exportItems = deps.map((dep) => { + const importedModule = + /** @type {Module} */ + (moduleGraph.getModule(dep)); + const importVar = + /** @type {ImportObjRequestItem} */ + (depModules.get(importedModule)).importVar; + return `${JSON.stringify( + dep.name + )}: ${runtimeTemplate.exportFromImport({ + moduleGraph, + module: importedModule, + chunkGraph, + request, + exportName: dep.name, + originModule: module, + asiSafe: true, + isCall: false, + callContext: false, + defaultInterop: true, + importVar, + initFragments, + runtime, + runtimeRequirements + })}`; + }); + return Template.asString([ + `${JSON.stringify(request)}: {`, + Template.indent(exportItems.join(",\n")), + "}" + ]); + } + ); + + const importsObj = + importObjRequestItems.length > 0 + ? Template.asString([ + "{", + Template.indent(importObjRequestItems.join(",\n")), + "}" + ]) + : undefined; + + const instantiateCall = `${RuntimeGlobals.instantiateWasm}(${module.exportsArgument}, ${ + module.moduleArgument + }.id, ${JSON.stringify( + chunkGraph.getRenderedModuleHash(module, runtime) + )}${importsObj ? `, ${importsObj})` : ")"}`; + + if (promises.length > 0) { + runtimeRequirements.add(RuntimeGlobals.asyncModule); + } + + const source = new RawSource( + promises.length > 0 + ? Template.asString([ + `var __webpack_instantiate__ = ${runtimeTemplate.basicFunction( + `[${promises.join(", ")}]`, + `${importsCompatCode}return ${instantiateCall};` + )}`, + `${RuntimeGlobals.asyncModule}(${ + module.moduleArgument + }, async ${runtimeTemplate.basicFunction( + "__webpack_handle_async_dependencies__, __webpack_async_result__", + [ + "try {", + importsCode, + `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${promises.join( + ", " + )}]);`, + `var [${promises.join( + ", " + )}] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__;`, + `${importsCompatCode}await ${instantiateCall};`, + "__webpack_async_result__();", + "} catch(e) { __webpack_async_result__(e); }" + ] + )}, 1);` + ]) + : `${importsCode}${importsCompatCode}module.exports = ${instantiateCall};` + ); + + return InitFragment.addToSource(source, initFragments, generateContext); + } + + /** + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generateError(error, module, generateContext) { + return new RawSource(`throw new Error(${JSON.stringify(error.message)});`); + } +} + +module.exports = AsyncWebAssemblyJavascriptGenerator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..77925068a10668b20938bdeec0860d076b930bed --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyModulesPlugin.js @@ -0,0 +1,215 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { SyncWaterfallHook } = require("tapable"); +const Compilation = require("../Compilation"); +const Generator = require("../Generator"); +const { tryRunOrWebpackError } = require("../HookWebpackError"); +const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants"); +const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); +const { compareModulesByIdOrIdentifier } = require("../util/comparators"); +const memoize = require("../util/memoize"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../Template").RenderManifestEntry} RenderManifestEntry */ +/** @typedef {import("../Template").RenderManifestOptions} RenderManifestOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ + +const getAsyncWebAssemblyGenerator = memoize(() => + require("./AsyncWebAssemblyGenerator") +); +const getAsyncWebAssemblyJavascriptGenerator = memoize(() => + require("./AsyncWebAssemblyJavascriptGenerator") +); +const getAsyncWebAssemblyParser = memoize(() => + require("./AsyncWebAssemblyParser") +); + +/** + * @typedef {object} WebAssemblyRenderContext + * @property {Chunk} chunk the chunk + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults results of code generation + */ + +/** + * @typedef {object} CompilationHooks + * @property {SyncWaterfallHook<[Source, Module, WebAssemblyRenderContext]>} renderModuleContent + */ + +/** + * @typedef {object} AsyncWebAssemblyModulesPluginOptions + * @property {boolean=} mangleImports mangle imports + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +const PLUGIN_NAME = "AsyncWebAssemblyModulesPlugin"; + +class AsyncWebAssemblyModulesPlugin { + /** + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} the attached hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + renderModuleContent: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** + * @param {AsyncWebAssemblyModulesPluginOptions} options options + */ + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + const hooks = + AsyncWebAssemblyModulesPlugin.getCompilationHooks(compilation); + compilation.dependencyFactories.set( + WebAssemblyImportDependency, + normalModuleFactory + ); + + normalModuleFactory.hooks.createParser + .for(WEBASSEMBLY_MODULE_TYPE_ASYNC) + .tap(PLUGIN_NAME, () => { + const AsyncWebAssemblyParser = getAsyncWebAssemblyParser(); + + return new AsyncWebAssemblyParser(); + }); + normalModuleFactory.hooks.createGenerator + .for(WEBASSEMBLY_MODULE_TYPE_ASYNC) + .tap(PLUGIN_NAME, () => { + const AsyncWebAssemblyJavascriptGenerator = + getAsyncWebAssemblyJavascriptGenerator(); + const AsyncWebAssemblyGenerator = getAsyncWebAssemblyGenerator(); + + return Generator.byType({ + javascript: new AsyncWebAssemblyJavascriptGenerator( + compilation.outputOptions.webassemblyModuleFilename + ), + webassembly: new AsyncWebAssemblyGenerator(this.options) + }); + }); + + compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => { + const { moduleGraph, chunkGraph, runtimeTemplate } = compilation; + const { + chunk, + outputOptions, + dependencyTemplates, + codeGenerationResults + } = options; + + for (const module of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdOrIdentifier(chunkGraph) + )) { + if (module.type === WEBASSEMBLY_MODULE_TYPE_ASYNC) { + const filenameTemplate = + /** @type {NonNullable} */ + (outputOptions.webassemblyModuleFilename); + + result.push({ + render: () => + this.renderModule( + module, + { + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults + }, + hooks + ), + filenameTemplate, + pathOptions: { + module, + runtime: chunk.runtime, + chunkGraph + }, + auxiliary: true, + identifier: `webassemblyAsyncModule${chunkGraph.getModuleId( + module + )}`, + hash: chunkGraph.getModuleHash(module, chunk.runtime) + }); + } + } + + return result; + }); + } + ); + } + + /** + * @param {Module} module the rendered module + * @param {WebAssemblyRenderContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @returns {Source} the newly generated source from rendering + */ + renderModule(module, renderContext, hooks) { + const { codeGenerationResults, chunk } = renderContext; + try { + const moduleSource = codeGenerationResults.getSource( + module, + chunk.runtime, + "webassembly" + ); + return tryRunOrWebpackError( + () => + hooks.renderModuleContent.call(moduleSource, module, renderContext), + "AsyncWebAssemblyModulesPlugin.getCompilationHooks().renderModuleContent" + ); + } catch (err) { + /** @type {WebpackError} */ (err).module = module; + throw err; + } + } +} + +module.exports = AsyncWebAssemblyModulesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyParser.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyParser.js new file mode 100644 index 0000000000000000000000000000000000000000..40f1c79eacca48e8373c43e49b209146a61000b2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/AsyncWebAssemblyParser.js @@ -0,0 +1,88 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const t = require("@webassemblyjs/ast"); +const { decode } = require("@webassemblyjs/wasm-parser"); +const EnvironmentNotSupportAsyncWarning = require("../EnvironmentNotSupportAsyncWarning"); +const Parser = require("../Parser"); +const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); +const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); + +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +const decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true, + + // this will avoid having to lookup with identifiers in the ModuleContext + ignoreCustomNameSection: true +}; + +class WebAssemblyParser extends Parser { + /** + * @param {{}=} options parser options + */ + constructor(options) { + super(); + this.hooks = Object.freeze({}); + this.options = options; + } + + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (!Buffer.isBuffer(source)) { + throw new Error("WebAssemblyParser input must be a Buffer"); + } + + // flag it as async module + const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo); + buildInfo.strict = true; + const BuildMeta = /** @type {BuildMeta} */ (state.module.buildMeta); + BuildMeta.exportsType = "namespace"; + BuildMeta.async = true; + EnvironmentNotSupportAsyncWarning.check( + state.module, + state.compilation.runtimeTemplate, + "asyncWebAssembly" + ); + + // parse it + const program = decode(source, decoderOpts); + const module = program.body[0]; + /** @type {Array} */ + const exports = []; + t.traverse(module, { + ModuleExport({ node }) { + exports.push(node.name); + }, + + ModuleImport({ node }) { + const dep = new WebAssemblyImportDependency( + node.module, + node.name, + node.descr, + false + ); + + state.module.addDependency(dep); + } + }); + + state.module.addDependency(new StaticExportsDependency(exports, false)); + + return state; + } +} + +module.exports = WebAssemblyParser; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..043888c0e7ce7f2d5a888fcb959b619403a6dd70 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js @@ -0,0 +1,107 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Alexander Akait @alexander-akait +*/ + +"use strict"; + +const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const AsyncWasmLoadingRuntimeModule = require("../wasm-async/AsyncWasmLoadingRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "UniversalCompileAsyncWasmPlugin"; + +class UniversalCompileAsyncWasmPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + /** + * @param {Chunk} chunk chunk + * @returns {boolean} true, if wasm loading is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "universal"; + }; + const generateBeforeInstantiateStreaming = () => + Template.asString([ + "if (!useFetch) {", + Template.indent(["return fallback();"]), + "}" + ]); + /** + * @param {string} path path + * @returns {string} code + */ + const generateBeforeLoadBinaryCode = (path) => + Template.asString([ + "var useFetch = typeof document !== 'undefined' || typeof self !== 'undefined';", + `var wasmUrl = ${path};` + ]); + /** + * @type {(path: string) => string} + */ + const generateLoadBinaryCode = () => + Template.asString([ + "(useFetch", + Template.indent([ + `? fetch(new URL(wasmUrl, ${compilation.outputOptions.importMetaName}.url))` + ]), + Template.indent([ + ": Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {", + Template.indent([ + `readFile(new URL(wasmUrl, ${compilation.outputOptions.importMetaName}.url), (err, buffer) => {`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "})))" + ]) + ]); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.instantiateWasm) + .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + (m) => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC + ) + ) { + return; + } + compilation.addRuntimeModule( + chunk, + new AsyncWasmLoadingRuntimeModule({ + generateBeforeLoadBinaryCode, + generateLoadBinaryCode, + generateBeforeInstantiateStreaming, + supportsStreaming: true + }) + ); + }); + }); + } +} + +module.exports = UniversalCompileAsyncWasmPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/UnsupportedWebAssemblyFeatureError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/UnsupportedWebAssemblyFeatureError.js new file mode 100644 index 0000000000000000000000000000000000000000..5174862ca5c69dbab3784109071603b8ba665cea --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/UnsupportedWebAssemblyFeatureError.js @@ -0,0 +1,16 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const WebpackError = require("../WebpackError"); + +module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "UnsupportedWebAssemblyFeatureError"; + this.hideStack = true; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..6be0788886db8b69840e7a802a5a2b8736f2b2fc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js @@ -0,0 +1,417 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const { compareModulesByIdentifier } = require("../util/comparators"); +const WebAssemblyUtils = require("./WebAssemblyUtils"); + +/** @typedef {import("@webassemblyjs/ast").Signature} Signature */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGraph").ModuleId} ModuleId */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +// TODO webpack 6 remove the whole folder + +// Get all wasm modules +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} chunk the chunk + * @returns {Module[]} all wasm modules + */ +const getAllWasmModules = (moduleGraph, chunkGraph, chunk) => { + const wasmModules = chunk.getAllAsyncChunks(); + const array = []; + for (const chunk of wasmModules) { + for (const m of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdentifier + )) { + if (m.type.startsWith("webassembly")) { + array.push(m); + } + } + } + + return array; +}; + +/** + * generates the import object function for a module + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Module} module the module + * @param {boolean | undefined} mangle mangle imports + * @param {string[]} declarations array where declarations are pushed to + * @param {RuntimeSpec} runtime the runtime + * @returns {string} source code + */ +const generateImportObject = ( + chunkGraph, + module, + mangle, + declarations, + runtime +) => { + const moduleGraph = chunkGraph.moduleGraph; + /** @type {Map} */ + const waitForInstances = new Map(); + const properties = []; + const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies( + moduleGraph, + module, + mangle + ); + for (const usedDep of usedWasmDependencies) { + const dep = usedDep.dependency; + const importedModule = moduleGraph.getModule(dep); + const exportName = dep.name; + const usedName = + importedModule && + moduleGraph + .getExportsInfo(importedModule) + .getUsedName(exportName, runtime); + const description = dep.description; + const direct = dep.onlyDirectImport; + + const module = usedDep.module; + const name = usedDep.name; + + if (direct) { + const instanceVar = `m${waitForInstances.size}`; + waitForInstances.set( + instanceVar, + /** @type {ModuleId} */ + (chunkGraph.getModuleId(/** @type {Module} */ (importedModule))) + ); + properties.push({ + module, + name, + value: `${instanceVar}[${JSON.stringify(usedName)}]` + }); + } else { + const params = + /** @type {Signature} */ + (description.signature).params.map( + (param, k) => `p${k}${param.valtype}` + ); + + const mod = `${RuntimeGlobals.moduleCache}[${JSON.stringify( + chunkGraph.getModuleId(/** @type {Module} */ (importedModule)) + )}]`; + const modExports = `${mod}.exports`; + + const cache = `wasmImportedFuncCache${declarations.length}`; + declarations.push(`var ${cache};`); + + const modCode = + /** @type {Module} */ + (importedModule).type.startsWith("webassembly") + ? `${mod} ? ${modExports}[${JSON.stringify(usedName)}] : ` + : ""; + + properties.push({ + module, + name, + value: Template.asString([ + `${modCode}function(${params}) {`, + Template.indent([ + `if(${cache} === undefined) ${cache} = ${modExports};`, + `return ${cache}[${JSON.stringify(usedName)}](${params});` + ]), + "}" + ]) + }); + } + } + + let importObject; + if (mangle) { + importObject = [ + "return {", + Template.indent([ + properties + .map((p) => `${JSON.stringify(p.name)}: ${p.value}`) + .join(",\n") + ]), + "};" + ]; + } else { + /** @type {Map>} */ + const propertiesByModule = new Map(); + for (const p of properties) { + let list = propertiesByModule.get(p.module); + if (list === undefined) { + propertiesByModule.set(p.module, (list = [])); + } + list.push(p); + } + importObject = [ + "return {", + Template.indent([ + Array.from(propertiesByModule, ([module, list]) => + Template.asString([ + `${JSON.stringify(module)}: {`, + Template.indent([ + list + .map((p) => `${JSON.stringify(p.name)}: ${p.value}`) + .join(",\n") + ]), + "}" + ]) + ).join(",\n") + ]), + "};" + ]; + } + + const moduleIdStringified = JSON.stringify(chunkGraph.getModuleId(module)); + if (waitForInstances.size === 1) { + const moduleId = [...waitForInstances.values()][0]; + const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`; + const variable = [...waitForInstances.keys()][0]; + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent([ + `return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`, + Template.indent(importObject), + "});" + ]), + "}," + ]); + } else if (waitForInstances.size > 0) { + const promises = Array.from( + waitForInstances.values(), + (id) => `installedWasmModules[${JSON.stringify(id)}]` + ).join(", "); + const variables = Array.from( + waitForInstances.keys(), + (name, i) => `${name} = array[${i}]` + ).join(", "); + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent([ + `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`, + Template.indent([`var ${variables};`, ...importObject]), + "});" + ]), + "}," + ]); + } + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent(importObject), + "}," + ]); +}; + +/** + * @typedef {object} WasmChunkLoadingRuntimeModuleOptions + * @property {(path: string) => string} generateLoadBinaryCode + * @property {boolean=} supportsStreaming + * @property {boolean=} mangleImports + * @property {ReadOnlyRuntimeRequirements} runtimeRequirements + */ + +class WasmChunkLoadingRuntimeModule extends RuntimeModule { + /** + * @param {WasmChunkLoadingRuntimeModuleOptions} options options + */ + constructor({ + generateLoadBinaryCode, + supportsStreaming, + mangleImports, + runtimeRequirements + }) { + super("wasm chunk loading", RuntimeModule.STAGE_ATTACH); + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.supportsStreaming = supportsStreaming; + this.mangleImports = mangleImports; + this._runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const fn = RuntimeGlobals.ensureChunkHandlers; + const withHmr = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const compilation = /** @type {Compilation} */ (this.compilation); + const { moduleGraph, outputOptions } = compilation; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const wasmModules = getAllWasmModules(moduleGraph, chunkGraph, chunk); + const { mangleImports } = this; + /** @type {string[]} */ + const declarations = []; + const importObjects = wasmModules.map((module) => + generateImportObject( + chunkGraph, + module, + mangleImports, + declarations, + chunk.runtime + ) + ); + const chunkModuleIdMap = chunkGraph.getChunkModuleIdMap(chunk, (m) => + m.type.startsWith("webassembly") + ); + /** + * @param {string} content content + * @returns {string} created import object + */ + const createImportObject = (content) => + mangleImports + ? `{ ${JSON.stringify(WebAssemblyUtils.MANGLED_MODULE)}: ${content} }` + : content; + const wasmModuleSrcPath = compilation.getPath( + JSON.stringify(outputOptions.webassemblyModuleFilename), + { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: (length) => + `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, + module: { + id: '" + wasmModuleId + "', + hash: `" + ${JSON.stringify( + chunkGraph.getChunkModuleRenderedHashMap(chunk, (m) => + m.type.startsWith("webassembly") + ) + )}[chunkId][wasmModuleId] + "`, + hashWithLength(length) { + return `" + ${JSON.stringify( + chunkGraph.getChunkModuleRenderedHashMap( + chunk, + (m) => m.type.startsWith("webassembly"), + length + ) + )}[chunkId][wasmModuleId] + "`; + } + }, + runtime: chunk.runtime + } + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_wasm` + : undefined; + + return Template.asString([ + "// object to store loaded and loading wasm modules", + `var installedWasmModules = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{};`, + "", + // This function is used to delay reading the installed wasm module promises + // by a microtask. Sorting them doesn't help because there are edge cases where + // sorting is not possible (modules splitted into different chunks). + // So we not even trying and solve this by a microtask delay. + "function promiseResolve() { return Promise.resolve(); }", + "", + Template.asString(declarations), + "var wasmImportObjects = {", + Template.indent(importObjects), + "};", + "", + `var wasmModuleMap = ${JSON.stringify( + chunkModuleIdMap, + undefined, + "\t" + )};`, + "", + "// object with all WebAssembly.instance exports", + `${RuntimeGlobals.wasmInstances} = {};`, + "", + "// Fetch + compile chunk loading for webassembly", + `${fn}.wasm = function(chunkId, promises) {`, + Template.indent([ + "", + "var wasmModules = wasmModuleMap[chunkId] || [];", + "", + "wasmModules.forEach(function(wasmModuleId, idx) {", + Template.indent([ + "var installedWasmModuleData = installedWasmModules[wasmModuleId];", + "", + '// a Promise means "currently loading" or "already loaded".', + "if(installedWasmModuleData)", + Template.indent(["promises.push(installedWasmModuleData);"]), + "else {", + Template.indent([ + "var importObject = wasmImportObjects[wasmModuleId]();", + `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, + "var promise;", + this.supportsStreaming + ? Template.asString([ + "if(importObject && typeof importObject.then === 'function' && typeof WebAssembly.compileStreaming === 'function') {", + Template.indent([ + "promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) {", + Template.indent([ + `return WebAssembly.instantiate(items[0], ${createImportObject( + "items[1]" + )});` + ]), + "});" + ]), + "} else if(typeof WebAssembly.instantiateStreaming === 'function') {", + Template.indent([ + `promise = WebAssembly.instantiateStreaming(req, ${createImportObject( + "importObject" + )});` + ]) + ]) + : Template.asString([ + "if(importObject && typeof importObject.then === 'function') {", + Template.indent([ + "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "promise = Promise.all([", + Template.indent([ + "bytesPromise.then(function(bytes) { return WebAssembly.compile(bytes); }),", + "importObject" + ]), + "]).then(function(items) {", + Template.indent([ + `return WebAssembly.instantiate(items[0], ${createImportObject( + "items[1]" + )});` + ]), + "});" + ]) + ]), + "} else {", + Template.indent([ + "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "promise = bytesPromise.then(function(bytes) {", + Template.indent([ + `return WebAssembly.instantiate(bytes, ${createImportObject( + "importObject" + )});` + ]), + "});" + ]), + "}", + "promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) {", + Template.indent([ + `return ${RuntimeGlobals.wasmInstances}[wasmModuleId] = (res.instance || res).exports;` + ]), + "}));" + ]), + "}" + ]), + "});" + ]), + "};" + ]); + } +} + +module.exports = WasmChunkLoadingRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WasmFinalizeExportsPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WasmFinalizeExportsPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..4980ec47e431ea2a60914cca2c36b29cf5b86661 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WasmFinalizeExportsPlugin.js @@ -0,0 +1,91 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const formatLocation = require("../formatLocation"); +const UnsupportedWebAssemblyFeatureError = require("./UnsupportedWebAssemblyFeatureError"); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ + +const PLUGIN_NAME = "WasmFinalizeExportsPlugin"; + +class WasmFinalizeExportsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.finishModules.tap(PLUGIN_NAME, (modules) => { + for (const module of modules) { + // 1. if a WebAssembly module + if (module.type.startsWith("webassembly") === true) { + const jsIncompatibleExports = + /** @type {BuildMeta} */ + (module.buildMeta).jsIncompatibleExports; + + if (jsIncompatibleExports === undefined) { + continue; + } + + for (const connection of compilation.moduleGraph.getIncomingConnections( + module + )) { + // 2. is active and referenced by a non-WebAssembly module + if ( + connection.isTargetActive(undefined) && + /** @type {Module} */ + (connection.originModule).type.startsWith("webassembly") === + false + ) { + const referencedExports = + compilation.getDependencyReferencedExports( + /** @type {Dependency} */ (connection.dependency), + undefined + ); + + for (const info of referencedExports) { + const names = Array.isArray(info) ? info : info.name; + if (names.length === 0) continue; + const name = names[0]; + if (typeof name === "object") continue; + // 3. and uses a func with an incompatible JS signature + if ( + Object.prototype.hasOwnProperty.call( + jsIncompatibleExports, + name + ) + ) { + // 4. error + const error = new UnsupportedWebAssemblyFeatureError( + `Export "${name}" with ${jsIncompatibleExports[name]} can only be used for direct wasm to wasm dependencies\n` + + `It's used from ${ + /** @type {Module} */ + (connection.originModule).readableIdentifier( + compilation.requestShortener + ) + } at ${formatLocation( + /** @type {Dependency} */ (connection.dependency).loc + )}.` + ); + error.module = module; + compilation.errors.push(error); + } + } + } + } + } + } + }); + }); + } +} + +module.exports = WasmFinalizeExportsPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyGenerator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..96811fc9d796a4b586910050b4fe540cfc50fede --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyGenerator.js @@ -0,0 +1,534 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const t = require("@webassemblyjs/ast"); +const { moduleContextFromModuleAST } = require("@webassemblyjs/ast"); +const { addWithAST, editWithAST } = require("@webassemblyjs/wasm-edit"); +const { decode } = require("@webassemblyjs/wasm-parser"); +const { RawSource } = require("webpack-sources"); +const Generator = require("../Generator"); +const { WEBASSEMBLY_TYPES } = require("../ModuleSourceTypesConstants"); +const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); +const WebAssemblyUtils = require("./WebAssemblyUtils"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */ +/** @typedef {import("@webassemblyjs/ast").Instruction} Instruction */ +/** @typedef {import("@webassemblyjs/ast").ModuleImport} ModuleImport */ +/** @typedef {import("@webassemblyjs/ast").ModuleExport} ModuleExport */ +/** @typedef {import("@webassemblyjs/ast").Global} Global */ +/** @typedef {import("@webassemblyjs/ast").AST} AST */ +/** @typedef {import("@webassemblyjs/ast").GlobalType} GlobalType */ +/** + * @template T + * @typedef {import("@webassemblyjs/ast").NodePath} NodePath + */ + +/** + * @typedef {(buf: ArrayBuffer) => ArrayBuffer} ArrayBufferTransform + */ + +/** + * @template T + * @param {((prev: ArrayBuffer) => ArrayBuffer)[]} fns transforms + * @returns {(buf: ArrayBuffer) => ArrayBuffer} composed transform + */ +const compose = (...fns) => + fns.reduce( + (prevFn, nextFn) => (value) => nextFn(prevFn(value)), + (value) => value + ); + +/** + * Removes the start instruction + * @param {object} state state + * @param {AST} state.ast Module's ast + * @returns {ArrayBufferTransform} transform + */ +const removeStartFunc = (state) => (bin) => + editWithAST(state.ast, bin, { + Start(path) { + path.remove(); + } + }); + +/** + * Get imported globals + * @param {AST} ast Module's AST + * @returns {t.ModuleImport[]} - nodes + */ +const getImportedGlobals = (ast) => { + /** @type {t.ModuleImport[]} */ + const importedGlobals = []; + + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); + } + } + }); + + return importedGlobals; +}; + +/** + * Get the count for imported func + * @param {AST} ast Module's AST + * @returns {number} - count + */ +const getCountImportedFunc = (ast) => { + let count = 0; + + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isFuncImportDescr(node.descr)) { + count++; + } + } + }); + + return count; +}; + +/** + * Get next type index + * @param {AST} ast Module's AST + * @returns {t.Index} - index + */ +const getNextTypeIndex = (ast) => { + const typeSectionMetadata = t.getSectionMetadata(ast, "type"); + + if (typeSectionMetadata === undefined) { + return t.indexLiteral(0); + } + + return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); +}; + +/** + * Get next func index + * The Func section metadata provide information for implemented funcs + * in order to have the correct index we shift the index by number of external + * functions. + * @param {AST} ast Module's AST + * @param {number} countImportedFunc number of imported funcs + * @returns {t.Index} - index + */ +const getNextFuncIndex = (ast, countImportedFunc) => { + const funcSectionMetadata = t.getSectionMetadata(ast, "func"); + + if (funcSectionMetadata === undefined) { + return t.indexLiteral(0 + countImportedFunc); + } + + const vectorOfSize = funcSectionMetadata.vectorOfSize.value; + + return t.indexLiteral(vectorOfSize + countImportedFunc); +}; + +/** + * Creates an init instruction for a global type + * @param {t.GlobalType} globalType the global type + * @returns {t.Instruction} init expression + */ +const createDefaultInitForGlobal = (globalType) => { + if (globalType.valtype[0] === "i") { + // create NumberLiteral global initializer + return t.objectInstruction("const", globalType.valtype, [ + t.numberLiteralFromRaw(66) + ]); + } else if (globalType.valtype[0] === "f") { + // create FloatLiteral global initializer + return t.objectInstruction("const", globalType.valtype, [ + t.floatLiteral(66, false, false, "66") + ]); + } + throw new Error(`unknown type: ${globalType.valtype}`); +}; + +/** + * Rewrite the import globals: + * - removes the ModuleImport instruction + * - injects at the same offset a mutable global of the same type + * + * Since the imported globals are before the other global declarations, our + * indices will be preserved. + * + * Note that globals will become mutable. + * @param {object} state transformation state + * @param {AST} state.ast Module's ast + * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function + * @returns {ArrayBufferTransform} transform + */ +const rewriteImportedGlobals = (state) => (bin) => { + const additionalInitCode = state.additionalInitCode; + /** @type {Array} */ + const newGlobals = []; + + bin = editWithAST(state.ast, bin, { + ModuleImport(path) { + if (t.isGlobalType(path.node.descr)) { + const globalType = + /** @type {GlobalType} */ + (path.node.descr); + + globalType.mutability = "var"; + + const init = [ + createDefaultInitForGlobal(globalType), + t.instruction("end") + ]; + + newGlobals.push(t.global(globalType, init)); + + path.remove(); + } + }, + + // in order to preserve non-imported global's order we need to re-inject + // those as well + /** + * @param {NodePath} path path + */ + Global(path) { + const { node } = path; + const [init] = node.init; + + if (init.id === "get_global") { + node.globalType.mutability = "var"; + + const initialGlobalIdx = init.args[0]; + + node.init = [ + createDefaultInitForGlobal(node.globalType), + t.instruction("end") + ]; + + additionalInitCode.push( + /** + * get_global in global initializer only works for imported globals. + * They have the same indices as the init params, so use the + * same index. + */ + t.instruction("get_local", [initialGlobalIdx]), + t.instruction("set_global", [t.indexLiteral(newGlobals.length)]) + ); + } + + newGlobals.push(node); + + path.remove(); + } + }); + + // Add global declaration instructions + return addWithAST(state.ast, bin, newGlobals); +}; + +/** + * Rewrite the export names + * @param {object} state state + * @param {AST} state.ast Module's ast + * @param {Module} state.module Module + * @param {ModuleGraph} state.moduleGraph module graph + * @param {Set} state.externalExports Module + * @param {RuntimeSpec} state.runtime runtime + * @returns {ArrayBufferTransform} transform + */ +const rewriteExportNames = + ({ ast, moduleGraph, module, externalExports, runtime }) => + (bin) => + editWithAST(ast, bin, { + /** + * @param {NodePath} path path + */ + ModuleExport(path) { + const isExternal = externalExports.has(path.node.name); + if (isExternal) { + path.remove(); + return; + } + const usedName = moduleGraph + .getExportsInfo(module) + .getUsedName(path.node.name, runtime); + if (!usedName) { + path.remove(); + return; + } + path.node.name = /** @type {string} */ (usedName); + } + }); + +/** + * Mangle import names and modules + * @param {object} state state + * @param {AST} state.ast Module's ast + * @param {Map} state.usedDependencyMap mappings to mangle names + * @returns {ArrayBufferTransform} transform + */ +const rewriteImports = + ({ ast, usedDependencyMap }) => + (bin) => + editWithAST(ast, bin, { + /** + * @param {NodePath} path path + */ + ModuleImport(path) { + const result = usedDependencyMap.get( + `${path.node.module}:${path.node.name}` + ); + + if (result !== undefined) { + path.node.module = result.module; + path.node.name = result.name; + } + } + }); + +/** + * Add an init function. + * + * The init function fills the globals given input arguments. + * @param {object} state transformation state + * @param {AST} state.ast Module's ast + * @param {t.Identifier} state.initFuncId identifier of the init function + * @param {t.Index} state.startAtFuncOffset index of the start function + * @param {t.ModuleImport[]} state.importedGlobals list of imported globals + * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function + * @param {t.Index} state.nextFuncIndex index of the next function + * @param {t.Index} state.nextTypeIndex index of the next type + * @returns {ArrayBufferTransform} transform + */ +const addInitFunction = + ({ + ast, + initFuncId, + startAtFuncOffset, + importedGlobals, + additionalInitCode, + nextFuncIndex, + nextTypeIndex + }) => + (bin) => { + const funcParams = importedGlobals.map((importedGlobal) => { + // used for debugging + const id = t.identifier( + `${importedGlobal.module}.${importedGlobal.name}` + ); + + return t.funcParam( + /** @type {string} */ (importedGlobal.descr.valtype), + id + ); + }); + + /** @type {Instruction[]} */ + const funcBody = []; + for (const [index, _importedGlobal] of importedGlobals.entries()) { + const args = [t.indexLiteral(index)]; + const body = [ + t.instruction("get_local", args), + t.instruction("set_global", args) + ]; + + funcBody.push(...body); + } + + if (typeof startAtFuncOffset === "number") { + funcBody.push( + t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset)) + ); + } + + for (const instr of additionalInitCode) { + funcBody.push(instr); + } + + funcBody.push(t.instruction("end")); + + /** @type {string[]} */ + const funcResults = []; + + // Code section + const funcSignature = t.signature(funcParams, funcResults); + const func = t.func(initFuncId, funcSignature, funcBody); + + // Type section + const functype = t.typeInstruction(undefined, funcSignature); + + // Func section + const funcindex = t.indexInFuncSection(nextTypeIndex); + + // Export section + const moduleExport = t.moduleExport( + initFuncId.value, + t.moduleExportDescr("Func", nextFuncIndex) + ); + + return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); + }; + +/** + * Extract mangle mappings from module + * @param {ModuleGraph} moduleGraph module graph + * @param {Module} module current module + * @param {boolean | undefined} mangle mangle imports + * @returns {Map} mappings to mangled names + */ +const getUsedDependencyMap = (moduleGraph, module, mangle) => { + /** @type {Map} */ + const map = new Map(); + for (const usedDep of WebAssemblyUtils.getUsedDependencies( + moduleGraph, + module, + mangle + )) { + const dep = usedDep.dependency; + const request = dep.request; + const exportName = dep.name; + map.set(`${request}:${exportName}`, usedDep); + } + return map; +}; + +/** + * @typedef {object} WebAssemblyGeneratorOptions + * @property {boolean=} mangleImports mangle imports + */ + +class WebAssemblyGenerator extends Generator { + /** + * @param {WebAssemblyGeneratorOptions} options options + */ + constructor(options) { + super(); + this.options = options; + } + + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + return WEBASSEMBLY_TYPES; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + const originalSource = module.originalSource(); + if (!originalSource) { + return 0; + } + return originalSource.size(); + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate(module, { moduleGraph, runtime }) { + const bin = + /** @type {Buffer} */ + (/** @type {Source} */ (module.originalSource()).source()); + + const initFuncId = t.identifier(""); + + // parse it + const ast = decode(bin, { + ignoreDataSection: true, + ignoreCodeSection: true, + ignoreCustomNameSection: true + }); + + const moduleContext = moduleContextFromModuleAST(ast.body[0]); + + const importedGlobals = getImportedGlobals(ast); + const countImportedFunc = getCountImportedFunc(ast); + const startAtFuncOffset = moduleContext.getStart(); + const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); + const nextTypeIndex = getNextTypeIndex(ast); + + const usedDependencyMap = getUsedDependencyMap( + moduleGraph, + module, + this.options.mangleImports + ); + const externalExports = new Set( + module.dependencies + .filter((d) => d instanceof WebAssemblyExportImportedDependency) + .map((d) => { + const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ ( + d + ); + return wasmDep.exportName; + }) + ); + + /** @type {t.Instruction[]} */ + const additionalInitCode = []; + + const transform = compose( + rewriteExportNames({ + ast, + moduleGraph, + module, + externalExports, + runtime + }), + + removeStartFunc({ ast }), + + rewriteImportedGlobals({ ast, additionalInitCode }), + + rewriteImports({ + ast, + usedDependencyMap + }), + + addInitFunction({ + ast, + initFuncId, + importedGlobals, + additionalInitCode, + startAtFuncOffset, + nextFuncIndex, + nextTypeIndex + }) + ); + + const newBin = transform(/** @type {ArrayBuffer} */ (bin.buffer)); + const newBuf = Buffer.from(newBin); + + return new RawSource(newBuf); + } + + /** + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generateError(error, module, generateContext) { + return new RawSource(error.message); + } +} + +module.exports = WebAssemblyGenerator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyInInitialChunkError.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyInInitialChunkError.js new file mode 100644 index 0000000000000000000000000000000000000000..099c821734f80aa04c4c9a300a00b30c598f566d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyInInitialChunkError.js @@ -0,0 +1,109 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const WebpackError = require("../WebpackError"); + +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RequestShortener")} RequestShortener */ + +/** + * @param {Module} module module to get chains from + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {RequestShortener} requestShortener to make readable identifiers + * @returns {string[]} all chains to the module + */ +const getInitialModuleChains = ( + module, + moduleGraph, + chunkGraph, + requestShortener +) => { + const queue = [ + { head: module, message: module.readableIdentifier(requestShortener) } + ]; + /** @type {Set} */ + const results = new Set(); + /** @type {Set} */ + const incompleteResults = new Set(); + /** @type {Set} */ + const visitedModules = new Set(); + + for (const chain of queue) { + const { head, message } = chain; + let final = true; + /** @type {Set} */ + const alreadyReferencedModules = new Set(); + for (const connection of moduleGraph.getIncomingConnections(head)) { + const newHead = connection.originModule; + if (newHead) { + if ( + !chunkGraph.getModuleChunks(newHead).some((c) => c.canBeInitial()) + ) { + continue; + } + final = false; + if (alreadyReferencedModules.has(newHead)) continue; + alreadyReferencedModules.add(newHead); + const moduleName = newHead.readableIdentifier(requestShortener); + const detail = connection.explanation + ? ` (${connection.explanation})` + : ""; + const newMessage = `${moduleName}${detail} --> ${message}`; + if (visitedModules.has(newHead)) { + incompleteResults.add(`... --> ${newMessage}`); + continue; + } + visitedModules.add(newHead); + queue.push({ + head: newHead, + message: newMessage + }); + } else { + final = false; + const newMessage = connection.explanation + ? `(${connection.explanation}) --> ${message}` + : message; + results.add(newMessage); + } + } + if (final) { + results.add(message); + } + } + for (const result of incompleteResults) { + results.add(result); + } + return [...results]; +}; + +module.exports = class WebAssemblyInInitialChunkError extends WebpackError { + /** + * @param {Module} module WASM module + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {RequestShortener} requestShortener request shortener + */ + constructor(module, moduleGraph, chunkGraph, requestShortener) { + const moduleChains = getInitialModuleChains( + module, + moduleGraph, + chunkGraph, + requestShortener + ); + const message = `WebAssembly module is included in initial chunk. +This is not allowed, because WebAssembly download and compilation must happen asynchronous. +Add an async split point (i. e. import()) somewhere between your entrypoint and the WebAssembly module: +${moduleChains.map((s) => `* ${s}`).join("\n")}`; + + super(message); + this.name = "WebAssemblyInInitialChunkError"; + this.hideStack = true; + this.module = module; + } +}; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyJavascriptGenerator.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyJavascriptGenerator.js new file mode 100644 index 0000000000000000000000000000000000000000..5bd81a705c6b3fda208f4e68870b8c3caa57d371 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyJavascriptGenerator.js @@ -0,0 +1,230 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { RawSource } = require("webpack-sources"); +const { UsageState } = require("../ExportsInfo"); +const Generator = require("../Generator"); +const InitFragment = require("../InitFragment"); +const { WEBASSEMBLY_TYPES } = require("../ModuleSourceTypesConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const Template = require("../Template"); +const ModuleDependency = require("../dependencies/ModuleDependency"); +const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); +const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").SourceTypes} SourceTypes */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class WebAssemblyJavascriptGenerator extends Generator { + /** + * @param {NormalModule} module fresh module + * @returns {SourceTypes} available types (do not mutate) + */ + getTypes(module) { + return WEBASSEMBLY_TYPES; + } + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + return 95 + module.dependencies.length * 5; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generate(module, generateContext) { + const { + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements, + runtime + } = generateContext; + /** @type {InitFragment>[]} */ + const initFragments = []; + + const exportsInfo = moduleGraph.getExportsInfo(module); + + let needExportsCopy = false; + const importedModules = new Map(); + const initParams = []; + let index = 0; + for (const dep of module.dependencies) { + const moduleDep = + dep && dep instanceof ModuleDependency ? dep : undefined; + if (moduleGraph.getModule(dep)) { + let importData = importedModules.get(moduleGraph.getModule(dep)); + if (importData === undefined) { + importedModules.set( + moduleGraph.getModule(dep), + (importData = { + importVar: `m${index}`, + index, + request: (moduleDep && moduleDep.userRequest) || undefined, + names: new Set(), + reexports: [] + }) + ); + index++; + } + if (dep instanceof WebAssemblyImportDependency) { + importData.names.add(dep.name); + if (dep.description.type === "GlobalType") { + const exportName = dep.name; + const importedModule = moduleGraph.getModule(dep); + + if (importedModule) { + const usedName = moduleGraph + .getExportsInfo(importedModule) + .getUsedName(exportName, runtime); + if (usedName) { + initParams.push( + runtimeTemplate.exportFromImport({ + moduleGraph, + chunkGraph, + module: importedModule, + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null, + defaultInterop: true, + initFragments, + runtime, + runtimeRequirements + }) + ); + } + } + } + } + if (dep instanceof WebAssemblyExportImportedDependency) { + importData.names.add(dep.name); + const usedName = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.exportName, runtime); + if (usedName) { + runtimeRequirements.add(RuntimeGlobals.exports); + const exportProp = `${module.exportsArgument}[${JSON.stringify( + usedName + )}]`; + const defineStatement = Template.asString([ + `${exportProp} = ${runtimeTemplate.exportFromImport({ + moduleGraph, + module: /** @type {Module} */ (moduleGraph.getModule(dep)), + chunkGraph, + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null, + defaultInterop: true, + initFragments, + runtime, + runtimeRequirements + })};`, + `if(WebAssembly.Global) ${exportProp} = ` + + `new WebAssembly.Global({ value: ${JSON.stringify( + dep.valueType + )} }, ${exportProp});` + ]); + importData.reexports.push(defineStatement); + needExportsCopy = true; + } + } + } + } + const importsCode = Template.asString( + Array.from( + importedModules, + ([module, { importVar, request, reexports }]) => { + const importStatement = runtimeTemplate.importStatement({ + module, + moduleGraph, + chunkGraph, + request, + importVar, + originModule: module, + runtimeRequirements + }); + return importStatement[0] + importStatement[1] + reexports.join("\n"); + } + ) + ); + + const copyAllExports = + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused && + !needExportsCopy; + + // need these globals + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.moduleId); + runtimeRequirements.add(RuntimeGlobals.wasmInstances); + if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); + runtimeRequirements.add(RuntimeGlobals.exports); + } + if (!copyAllExports) { + runtimeRequirements.add(RuntimeGlobals.exports); + } + + // create source + const source = new RawSource( + [ + '"use strict";', + "// Instantiate WebAssembly module", + `var wasmExports = ${RuntimeGlobals.wasmInstances}[${module.moduleArgument}.id];`, + + exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused + ? `${RuntimeGlobals.makeNamespaceObject}(${module.exportsArgument});` + : "", + + // this must be before import for circular dependencies + "// export exports from WebAssembly module", + copyAllExports + ? `${module.moduleArgument}.exports = wasmExports;` + : "for(var name in wasmExports) " + + "if(name) " + + `${module.exportsArgument}[name] = wasmExports[name];`, + "// exec imports from WebAssembly module (for esm order)", + importsCode, + "", + "// exec wasm module", + `wasmExports[""](${initParams.join(", ")})` + ].join("\n") + ); + return InitFragment.addToSource(source, initFragments, generateContext); + } + + /** + * @param {Error} error the error + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source | null} generated code + */ + generateError(error, module, generateContext) { + return new RawSource(`throw new Error(${JSON.stringify(error.message)});`); + } +} + +module.exports = WebAssemblyJavascriptGenerator; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyModulesPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyModulesPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..bdad089ddcad74f03f8f69710e02ef551df0b0a4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyModulesPlugin.js @@ -0,0 +1,152 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Generator = require("../Generator"); +const { WEBASSEMBLY_MODULE_TYPE_SYNC } = require("../ModuleTypeConstants"); +const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); +const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); +const { compareModulesByIdOrIdentifier } = require("../util/comparators"); +const memoize = require("../util/memoize"); +const WebAssemblyInInitialChunkError = require("./WebAssemblyInInitialChunkError"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ + +const getWebAssemblyGenerator = memoize(() => + require("./WebAssemblyGenerator") +); +const getWebAssemblyJavascriptGenerator = memoize(() => + require("./WebAssemblyJavascriptGenerator") +); +const getWebAssemblyParser = memoize(() => require("./WebAssemblyParser")); + +const PLUGIN_NAME = "WebAssemblyModulesPlugin"; + +/** + * @typedef {object} WebAssemblyModulesPluginOptions + * @property {boolean=} mangleImports mangle imports + */ + +class WebAssemblyModulesPlugin { + /** + * @param {WebAssemblyModulesPluginOptions} options options + */ + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WebAssemblyImportDependency, + normalModuleFactory + ); + + compilation.dependencyFactories.set( + WebAssemblyExportImportedDependency, + normalModuleFactory + ); + + normalModuleFactory.hooks.createParser + .for(WEBASSEMBLY_MODULE_TYPE_SYNC) + .tap(PLUGIN_NAME, () => { + const WebAssemblyParser = getWebAssemblyParser(); + + return new WebAssemblyParser(); + }); + + normalModuleFactory.hooks.createGenerator + .for(WEBASSEMBLY_MODULE_TYPE_SYNC) + .tap(PLUGIN_NAME, () => { + const WebAssemblyJavascriptGenerator = + getWebAssemblyJavascriptGenerator(); + const WebAssemblyGenerator = getWebAssemblyGenerator(); + + return Generator.byType({ + javascript: new WebAssemblyJavascriptGenerator(), + webassembly: new WebAssemblyGenerator(this.options) + }); + }); + + compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => { + const { chunkGraph } = compilation; + const { chunk, outputOptions, codeGenerationResults } = options; + + for (const module of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdOrIdentifier(chunkGraph) + )) { + if (module.type === WEBASSEMBLY_MODULE_TYPE_SYNC) { + const filenameTemplate = + /** @type {NonNullable} */ + (outputOptions.webassemblyModuleFilename); + + result.push({ + render: () => + codeGenerationResults.getSource( + module, + chunk.runtime, + "webassembly" + ), + filenameTemplate, + pathOptions: { + module, + runtime: chunk.runtime, + chunkGraph + }, + auxiliary: true, + identifier: `webassemblyModule${chunkGraph.getModuleId( + module + )}`, + hash: chunkGraph.getModuleHash(module, chunk.runtime) + }); + } + } + + return result; + }); + + compilation.hooks.afterChunks.tap(PLUGIN_NAME, () => { + const chunkGraph = compilation.chunkGraph; + const initialWasmModules = new Set(); + for (const chunk of compilation.chunks) { + if (chunk.canBeInitial()) { + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (module.type === WEBASSEMBLY_MODULE_TYPE_SYNC) { + initialWasmModules.add(module); + } + } + } + } + for (const module of initialWasmModules) { + compilation.errors.push( + new WebAssemblyInInitialChunkError( + module, + compilation.moduleGraph, + compilation.chunkGraph, + compilation.requestShortener + ) + ); + } + }); + } + ); + } +} + +module.exports = WebAssemblyModulesPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyParser.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyParser.js new file mode 100644 index 0000000000000000000000000000000000000000..8e980ad8230987d4d43b2f150e5164ee1932a76e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyParser.js @@ -0,0 +1,211 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const t = require("@webassemblyjs/ast"); +const { moduleContextFromModuleAST } = require("@webassemblyjs/ast"); +const { decode } = require("@webassemblyjs/wasm-parser"); +const Parser = require("../Parser"); +const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); +const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency"); +const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); + +/** @typedef {import("@webassemblyjs/ast").ModuleImport} ModuleImport */ +/** @typedef {import("@webassemblyjs/ast").NumberLiteral} NumberLiteral */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").BuildInfo} BuildInfo */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +const JS_COMPAT_TYPES = new Set(["i32", "i64", "f32", "f64", "externref"]); + +/** + * @param {t.Signature} signature the func signature + * @returns {null | string} the type incompatible with js types + */ +const getJsIncompatibleType = (signature) => { + for (const param of signature.params) { + if (!JS_COMPAT_TYPES.has(param.valtype)) { + return `${param.valtype} as parameter`; + } + } + for (const type of signature.results) { + if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; + } + return null; +}; + +/** + * TODO why are there two different Signature types? + * @param {t.FuncSignature} signature the func signature + * @returns {null | string} the type incompatible with js types + */ +const getJsIncompatibleTypeOfFuncSignature = (signature) => { + for (const param of signature.args) { + if (!JS_COMPAT_TYPES.has(param)) { + return `${param} as parameter`; + } + } + for (const type of signature.result) { + if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; + } + return null; +}; + +const decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true, + + // this will avoid having to lookup with identifiers in the ModuleContext + ignoreCustomNameSection: true +}; + +class WebAssemblyParser extends Parser { + /** + * @param {{}=} options parser options + */ + constructor(options) { + super(); + this.hooks = Object.freeze({}); + this.options = options; + } + + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (!Buffer.isBuffer(source)) { + throw new Error("WebAssemblyParser input must be a Buffer"); + } + + // flag it as ESM + /** @type {BuildInfo} */ + (state.module.buildInfo).strict = true; + /** @type {BuildMeta} */ + (state.module.buildMeta).exportsType = "namespace"; + + // parse it + const program = decode(source, decoderOpts); + const module = program.body[0]; + + const moduleContext = moduleContextFromModuleAST(module); + + // extract imports and exports + /** @type {string[]} */ + const exports = []; + const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta); + /** @type {Record | undefined} */ + let jsIncompatibleExports = (buildMeta.jsIncompatibleExports = undefined); + + /** @type {(ModuleImport | null)[]} */ + const importedGlobals = []; + + t.traverse(module, { + ModuleExport({ node }) { + const descriptor = node.descr; + + if (descriptor.exportType === "Func") { + const funcIdx = descriptor.id.value; + + /** @type {t.FuncSignature} */ + const funcSignature = moduleContext.getFunction(funcIdx); + + const incompatibleType = + getJsIncompatibleTypeOfFuncSignature(funcSignature); + + if (incompatibleType) { + if (jsIncompatibleExports === undefined) { + jsIncompatibleExports = + /** @type {BuildMeta} */ + (state.module.buildMeta).jsIncompatibleExports = {}; + } + jsIncompatibleExports[node.name] = incompatibleType; + } + } + + exports.push(node.name); + + if (node.descr && node.descr.exportType === "Global") { + const refNode = + importedGlobals[/** @type {NumberLiteral} */ (node.descr.id).value]; + if (refNode) { + const dep = new WebAssemblyExportImportedDependency( + node.name, + refNode.module, + refNode.name, + /** @type {string} */ + (refNode.descr.valtype) + ); + + state.module.addDependency(dep); + } + } + }, + + Global({ node }) { + const init = node.init[0]; + + let importNode = null; + + if (init.id === "get_global") { + const globalIdx = init.args[0].value; + + if (globalIdx < importedGlobals.length) { + importNode = importedGlobals[globalIdx]; + } + } + + importedGlobals.push(importNode); + }, + + ModuleImport({ node }) { + /** @type {false | string} */ + let onlyDirectImport = false; + + if (t.isMemory(node.descr) === true) { + onlyDirectImport = "Memory"; + } else if (t.isTable(node.descr) === true) { + onlyDirectImport = "Table"; + } else if (t.isFuncImportDescr(node.descr) === true) { + const incompatibleType = getJsIncompatibleType( + /** @type {t.Signature} */ + (node.descr.signature) + ); + if (incompatibleType) { + onlyDirectImport = `Non-JS-compatible Func Signature (${incompatibleType})`; + } + } else if (t.isGlobalType(node.descr) === true) { + const type = /** @type {string} */ (node.descr.valtype); + if (!JS_COMPAT_TYPES.has(type)) { + onlyDirectImport = `Non-JS-compatible Global Type (${type})`; + } + } + + const dep = new WebAssemblyImportDependency( + node.module, + node.name, + node.descr, + onlyDirectImport + ); + + state.module.addDependency(dep); + + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); + } + } + }); + + state.module.addDependency(new StaticExportsDependency(exports, false)); + + return state; + } +} + +module.exports = WebAssemblyParser; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyUtils.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyUtils.js new file mode 100644 index 0000000000000000000000000000000000000000..27c5111d3f1aef98d4050ec6e57e5bc5027cd242 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm-sync/WebAssemblyUtils.js @@ -0,0 +1,66 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const Template = require("../Template"); +const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); + +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ + +/** + * @typedef {object} UsedWasmDependency + * @property {WebAssemblyImportDependency} dependency the dependency + * @property {string} name the export name + * @property {string} module the module name + */ + +const MANGLED_MODULE = "a"; + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} module the module + * @param {boolean | undefined} mangle mangle module and export names + * @returns {UsedWasmDependency[]} used dependencies and (mangled) name + */ +const getUsedDependencies = (moduleGraph, module, mangle) => { + /** @type {UsedWasmDependency[]} */ + const array = []; + let importIndex = 0; + for (const dep of module.dependencies) { + if (dep instanceof WebAssemblyImportDependency) { + if ( + dep.description.type === "GlobalType" || + moduleGraph.getModule(dep) === null + ) { + continue; + } + + const exportName = dep.name; + // TODO add the following 3 lines when removing of ModuleExport is possible + // const importedModule = moduleGraph.getModule(dep); + // const usedName = importedModule && moduleGraph.getExportsInfo(importedModule).getUsedName(exportName, runtime); + // if (usedName !== false) { + if (mangle) { + array.push({ + dependency: dep, + name: Template.numberToIdentifier(importIndex++), + module: MANGLED_MODULE + }); + } else { + array.push({ + dependency: dep, + name: exportName, + module: dep.request + }); + } + } + } + return array; +}; + +module.exports.MANGLED_MODULE = MANGLED_MODULE; +module.exports.getUsedDependencies = getUsedDependencies; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm/EnableWasmLoadingPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm/EnableWasmLoadingPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..365438d07bdea2326d2f45a3852b4b5991a0f2ea --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/wasm/EnableWasmLoadingPlugin.js @@ -0,0 +1,137 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").WasmLoadingType} WasmLoadingType */ +/** @typedef {import("../Compiler")} Compiler */ + +/** @type {WeakMap>} */ +const enabledTypes = new WeakMap(); + +/** + * @param {Compiler} compiler compiler instance + * @returns {Set} enabled types + */ +const getEnabledTypes = (compiler) => { + let set = enabledTypes.get(compiler); + if (set === undefined) { + set = new Set(); + enabledTypes.set(compiler, set); + } + return set; +}; + +class EnableWasmLoadingPlugin { + /** + * @param {WasmLoadingType} type library type that should be available + */ + constructor(type) { + this.type = type; + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {WasmLoadingType} type type of library + * @returns {void} + */ + static setEnabled(compiler, type) { + getEnabledTypes(compiler).add(type); + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {WasmLoadingType} type type of library + * @returns {void} + */ + static checkEnabled(compiler, type) { + if (!getEnabledTypes(compiler).has(type)) { + throw new Error( + `Library type "${type}" is not enabled. ` + + "EnableWasmLoadingPlugin need to be used to enable this type of wasm loading. " + + 'This usually happens through the "output.enabledWasmLoadingTypes" option. ' + + 'If you are using a function as entry which sets "wasmLoading", you need to add all potential library types to "output.enabledWasmLoadingTypes". ' + + `These types are enabled: ${[...getEnabledTypes(compiler)].join(", ")}` + ); + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { type } = this; + + // Only enable once + const enabled = getEnabledTypes(compiler); + if (enabled.has(type)) return; + enabled.add(type); + + if (typeof type === "string") { + switch (type) { + case "fetch": { + if (compiler.options.experiments.syncWebAssembly) { + // TODO webpack 6 remove FetchCompileWasmPlugin + const FetchCompileWasmPlugin = require("../web/FetchCompileWasmPlugin"); + + new FetchCompileWasmPlugin({ + mangleImports: compiler.options.optimization.mangleWasmImports + }).apply(compiler); + } + + if (compiler.options.experiments.asyncWebAssembly) { + const FetchCompileAsyncWasmPlugin = require("../web/FetchCompileAsyncWasmPlugin"); + + new FetchCompileAsyncWasmPlugin().apply(compiler); + } + + break; + } + case "async-node": { + if (compiler.options.experiments.syncWebAssembly) { + // TODO webpack 6 remove ReadFileCompileWasmPlugin + const ReadFileCompileWasmPlugin = require("../node/ReadFileCompileWasmPlugin"); + + new ReadFileCompileWasmPlugin({ + mangleImports: compiler.options.optimization.mangleWasmImports, + import: + compiler.options.output.module && + compiler.options.output.environment.dynamicImport + }).apply(compiler); + } + + if (compiler.options.experiments.asyncWebAssembly) { + const ReadFileCompileAsyncWasmPlugin = require("../node/ReadFileCompileAsyncWasmPlugin"); + + new ReadFileCompileAsyncWasmPlugin({ + import: + compiler.options.output.module && + compiler.options.output.environment.dynamicImport + }).apply(compiler); + } + + break; + } + case "universal": { + const UniversalCompileAsyncWasmPlugin = require("../wasm-async/UniversalCompileAsyncWasmPlugin"); + + new UniversalCompileAsyncWasmPlugin().apply(compiler); + break; + } + default: + throw new Error(`Unsupported wasm loading type ${type}. +Plugins which provide custom wasm loading types must call EnableWasmLoadingPlugin.setEnabled(compiler, type) to disable this error.`); + } + } else { + // TODO support plugin instances here + // apply them to the compiler + } + } +} + +module.exports = EnableWasmLoadingPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/FetchCompileAsyncWasmPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/FetchCompileAsyncWasmPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..088b7b583f9cdcc2078f4a732d3e9425e3000093 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/FetchCompileAsyncWasmPlugin.js @@ -0,0 +1,70 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const AsyncWasmLoadingRuntimeModule = require("../wasm-async/AsyncWasmLoadingRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "FetchCompileAsyncWasmPlugin"; + +class FetchCompileAsyncWasmPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + /** + * @param {Chunk} chunk chunk + * @returns {boolean} true, if wasm loading is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "fetch"; + }; + /** + * @param {string} path path to the wasm file + * @returns {string} code to load the wasm file + */ + const generateLoadBinaryCode = (path) => + `fetch(${RuntimeGlobals.publicPath} + ${path})`; + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.instantiateWasm) + .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + (m) => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC + ) + ) { + return; + } + set.add(RuntimeGlobals.publicPath); + compilation.addRuntimeModule( + chunk, + new AsyncWasmLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: true + }) + ); + }); + }); + } +} + +module.exports = FetchCompileAsyncWasmPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/FetchCompileWasmPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/FetchCompileWasmPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..91edf0928e6016e087a55a2f2540960d02b8a845 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/FetchCompileWasmPlugin.js @@ -0,0 +1,87 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { WEBASSEMBLY_MODULE_TYPE_SYNC } = require("../ModuleTypeConstants"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const WasmChunkLoadingRuntimeModule = require("../wasm-sync/WasmChunkLoadingRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {object} FetchCompileWasmPluginOptions + * @property {boolean=} mangleImports mangle imports + */ + +// TODO webpack 6 remove + +const PLUGIN_NAME = "FetchCompileWasmPlugin"; + +class FetchCompileWasmPlugin { + /** + * @param {FetchCompileWasmPluginOptions=} options options + */ + constructor(options = {}) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + /** + * @param {Chunk} chunk chunk + * @returns {boolean} true, if wasm loading is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "fetch"; + }; + /** + * @param {string} path path to the wasm file + * @returns {string} code to load the wasm file + */ + const generateLoadBinaryCode = (path) => + `fetch(${RuntimeGlobals.publicPath} + ${path})`; + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + (m) => m.type === WEBASSEMBLY_MODULE_TYPE_SYNC + ) + ) { + return; + } + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.publicPath); + compilation.addRuntimeModule( + chunk, + new WasmChunkLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: true, + mangleImports: this.options.mangleImports, + runtimeRequirements: set + }) + ); + }); + }); + } +} + +module.exports = FetchCompileWasmPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/JsonpChunkLoadingPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/JsonpChunkLoadingPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..49fbd33f322fb174fa040467aeccf9031abc78b1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/JsonpChunkLoadingPlugin.js @@ -0,0 +1,99 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const JsonpChunkLoadingRuntimeModule = require("./JsonpChunkLoadingRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "JsonpChunkLoadingPlugin"; + +class JsonpChunkLoadingPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + /** + * @param {Chunk} chunk chunk + * @returns {boolean} true, if wasm loading is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === "jsonp"; + }; + const onceForChunkSet = new WeakSet(); + /** + * @param {Chunk} chunk chunk + * @param {Set} set runtime requirements + */ + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new JsonpChunkLoadingRuntimeModule(set) + ); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap(PLUGIN_NAME, handler); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.loadScript); + set.add(RuntimeGlobals.getChunkScriptFilename); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.loadScript); + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getUpdateManifestFilename); + }); + }); + } +} + +module.exports = JsonpChunkLoadingPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/JsonpChunkLoadingRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/JsonpChunkLoadingRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..d043dd93e8adfc85424c86a8856691c0250af6f1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/JsonpChunkLoadingRuntimeModule.js @@ -0,0 +1,454 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const { SyncWaterfallHook } = require("tapable"); +const Compilation = require("../Compilation"); +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const { + generateJavascriptHMR +} = require("../hmr/JavascriptHotModuleReplacementHelper"); +const chunkHasJs = require("../javascript/JavascriptModulesPlugin").chunkHasJs; +const { getInitialChunkIds } = require("../javascript/StartupHelpers"); +const compileBooleanMatcher = require("../util/compileBooleanMatcher"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ + +/** + * @typedef {object} JsonpCompilationPluginHooks + * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload + * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class JsonpChunkLoadingRuntimeModule extends RuntimeModule { + /** + * @param {Compilation} compilation the compilation + * @returns {JsonpCompilationPluginHooks} hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); + } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + linkPreload: new SyncWaterfallHook(["source", "chunk"]), + linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** + * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super("jsonp chunk loading", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; + } + + /** + * @private + * @param {Chunk} chunk chunk + * @returns {string} generated code + */ + _generateBaseUri(chunk) { + const options = chunk.getEntryOptions(); + if (options && options.baseUri) { + return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`; + } + return `${RuntimeGlobals.baseURI} = document.baseURI || self.location.href;`; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const { + runtimeTemplate, + outputOptions: { + chunkLoadingGlobal, + hotUpdateGlobal, + crossOriginLoading, + scriptType, + charset + } + } = compilation; + const globalObject = runtimeTemplate.globalObject; + const { linkPreload, linkPrefetch } = + JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); + const withLoading = this._runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withCallback = this._runtimeRequirements.has( + RuntimeGlobals.chunkCallback + ); + const withOnChunkLoad = this._runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withHmr = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const withFetchPriority = this._runtimeRequirements.has( + RuntimeGlobals.hasFetchPriority + ); + const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}]`; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const withPrefetch = + this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) && + chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasJs); + const withPreload = + this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) && + chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasJs); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_jsonp` + : undefined; + + return Template.asString([ + withBaseURI ? this._generateBaseUri(chunk) : "// no baseURI", + "", + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), + "};", + "", + withLoading + ? Template.asString([ + `${fn}.j = ${runtimeTemplate.basicFunction( + `chunkId, promises${withFetchPriority ? ", fetchPriority" : ""}`, + hasJsMatcher !== false + ? Template.indent([ + "// JSONP chunk loading for javascript", + `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent([ + "promises.push(installedChunkData[2]);" + ]), + "} else {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + "// setup Promise in chunk cache", + `var promise = new Promise(${runtimeTemplate.expressionFunction( + "installedChunkData = installedChunks[chunkId] = [resolve, reject]", + "resolve, reject" + )});`, + "promises.push(installedChunkData[2] = promise);", + "", + "// start chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + `var loadingEnded = ${runtimeTemplate.basicFunction( + "event", + [ + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, + Template.indent([ + "installedChunkData = installedChunks[chunkId];", + "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", + "if(installedChunkData) {", + Template.indent([ + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "installedChunkData[1](error);" + ]), + "}" + ]), + "}" + ] + )};`, + `${ + RuntimeGlobals.loadScript + }(url, loadingEnded, "chunk-" + chunkId, chunkId${ + withFetchPriority ? ", fetchPriority" : "" + });` + ]), + hasJsMatcher === true + ? "}" + : "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ]) + : Template.indent(["installedChunks[chunkId] = 0;"]) + )};` + ]) + : "// no chunk on demand loading", + "", + withPrefetch && hasJsMatcher !== false + ? `${ + RuntimeGlobals.prefetchChunkHandlers + }.j = ${runtimeTemplate.basicFunction("chunkId", [ + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + linkPrefetch.call( + Template.asString([ + "var link = document.createElement('link');", + charset ? "link.charset = 'utf-8';" : "", + crossOriginLoading + ? `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + : "", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + 'link.rel = "prefetch";', + 'link.as = "script";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);` + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no prefetching", + "", + withPreload && hasJsMatcher !== false + ? `${ + RuntimeGlobals.preloadChunkHandlers + }.j = ${runtimeTemplate.basicFunction("chunkId", [ + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + linkPreload.call( + Template.asString([ + "var link = document.createElement('link');", + scriptType && scriptType !== "module" + ? `link.type = ${JSON.stringify(scriptType)};` + : "", + charset ? "link.charset = 'utf-8';" : "", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + scriptType === "module" + ? 'link.rel = "modulepreload";' + : 'link.rel = "preload";', + scriptType === "module" ? "" : 'link.as = "script";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, + crossOriginLoading + ? crossOriginLoading === "use-credentials" + ? 'link.crossOrigin = "use-credentials";' + : Template.asString([ + "if (link.href.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + ), + "}" + ]) + : "" + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no preloaded", + "", + withHmr + ? Template.asString([ + "var currentUpdatedModulesList;", + "var waitingUpdateResolves = {};", + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + "currentUpdatedModulesList = updatedModulesList;", + `return new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + "waitingUpdateResolves[chunkId] = resolve;", + "// start update chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + `var loadingEnded = ${runtimeTemplate.basicFunction("event", [ + "if(waitingUpdateResolves[chunkId]) {", + Template.indent([ + "waitingUpdateResolves[chunkId] = undefined", + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "reject(error);" + ]), + "}" + ])};`, + `${RuntimeGlobals.loadScript}(url, loadingEnded);` + ] + )});` + ]), + "}", + "", + `${globalObject}[${JSON.stringify( + hotUpdateGlobal + )}] = ${runtimeTemplate.basicFunction( + "chunkId, moreModules, runtime", + [ + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + "currentUpdate[moduleId] = moreModules[moduleId];", + "if(currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);", + "if(waitingUpdateResolves[chunkId]) {", + Template.indent([ + "waitingUpdateResolves[chunkId]();", + "waitingUpdateResolves[chunkId] = undefined;" + ]), + "}" + ] + )};`, + "", + generateJavascriptHMR("jsonp") + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${ + RuntimeGlobals.hmrDownloadManifest + } = ${runtimeTemplate.basicFunction("", [ + 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', + `return fetch(${RuntimeGlobals.publicPath} + ${ + RuntimeGlobals.getUpdateManifestFilename + }()).then(${runtimeTemplate.basicFunction("response", [ + "if(response.status === 404) return; // no update available", + 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', + "return response.json();" + ])});` + ])};` + ]) + : "// no HMR manifest", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.j = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId] === 0", + "chunkId" + )};` + : "// no on chunks loaded", + "", + withCallback || withLoading + ? Template.asString([ + "// install a JSONP callback for chunk loading", + `var webpackJsonpCallback = ${runtimeTemplate.basicFunction( + "parentChunkLoadingFunction, data", + [ + runtimeTemplate.destructureArray( + ["chunkIds", "moreModules", "runtime"], + "data" + ), + '// add "moreModules" to the modules object,', + '// then flag all "chunkIds" as loaded and fire callback', + "var moduleId, chunkId, i = 0;", + `if(chunkIds.some(${runtimeTemplate.returningFunction( + "installedChunks[id] !== 0", + "id" + )})) {`, + Template.indent([ + "for(moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ), + "}" + ]), + "}", + `if(runtime) var result = runtime(${RuntimeGlobals.require});` + ]), + "}", + "if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);", + "for(;i < chunkIds.length; i++) {", + Template.indent([ + "chunkId = chunkIds[i];", + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, + Template.indent("installedChunks[chunkId][0]();"), + "}", + "installedChunks[chunkId] = 0;" + ]), + "}", + withOnChunkLoad + ? `return ${RuntimeGlobals.onChunksLoaded}(result);` + : "" + ] + )}`, + "", + `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, + "chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));", + "chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));" + ]) + : "// no jsonp function" + ]); + } +} + +module.exports = JsonpChunkLoadingRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/JsonpTemplatePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/JsonpTemplatePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..eeed68a28ba65f2089970b85e21ca7c55e079fdf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/web/JsonpTemplatePlugin.js @@ -0,0 +1,38 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ArrayPushCallbackChunkFormatPlugin = require("../javascript/ArrayPushCallbackChunkFormatPlugin"); +const EnableChunkLoadingPlugin = require("../javascript/EnableChunkLoadingPlugin"); +const JsonpChunkLoadingRuntimeModule = require("./JsonpChunkLoadingRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ + +class JsonpTemplatePlugin { + /** + * @deprecated use JsonpChunkLoadingRuntimeModule.getCompilationHooks instead + * @param {Compilation} compilation the compilation + * @returns {JsonpChunkLoadingRuntimeModule.JsonpCompilationPluginHooks} hooks + */ + static getCompilationHooks(compilation) { + return JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.options.output.chunkLoading = "jsonp"; + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin("jsonp").apply(compiler); + } +} + +module.exports = JsonpTemplatePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webpack.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webpack.js new file mode 100644 index 0000000000000000000000000000000000000000..75b93687bd0aed8c372c3d58a65ff77b5d1b7b16 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webpack.js @@ -0,0 +1,199 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const util = require("util"); +const webpackOptionsSchemaCheck = require("../schemas/WebpackOptions.check"); +const webpackOptionsSchema = require("../schemas/WebpackOptions.json"); +const Compiler = require("./Compiler"); +const MultiCompiler = require("./MultiCompiler"); +const WebpackOptionsApply = require("./WebpackOptionsApply"); +const { + applyWebpackOptionsBaseDefaults, + applyWebpackOptionsDefaults +} = require("./config/defaults"); +const { getNormalizedWebpackOptions } = require("./config/normalization"); +const NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin"); +const memoize = require("./util/memoize"); + +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ +/** @typedef {import("./Compiler").WatchOptions} WatchOptions */ +/** @typedef {import("./MultiCompiler").MultiCompilerOptions} MultiCompilerOptions */ +/** @typedef {import("./MultiCompiler").MultiWebpackOptions} MultiWebpackOptions */ +/** @typedef {import("./MultiStats")} MultiStats */ +/** @typedef {import("./Stats")} Stats */ + +const getValidateSchema = memoize(() => require("./validateSchema")); + +/** + * @template T + * @callback Callback + * @param {Error | null} err + * @param {T=} stats + * @returns {void} + */ + +/** + * @param {ReadonlyArray} childOptions options array + * @param {MultiCompilerOptions} options options + * @returns {MultiCompiler} a multi-compiler + */ +const createMultiCompiler = (childOptions, options) => { + const compilers = childOptions.map((options, index) => + createCompiler(options, index) + ); + const compiler = new MultiCompiler(compilers, options); + for (const childCompiler of compilers) { + if (childCompiler.options.dependencies) { + compiler.setDependencies( + childCompiler, + childCompiler.options.dependencies + ); + } + } + return compiler; +}; + +/** + * @param {WebpackOptions} rawOptions options object + * @param {number=} compilerIndex index of compiler + * @returns {Compiler} a compiler + */ +const createCompiler = (rawOptions, compilerIndex) => { + const options = getNormalizedWebpackOptions(rawOptions); + applyWebpackOptionsBaseDefaults(options); + const compiler = new Compiler( + /** @type {string} */ (options.context), + options + ); + new NodeEnvironmentPlugin({ + infrastructureLogging: options.infrastructureLogging + }).apply(compiler); + if (Array.isArray(options.plugins)) { + for (const plugin of options.plugins) { + if (typeof plugin === "function") { + /** @type {WebpackPluginFunction} */ + (plugin).call(compiler, compiler); + } else if (plugin) { + plugin.apply(compiler); + } + } + } + const resolvedDefaultOptions = applyWebpackOptionsDefaults( + options, + compilerIndex + ); + if (resolvedDefaultOptions.platform) { + compiler.platform = resolvedDefaultOptions.platform; + } + compiler.hooks.environment.call(); + compiler.hooks.afterEnvironment.call(); + new WebpackOptionsApply().process(options, compiler); + compiler.hooks.initialize.call(); + return compiler; +}; + +/** + * @callback WebpackFunctionSingle + * @param {WebpackOptions} options options object + * @param {Callback=} callback callback + * @returns {Compiler | null} the compiler object + */ + +/** + * @callback WebpackFunctionMulti + * @param {MultiWebpackOptions} options options objects + * @param {Callback=} callback callback + * @returns {MultiCompiler | null} the multi compiler object + */ + +/** + * @template T + * @param {Array | T} options options + * @returns {Array} array of options + */ +const asArray = (options) => + Array.isArray(options) ? [...options] : [options]; + +/** + * @callback WebpackCallback + * @param {WebpackOptions | MultiWebpackOptions} options options + * @param {Callback & Callback=} callback callback + * @returns {Compiler | MultiCompiler | null} Compiler or MultiCompiler + */ + +const webpack = /** @type {WebpackFunctionSingle & WebpackFunctionMulti} */ ( + /** @type {WebpackCallback} */ + (options, callback) => { + const create = () => { + if (!asArray(options).every(webpackOptionsSchemaCheck)) { + getValidateSchema()(webpackOptionsSchema, options); + util.deprecate( + () => {}, + "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", + "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" + )(); + } + /** @type {MultiCompiler|Compiler} */ + let compiler; + /** @type {boolean | undefined} */ + let watch = false; + /** @type {WatchOptions|WatchOptions[]} */ + let watchOptions; + if (Array.isArray(options)) { + /** @type {MultiCompiler} */ + compiler = createMultiCompiler( + options, + /** @type {MultiCompilerOptions} */ (options) + ); + watch = options.some((options) => options.watch); + watchOptions = options.map((options) => options.watchOptions || {}); + } else { + const webpackOptions = /** @type {WebpackOptions} */ (options); + /** @type {Compiler} */ + compiler = createCompiler(webpackOptions); + watch = webpackOptions.watch; + watchOptions = webpackOptions.watchOptions || {}; + } + return { compiler, watch, watchOptions }; + }; + if (callback) { + try { + const { compiler, watch, watchOptions } = create(); + if (watch) { + compiler.watch(watchOptions, callback); + } else { + compiler.run((err, stats) => { + compiler.close((err2) => { + callback( + err || err2, + /** @type {options extends WebpackOptions ? Stats : MultiStats} */ + (stats) + ); + }); + }); + } + return compiler; + } catch (err) { + process.nextTick(() => callback(/** @type {Error} */ (err))); + return null; + } + } else { + const { compiler, watch } = create(); + if (watch) { + util.deprecate( + () => {}, + "A 'callback' argument needs to be provided to the 'webpack(options, callback)' function when the 'watch' option is set. There is no way to handle the 'watch' option without a callback.", + "DEP_WEBPACK_WATCH_WITHOUT_CALLBACK" + )(); + } + return compiler; + } + } +); + +module.exports = webpack; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webworker/ImportScriptsChunkLoadingPlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webworker/ImportScriptsChunkLoadingPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..661df29616ef8d914bea2c2501754d94422ee375 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webworker/ImportScriptsChunkLoadingPlugin.js @@ -0,0 +1,108 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const StartupChunkDependenciesPlugin = require("../runtime/StartupChunkDependenciesPlugin"); +const ImportScriptsChunkLoadingRuntimeModule = require("./ImportScriptsChunkLoadingRuntimeModule"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const PLUGIN_NAME = "ImportScriptsChunkLoadingPlugin"; + +class ImportScriptsChunkLoadingPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + new StartupChunkDependenciesPlugin({ + chunkLoading: "import-scripts", + asyncChunkLoading: true + }).apply(compiler); + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + /** + * @param {Chunk} chunk chunk + * @returns {boolean} true, if wasm loading is enabled for the chunk + */ + const isEnabledForChunk = (chunk) => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === "import-scripts"; + }; + const onceForChunkSet = new WeakSet(); + /** + * @param {Chunk} chunk chunk + * @param {Set} set runtime requirements + */ + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + const withCreateScriptUrl = Boolean( + compilation.outputOptions.trustedTypes + ); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + if (withCreateScriptUrl) { + set.add(RuntimeGlobals.createScriptUrl); + } + compilation.addRuntimeModule( + chunk, + new ImportScriptsChunkLoadingRuntimeModule(set, withCreateScriptUrl) + ); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap(PLUGIN_NAME, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap(PLUGIN_NAME, handler); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkScriptFilename); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap(PLUGIN_NAME, (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getUpdateManifestFilename); + }); + }); + } +} + +module.exports = ImportScriptsChunkLoadingPlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js new file mode 100644 index 0000000000000000000000000000000000000000..4ec9b34b165e7d08c71369ed7c85e8ffaaf2a10b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js @@ -0,0 +1,229 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); +const Template = require("../Template"); +const { + generateJavascriptHMR +} = require("../hmr/JavascriptHotModuleReplacementHelper"); +const { + chunkHasJs, + getChunkFilenameTemplate +} = require("../javascript/JavascriptModulesPlugin"); +const { getInitialChunkIds } = require("../javascript/StartupHelpers"); +const compileBooleanMatcher = require("../util/compileBooleanMatcher"); +const { getUndoPath } = require("../util/identifier"); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */ + +class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { + /** + * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements + * @param {boolean} withCreateScriptUrl with createScriptUrl support + */ + constructor(runtimeRequirements, withCreateScriptUrl) { + super("importScripts chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; + this._withCreateScriptUrl = withCreateScriptUrl; + } + + /** + * @private + * @param {Chunk} chunk chunk + * @returns {string} generated code + */ + _generateBaseUri(chunk) { + const options = chunk.getEntryOptions(); + if (options && options.baseUri) { + return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`; + } + const compilation = /** @type {Compilation} */ (this.compilation); + const outputName = compilation.getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + /** @type {string} */ (compilation.outputOptions.path), + false + ); + return `${RuntimeGlobals.baseURI} = self.location + ${JSON.stringify( + rootOutputDir ? `/../${rootOutputDir}` : "" + )};`; + } + + /** + * @returns {string | null} runtime code + */ + generate() { + const compilation = /** @type {Compilation} */ (this.compilation); + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); + const withLoading = this.runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withCallback = this.runtimeRequirements.has( + RuntimeGlobals.chunkCallback + ); + const withHmr = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const globalObject = compilation.runtimeTemplate.globalObject; + const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( + compilation.outputOptions.chunkLoadingGlobal + )}]`; + const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph); + const chunk = /** @type {Chunk} */ (this.chunk); + const hasJsMatcher = compileBooleanMatcher( + chunkGraph.getChunkConditionMap(chunk, chunkHasJs) + ); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts` + : undefined; + const runtimeTemplate = compilation.runtimeTemplate; + const { _withCreateScriptUrl: withCreateScriptUrl } = this; + + return Template.asString([ + withBaseURI ? this._generateBaseUri(chunk) : "// no baseURI", + "", + "// object to store loaded chunks", + '// "1" means "already loaded"', + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 1`).join( + ",\n" + ) + ), + "};", + "", + withCallback || withLoading + ? Template.asString([ + "// importScripts chunk loading", + `var installChunk = ${runtimeTemplate.basicFunction("data", [ + runtimeTemplate.destructureArray( + ["chunkIds", "moreModules", "runtime"], + "data" + ), + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ), + "}" + ]), + "}", + `if(runtime) runtime(${RuntimeGlobals.require});`, + "while(chunkIds.length)", + Template.indent("installedChunks[chunkIds.pop()] = 1;"), + "parentChunkLoadingFunction(data);" + ])};` + ]) + : "// no chunk install function needed", + withCallback || withLoading + ? Template.asString([ + withLoading + ? `${fn}.i = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? [ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent( + `importScripts(${ + withCreateScriptUrl + ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))` + : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)` + });` + ), + "}" + ]), + "}" + ] + : "installedChunks[chunkId] = 1;" + )};` + : "", + "", + `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, + "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);", + "chunkLoadingGlobal.push = installChunk;" + ]) + : "// no chunk loading", + "", + withHmr + ? Template.asString([ + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + "var success = false;", + `${globalObject}[${JSON.stringify( + compilation.outputOptions.hotUpdateGlobal + )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [ + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + "currentUpdate[moduleId] = moreModules[moduleId];", + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);", + "success = true;" + ])};`, + "// start update chunk loading", + `importScripts(${ + withCreateScriptUrl + ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))` + : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)` + });`, + 'if(!success) throw new Error("Loading update chunk failed for unknown reason");' + ]), + "}", + "", + generateJavascriptHMR("importScripts") + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${ + RuntimeGlobals.hmrDownloadManifest + } = ${runtimeTemplate.basicFunction("", [ + 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', + `return fetch(${RuntimeGlobals.publicPath} + ${ + RuntimeGlobals.getUpdateManifestFilename + }()).then(${runtimeTemplate.basicFunction("response", [ + "if(response.status === 404) return; // no update available", + 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', + "return response.json();" + ])});` + ])};` + ]) + : "// no HMR manifest" + ]); + } +} + +module.exports = ImportScriptsChunkLoadingRuntimeModule; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webworker/WebWorkerTemplatePlugin.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webworker/WebWorkerTemplatePlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..4001aa1a9fc61c671559789fdbbbf81b3e4689fa --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/lib/webworker/WebWorkerTemplatePlugin.js @@ -0,0 +1,26 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const ArrayPushCallbackChunkFormatPlugin = require("../javascript/ArrayPushCallbackChunkFormatPlugin"); +const EnableChunkLoadingPlugin = require("../javascript/EnableChunkLoadingPlugin"); + +/** @typedef {import("../Compiler")} Compiler */ + +class WebWorkerTemplatePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.options.output.chunkLoading = "import-scripts"; + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin("import-scripts").apply(compiler); + } +} + +module.exports = WebWorkerTemplatePlugin; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/CHANGELOG.md b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..cc07de01cf8e2bd7e6dde0e351f3e0c5a2740ff3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/CHANGELOG.md @@ -0,0 +1,70 @@ +v5.1.1 - September 12, 2020 + +* [`9b528d7`](https://github.com/eslint/eslint-scope/commit/9b528d778c381718c12dabfb7f1c0e0dc6b36e49) Upgrade: esrecurse version to ^4.3.0 (#64) (Timofey Kachalov) +* [`f758bbc`](https://github.com/eslint/eslint-scope/commit/f758bbc3d49b9b9ea2289a5d6a6bba8dcf2c4903) Chore: fix definiton -> definition typo in comments (#63) (Kevin Kirsche) +* [`7513734`](https://github.com/eslint/eslint-scope/commit/751373473375b3f2edc4eaf1c8d2763d8435bb72) Chore: move to GitHub Actions (#62) (Kai Cataldo) + +v5.1.0 - June 4, 2020 + +* [`d4a3764`](https://github.com/eslint/eslint-scope/commit/d4a376434b16289c1a428d7e304576e997520873) Update: support new export syntax (#56) (Toru Nagashima) + +v5.0.0 - July 20, 2019 + +* [`e9fa22e`](https://github.com/eslint/eslint-scope/commit/e9fa22ea412c26cf2761fa98af7e715644bdb464) Upgrade: update dependencies after dropping support for Node <8 (#53) (Kai Cataldo) +* [`ee9f7c1`](https://github.com/eslint/eslint-scope/commit/ee9f7c12721aa195ba7e0e69551f49bfdb479951) Breaking: drop support for Node v6 (#54) (Kai Cataldo) + +v4.0.3 - March 15, 2019 + +* [`299df64`](https://github.com/eslint/eslint-scope/commit/299df64bdafb30b4d9372e4b7af0cf51a3818c4a) Fix: arrow function scope strictness (take 2) (#52) (futpib) + +v4.0.2 - March 1, 2019 + +* [`c925600`](https://github.com/eslint/eslint-scope/commit/c925600a684ae0f71b96f85339437a43b4d50d99) Revert "Fix: Arrow function scope strictness (fixes #49) (#50)" (#51) (Teddy Katz) + +v4.0.1 - March 1, 2019 + +* [`2533966`](https://github.com/eslint/eslint-scope/commit/2533966faf317df5a3847fab937ba462c16808b8) Fix: Arrow function scope strictness (fixes #49) (#50) (futpib) +* [`0cbeea5`](https://github.com/eslint/eslint-scope/commit/0cbeea51dfb66ab88ea34b0e3b4ad5e6cc210f2f) Chore: add supported Node.js versions to CI (#47) (Kai Cataldo) +* [`b423057`](https://github.com/eslint/eslint-scope/commit/b42305760638b8edf4667acf1445e450869bd983) Upgrade: eslint-release@1.0.0 (#46) (Teddy Katz) + +v4.0.0 - June 21, 2018 + + + +v4.0.0-rc.0 - June 9, 2018 + +* 3b919b8 Build: Adding rc release script to package.json (#38) (Kevin Partington) +* 137732a Chore: avoid creating package-lock.json files (#37) (Teddy Katz) + +v4.0.0-alpha.0 - April 27, 2018 + +* 7cc3769 Upgrade: eslint-release ^0.11.1 (#36) (Teddy Katz) +* c9f6967 Breaking: remove TDZScope (refs eslint/eslint#10245) (#35) (Toru Nagashima) +* 982a71f Fix: wrong resolution about default parameters (#33) (Toru Nagashima) +* 57889f1 Docs: Remove extra header line from LICENSE (#32) (Gyandeep Singh) + +v3.7.1 - April 12, 2017 + +* ced6262 Fix: restore previous Scope API exports from escope (#31) (Vitor Balocco) +* 5c3d966 Fix: Remove and Modify tests that contain invalid ES6 syntax (#29) (Reyad Attiyat) + +v3.7.0 - March 17, 2017 + +* 9e27835 Chore: Add files section to package.json (#24) (Ilya Volodin) +* 3e4d123 Upgrade: eslint-config-eslint to 4.0.0 (#21) (Teddy Katz) +* 38c50fb Chore: Rename src to lib and test to tests (#20) (Corbin Uselton) +* f4cd920 Chore: Remove esprima (#19) (Corbin Uselton) +* f81fad5 Revert "Chore: Remove esprima" (#18) (James Henry) +* 31b0085 Chore: Remove es6-map and es6-weakmap as they are included in node4 (#10) (#13) (Corbin Uselton) +* 12a1ca1 Add Makefile.js and eslint (#15) (Reyad Attiyat) +* 7d23f8e Chore: Remove es6-map and es6-weakmap as they are included in node4 (#10) (Corbin Uselton) +* 019441e Chore: Convert to ES6 that is supported on Node 4, commonjs modules and remove Babel (#14) (Corbin Uselton) +* c647f65 Update: Add check for node.body in referencer (#2) (Corbin Uselton) +* eb5c9db Remove browserify and jsdoc (#12) (Corbin Uselton) +* cf38df0 Chore: Update README.md (#3) (James Henry) +* 8a142ca Chore: Add eslint-release scripts (#6) (James Henry) +* e60d8cb Chore: Remove unused bower.json (#5) (James Henry) +* 049c545 Chore: Fix tests for eslint-scope (#4) (James Henry) +* f026aab Chore: Update package.json for eslint fork (#1) (James Henry) +* a94d281 Chore: Update license with JSF copyright (Nicholas C. Zakas) + diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/LICENSE b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d36a526f7ed5d10c43c68f34622efba7e62fc8a7 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/LICENSE @@ -0,0 +1,22 @@ +Copyright JS Foundation and other contributors, https://js.foundation +Copyright (C) 2012-2013 Yusuke Suzuki (twitter: @Constellation) and other contributors. + +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. + +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 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. diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/README.md b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7e7ce0d345cdf2aa88d39d757a9fd5c5abc7575c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/README.md @@ -0,0 +1,54 @@ +# ESLint Scope + +ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope). + +## Usage + +Install: + +``` +npm i eslint-scope --save +``` + +Example: + +```js +var eslintScope = require('eslint-scope'); +var espree = require('espree'); +var estraverse = require('estraverse'); + +var ast = espree.parse(code); +var scopeManager = eslintScope.analyze(ast); + +var currentScope = scopeManager.acquire(ast); // global scope + +estraverse.traverse(ast, { + enter: function(node, parent) { + // do stuff + + if (/Function/.test(node.type)) { + currentScope = scopeManager.acquire(node); // get current function scope + } + }, + leave: function(node, parent) { + if (/Function/.test(node.type)) { + currentScope = currentScope.upper; // set to parent scope + } + + // do stuff + } +}); +``` + +## Contributing + +Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/eslint-scope/issues). + +## Build Commands + +* `npm test` - run all linting and tests +* `npm run lint` - run all linting + +## License + +ESLint Scope is licensed under a permissive BSD 2-clause license. diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/definition.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/definition.js new file mode 100644 index 0000000000000000000000000000000000000000..172bfe23b5fdcf07c827559f46be1e54f6b6de37 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/definition.js @@ -0,0 +1,86 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ +"use strict"; + +const Variable = require("./variable"); + +/** + * @class Definition + */ +class Definition { + constructor(type, name, node, parent, index, kind) { + + /** + * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; + + /** + * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; + + /** + * @member {espree.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; + + /** + * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; + + /** + * @member {Number?} Definition#index - the index in the declaration statement. + */ + this.index = index; + + /** + * @member {String?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; + } +} + +/** + * @class ParameterDefinition + */ +class ParameterDefinition extends Definition { + constructor(name, node, index, rest) { + super(Variable.Parameter, name, node, null, index, null); + + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + this.rest = rest; + } +} + +module.exports = { + ParameterDefinition, + Definition +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/index.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0f16fa40f8323ffd08439d1812cdd0603ec2dd75 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/index.js @@ -0,0 +1,165 @@ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda + + 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. + + 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 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. +*/ + +/** + * Escope (
escope) is an ECMAScript + * scope analyzer extracted from the esmangle project. + *

+ * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

+ * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. espree is a parser + * that produces such syntax trees. + *

+ * The main interface is the {@link analyze} function. + * @module escope + */ +"use strict"; + +/* eslint no-underscore-dangle: ["error", { "allow": ["__currentScope"] }] */ + +const assert = require("assert"); + +const ScopeManager = require("./scope-manager"); +const Referencer = require("./referencer"); +const Reference = require("./reference"); +const Variable = require("./variable"); +const Scope = require("./scope").Scope; +const version = require("../package.json").version; + +/** + * Set the default options + * @returns {Object} options + */ +function defaultOptions() { + return { + optimistic: false, + directive: false, + nodejsScope: false, + impliedStrict: false, + sourceType: "script", // one of ['script', 'module'] + ecmaVersion: 5, + childVisitorKeys: null, + fallback: "iteration" + }; +} + +/** + * Preform deep update on option object + * @param {Object} target - Options + * @param {Object} override - Updates + * @returns {Object} Updated options + */ +function updateDeeply(target, override) { + + /** + * Is hash object + * @param {Object} value - Test value + * @returns {boolean} Result + */ + function isHashObject(value) { + return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); + } + + for (const key in override) { + if (Object.prototype.hasOwnProperty.call(override, key)) { + const val = override[key]; + + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} + +/** + * Main interface function. Takes an Espree syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {espree.Tree} tree - Abstract Syntax Tree + * @param {Object} providedOptions - Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag + * @param {boolean} [providedOptions.directive=false]- the directive flag + * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls + * @param {boolean} [providedOptions.nodejsScope=false]- whether the whole + * script is executed under node.js environment. When enabled, escope adds + * a function scope immediately following the global scope. + * @param {boolean} [providedOptions.impliedStrict=false]- implied strict mode + * (if ecmaVersion >= 5). + * @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module' + * @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered + * @param {Object} [providedOptions.childVisitorKeys=null] - Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. + * @param {string} [providedOptions.fallback='iteration'] - A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. + * @returns {ScopeManager} ScopeManager + */ +function analyze(tree, providedOptions) { + const options = updateDeeply(defaultOptions(), providedOptions); + const scopeManager = new ScopeManager(options); + const referencer = new Referencer(options, scopeManager); + + referencer.visit(tree); + + assert(scopeManager.__currentScope === null, "currentScope should be null."); + + return scopeManager; +} + +module.exports = { + + /** @name module:escope.version */ + version, + + /** @name module:escope.Reference */ + Reference, + + /** @name module:escope.Variable */ + Variable, + + /** @name module:escope.Scope */ + Scope, + + /** @name module:escope.ScopeManager */ + ScopeManager, + analyze +}; + + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/pattern-visitor.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/pattern-visitor.js new file mode 100644 index 0000000000000000000000000000000000000000..afa629173b73aef59de6eca0ed52e5216d879648 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/pattern-visitor.js @@ -0,0 +1,152 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ +"use strict"; + +/* eslint-disable no-undefined */ + +const Syntax = require("estraverse").Syntax; +const esrecurse = require("esrecurse"); + +/** + * Get last array element + * @param {array} xs - array + * @returns {any} Last elment + */ +function getLast(xs) { + return xs[xs.length - 1] || null; +} + +class PatternVisitor extends esrecurse.Visitor { + static isPattern(node) { + const nodeType = node.type; + + return ( + nodeType === Syntax.Identifier || + nodeType === Syntax.ObjectPattern || + nodeType === Syntax.ArrayPattern || + nodeType === Syntax.SpreadElement || + nodeType === Syntax.RestElement || + nodeType === Syntax.AssignmentPattern + ); + } + + constructor(options, rootPattern, callback) { + super(null, options); + this.rootPattern = rootPattern; + this.callback = callback; + this.assignments = []; + this.rightHandNodes = []; + this.restElements = []; + } + + Identifier(pattern) { + const lastRestElement = getLast(this.restElements); + + this.callback(pattern, { + topLevel: pattern === this.rootPattern, + rest: lastRestElement !== null && lastRestElement !== undefined && lastRestElement.argument === pattern, + assignments: this.assignments + }); + } + + Property(property) { + + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } + + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); + } + + ArrayPattern(pattern) { + for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { + const element = pattern.elements[i]; + + this.visit(element); + } + } + + AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); + } + + RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); + } + + MemberExpression(node) { + + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } + + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } + + // + // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. + // By spec, LeftHandSideExpression is Pattern or MemberExpression. + // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) + // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... + // + + SpreadElement(node) { + this.visit(node.argument); + } + + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } + + AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); + } + + CallExpression(node) { + + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } +} + +module.exports = PatternVisitor; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/reference.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/reference.js new file mode 100644 index 0000000000000000000000000000000000000000..9529827fe786c63389d1727f85fe07ea72365f15 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/reference.js @@ -0,0 +1,167 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ +"use strict"; + +const READ = 0x1; +const WRITE = 0x2; +const RW = READ | WRITE; + +/** + * A Reference represents a single occurrence of an identifier in code. + * @class Reference + */ +class Reference { + constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { + + /** + * Identifier syntax node. + * @member {espreeIdentifier} Reference#identifier + */ + this.identifier = ident; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { + + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; + + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; + + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * Whether the reference is static. + * @method Reference#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } + + /** + * Whether the reference is writeable. + * @method Reference#isWrite + * @returns {boolean} write + */ + isWrite() { + return !!(this.flag & Reference.WRITE); + } + + /** + * Whether the reference is readable. + * @method Reference#isRead + * @returns {boolean} read + */ + isRead() { + return !!(this.flag & Reference.READ); + } + + /** + * Whether the reference is read-only. + * @method Reference#isReadOnly + * @returns {boolean} read only + */ + isReadOnly() { + return this.flag === Reference.READ; + } + + /** + * Whether the reference is write-only. + * @method Reference#isWriteOnly + * @returns {boolean} write only + */ + isWriteOnly() { + return this.flag === Reference.WRITE; + } + + /** + * Whether the reference is read-write. + * @method Reference#isReadWrite + * @returns {boolean} read write + */ + isReadWrite() { + return this.flag === Reference.RW; + } +} + +/** + * @constant Reference.READ + * @private + */ +Reference.READ = READ; + +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; + +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; + +module.exports = Reference; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/referencer.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/referencer.js new file mode 100644 index 0000000000000000000000000000000000000000..63d1935b3a957f15975282072cf36113b125b61a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/referencer.js @@ -0,0 +1,629 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ +"use strict"; + +/* eslint-disable no-underscore-dangle */ +/* eslint-disable no-undefined */ + +const Syntax = require("estraverse").Syntax; +const esrecurse = require("esrecurse"); +const Reference = require("./reference"); +const Variable = require("./variable"); +const PatternVisitor = require("./pattern-visitor"); +const definition = require("./definition"); +const assert = require("assert"); + +const ParameterDefinition = definition.ParameterDefinition; +const Definition = definition.Definition; + +/** + * Traverse identifier in pattern + * @param {Object} options - options + * @param {pattern} rootPattern - root pattern + * @param {Refencer} referencer - referencer + * @param {callback} callback - callback + * @returns {void} + */ +function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { + + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + const visitor = new PatternVisitor(options, rootPattern, callback); + + visitor.visit(rootPattern); + + // Process the right hand nodes recursively. + if (referencer !== null && referencer !== undefined) { + visitor.rightHandNodes.forEach(referencer.visit, referencer); + } +} + +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. + +class Importer extends esrecurse.Visitor { + constructor(declaration, referencer) { + super(null, referencer.options); + this.declaration = declaration; + this.referencer = referencer; + } + + visitImport(id, specifier) { + this.referencer.visitPattern(id, pattern => { + this.referencer.currentScope().__define(pattern, + new Definition( + Variable.ImportBinding, + pattern, + specifier, + this.declaration, + null, + null + )); + }); + } + + ImportNamespaceSpecifier(node) { + const local = (node.local || node.id); + + if (local) { + this.visitImport(local, node); + } + } + + ImportDefaultSpecifier(node) { + const local = (node.local || node.id); + + this.visitImport(local, node); + } + + ImportSpecifier(node) { + const local = (node.local || node.id); + + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } +} + +// Referencing variables and creating bindings. +class Referencer extends esrecurse.Visitor { + constructor(options, scopeManager) { + super(null, options); + this.options = options; + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } + + currentScope() { + return this.scopeManager.__currentScope; + } + + close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + } + } + + pushInnerMethodDefinition(isInnerMethodDefinition) { + const previous = this.isInnerMethodDefinition; + + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } + + popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } + + referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + const scope = this.currentScope(); + + assignments.forEach(assignment => { + scope.__referencing( + pattern, + Reference.WRITE, + assignment.right, + maybeImplicitGlobal, + pattern !== assignment.left, + init + ); + }); + } + + visitPattern(node, options, callback) { + let visitPatternOptions = options; + let visitPatternCallback = callback; + + if (typeof options === "function") { + visitPatternCallback = options; + visitPatternOptions = { processRightHandNodes: false }; + } + + traverseIdentifierInPattern( + this.options, + node, + visitPatternOptions.processRightHandNodes ? this : null, + visitPatternCallback + ); + } + + visitFunction(node) { + let i, iz; + + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. + + if (node.type === Syntax.FunctionDeclaration) { + + // id is defined in upper scope + this.currentScope().__define(node.id, + new Definition( + Variable.FunctionName, + node.id, + node, + null, + null, + null + )); + } + + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } + + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); + + const that = this; + + /** + * Visit pattern callback + * @param {pattern} pattern - pattern + * @param {Object} info - info + * @returns {void} + */ + function visitPatternCallback(pattern, info) { + that.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + i, + info.rest + )); + + that.referencingDefaultValue(pattern, info.assignments, null, true); + } + + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); + } + + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: "RestElement", + argument: node.rest + }, pattern => { + this.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + node.params.length, + true + )); + }); + } + + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { + + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + } + + this.close(node); + } + + visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node, + null, + null, + null + )); + } + + this.visit(node.superClass); + + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node + )); + } + this.visit(node.body); + + this.close(node); + } + + visitProperty(node) { + let previous; + + if (node.computed) { + this.visit(node.key); + } + + const isMethodDefinition = node.type === Syntax.MethodDefinition; + + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } + + visitForIn(node) { + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, pattern => { + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); + }); + } else { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); + }); + } + this.visit(node.right); + this.visit(node.body); + + this.close(node); + } + + visitVariableDeclaration(variableTargetScope, type, node, index) { + + const decl = node.declarations[index]; + const init = decl.init; + + this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => { + variableTargetScope.__define( + pattern, + new Definition( + type, + pattern, + decl, + node, + index, + node.kind + ) + ); + + this.referencingDefaultValue(pattern, info.assignments, null, true); + if (init) { + this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); + } + }); + } + + AssignmentExpression(node) { + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + + CatchClause(node) { + this.scopeManager.__nestCatchScope(node); + + this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => { + this.currentScope().__define(pattern, + new Definition( + Variable.CatchClause, + node.param, + node, + null, + null, + null + )); + this.referencingDefaultValue(pattern, info.assignments, null, true); + }); + this.visit(node.body); + + this.close(node); + } + + Program(node) { + this.scopeManager.__nestGlobalScope(node); + + if (this.scopeManager.__isNodejsScope()) { + + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } + + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } + + if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; + } + + this.visitChildren(node); + this.close(node); + } + + Identifier(node) { + this.currentScope().__referencing(node); + } + + UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } + + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + + Property(node) { + this.visitProperty(node); + } + + MethodDefinition(node) { + this.visitProperty(node); + } + + BreakStatement() {} // eslint-disable-line class-methods-use-this + + ContinueStatement() {} // eslint-disable-line class-methods-use-this + + LabeledStatement(node) { + this.visit(node.body); + } + + ForStatement(node) { + + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ClassExpression(node) { + this.visitClass(node); + } + + ClassDeclaration(node) { + this.visitClass(node); + } + + CallExpression(node) { + + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } + + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + + WithStatement(node) { + this.visit(node.object); + + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + + this.visit(node.body); + + this.close(node); + } + + VariableDeclaration(node) { + const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); + + for (let i = 0, iz = node.declarations.length; i < iz; ++i) { + const decl = node.declarations[i]; + + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } + + // sec 13.11.8 + SwitchStatement(node) { + this.visit(node.discriminant); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } + + for (let i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } + + this.close(node); + } + + FunctionDeclaration(node) { + this.visitFunction(node); + } + + FunctionExpression(node) { + this.visitFunction(node); + } + + ForOfStatement(node) { + this.visitForIn(node); + } + + ForInStatement(node) { + this.visitForIn(node); + } + + ArrowFunctionExpression(node) { + this.visitFunction(node); + } + + ImportDeclaration(node) { + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); + + const importer = new Importer(node, this); + + importer.visit(node); + } + + visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } + + this.visitChildren(node); + } + + // TODO: ExportDeclaration doesn't exist. for bc? + ExportDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportAllDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportDefaultDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportSpecifier(node) { + + // TODO: `node.id` doesn't exist. for bc? + const local = (node.id || node.local); + + this.visit(local); + } + + MetaProperty() { // eslint-disable-line class-methods-use-this + + // do nothing. + } +} + +module.exports = Referencer; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/scope-manager.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/scope-manager.js new file mode 100644 index 0000000000000000000000000000000000000000..c1927994b1166ea3100cc42fa2e61ca2de3b367e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/scope-manager.js @@ -0,0 +1,247 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ +"use strict"; + +/* eslint-disable no-underscore-dangle */ + +const Scope = require("./scope"); +const assert = require("assert"); + +const GlobalScope = Scope.GlobalScope; +const CatchScope = Scope.CatchScope; +const WithScope = Scope.WithScope; +const ModuleScope = Scope.ModuleScope; +const ClassScope = Scope.ClassScope; +const SwitchScope = Scope.SwitchScope; +const FunctionScope = Scope.FunctionScope; +const ForScope = Scope.ForScope; +const FunctionExpressionNameScope = Scope.FunctionExpressionNameScope; +const BlockScope = Scope.BlockScope; + +/** + * @class ScopeManager + */ +class ScopeManager { + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + this.__declaredVariables = new WeakMap(); + } + + __useDirective() { + return this.__options.directive; + } + + __isOptimistic() { + return this.__options.optimistic; + } + + __ignoreEval() { + return this.__options.ignoreEval; + } + + __isNodejsScope() { + return this.__options.nodejsScope; + } + + isModule() { + return this.__options.sourceType === "module"; + } + + isImpliedStrict() { + return this.__options.impliedStrict; + } + + isStrictModeSupported() { + return this.__options.ecmaVersion >= 5; + } + + // Returns appropriate scope for this node. + __get(node) { + return this.__nodeToScope.get(node); + } + + /** + * Get variables that are declared by the node. + * + * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. + * If the node declares nothing, this method returns an empty array. + * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. + * + * @param {Espree.Node} node - a node to get. + * @returns {Variable[]} variables that declared by the node. + */ + getDeclaredVariables(node) { + return this.__declaredVariables.get(node) || []; + } + + /** + * acquire scope from node. + * @method ScopeManager#acquire + * @param {Espree.Node} node - node for the acquired scope. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @returns {Scope?} Scope from node + */ + acquire(node, inner) { + + /** + * predicate + * @param {Scope} testScope - scope to test + * @returns {boolean} predicate + */ + function predicate(testScope) { + if (testScope.type === "function" && testScope.functionExpressionScope) { + return false; + } + return true; + } + + const scopes = this.__get(node); + + if (!scopes || scopes.length === 0) { + return null; + } + + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } + + if (inner) { + for (let i = scopes.length - 1; i >= 0; --i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } else { + for (let i = 0, iz = scopes.length; i < iz; ++i) { + const scope = scopes[i]; + + if (predicate(scope)) { + return scope; + } + } + } + + return null; + } + + /** + * acquire all scopes from node. + * @method ScopeManager#acquireAll + * @param {Espree.Node} node - node for the acquired scope. + * @returns {Scopes?} Scope array + */ + acquireAll(node) { + return this.__get(node); + } + + /** + * release the node. + * @method ScopeManager#release + * @param {Espree.Node} node - releasing node. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @returns {Scope?} upper scope for the node. + */ + release(node, inner) { + const scopes = this.__get(node); + + if (scopes && scopes.length) { + const scope = scopes[0].upper; + + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + + attach() { } // eslint-disable-line class-methods-use-this + + detach() { } // eslint-disable-line class-methods-use-this + + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } + + __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } + + __nestBlockScope(node) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); + } + + __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } + + __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + + __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } + + __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + + __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } + + __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } + + __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } + + __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } + + __isES6() { + return this.__options.ecmaVersion >= 6; + } +} + +module.exports = ScopeManager; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/scope.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/scope.js new file mode 100644 index 0000000000000000000000000000000000000000..bdb5f637f684e5d6490abcd9a001a9e09a35d1da --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/scope.js @@ -0,0 +1,748 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ +"use strict"; + +/* eslint-disable no-underscore-dangle */ +/* eslint-disable no-undefined */ + +const Syntax = require("estraverse").Syntax; + +const Reference = require("./reference"); +const Variable = require("./variable"); +const Definition = require("./definition").Definition; +const assert = require("assert"); + +/** + * Test if scope is struct + * @param {Scope} scope - scope + * @param {Block} block - block + * @param {boolean} isMethodDefinition - is method definition + * @param {boolean} useDirective - use directive + * @returns {boolean} is strict scope + */ +function isStrictScope(scope, block, isMethodDefinition, useDirective) { + let body; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === "class" || scope.type === "module") { + return true; + } + + if (scope.type === "block" || scope.type === "switch") { + return false; + } + + if (scope.type === "function") { + if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) { + return false; + } + + if (block.type === Syntax.Program) { + body = block; + } else { + body = block.body; + } + + if (!body) { + return false; + } + } else if (scope.type === "global") { + body = block; + } else { + return false; + } + + // Search 'use strict' directive. + if (useDirective) { + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; + + if (stmt.type !== Syntax.DirectiveStatement) { + break; + } + if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") { + return true; + } + } + } else { + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; + + if (stmt.type !== Syntax.ExpressionStatement) { + break; + } + const expr = stmt.expression; + + if (expr.type !== Syntax.Literal || typeof expr.value !== "string") { + break; + } + if (expr.raw !== null && expr.raw !== undefined) { + if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") { + return true; + } + } else { + if (expr.value === "use strict") { + return true; + } + } + } + } + return false; +} + +/** + * Register scope + * @param {ScopeManager} scopeManager - scope manager + * @param {Scope} scope - scope + * @returns {void} + */ +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); + + const scopes = scopeManager.__nodeToScope.get(scope.block); + + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} + +/** + * Should be statically + * @param {Object} def - def + * @returns {boolean} should be statically + */ +function shouldBeStatically(def) { + return ( + (def.type === Variable.ClassName) || + (def.type === Variable.Variable && def.parent.kind !== "var") + ); +} + +/** + * @class Scope + */ +class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + + /** + * One of 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'. + * @member {String} Scope#type + */ + this.type = type; + + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints */ + this.taints = new Map(); + + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its parent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; + + /** + * A reference to the scope-defining syntax node. + * @member {espree.Node} Scope#block + */ + this.block = block; + + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + (this.type === "global" || this.type === "function" || this.type === "module") ? this : upperScope.variableScope; + + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + + this.__left = []; + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; + + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective()); + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } + + this.__declaredVariables = scopeManager.__declaredVariables; + + registerScope(scopeManager, this); + } + + __shouldStaticallyClose(scopeManager) { + return (!this.dynamic || scopeManager.__isOptimistic()); + } + + __shouldStaticallyCloseForGlobal(ref) { + + // On global scope, let/const/class declarations should be resolved statically. + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + + const variable = this.set.get(name); + const defs = variable.defs; + + return defs.length > 0 && defs.every(shouldBeStatically); + } + + __staticCloseRef(ref) { + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + + __dynamicCloseRef(ref) { + + // notify all names are through to global + let current = this; + + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + + __globalCloseRef(ref) { + + // let/const/class declarations should be resolved statically. + // others should be resolved dynamically. + if (this.__shouldStaticallyCloseForGlobal(ref)) { + this.__staticCloseRef(ref); + } else { + this.__dynamicCloseRef(ref); + } + } + + __close(scopeManager) { + let closeRef; + + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else if (this.type !== "global") { + closeRef = this.__dynamicCloseRef; + } else { + closeRef = this.__globalCloseRef; + } + + // Try Resolving all references in this scope. + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + closeRef.call(this, ref); + } + this.__left = null; + + return this.upper; + } + + // To override by function scopes. + // References in default parameters isn't resolved to variables which are in their function body. + __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars + return true; + } + + __resolve(ref) { + const name = ref.identifier.name; + + if (!this.set.has(name)) { + return false; + } + const variable = this.set.get(name); + + if (!this.__isValidResolution(ref, variable)) { + return false; + } + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + + return true; + } + + __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } + + __addDeclaredVariablesOfNode(variable, node) { + if (node === null || node === undefined) { + return; + } + + let variables = this.__declaredVariables.get(node); + + if (variables === null || variables === undefined) { + variables = []; + this.__declaredVariables.set(node, variables); + } + if (variables.indexOf(variable) === -1) { + variables.push(variable); + } + } + + __defineGeneric(name, set, variables, node, def) { + let variable; + + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } + + if (def) { + variable.defs.push(def); + this.__addDeclaredVariablesOfNode(variable, def.node); + this.__addDeclaredVariablesOfNode(variable, def.parent); + } + if (node) { + variable.identifiers.push(node); + } + } + + __define(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.set, + this.variables, + node, + def + ); + } + } + + __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { + + // because Array element may be null + if (!node || node.type !== Syntax.Identifier) { + return; + } + + // Specially handle like `this`. + if (node.name === "super") { + return; + } + + const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); + + this.references.push(ref); + this.__left.push(ref); + } + + __detectEval() { + let current = this; + + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } + + __detectThis() { + this.thisFound = true; + } + + __isClosed() { + return this.__left === null; + } + + /** + * returns resolved {Reference} + * @method Scope#resolve + * @param {Espree.Identifier} ident - identifier to be resolved. + * @returns {Reference} reference + */ + resolve(ident) { + let ref, i, iz; + + assert(this.__isClosed(), "Scope should be closed."); + assert(ident.type === Syntax.Identifier, "Target should be identifier."); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } + + /** + * returns this scope is static + * @method Scope#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.dynamic; + } + + /** + * returns this scope has materialized arguments + * @method Scope#isArgumentsMaterialized + * @returns {boolean} arguemnts materialized + */ + isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this + return true; + } + + /** + * returns this scope has materialized `this` reference + * @method Scope#isThisMaterialized + * @returns {boolean} this materialized + */ + isThisMaterialized() { // eslint-disable-line class-methods-use-this + return true; + } + + isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (let i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } +} + +class GlobalScope extends Scope { + constructor(scopeManager, block) { + super(scopeManager, "global", null, block, false); + this.implicit = { + set: new Map(), + variables: [], + + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] + }; + } + + __close(scopeManager) { + const implicit = []; + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (let i = 0, iz = implicit.length; i < iz; ++i) { + const info = implicit[i]; + + this.__defineImplicit(info.pattern, + new Definition( + Variable.ImplicitGlobalVariable, + info.pattern, + info.node, + null, + null, + null + )); + + } + + this.implicit.left = this.__left; + + return super.__close(scopeManager); + } + + __defineImplicit(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.implicit.set, + this.implicit.variables, + node, + def + ); + } + } +} + +class ModuleScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "module", upperScope, block, false); + } +} + +class FunctionExpressionNameScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "function-expression-name", upperScope, block, false); + this.__define(block.id, + new Definition( + Variable.FunctionName, + block.id, + block, + null, + null, + null + )); + this.functionExpressionScope = true; + } +} + +class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "catch", upperScope, block, false); + } +} + +class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "with", upperScope, block, false); + } + + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; + + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; + + return this.upper; + } +} + +class BlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "block", upperScope, block, false); + } +} + +class SwitchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "switch", upperScope, block, false); + } +} + +class FunctionScope extends Scope { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, "function", upperScope, block, isMethodDefinition); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax.ArrowFunctionExpression) { + this.__defineArguments(); + } + } + + isArgumentsMaterialized() { + + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax.ArrowFunctionExpression) { + return false; + } + + if (!this.isStatic()) { + return true; + } + + const variable = this.set.get("arguments"); + + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } + + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } + + __defineArguments() { + this.__defineGeneric( + "arguments", + this.set, + this.variables, + null, + null + ); + this.taints.set("arguments", true); + } + + // References in default parameters isn't resolved to variables which are in their function body. + // const x = 1 + // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. + // const x = 2 + // console.log(a) + // } + __isValidResolution(ref, variable) { + + // If `options.nodejsScope` is true, `this.block` becomes a Program node. + if (this.block.type === "Program") { + return true; + } + + const bodyStart = this.block.body.range[0]; + + // It's invalid resolution in the following case: + return !( + variable.scope === this && + ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. + variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body. + ); + } +} + +class ForScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "for", upperScope, block, false); + } +} + +class ClassScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class", upperScope, block, false); + } +} + +module.exports = { + Scope, + GlobalScope, + ModuleScope, + FunctionExpressionNameScope, + CatchScope, + WithScope, + BlockScope, + SwitchScope, + FunctionScope, + ForScope, + ClassScope +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/variable.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/variable.js new file mode 100644 index 0000000000000000000000000000000000000000..702c4780a248a34be5d574bf9391b98df18396cb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/lib/variable.js @@ -0,0 +1,88 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + 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. + + 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 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. +*/ +"use strict"; + +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @class Variable + */ +class Variable { + constructor(name, scope) { + + /** + * The variable name, as given in the source code. + * @member {String} Variable#name + */ + this.name = name; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {espree.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} + +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + +module.exports = Variable; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/package.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b700b92afbea29f43d179886fefb777bed6f527b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/eslint-scope/package.json @@ -0,0 +1,48 @@ +{ + "name": "eslint-scope", + "description": "ECMAScript scope analyzer for ESLint", + "homepage": "http://github.com/eslint/eslint-scope", + "main": "lib/index.js", + "version": "5.1.1", + "engines": { + "node": ">=8.0.0" + }, + "repository": "eslint/eslint-scope", + "bugs": { + "url": "https://github.com/eslint/eslint-scope/issues" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "node Makefile.js test", + "lint": "node Makefile.js lint", + "generate-release": "eslint-generate-release", + "generate-alpharelease": "eslint-generate-prerelease alpha", + "generate-betarelease": "eslint-generate-prerelease beta", + "generate-rcrelease": "eslint-generate-prerelease rc", + "publish-release": "eslint-publish-release" + }, + "files": [ + "LICENSE", + "README.md", + "lib" + ], + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "devDependencies": { + "@typescript-eslint/parser": "^1.11.0", + "chai": "^4.2.0", + "eslint": "^6.0.1", + "eslint-config-eslint": "^5.0.1", + "eslint-plugin-node": "^9.1.0", + "eslint-release": "^1.0.0", + "eslint-visitor-keys": "^1.2.0", + "espree": "^7.1.0", + "istanbul": "^0.4.5", + "mocha": "^6.1.4", + "npm-license": "^0.3.3", + "shelljs": "^0.8.3", + "typescript": "^3.5.2" + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/.jshintrc b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..f642dae7683b8155bd800db2aa3bfd574c2f7b64 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/.jshintrc @@ -0,0 +1,16 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "eqnull": true, + "latedef": true, + "noarg": true, + "noempty": true, + "quotmark": "single", + "undef": true, + "unused": true, + "strict": true, + "trailing": true, + + "node": true +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/LICENSE.BSD b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..3e580c355a96e5ab8c4fb2ea4ada2d62287de41f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/LICENSE.BSD @@ -0,0 +1,19 @@ +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. + +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 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. diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/README.md b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ccd3377f3e9449547787f8f8f969def96e3f6d23 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/README.md @@ -0,0 +1,153 @@ +### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) + +Estraverse ([estraverse](http://github.com/estools/estraverse)) is +[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +traversal functions from [esmangle project](http://github.com/estools/esmangle). + +### Documentation + +You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +estraverse.traverse(ast, { + enter: function (node, parent) { + if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') + return estraverse.VisitorOption.Skip; + }, + leave: function (node, parent) { + if (node.type == 'VariableDeclarator') + console.log(node.id.name); + } +}); +``` + +We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. + +```javascript +estraverse.traverse(ast, { + enter: function (node) { + this.break(); + } +}); +``` + +And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. + +```javascript +result = estraverse.replace(tree, { + enter: function (node) { + // Replace it with replaced. + if (node.type === 'Literal') + return replaced; + } +}); +``` + +By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Extending the existing traversing rules. + keys: { + // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] + TestExpression: ['argument'] + } +}); +``` + +By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Iterating the child **nodes** of unknown nodes. + fallback: 'iteration' +}); +``` + +When `visitor.fallback` is a function, we can determine which keys to visit on each node. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Skip the `argument` property of each node + fallback: function(node) { + return Object.keys(node).filter(function(key) { + return key !== 'argument'; + }); + } +}); +``` + +### License + +Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +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. + +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 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. diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/estraverse.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/estraverse.js new file mode 100644 index 0000000000000000000000000000000000000000..b106d386a6e1af265a4e8a7fc665561dc88cb291 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/estraverse.js @@ -0,0 +1,782 @@ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + 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. + + 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 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. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; + + var Syntax, + VisitorOption, + VisitorKeys, + BREAK, + SKIP, + REMOVE; + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } + + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + function removeElem(element) { + var i, + key, + nextElem, + parent; + + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.version = require('./package.json').version; + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; + + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/gulpfile.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..8772bbcca542a8dc43f1e08f55126ae24426f983 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/gulpfile.js @@ -0,0 +1,70 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + 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. + + 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 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. +*/ + +'use strict'; + +var gulp = require('gulp'), + git = require('gulp-git'), + bump = require('gulp-bump'), + filter = require('gulp-filter'), + tagVersion = require('gulp-tag-version'); + +var TEST = [ 'test/*.js' ]; +var POWERED = [ 'powered-test/*.js' ]; +var SOURCE = [ 'src/**/*.js' ]; + +/** + * Bumping version number and tagging the repository with it. + * Please read http://semver.org/ + * + * You can use the commands + * + * gulp patch # makes v0.1.0 -> v0.1.1 + * gulp feature # makes v0.1.1 -> v0.2.0 + * gulp release # makes v0.2.1 -> v1.0.0 + * + * To bump the version numbers accordingly after you did a patch, + * introduced a feature or made a backwards-incompatible release. + */ + +function inc(importance) { + // get all the files to bump version in + return gulp.src(['./package.json']) + // bump the version number in those files + .pipe(bump({type: importance})) + // save it back to filesystem + .pipe(gulp.dest('./')) + // commit the changed version number + .pipe(git.commit('Bumps package version')) + // read only one file to get the version number + .pipe(filter('package.json')) + // **tag it in the repository** + .pipe(tagVersion({ + prefix: '' + })); +} + +gulp.task('patch', [ ], function () { return inc('patch'); }) +gulp.task('minor', [ ], function () { return inc('minor'); }) +gulp.task('major', [ ], function () { return inc('major'); }) diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/package.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1138238672309b31209f852f596e3627299d7039 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/node_modules/estraverse/package.json @@ -0,0 +1,40 @@ +{ + "name": "estraverse", + "description": "ECMAScript JS AST traversal functions", + "homepage": "https://github.com/estools/estraverse", + "main": "estraverse.js", + "version": "4.3.0", + "engines": { + "node": ">=4.0" + }, + "maintainers": [ + { + "name": "Yusuke Suzuki", + "email": "utatane.tea@gmail.com", + "web": "http://github.com/Constellation" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/estools/estraverse.git" + }, + "devDependencies": { + "babel-preset-env": "^1.6.1", + "babel-register": "^6.3.13", + "chai": "^2.1.1", + "espree": "^1.11.0", + "gulp": "^3.8.10", + "gulp-bump": "^0.2.2", + "gulp-filter": "^2.0.0", + "gulp-git": "^1.0.1", + "gulp-tag-version": "^1.3.0", + "jshint": "^2.5.6", + "mocha": "^2.1.0" + }, + "license": "BSD-2-Clause", + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint estraverse.js", + "unit-test": "mocha --compilers js:babel-register" + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/WebpackOptions.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/WebpackOptions.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..40908b092688409b4c673c280b115eb86483055e --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/WebpackOptions.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../declarations/WebpackOptions").WebpackOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/WebpackOptions.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/WebpackOptions.check.js new file mode 100644 index 0000000000000000000000000000000000000000..dd3d720b1fb51b9f0a13da49cee9f94b91ab5061 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/WebpackOptions.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +const e=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;module.exports=_e,module.exports.default=_e;const t={definitions:{Amd:{anyOf:[{enum:[!1]},{type:"object"}]},AmdContainer:{type:"string",minLength:1},AssetFilterItemTypes:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!1},{instanceof:"Function"}]},AssetFilterTypes:{anyOf:[{type:"array",items:{oneOf:[{$ref:"#/definitions/AssetFilterItemTypes"}]}},{$ref:"#/definitions/AssetFilterItemTypes"}]},AssetGeneratorDataUrl:{anyOf:[{$ref:"#/definitions/AssetGeneratorDataUrlOptions"},{$ref:"#/definitions/AssetGeneratorDataUrlFunction"}]},AssetGeneratorDataUrlFunction:{instanceof:"Function"},AssetGeneratorDataUrlOptions:{type:"object",additionalProperties:!1,properties:{encoding:{enum:[!1,"base64"]},mimetype:{type:"string"}}},AssetGeneratorOptions:{type:"object",additionalProperties:!1,properties:{binary:{type:"boolean"},dataUrl:{$ref:"#/definitions/AssetGeneratorDataUrl"},emit:{type:"boolean"},filename:{$ref:"#/definitions/FilenameTemplate"},outputPath:{$ref:"#/definitions/AssetModuleOutputPath"},publicPath:{$ref:"#/definitions/RawPublicPath"}}},AssetInlineGeneratorOptions:{type:"object",additionalProperties:!1,properties:{binary:{type:"boolean"},dataUrl:{$ref:"#/definitions/AssetGeneratorDataUrl"}}},AssetModuleFilename:{anyOf:[{type:"string",absolutePath:!1},{instanceof:"Function"}]},AssetModuleOutputPath:{anyOf:[{type:"string",absolutePath:!1},{instanceof:"Function"}]},AssetParserDataUrlFunction:{instanceof:"Function"},AssetParserDataUrlOptions:{type:"object",additionalProperties:!1,properties:{maxSize:{type:"number"}}},AssetParserOptions:{type:"object",additionalProperties:!1,properties:{dataUrlCondition:{anyOf:[{$ref:"#/definitions/AssetParserDataUrlOptions"},{$ref:"#/definitions/AssetParserDataUrlFunction"}]}}},AssetResourceGeneratorOptions:{type:"object",additionalProperties:!1,properties:{binary:{type:"boolean"},emit:{type:"boolean"},filename:{$ref:"#/definitions/FilenameTemplate"},outputPath:{$ref:"#/definitions/AssetModuleOutputPath"},publicPath:{$ref:"#/definitions/RawPublicPath"}}},AuxiliaryComment:{anyOf:[{type:"string"},{$ref:"#/definitions/LibraryCustomUmdCommentObject"}]},Bail:{type:"boolean"},CacheOptions:{anyOf:[{enum:[!0]},{$ref:"#/definitions/CacheOptionsNormalized"}]},CacheOptionsNormalized:{anyOf:[{enum:[!1]},{$ref:"#/definitions/MemoryCacheOptions"},{$ref:"#/definitions/FileCacheOptions"}]},Charset:{type:"boolean"},ChunkFilename:{oneOf:[{$ref:"#/definitions/FilenameTemplate"}]},ChunkFormat:{anyOf:[{enum:["array-push","commonjs","module",!1]},{type:"string"}]},ChunkLoadTimeout:{type:"number"},ChunkLoading:{anyOf:[{enum:[!1]},{$ref:"#/definitions/ChunkLoadingType"}]},ChunkLoadingGlobal:{type:"string"},ChunkLoadingType:{anyOf:[{enum:["jsonp","import-scripts","require","async-node","import"]},{type:"string"}]},Clean:{anyOf:[{type:"boolean"},{$ref:"#/definitions/CleanOptions"}]},CleanOptions:{type:"object",additionalProperties:!1,properties:{dry:{type:"boolean"},keep:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!1},{instanceof:"Function"}]}}},CompareBeforeEmit:{type:"boolean"},Context:{type:"string",absolutePath:!0},CrossOriginLoading:{enum:[!1,"anonymous","use-credentials"]},CssAutoGeneratorOptions:{type:"object",additionalProperties:!1,properties:{esModule:{$ref:"#/definitions/CssGeneratorEsModule"},exportsConvention:{$ref:"#/definitions/CssGeneratorExportsConvention"},exportsOnly:{$ref:"#/definitions/CssGeneratorExportsOnly"},localIdentName:{$ref:"#/definitions/CssGeneratorLocalIdentName"}}},CssAutoParserOptions:{type:"object",additionalProperties:!1,properties:{import:{$ref:"#/definitions/CssParserImport"},namedExports:{$ref:"#/definitions/CssParserNamedExports"},url:{$ref:"#/definitions/CssParserUrl"}}},CssChunkFilename:{oneOf:[{$ref:"#/definitions/FilenameTemplate"}]},CssFilename:{oneOf:[{$ref:"#/definitions/FilenameTemplate"}]},CssGeneratorEsModule:{type:"boolean"},CssGeneratorExportsConvention:{anyOf:[{enum:["as-is","camel-case","camel-case-only","dashes","dashes-only"]},{instanceof:"Function"}]},CssGeneratorExportsOnly:{type:"boolean"},CssGeneratorLocalIdentName:{type:"string"},CssGeneratorOptions:{type:"object",additionalProperties:!1,properties:{esModule:{$ref:"#/definitions/CssGeneratorEsModule"},exportsOnly:{$ref:"#/definitions/CssGeneratorExportsOnly"}}},CssGlobalGeneratorOptions:{type:"object",additionalProperties:!1,properties:{esModule:{$ref:"#/definitions/CssGeneratorEsModule"},exportsConvention:{$ref:"#/definitions/CssGeneratorExportsConvention"},exportsOnly:{$ref:"#/definitions/CssGeneratorExportsOnly"},localIdentName:{$ref:"#/definitions/CssGeneratorLocalIdentName"}}},CssGlobalParserOptions:{type:"object",additionalProperties:!1,properties:{import:{$ref:"#/definitions/CssParserImport"},namedExports:{$ref:"#/definitions/CssParserNamedExports"},url:{$ref:"#/definitions/CssParserUrl"}}},CssModuleGeneratorOptions:{type:"object",additionalProperties:!1,properties:{esModule:{$ref:"#/definitions/CssGeneratorEsModule"},exportsConvention:{$ref:"#/definitions/CssGeneratorExportsConvention"},exportsOnly:{$ref:"#/definitions/CssGeneratorExportsOnly"},localIdentName:{$ref:"#/definitions/CssGeneratorLocalIdentName"}}},CssModuleParserOptions:{type:"object",additionalProperties:!1,properties:{import:{$ref:"#/definitions/CssParserImport"},namedExports:{$ref:"#/definitions/CssParserNamedExports"},url:{$ref:"#/definitions/CssParserUrl"}}},CssParserImport:{type:"boolean"},CssParserNamedExports:{type:"boolean"},CssParserOptions:{type:"object",additionalProperties:!1,properties:{import:{$ref:"#/definitions/CssParserImport"},namedExports:{$ref:"#/definitions/CssParserNamedExports"},url:{$ref:"#/definitions/CssParserUrl"}}},CssParserUrl:{type:"boolean"},DeferImportExperimentOptions:{type:"boolean",required:["asyncModule"]},Dependencies:{type:"array",items:{type:"string"}},DevServer:{anyOf:[{enum:[!1]},{type:"object"}]},DevTool:{anyOf:[{enum:[!1,"eval"]},{type:"string",pattern:"^(inline-|hidden-|eval-)?(nosources-)?(cheap-(module-)?)?source-map(-debugids)?$"}]},DevtoolFallbackModuleFilenameTemplate:{anyOf:[{type:"string"},{instanceof:"Function"}]},DevtoolModuleFilenameTemplate:{anyOf:[{type:"string"},{instanceof:"Function"}]},DevtoolNamespace:{type:"string"},EmptyGeneratorOptions:{type:"object",additionalProperties:!1},EmptyParserOptions:{type:"object",additionalProperties:!1},EnabledChunkLoadingTypes:{type:"array",items:{$ref:"#/definitions/ChunkLoadingType"}},EnabledLibraryTypes:{type:"array",items:{$ref:"#/definitions/LibraryType"}},EnabledWasmLoadingTypes:{type:"array",items:{$ref:"#/definitions/WasmLoadingType"}},Entry:{anyOf:[{$ref:"#/definitions/EntryDynamic"},{$ref:"#/definitions/EntryStatic"}]},EntryDescription:{type:"object",additionalProperties:!1,properties:{asyncChunks:{type:"boolean"},baseUri:{type:"string"},chunkLoading:{$ref:"#/definitions/ChunkLoading"},dependOn:{anyOf:[{type:"array",items:{type:"string",minLength:1},minItems:1,uniqueItems:!0},{type:"string",minLength:1}]},filename:{$ref:"#/definitions/EntryFilename"},import:{$ref:"#/definitions/EntryItem"},layer:{$ref:"#/definitions/Layer"},library:{$ref:"#/definitions/LibraryOptions"},publicPath:{$ref:"#/definitions/PublicPath"},runtime:{$ref:"#/definitions/EntryRuntime"},wasmLoading:{$ref:"#/definitions/WasmLoading"}},required:["import"]},EntryDescriptionNormalized:{type:"object",additionalProperties:!1,properties:{asyncChunks:{type:"boolean"},baseUri:{type:"string"},chunkLoading:{$ref:"#/definitions/ChunkLoading"},dependOn:{type:"array",items:{type:"string",minLength:1},minItems:1,uniqueItems:!0},filename:{$ref:"#/definitions/Filename"},import:{type:"array",items:{type:"string",minLength:1},minItems:1,uniqueItems:!0},layer:{$ref:"#/definitions/Layer"},library:{$ref:"#/definitions/LibraryOptions"},publicPath:{$ref:"#/definitions/PublicPath"},runtime:{$ref:"#/definitions/EntryRuntime"},wasmLoading:{$ref:"#/definitions/WasmLoading"}}},EntryDynamic:{instanceof:"Function"},EntryDynamicNormalized:{instanceof:"Function"},EntryFilename:{oneOf:[{$ref:"#/definitions/FilenameTemplate"}]},EntryItem:{anyOf:[{type:"array",items:{type:"string",minLength:1},minItems:1,uniqueItems:!0},{type:"string",minLength:1}]},EntryNormalized:{anyOf:[{$ref:"#/definitions/EntryDynamicNormalized"},{$ref:"#/definitions/EntryStaticNormalized"}]},EntryObject:{type:"object",additionalProperties:{anyOf:[{$ref:"#/definitions/EntryItem"},{$ref:"#/definitions/EntryDescription"}]}},EntryRuntime:{anyOf:[{enum:[!1]},{type:"string",minLength:1}]},EntryStatic:{anyOf:[{$ref:"#/definitions/EntryObject"},{$ref:"#/definitions/EntryUnnamed"}]},EntryStaticNormalized:{type:"object",additionalProperties:{oneOf:[{$ref:"#/definitions/EntryDescriptionNormalized"}]}},EntryUnnamed:{oneOf:[{$ref:"#/definitions/EntryItem"}]},Environment:{type:"object",additionalProperties:!1,properties:{arrowFunction:{type:"boolean"},asyncFunction:{type:"boolean"},bigIntLiteral:{type:"boolean"},const:{type:"boolean"},destructuring:{type:"boolean"},document:{type:"boolean"},dynamicImport:{type:"boolean"},dynamicImportInWorker:{type:"boolean"},forOf:{type:"boolean"},globalThis:{type:"boolean"},module:{type:"boolean"},nodePrefixForCoreModules:{type:"boolean"},optionalChaining:{type:"boolean"},templateLiteral:{type:"boolean"}}},Experiments:{type:"object",additionalProperties:!1,properties:{asyncWebAssembly:{type:"boolean"},backCompat:{type:"boolean"},buildHttp:{anyOf:[{$ref:"#/definitions/HttpUriAllowedUris"},{$ref:"#/definitions/HttpUriOptions"}]},cacheUnaffected:{type:"boolean"},css:{type:"boolean"},deferImport:{type:"boolean"},futureDefaults:{type:"boolean"},layers:{type:"boolean"},lazyCompilation:{anyOf:[{type:"boolean"},{$ref:"#/definitions/LazyCompilationOptions"}]},outputModule:{type:"boolean"},syncWebAssembly:{type:"boolean"},topLevelAwait:{type:"boolean"}}},ExperimentsCommon:{type:"object",additionalProperties:!1,properties:{asyncWebAssembly:{type:"boolean"},backCompat:{type:"boolean"},cacheUnaffected:{type:"boolean"},futureDefaults:{type:"boolean"},layers:{type:"boolean"},outputModule:{type:"boolean"},syncWebAssembly:{type:"boolean"},topLevelAwait:{type:"boolean"}}},ExperimentsNormalized:{type:"object",additionalProperties:!1,properties:{asyncWebAssembly:{type:"boolean"},backCompat:{type:"boolean"},buildHttp:{oneOf:[{$ref:"#/definitions/HttpUriOptions"}]},cacheUnaffected:{type:"boolean"},css:{type:"boolean"},deferImport:{type:"boolean"},futureDefaults:{type:"boolean"},layers:{type:"boolean"},lazyCompilation:{anyOf:[{enum:[!1]},{$ref:"#/definitions/LazyCompilationOptions"}]},outputModule:{type:"boolean"},syncWebAssembly:{type:"boolean"},topLevelAwait:{type:"boolean"}}},Extends:{anyOf:[{type:"array",items:{$ref:"#/definitions/ExtendsItem"}},{$ref:"#/definitions/ExtendsItem"}]},ExtendsItem:{type:"string"},ExternalItem:{anyOf:[{instanceof:"RegExp"},{type:"string"},{type:"object",additionalProperties:{$ref:"#/definitions/ExternalItemValue"},properties:{byLayer:{anyOf:[{type:"object",additionalProperties:{$ref:"#/definitions/ExternalItem"}},{instanceof:"Function"}]}}},{$ref:"#/definitions/ExternalItemFunction"}]},ExternalItemFunction:{anyOf:[{$ref:"#/definitions/ExternalItemFunctionCallback"},{$ref:"#/definitions/ExternalItemFunctionPromise"}]},ExternalItemFunctionCallback:{instanceof:"Function"},ExternalItemFunctionData:{type:"object",additionalProperties:!1,properties:{context:{type:"string"},contextInfo:{type:"object"},dependencyType:{type:"string"},getResolve:{$ref:"#/definitions/ExternalItemFunctionDataGetResolve"},request:{type:"string"}}},ExternalItemFunctionDataGetResolve:{instanceof:"Function"},ExternalItemFunctionDataGetResolveCallbackResult:{instanceof:"Function"},ExternalItemFunctionDataGetResolveResult:{instanceof:"Function"},ExternalItemFunctionPromise:{instanceof:"Function"},ExternalItemValue:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{type:"boolean"},{type:"string"},{type:"object"}]},Externals:{anyOf:[{type:"array",items:{$ref:"#/definitions/ExternalItem"}},{$ref:"#/definitions/ExternalItem"}]},ExternalsPresets:{type:"object",additionalProperties:!1,properties:{electron:{type:"boolean"},electronMain:{type:"boolean"},electronPreload:{type:"boolean"},electronRenderer:{type:"boolean"},node:{type:"boolean"},nwjs:{type:"boolean"},web:{type:"boolean"},webAsync:{type:"boolean"}}},ExternalsType:{enum:["var","module","assign","this","window","self","global","commonjs","commonjs2","commonjs-module","commonjs-static","amd","amd-require","umd","umd2","jsonp","system","promise","import","module-import","script","node-commonjs"]},Falsy:{enum:[!1,0,"",null],undefinedAsNull:!0},FileCacheOptions:{type:"object",additionalProperties:!1,properties:{allowCollectingMemory:{type:"boolean"},buildDependencies:{type:"object",additionalProperties:{type:"array",items:{type:"string",minLength:1}}},cacheDirectory:{type:"string",absolutePath:!0},cacheLocation:{type:"string",absolutePath:!0},compression:{enum:[!1,"gzip","brotli"]},hashAlgorithm:{type:"string"},idleTimeout:{type:"number",minimum:0},idleTimeoutAfterLargeChanges:{type:"number",minimum:0},idleTimeoutForInitialStore:{type:"number",minimum:0},immutablePaths:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0,minLength:1}]}},managedPaths:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0,minLength:1}]}},maxAge:{type:"number",minimum:0},maxMemoryGenerations:{type:"number",minimum:0},memoryCacheUnaffected:{type:"boolean"},name:{type:"string"},profile:{type:"boolean"},readonly:{type:"boolean"},store:{enum:["pack"]},type:{enum:["filesystem"]},version:{type:"string"}},required:["type"]},Filename:{oneOf:[{$ref:"#/definitions/FilenameTemplate"}]},FilenameTemplate:{anyOf:[{type:"string",absolutePath:!1,minLength:1},{instanceof:"Function"}]},FilterItemTypes:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!1},{instanceof:"Function"}]},FilterTypes:{anyOf:[{type:"array",items:{oneOf:[{$ref:"#/definitions/FilterItemTypes"}]}},{$ref:"#/definitions/FilterItemTypes"}]},GeneratorOptionsByModuleType:{type:"object",additionalProperties:{type:"object",additionalProperties:!0},properties:{asset:{$ref:"#/definitions/AssetGeneratorOptions"},"asset/inline":{$ref:"#/definitions/AssetInlineGeneratorOptions"},"asset/resource":{$ref:"#/definitions/AssetResourceGeneratorOptions"},css:{$ref:"#/definitions/CssGeneratorOptions"},"css/auto":{$ref:"#/definitions/CssAutoGeneratorOptions"},"css/global":{$ref:"#/definitions/CssGlobalGeneratorOptions"},"css/module":{$ref:"#/definitions/CssModuleGeneratorOptions"},javascript:{$ref:"#/definitions/EmptyGeneratorOptions"},"javascript/auto":{$ref:"#/definitions/EmptyGeneratorOptions"},"javascript/dynamic":{$ref:"#/definitions/EmptyGeneratorOptions"},"javascript/esm":{$ref:"#/definitions/EmptyGeneratorOptions"},json:{$ref:"#/definitions/JsonGeneratorOptions"}}},GlobalObject:{type:"string",minLength:1},HashDigest:{type:"string"},HashDigestLength:{type:"number",minimum:1},HashFunction:{anyOf:[{type:"string",minLength:1},{instanceof:"Function"}]},HashSalt:{type:"string",minLength:1},HotUpdateChunkFilename:{type:"string",absolutePath:!1},HotUpdateGlobal:{type:"string"},HotUpdateMainFilename:{type:"string",absolutePath:!1},HttpUriAllowedUris:{oneOf:[{$ref:"#/definitions/HttpUriOptionsAllowedUris"}]},HttpUriOptions:{type:"object",additionalProperties:!1,properties:{allowedUris:{$ref:"#/definitions/HttpUriOptionsAllowedUris"},cacheLocation:{anyOf:[{enum:[!1]},{type:"string",absolutePath:!0}]},frozen:{type:"boolean"},lockfileLocation:{type:"string",absolutePath:!0},proxy:{type:"string"},upgrade:{type:"boolean"}},required:["allowedUris"]},HttpUriOptionsAllowedUris:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",pattern:"^https?://"},{instanceof:"Function"}]}},IgnoreWarnings:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"object",additionalProperties:!1,properties:{file:{instanceof:"RegExp"},message:{instanceof:"RegExp"},module:{instanceof:"RegExp"}}},{instanceof:"Function"}]}},IgnoreWarningsNormalized:{type:"array",items:{instanceof:"Function"}},Iife:{type:"boolean"},ImportFunctionName:{type:"string"},ImportMetaName:{type:"string"},InfrastructureLogging:{type:"object",additionalProperties:!1,properties:{appendOnly:{type:"boolean"},colors:{type:"boolean"},console:{},debug:{anyOf:[{type:"boolean"},{$ref:"#/definitions/FilterTypes"}]},level:{enum:["none","error","warn","info","log","verbose"]},stream:{}}},JavascriptParserOptions:{type:"object",additionalProperties:!0,properties:{amd:{$ref:"#/definitions/Amd"},browserify:{type:"boolean"},commonjs:{type:"boolean"},commonjsMagicComments:{type:"boolean"},createRequire:{anyOf:[{type:"boolean"},{type:"string"}]},deferImport:{type:"boolean"},dynamicImportFetchPriority:{enum:["low","high","auto",!1]},dynamicImportMode:{enum:["eager","weak","lazy","lazy-once"]},dynamicImportPrefetch:{anyOf:[{type:"number"},{type:"boolean"}]},dynamicImportPreload:{anyOf:[{type:"number"},{type:"boolean"}]},dynamicUrl:{type:"boolean"},exportsPresence:{enum:["error","warn","auto",!1]},exprContextCritical:{type:"boolean"},exprContextRecursive:{type:"boolean"},exprContextRegExp:{anyOf:[{instanceof:"RegExp"},{type:"boolean"}]},exprContextRequest:{type:"string"},harmony:{type:"boolean"},import:{type:"boolean"},importExportsPresence:{enum:["error","warn","auto",!1]},importMeta:{type:"boolean"},importMetaContext:{type:"boolean"},node:{$ref:"#/definitions/Node"},overrideStrict:{enum:["strict","non-strict"]},reexportExportsPresence:{enum:["error","warn","auto",!1]},requireContext:{type:"boolean"},requireEnsure:{type:"boolean"},requireInclude:{type:"boolean"},requireJs:{type:"boolean"},strictExportPresence:{type:"boolean"},strictThisContextOnImports:{type:"boolean"},system:{type:"boolean"},unknownContextCritical:{type:"boolean"},unknownContextRecursive:{type:"boolean"},unknownContextRegExp:{anyOf:[{instanceof:"RegExp"},{type:"boolean"}]},unknownContextRequest:{type:"string"},url:{anyOf:[{enum:["relative"]},{type:"boolean"}]},worker:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{type:"boolean"}]},wrappedContextCritical:{type:"boolean"},wrappedContextRecursive:{type:"boolean"},wrappedContextRegExp:{instanceof:"RegExp"}}},JsonGeneratorOptions:{type:"object",additionalProperties:!1,properties:{JSONParse:{type:"boolean"}}},JsonParserOptions:{type:"object",additionalProperties:!1,properties:{exportsDepth:{type:"number"},parse:{instanceof:"Function"}}},Layer:{anyOf:[{enum:[null]},{type:"string",minLength:1}]},LazyCompilationDefaultBackendOptions:{type:"object",additionalProperties:!1,properties:{client:{type:"string"},listen:{anyOf:[{type:"number"},{type:"object",additionalProperties:!0,properties:{host:{type:"string"},port:{type:"number"}}},{instanceof:"Function"}]},protocol:{enum:["http","https"]},server:{anyOf:[{type:"object",additionalProperties:!0,properties:{}},{instanceof:"Function"}]}}},LazyCompilationOptions:{type:"object",additionalProperties:!1,properties:{backend:{anyOf:[{instanceof:"Function"},{$ref:"#/definitions/LazyCompilationDefaultBackendOptions"}]},entries:{type:"boolean"},imports:{type:"boolean"},test:{anyOf:[{instanceof:"RegExp"},{type:"string"},{instanceof:"Function"}]}}},Library:{anyOf:[{$ref:"#/definitions/LibraryName"},{$ref:"#/definitions/LibraryOptions"}]},LibraryCustomUmdCommentObject:{type:"object",additionalProperties:!1,properties:{amd:{type:"string"},commonjs:{type:"string"},commonjs2:{type:"string"},root:{type:"string"}}},LibraryCustomUmdObject:{type:"object",additionalProperties:!1,properties:{amd:{type:"string",minLength:1},commonjs:{type:"string",minLength:1},root:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{type:"string",minLength:1}]}}},LibraryExport:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{type:"string",minLength:1}]},LibraryName:{anyOf:[{type:"array",items:{type:"string",minLength:1},minItems:1},{type:"string",minLength:1},{$ref:"#/definitions/LibraryCustomUmdObject"}]},LibraryOptions:{type:"object",additionalProperties:!1,properties:{amdContainer:{$ref:"#/definitions/AmdContainer"},auxiliaryComment:{$ref:"#/definitions/AuxiliaryComment"},export:{$ref:"#/definitions/LibraryExport"},name:{$ref:"#/definitions/LibraryName"},type:{$ref:"#/definitions/LibraryType"},umdNamedDefine:{$ref:"#/definitions/UmdNamedDefine"}},required:["type"]},LibraryType:{anyOf:[{enum:["var","module","assign","assign-properties","this","window","self","global","commonjs","commonjs2","commonjs-module","commonjs-static","amd","amd-require","umd","umd2","jsonp","system"]},{type:"string"}]},Loader:{type:"object"},MemoryCacheOptions:{type:"object",additionalProperties:!1,properties:{cacheUnaffected:{type:"boolean"},maxGenerations:{type:"number",minimum:1},type:{enum:["memory"]}},required:["type"]},Mode:{enum:["development","production","none"]},ModuleFilterItemTypes:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!1},{instanceof:"Function"}]},ModuleFilterTypes:{anyOf:[{type:"array",items:{oneOf:[{$ref:"#/definitions/ModuleFilterItemTypes"}]}},{$ref:"#/definitions/ModuleFilterItemTypes"}]},ModuleOptions:{type:"object",additionalProperties:!1,properties:{defaultRules:{oneOf:[{$ref:"#/definitions/RuleSetRules"}]},exprContextCritical:{type:"boolean"},exprContextRecursive:{type:"boolean"},exprContextRegExp:{anyOf:[{instanceof:"RegExp"},{type:"boolean"}]},exprContextRequest:{type:"string"},generator:{$ref:"#/definitions/GeneratorOptionsByModuleType"},noParse:{$ref:"#/definitions/NoParse"},parser:{$ref:"#/definitions/ParserOptionsByModuleType"},rules:{oneOf:[{$ref:"#/definitions/RuleSetRules"}]},strictExportPresence:{type:"boolean"},strictThisContextOnImports:{type:"boolean"},unknownContextCritical:{type:"boolean"},unknownContextRecursive:{type:"boolean"},unknownContextRegExp:{anyOf:[{instanceof:"RegExp"},{type:"boolean"}]},unknownContextRequest:{type:"string"},unsafeCache:{anyOf:[{type:"boolean"},{instanceof:"Function"}]},wrappedContextCritical:{type:"boolean"},wrappedContextRecursive:{type:"boolean"},wrappedContextRegExp:{instanceof:"RegExp"}}},ModuleOptionsNormalized:{type:"object",additionalProperties:!1,properties:{defaultRules:{oneOf:[{$ref:"#/definitions/RuleSetRules"}]},generator:{$ref:"#/definitions/GeneratorOptionsByModuleType"},noParse:{$ref:"#/definitions/NoParse"},parser:{$ref:"#/definitions/ParserOptionsByModuleType"},rules:{oneOf:[{$ref:"#/definitions/RuleSetRules"}]},unsafeCache:{anyOf:[{type:"boolean"},{instanceof:"Function"}]}},required:["defaultRules","generator","parser","rules"]},Name:{type:"string"},NoParse:{anyOf:[{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0},{instanceof:"Function"}]},minItems:1},{instanceof:"RegExp"},{type:"string",absolutePath:!0},{instanceof:"Function"}]},Node:{anyOf:[{enum:[!1]},{$ref:"#/definitions/NodeOptions"}]},NodeOptions:{type:"object",additionalProperties:!1,properties:{__dirname:{enum:[!1,!0,"warn-mock","mock","node-module","eval-only"]},__filename:{enum:[!1,!0,"warn-mock","mock","node-module","eval-only"]},global:{enum:[!1,!0,"warn"]}}},Optimization:{type:"object",additionalProperties:!1,properties:{avoidEntryIife:{type:"boolean"},checkWasmTypes:{type:"boolean"},chunkIds:{enum:["natural","named","deterministic","size","total-size",!1]},concatenateModules:{type:"boolean"},emitOnErrors:{type:"boolean"},flagIncludedChunks:{type:"boolean"},innerGraph:{type:"boolean"},mangleExports:{anyOf:[{enum:["size","deterministic"]},{type:"boolean"}]},mangleWasmImports:{type:"boolean"},mergeDuplicateChunks:{type:"boolean"},minimize:{type:"boolean"},minimizer:{type:"array",items:{anyOf:[{enum:["..."]},{$ref:"#/definitions/Falsy"},{$ref:"#/definitions/WebpackPluginInstance"},{$ref:"#/definitions/WebpackPluginFunction"}]}},moduleIds:{enum:["natural","named","hashed","deterministic","size",!1]},noEmitOnErrors:{type:"boolean"},nodeEnv:{anyOf:[{enum:[!1]},{type:"string"}]},portableRecords:{type:"boolean"},providedExports:{type:"boolean"},realContentHash:{type:"boolean"},removeAvailableModules:{type:"boolean"},removeEmptyChunks:{type:"boolean"},runtimeChunk:{$ref:"#/definitions/OptimizationRuntimeChunk"},sideEffects:{anyOf:[{enum:["flag"]},{type:"boolean"}]},splitChunks:{anyOf:[{enum:[!1]},{$ref:"#/definitions/OptimizationSplitChunksOptions"}]},usedExports:{anyOf:[{enum:["global"]},{type:"boolean"}]}}},OptimizationNormalized:{type:"object",additionalProperties:!1,properties:{avoidEntryIife:{type:"boolean"},checkWasmTypes:{type:"boolean"},chunkIds:{enum:["natural","named","deterministic","size","total-size",!1]},concatenateModules:{type:"boolean"},emitOnErrors:{type:"boolean"},flagIncludedChunks:{type:"boolean"},innerGraph:{type:"boolean"},mangleExports:{anyOf:[{enum:["size","deterministic"]},{type:"boolean"}]},mangleWasmImports:{type:"boolean"},mergeDuplicateChunks:{type:"boolean"},minimize:{type:"boolean"},minimizer:{type:"array",items:{anyOf:[{enum:["..."]},{$ref:"#/definitions/Falsy"},{$ref:"#/definitions/WebpackPluginInstance"},{$ref:"#/definitions/WebpackPluginFunction"}]}},moduleIds:{enum:["natural","named","hashed","deterministic","size",!1]},noEmitOnErrors:{type:"boolean"},nodeEnv:{anyOf:[{enum:[!1]},{type:"string"}]},portableRecords:{type:"boolean"},providedExports:{type:"boolean"},realContentHash:{type:"boolean"},removeAvailableModules:{type:"boolean"},removeEmptyChunks:{type:"boolean"},runtimeChunk:{$ref:"#/definitions/OptimizationRuntimeChunkNormalized"},sideEffects:{anyOf:[{enum:["flag"]},{type:"boolean"}]},splitChunks:{anyOf:[{enum:[!1]},{$ref:"#/definitions/OptimizationSplitChunksOptions"}]},usedExports:{anyOf:[{enum:["global"]},{type:"boolean"}]}}},OptimizationRuntimeChunk:{anyOf:[{enum:["single","multiple"]},{type:"boolean"},{type:"object",additionalProperties:!1,properties:{name:{anyOf:[{type:"string"},{instanceof:"Function"}]}}}]},OptimizationRuntimeChunkNormalized:{anyOf:[{enum:[!1]},{type:"object",additionalProperties:!1,properties:{name:{instanceof:"Function"}}}]},OptimizationSplitChunksCacheGroup:{type:"object",additionalProperties:!1,properties:{automaticNameDelimiter:{type:"string",minLength:1},chunks:{anyOf:[{enum:["initial","async","all"]},{instanceof:"RegExp"},{instanceof:"Function"}]},enforce:{type:"boolean"},enforceSizeThreshold:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},filename:{anyOf:[{type:"string",absolutePath:!1,minLength:1},{instanceof:"Function"}]},idHint:{type:"string"},layer:{anyOf:[{instanceof:"RegExp"},{type:"string"},{instanceof:"Function"}]},maxAsyncRequests:{type:"number",minimum:1},maxAsyncSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},maxInitialRequests:{type:"number",minimum:1},maxInitialSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},maxSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},minChunks:{type:"number",minimum:1},minRemainingSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},minSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},minSizeReduction:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},name:{anyOf:[{enum:[!1]},{type:"string"},{instanceof:"Function"}]},priority:{type:"number"},reuseExistingChunk:{type:"boolean"},test:{anyOf:[{instanceof:"RegExp"},{type:"string"},{instanceof:"Function"}]},type:{anyOf:[{instanceof:"RegExp"},{type:"string"},{instanceof:"Function"}]},usedExports:{type:"boolean"}}},OptimizationSplitChunksGetCacheGroups:{instanceof:"Function"},OptimizationSplitChunksOptions:{type:"object",additionalProperties:!1,properties:{automaticNameDelimiter:{type:"string",minLength:1},cacheGroups:{type:"object",additionalProperties:{anyOf:[{enum:[!1]},{instanceof:"RegExp"},{type:"string"},{$ref:"#/definitions/OptimizationSplitChunksGetCacheGroups"},{$ref:"#/definitions/OptimizationSplitChunksCacheGroup"}]},not:{type:"object",additionalProperties:!0,properties:{test:{anyOf:[{instanceof:"RegExp"},{type:"string"},{$ref:"#/definitions/OptimizationSplitChunksGetCacheGroups"}]}},required:["test"]}},chunks:{anyOf:[{enum:["initial","async","all"]},{instanceof:"RegExp"},{instanceof:"Function"}]},defaultSizeTypes:{type:"array",items:{type:"string"},minItems:1},enforceSizeThreshold:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},fallbackCacheGroup:{type:"object",additionalProperties:!1,properties:{automaticNameDelimiter:{type:"string",minLength:1},chunks:{anyOf:[{enum:["initial","async","all"]},{instanceof:"RegExp"},{instanceof:"Function"}]},maxAsyncSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},maxInitialSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},maxSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},minSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},minSizeReduction:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]}}},filename:{anyOf:[{type:"string",absolutePath:!1,minLength:1},{instanceof:"Function"}]},hidePathInfo:{type:"boolean"},maxAsyncRequests:{type:"number",minimum:1},maxAsyncSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},maxInitialRequests:{type:"number",minimum:1},maxInitialSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},maxSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},minChunks:{type:"number",minimum:1},minRemainingSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},minSize:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},minSizeReduction:{oneOf:[{$ref:"#/definitions/OptimizationSplitChunksSizes"}]},name:{anyOf:[{enum:[!1]},{type:"string"},{instanceof:"Function"}]},usedExports:{type:"boolean"}}},OptimizationSplitChunksSizes:{anyOf:[{type:"number",minimum:0},{type:"object",additionalProperties:{type:"number"}}]},Output:{type:"object",additionalProperties:!1,properties:{amdContainer:{oneOf:[{$ref:"#/definitions/AmdContainer"}]},assetModuleFilename:{$ref:"#/definitions/AssetModuleFilename"},asyncChunks:{type:"boolean"},auxiliaryComment:{oneOf:[{$ref:"#/definitions/AuxiliaryComment"}]},charset:{$ref:"#/definitions/Charset"},chunkFilename:{$ref:"#/definitions/ChunkFilename"},chunkFormat:{$ref:"#/definitions/ChunkFormat"},chunkLoadTimeout:{$ref:"#/definitions/ChunkLoadTimeout"},chunkLoading:{$ref:"#/definitions/ChunkLoading"},chunkLoadingGlobal:{$ref:"#/definitions/ChunkLoadingGlobal"},clean:{$ref:"#/definitions/Clean"},compareBeforeEmit:{$ref:"#/definitions/CompareBeforeEmit"},crossOriginLoading:{$ref:"#/definitions/CrossOriginLoading"},cssChunkFilename:{$ref:"#/definitions/CssChunkFilename"},cssFilename:{$ref:"#/definitions/CssFilename"},devtoolFallbackModuleFilenameTemplate:{$ref:"#/definitions/DevtoolFallbackModuleFilenameTemplate"},devtoolModuleFilenameTemplate:{$ref:"#/definitions/DevtoolModuleFilenameTemplate"},devtoolNamespace:{$ref:"#/definitions/DevtoolNamespace"},enabledChunkLoadingTypes:{$ref:"#/definitions/EnabledChunkLoadingTypes"},enabledLibraryTypes:{$ref:"#/definitions/EnabledLibraryTypes"},enabledWasmLoadingTypes:{$ref:"#/definitions/EnabledWasmLoadingTypes"},environment:{$ref:"#/definitions/Environment"},filename:{$ref:"#/definitions/Filename"},globalObject:{$ref:"#/definitions/GlobalObject"},hashDigest:{$ref:"#/definitions/HashDigest"},hashDigestLength:{$ref:"#/definitions/HashDigestLength"},hashFunction:{$ref:"#/definitions/HashFunction"},hashSalt:{$ref:"#/definitions/HashSalt"},hotUpdateChunkFilename:{$ref:"#/definitions/HotUpdateChunkFilename"},hotUpdateGlobal:{$ref:"#/definitions/HotUpdateGlobal"},hotUpdateMainFilename:{$ref:"#/definitions/HotUpdateMainFilename"},ignoreBrowserWarnings:{type:"boolean"},iife:{$ref:"#/definitions/Iife"},importFunctionName:{$ref:"#/definitions/ImportFunctionName"},importMetaName:{$ref:"#/definitions/ImportMetaName"},library:{$ref:"#/definitions/Library"},libraryExport:{oneOf:[{$ref:"#/definitions/LibraryExport"}]},libraryTarget:{oneOf:[{$ref:"#/definitions/LibraryType"}]},module:{$ref:"#/definitions/OutputModule"},path:{$ref:"#/definitions/Path"},pathinfo:{$ref:"#/definitions/Pathinfo"},publicPath:{$ref:"#/definitions/PublicPath"},scriptType:{$ref:"#/definitions/ScriptType"},sourceMapFilename:{$ref:"#/definitions/SourceMapFilename"},sourcePrefix:{$ref:"#/definitions/SourcePrefix"},strictModuleErrorHandling:{$ref:"#/definitions/StrictModuleErrorHandling"},strictModuleExceptionHandling:{$ref:"#/definitions/StrictModuleExceptionHandling"},trustedTypes:{anyOf:[{enum:[!0]},{type:"string",minLength:1},{$ref:"#/definitions/TrustedTypes"}]},umdNamedDefine:{oneOf:[{$ref:"#/definitions/UmdNamedDefine"}]},uniqueName:{$ref:"#/definitions/UniqueName"},wasmLoading:{$ref:"#/definitions/WasmLoading"},webassemblyModuleFilename:{$ref:"#/definitions/WebassemblyModuleFilename"},workerChunkLoading:{$ref:"#/definitions/ChunkLoading"},workerPublicPath:{$ref:"#/definitions/WorkerPublicPath"},workerWasmLoading:{$ref:"#/definitions/WasmLoading"}}},OutputModule:{type:"boolean"},OutputNormalized:{type:"object",additionalProperties:!1,properties:{assetModuleFilename:{$ref:"#/definitions/AssetModuleFilename"},asyncChunks:{type:"boolean"},charset:{$ref:"#/definitions/Charset"},chunkFilename:{$ref:"#/definitions/ChunkFilename"},chunkFormat:{$ref:"#/definitions/ChunkFormat"},chunkLoadTimeout:{$ref:"#/definitions/ChunkLoadTimeout"},chunkLoading:{$ref:"#/definitions/ChunkLoading"},chunkLoadingGlobal:{$ref:"#/definitions/ChunkLoadingGlobal"},clean:{$ref:"#/definitions/Clean"},compareBeforeEmit:{$ref:"#/definitions/CompareBeforeEmit"},crossOriginLoading:{$ref:"#/definitions/CrossOriginLoading"},cssChunkFilename:{$ref:"#/definitions/CssChunkFilename"},cssFilename:{$ref:"#/definitions/CssFilename"},devtoolFallbackModuleFilenameTemplate:{$ref:"#/definitions/DevtoolFallbackModuleFilenameTemplate"},devtoolModuleFilenameTemplate:{$ref:"#/definitions/DevtoolModuleFilenameTemplate"},devtoolNamespace:{$ref:"#/definitions/DevtoolNamespace"},enabledChunkLoadingTypes:{$ref:"#/definitions/EnabledChunkLoadingTypes"},enabledLibraryTypes:{$ref:"#/definitions/EnabledLibraryTypes"},enabledWasmLoadingTypes:{$ref:"#/definitions/EnabledWasmLoadingTypes"},environment:{$ref:"#/definitions/Environment"},filename:{$ref:"#/definitions/Filename"},globalObject:{$ref:"#/definitions/GlobalObject"},hashDigest:{$ref:"#/definitions/HashDigest"},hashDigestLength:{$ref:"#/definitions/HashDigestLength"},hashFunction:{$ref:"#/definitions/HashFunction"},hashSalt:{$ref:"#/definitions/HashSalt"},hotUpdateChunkFilename:{$ref:"#/definitions/HotUpdateChunkFilename"},hotUpdateGlobal:{$ref:"#/definitions/HotUpdateGlobal"},hotUpdateMainFilename:{$ref:"#/definitions/HotUpdateMainFilename"},ignoreBrowserWarnings:{type:"boolean"},iife:{$ref:"#/definitions/Iife"},importFunctionName:{$ref:"#/definitions/ImportFunctionName"},importMetaName:{$ref:"#/definitions/ImportMetaName"},library:{$ref:"#/definitions/LibraryOptions"},module:{$ref:"#/definitions/OutputModule"},path:{$ref:"#/definitions/Path"},pathinfo:{$ref:"#/definitions/Pathinfo"},publicPath:{$ref:"#/definitions/PublicPath"},scriptType:{$ref:"#/definitions/ScriptType"},sourceMapFilename:{$ref:"#/definitions/SourceMapFilename"},sourcePrefix:{$ref:"#/definitions/SourcePrefix"},strictModuleErrorHandling:{$ref:"#/definitions/StrictModuleErrorHandling"},strictModuleExceptionHandling:{$ref:"#/definitions/StrictModuleExceptionHandling"},trustedTypes:{$ref:"#/definitions/TrustedTypes"},uniqueName:{$ref:"#/definitions/UniqueName"},wasmLoading:{$ref:"#/definitions/WasmLoading"},webassemblyModuleFilename:{$ref:"#/definitions/WebassemblyModuleFilename"},workerChunkLoading:{$ref:"#/definitions/ChunkLoading"},workerPublicPath:{$ref:"#/definitions/WorkerPublicPath"},workerWasmLoading:{$ref:"#/definitions/WasmLoading"}},required:["environment","enabledChunkLoadingTypes","enabledLibraryTypes","enabledWasmLoadingTypes"]},Parallelism:{type:"number",minimum:1},ParserOptionsByModuleType:{type:"object",additionalProperties:{type:"object",additionalProperties:!0},properties:{asset:{$ref:"#/definitions/AssetParserOptions"},"asset/inline":{$ref:"#/definitions/EmptyParserOptions"},"asset/resource":{$ref:"#/definitions/EmptyParserOptions"},"asset/source":{$ref:"#/definitions/EmptyParserOptions"},css:{$ref:"#/definitions/CssParserOptions"},"css/auto":{$ref:"#/definitions/CssAutoParserOptions"},"css/global":{$ref:"#/definitions/CssGlobalParserOptions"},"css/module":{$ref:"#/definitions/CssModuleParserOptions"},javascript:{$ref:"#/definitions/JavascriptParserOptions"},"javascript/auto":{$ref:"#/definitions/JavascriptParserOptions"},"javascript/dynamic":{$ref:"#/definitions/JavascriptParserOptions"},"javascript/esm":{$ref:"#/definitions/JavascriptParserOptions"},json:{$ref:"#/definitions/JsonParserOptions"}}},Path:{type:"string",absolutePath:!0},Pathinfo:{anyOf:[{enum:["verbose"]},{type:"boolean"}]},Performance:{anyOf:[{enum:[!1]},{$ref:"#/definitions/PerformanceOptions"}]},PerformanceOptions:{type:"object",additionalProperties:!1,properties:{assetFilter:{instanceof:"Function"},hints:{enum:[!1,"warning","error"]},maxAssetSize:{type:"number"},maxEntrypointSize:{type:"number"}}},Plugins:{type:"array",items:{anyOf:[{$ref:"#/definitions/Falsy"},{$ref:"#/definitions/WebpackPluginInstance"},{$ref:"#/definitions/WebpackPluginFunction"}]}},Profile:{type:"boolean"},PublicPath:{anyOf:[{enum:["auto"]},{$ref:"#/definitions/RawPublicPath"}]},RawPublicPath:{anyOf:[{type:"string"},{instanceof:"Function"}]},RecordsInputPath:{anyOf:[{enum:[!1]},{type:"string",absolutePath:!0}]},RecordsOutputPath:{anyOf:[{enum:[!1]},{type:"string",absolutePath:!0}]},RecordsPath:{anyOf:[{enum:[!1]},{type:"string",absolutePath:!0}]},Resolve:{oneOf:[{$ref:"#/definitions/ResolveOptions"}]},ResolveAlias:{anyOf:[{type:"array",items:{type:"object",additionalProperties:!1,properties:{alias:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{enum:[!1]},{type:"string",minLength:1}]},name:{type:"string"},onlyModule:{type:"boolean"}},required:["alias","name"]}},{type:"object",additionalProperties:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{enum:[!1]},{type:"string",minLength:1}]}}]},ResolveLoader:{oneOf:[{$ref:"#/definitions/ResolveOptions"}]},ResolveOptions:{type:"object",additionalProperties:!1,properties:{alias:{$ref:"#/definitions/ResolveAlias"},aliasFields:{type:"array",items:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{type:"string",minLength:1}]}},byDependency:{type:"object",additionalProperties:{oneOf:[{$ref:"#/definitions/ResolveOptions"}]}},cache:{type:"boolean"},cachePredicate:{instanceof:"Function"},cacheWithContext:{type:"boolean"},conditionNames:{type:"array",items:{type:"string"}},descriptionFiles:{type:"array",items:{type:"string",minLength:1}},enforceExtension:{type:"boolean"},exportsFields:{type:"array",items:{type:"string"}},extensionAlias:{type:"object",additionalProperties:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{type:"string",minLength:1}]}},extensions:{type:"array",items:{type:"string"}},fallback:{oneOf:[{$ref:"#/definitions/ResolveAlias"}]},fileSystem:{},fullySpecified:{type:"boolean"},importsFields:{type:"array",items:{type:"string"}},mainFields:{type:"array",items:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{type:"string",minLength:1}]}},mainFiles:{type:"array",items:{type:"string",minLength:1}},modules:{type:"array",items:{type:"string",minLength:1}},plugins:{type:"array",items:{anyOf:[{enum:["..."]},{$ref:"#/definitions/Falsy"},{$ref:"#/definitions/ResolvePluginInstance"}]}},preferAbsolute:{type:"boolean"},preferRelative:{type:"boolean"},resolver:{},restrictions:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0,minLength:1}]}},roots:{type:"array",items:{type:"string"}},symlinks:{type:"boolean"},unsafeCache:{anyOf:[{type:"boolean"},{type:"object",additionalProperties:!0}]},useSyncFileSystemCalls:{type:"boolean"}}},ResolvePluginInstance:{anyOf:[{type:"object",additionalProperties:!0,properties:{apply:{instanceof:"Function"}},required:["apply"]},{instanceof:"Function"}]},RuleSetCondition:{anyOf:[{instanceof:"RegExp"},{type:"string"},{instanceof:"Function"},{$ref:"#/definitions/RuleSetLogicalConditions"},{$ref:"#/definitions/RuleSetConditions"}]},RuleSetConditionAbsolute:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0},{instanceof:"Function"},{$ref:"#/definitions/RuleSetLogicalConditionsAbsolute"},{$ref:"#/definitions/RuleSetConditionsAbsolute"}]},RuleSetConditionOrConditions:{anyOf:[{$ref:"#/definitions/RuleSetCondition"},{$ref:"#/definitions/RuleSetConditions"}]},RuleSetConditionOrConditionsAbsolute:{anyOf:[{$ref:"#/definitions/RuleSetConditionAbsolute"},{$ref:"#/definitions/RuleSetConditionsAbsolute"}]},RuleSetConditions:{type:"array",items:{oneOf:[{$ref:"#/definitions/RuleSetCondition"}]}},RuleSetConditionsAbsolute:{type:"array",items:{oneOf:[{$ref:"#/definitions/RuleSetConditionAbsolute"}]}},RuleSetLoader:{type:"string",minLength:1},RuleSetLoaderOptions:{anyOf:[{type:"string"},{type:"object"}]},RuleSetLogicalConditions:{type:"object",additionalProperties:!1,properties:{and:{oneOf:[{$ref:"#/definitions/RuleSetConditions"}]},not:{oneOf:[{$ref:"#/definitions/RuleSetCondition"}]},or:{oneOf:[{$ref:"#/definitions/RuleSetConditions"}]}}},RuleSetLogicalConditionsAbsolute:{type:"object",additionalProperties:!1,properties:{and:{oneOf:[{$ref:"#/definitions/RuleSetConditionsAbsolute"}]},not:{oneOf:[{$ref:"#/definitions/RuleSetConditionAbsolute"}]},or:{oneOf:[{$ref:"#/definitions/RuleSetConditionsAbsolute"}]}}},RuleSetRule:{type:"object",additionalProperties:!1,properties:{assert:{type:"object",additionalProperties:{$ref:"#/definitions/RuleSetConditionOrConditions"}},compiler:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditions"}]},dependency:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditions"}]},descriptionData:{type:"object",additionalProperties:{$ref:"#/definitions/RuleSetConditionOrConditions"}},enforce:{enum:["pre","post"]},exclude:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditionsAbsolute"}]},generator:{type:"object"},include:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditionsAbsolute"}]},issuer:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditionsAbsolute"}]},issuerLayer:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditions"}]},layer:{type:"string"},loader:{oneOf:[{$ref:"#/definitions/RuleSetLoader"}]},mimetype:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditions"}]},oneOf:{type:"array",items:{anyOf:[{$ref:"#/definitions/Falsy"},{$ref:"#/definitions/RuleSetRule"}]}},options:{oneOf:[{$ref:"#/definitions/RuleSetLoaderOptions"}]},parser:{type:"object",additionalProperties:!0},realResource:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditionsAbsolute"}]},resolve:{type:"object",oneOf:[{$ref:"#/definitions/ResolveOptions"}]},resource:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditionsAbsolute"}]},resourceFragment:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditions"}]},resourceQuery:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditions"}]},rules:{type:"array",items:{anyOf:[{$ref:"#/definitions/Falsy"},{$ref:"#/definitions/RuleSetRule"}]}},scheme:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditions"}]},sideEffects:{type:"boolean"},test:{oneOf:[{$ref:"#/definitions/RuleSetConditionOrConditionsAbsolute"}]},type:{type:"string"},use:{oneOf:[{$ref:"#/definitions/RuleSetUse"}]},with:{type:"object",additionalProperties:{$ref:"#/definitions/RuleSetConditionOrConditions"}}}},RuleSetRules:{type:"array",items:{anyOf:[{enum:["..."]},{$ref:"#/definitions/Falsy"},{$ref:"#/definitions/RuleSetRule"}]}},RuleSetUse:{anyOf:[{type:"array",items:{anyOf:[{$ref:"#/definitions/Falsy"},{$ref:"#/definitions/RuleSetUseItem"}]}},{$ref:"#/definitions/RuleSetUseFunction"},{$ref:"#/definitions/RuleSetUseItem"}]},RuleSetUseFunction:{instanceof:"Function"},RuleSetUseItem:{anyOf:[{type:"object",additionalProperties:!1,properties:{ident:{type:"string"},loader:{oneOf:[{$ref:"#/definitions/RuleSetLoader"}]},options:{oneOf:[{$ref:"#/definitions/RuleSetLoaderOptions"}]}}},{$ref:"#/definitions/RuleSetUseFunction"},{$ref:"#/definitions/RuleSetLoader"}]},ScriptType:{enum:[!1,"text/javascript","module"]},SnapshotOptions:{type:"object",additionalProperties:!1,properties:{buildDependencies:{type:"object",additionalProperties:!1,properties:{hash:{type:"boolean"},timestamp:{type:"boolean"}}},immutablePaths:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0,minLength:1}]}},managedPaths:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0,minLength:1}]}},module:{type:"object",additionalProperties:!1,properties:{hash:{type:"boolean"},timestamp:{type:"boolean"}}},resolve:{type:"object",additionalProperties:!1,properties:{hash:{type:"boolean"},timestamp:{type:"boolean"}}},resolveBuildDependencies:{type:"object",additionalProperties:!1,properties:{hash:{type:"boolean"},timestamp:{type:"boolean"}}},unmanagedPaths:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0,minLength:1}]}}}},SourceMapFilename:{type:"string",absolutePath:!1},SourcePrefix:{type:"string"},StatsOptions:{type:"object",additionalProperties:!1,properties:{all:{type:"boolean"},assets:{type:"boolean"},assetsSort:{anyOf:[{enum:[!1]},{type:"string"}]},assetsSpace:{type:"number"},builtAt:{type:"boolean"},cached:{type:"boolean"},cachedAssets:{type:"boolean"},cachedModules:{type:"boolean"},children:{type:"boolean"},chunkGroupAuxiliary:{type:"boolean"},chunkGroupChildren:{type:"boolean"},chunkGroupMaxAssets:{type:"number"},chunkGroups:{type:"boolean"},chunkModules:{type:"boolean"},chunkModulesSpace:{type:"number"},chunkOrigins:{type:"boolean"},chunkRelations:{type:"boolean"},chunks:{type:"boolean"},chunksSort:{anyOf:[{enum:[!1]},{type:"string"}]},colors:{anyOf:[{type:"boolean"},{type:"object",additionalProperties:!1,properties:{bold:{type:"string"},cyan:{type:"string"},green:{type:"string"},magenta:{type:"string"},red:{type:"string"},yellow:{type:"string"}}}]},context:{type:"string",absolutePath:!0},dependentModules:{type:"boolean"},depth:{type:"boolean"},entrypoints:{anyOf:[{enum:["auto"]},{type:"boolean"}]},env:{type:"boolean"},errorCause:{anyOf:[{enum:["auto"]},{type:"boolean"}]},errorDetails:{anyOf:[{enum:["auto"]},{type:"boolean"}]},errorErrors:{anyOf:[{enum:["auto"]},{type:"boolean"}]},errorStack:{type:"boolean"},errors:{type:"boolean"},errorsCount:{type:"boolean"},errorsSpace:{type:"number"},exclude:{anyOf:[{type:"boolean"},{$ref:"#/definitions/ModuleFilterTypes"}]},excludeAssets:{oneOf:[{$ref:"#/definitions/AssetFilterTypes"}]},excludeModules:{anyOf:[{type:"boolean"},{$ref:"#/definitions/ModuleFilterTypes"}]},groupAssetsByChunk:{type:"boolean"},groupAssetsByEmitStatus:{type:"boolean"},groupAssetsByExtension:{type:"boolean"},groupAssetsByInfo:{type:"boolean"},groupAssetsByPath:{type:"boolean"},groupModulesByAttributes:{type:"boolean"},groupModulesByCacheStatus:{type:"boolean"},groupModulesByExtension:{type:"boolean"},groupModulesByLayer:{type:"boolean"},groupModulesByPath:{type:"boolean"},groupModulesByType:{type:"boolean"},groupReasonsByOrigin:{type:"boolean"},hash:{type:"boolean"},ids:{type:"boolean"},logging:{anyOf:[{enum:["none","error","warn","info","log","verbose"]},{type:"boolean"}]},loggingDebug:{anyOf:[{type:"boolean"},{$ref:"#/definitions/FilterTypes"}]},loggingTrace:{type:"boolean"},moduleAssets:{type:"boolean"},moduleTrace:{type:"boolean"},modules:{type:"boolean"},modulesSort:{anyOf:[{enum:[!1]},{type:"string"}]},modulesSpace:{type:"number"},nestedModules:{type:"boolean"},nestedModulesSpace:{type:"number"},optimizationBailout:{type:"boolean"},orphanModules:{type:"boolean"},outputPath:{type:"boolean"},performance:{type:"boolean"},preset:{anyOf:[{type:"boolean"},{type:"string"}]},providedExports:{type:"boolean"},publicPath:{type:"boolean"},reasons:{type:"boolean"},reasonsSpace:{type:"number"},relatedAssets:{type:"boolean"},runtime:{type:"boolean"},runtimeModules:{type:"boolean"},source:{type:"boolean"},timings:{type:"boolean"},usedExports:{type:"boolean"},version:{type:"boolean"},warnings:{type:"boolean"},warningsCount:{type:"boolean"},warningsFilter:{oneOf:[{$ref:"#/definitions/WarningFilterTypes"}]},warningsSpace:{type:"number"}}},StatsValue:{anyOf:[{enum:["none","summary","errors-only","errors-warnings","minimal","normal","detailed","verbose"]},{type:"boolean"},{$ref:"#/definitions/StatsOptions"}]},StrictModuleErrorHandling:{type:"boolean"},StrictModuleExceptionHandling:{type:"boolean"},Target:{anyOf:[{type:"array",items:{type:"string",minLength:1},minItems:1},{enum:[!1]},{type:"string",minLength:1}]},TrustedTypes:{type:"object",additionalProperties:!1,properties:{onPolicyCreationFailure:{enum:["continue","stop"]},policyName:{type:"string",minLength:1}}},UmdNamedDefine:{type:"boolean"},UniqueName:{type:"string",minLength:1},WarningFilterItemTypes:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!1},{instanceof:"Function"}]},WarningFilterTypes:{anyOf:[{type:"array",items:{oneOf:[{$ref:"#/definitions/WarningFilterItemTypes"}]}},{$ref:"#/definitions/WarningFilterItemTypes"}]},WasmLoading:{anyOf:[{enum:[!1]},{$ref:"#/definitions/WasmLoadingType"}]},WasmLoadingType:{anyOf:[{enum:["fetch","async-node"]},{type:"string"}]},Watch:{type:"boolean"},WatchOptions:{type:"object",additionalProperties:!1,properties:{aggregateTimeout:{type:"number"},followSymlinks:{type:"boolean"},ignored:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{instanceof:"RegExp"},{type:"string",minLength:1}]},poll:{anyOf:[{type:"number"},{type:"boolean"}]},stdin:{type:"boolean"}}},WebassemblyModuleFilename:{type:"string",absolutePath:!1},WebpackOptionsNormalized:{type:"object",additionalProperties:!1,properties:{amd:{$ref:"#/definitions/Amd"},bail:{$ref:"#/definitions/Bail"},cache:{$ref:"#/definitions/CacheOptionsNormalized"},context:{$ref:"#/definitions/Context"},dependencies:{$ref:"#/definitions/Dependencies"},devServer:{$ref:"#/definitions/DevServer"},devtool:{$ref:"#/definitions/DevTool"},entry:{$ref:"#/definitions/EntryNormalized"},experiments:{$ref:"#/definitions/ExperimentsNormalized"},externals:{$ref:"#/definitions/Externals"},externalsPresets:{$ref:"#/definitions/ExternalsPresets"},externalsType:{$ref:"#/definitions/ExternalsType"},ignoreWarnings:{$ref:"#/definitions/IgnoreWarningsNormalized"},infrastructureLogging:{$ref:"#/definitions/InfrastructureLogging"},loader:{$ref:"#/definitions/Loader"},mode:{$ref:"#/definitions/Mode"},module:{$ref:"#/definitions/ModuleOptionsNormalized"},name:{$ref:"#/definitions/Name"},node:{$ref:"#/definitions/Node"},optimization:{$ref:"#/definitions/OptimizationNormalized"},output:{$ref:"#/definitions/OutputNormalized"},parallelism:{$ref:"#/definitions/Parallelism"},performance:{$ref:"#/definitions/Performance"},plugins:{$ref:"#/definitions/Plugins"},profile:{$ref:"#/definitions/Profile"},recordsInputPath:{$ref:"#/definitions/RecordsInputPath"},recordsOutputPath:{$ref:"#/definitions/RecordsOutputPath"},resolve:{$ref:"#/definitions/Resolve"},resolveLoader:{$ref:"#/definitions/ResolveLoader"},snapshot:{$ref:"#/definitions/SnapshotOptions"},stats:{$ref:"#/definitions/StatsValue"},target:{$ref:"#/definitions/Target"},watch:{$ref:"#/definitions/Watch"},watchOptions:{$ref:"#/definitions/WatchOptions"}},required:["cache","snapshot","entry","experiments","externals","externalsPresets","infrastructureLogging","module","node","optimization","output","plugins","resolve","resolveLoader","stats","watchOptions"]},WebpackPluginFunction:{instanceof:"Function"},WebpackPluginInstance:{type:"object",additionalProperties:!0,properties:{apply:{instanceof:"Function"}},required:["apply"]},WorkerPublicPath:{type:"string"}},type:"object",additionalProperties:!1,properties:{amd:{$ref:"#/definitions/Amd"},bail:{$ref:"#/definitions/Bail"},cache:{$ref:"#/definitions/CacheOptions"},context:{$ref:"#/definitions/Context"},dependencies:{$ref:"#/definitions/Dependencies"},devServer:{$ref:"#/definitions/DevServer"},devtool:{$ref:"#/definitions/DevTool"},entry:{$ref:"#/definitions/Entry"},experiments:{$ref:"#/definitions/Experiments"},extends:{$ref:"#/definitions/Extends"},externals:{$ref:"#/definitions/Externals"},externalsPresets:{$ref:"#/definitions/ExternalsPresets"},externalsType:{$ref:"#/definitions/ExternalsType"},ignoreWarnings:{$ref:"#/definitions/IgnoreWarnings"},infrastructureLogging:{$ref:"#/definitions/InfrastructureLogging"},loader:{$ref:"#/definitions/Loader"},mode:{$ref:"#/definitions/Mode"},module:{$ref:"#/definitions/ModuleOptions"},name:{$ref:"#/definitions/Name"},node:{$ref:"#/definitions/Node"},optimization:{$ref:"#/definitions/Optimization"},output:{$ref:"#/definitions/Output"},parallelism:{$ref:"#/definitions/Parallelism"},performance:{$ref:"#/definitions/Performance"},plugins:{$ref:"#/definitions/Plugins"},profile:{$ref:"#/definitions/Profile"},recordsInputPath:{$ref:"#/definitions/RecordsInputPath"},recordsOutputPath:{$ref:"#/definitions/RecordsOutputPath"},recordsPath:{$ref:"#/definitions/RecordsPath"},resolve:{$ref:"#/definitions/Resolve"},resolveLoader:{$ref:"#/definitions/ResolveLoader"},snapshot:{$ref:"#/definitions/SnapshotOptions"},stats:{$ref:"#/definitions/StatsValue"},target:{$ref:"#/definitions/Target"},watch:{$ref:"#/definitions/Watch"},watchOptions:{$ref:"#/definitions/WatchOptions"}}},n=Object.prototype.hasOwnProperty,r={type:"object",additionalProperties:!1,properties:{allowCollectingMemory:{type:"boolean"},buildDependencies:{type:"object",additionalProperties:{type:"array",items:{type:"string",minLength:1}}},cacheDirectory:{type:"string",absolutePath:!0},cacheLocation:{type:"string",absolutePath:!0},compression:{enum:[!1,"gzip","brotli"]},hashAlgorithm:{type:"string"},idleTimeout:{type:"number",minimum:0},idleTimeoutAfterLargeChanges:{type:"number",minimum:0},idleTimeoutForInitialStore:{type:"number",minimum:0},immutablePaths:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0,minLength:1}]}},managedPaths:{type:"array",items:{anyOf:[{instanceof:"RegExp"},{type:"string",absolutePath:!0,minLength:1}]}},maxAge:{type:"number",minimum:0},maxMemoryGenerations:{type:"number",minimum:0},memoryCacheUnaffected:{type:"boolean"},name:{type:"string"},profile:{type:"boolean"},readonly:{type:"boolean"},store:{enum:["pack"]},type:{enum:["filesystem"]},version:{type:"string"}},required:["type"]};function o(t,{instancePath:s="",parentData:i,parentDataProperty:a,rootData:l=t}={}){let p=null,f=0;const u=f;let c=!1;const y=f;if(!1!==t){const e={params:{}};null===p?p=[e]:p.push(e),f++}var m=y===f;if(c=c||m,!c){const o=f;if(f==f)if(t&&"object"==typeof t&&!Array.isArray(t)){let e;if(void 0===t.type&&(e="type")){const t={params:{missingProperty:e}};null===p?p=[t]:p.push(t),f++}else{const e=f;for(const e in t)if("cacheUnaffected"!==e&&"maxGenerations"!==e&&"type"!==e){const t={params:{additionalProperty:e}};null===p?p=[t]:p.push(t),f++;break}if(e===f){if(void 0!==t.cacheUnaffected){const e=f;if("boolean"!=typeof t.cacheUnaffected){const e={params:{type:"boolean"}};null===p?p=[e]:p.push(e),f++}var d=e===f}else d=!0;if(d){if(void 0!==t.maxGenerations){let e=t.maxGenerations;const n=f;if(f===n)if("number"==typeof e){if(e<1||isNaN(e)){const e={params:{comparison:">=",limit:1}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"number"}};null===p?p=[e]:p.push(e),f++}d=n===f}else d=!0;if(d)if(void 0!==t.type){const e=f;if("memory"!==t.type){const e={params:{}};null===p?p=[e]:p.push(e),f++}d=e===f}else d=!0}}}}else{const e={params:{type:"object"}};null===p?p=[e]:p.push(e),f++}if(m=o===f,c=c||m,!c){const o=f;if(f==f)if(t&&"object"==typeof t&&!Array.isArray(t)){let o;if(void 0===t.type&&(o="type")){const e={params:{missingProperty:o}};null===p?p=[e]:p.push(e),f++}else{const o=f;for(const e in t)if(!n.call(r.properties,e)){const t={params:{additionalProperty:e}};null===p?p=[t]:p.push(t),f++;break}if(o===f){if(void 0!==t.allowCollectingMemory){const e=f;if("boolean"!=typeof t.allowCollectingMemory){const e={params:{type:"boolean"}};null===p?p=[e]:p.push(e),f++}var h=e===f}else h=!0;if(h){if(void 0!==t.buildDependencies){let e=t.buildDependencies;const n=f;if(f===n)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){let n=e[t];const r=f;if(f===r)if(Array.isArray(n)){const e=n.length;for(let t=0;t=",limit:0}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"number"}};null===p?p=[e]:p.push(e),f++}h=n===f}else h=!0;if(h){if(void 0!==t.idleTimeoutAfterLargeChanges){let e=t.idleTimeoutAfterLargeChanges;const n=f;if(f===n)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"number"}};null===p?p=[e]:p.push(e),f++}h=n===f}else h=!0;if(h){if(void 0!==t.idleTimeoutForInitialStore){let e=t.idleTimeoutForInitialStore;const n=f;if(f===n)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"number"}};null===p?p=[e]:p.push(e),f++}h=n===f}else h=!0;if(h){if(void 0!==t.immutablePaths){let n=t.immutablePaths;const r=f;if(f===r)if(Array.isArray(n)){const t=n.length;for(let r=0;r=",limit:0}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"number"}};null===p?p=[e]:p.push(e),f++}h=n===f}else h=!0;if(h){if(void 0!==t.maxMemoryGenerations){let e=t.maxMemoryGenerations;const n=f;if(f===n)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"number"}};null===p?p=[e]:p.push(e),f++}h=n===f}else h=!0;if(h){if(void 0!==t.memoryCacheUnaffected){const e=f;if("boolean"!=typeof t.memoryCacheUnaffected){const e={params:{type:"boolean"}};null===p?p=[e]:p.push(e),f++}h=e===f}else h=!0;if(h){if(void 0!==t.name){const e=f;if("string"!=typeof t.name){const e={params:{type:"string"}};null===p?p=[e]:p.push(e),f++}h=e===f}else h=!0;if(h){if(void 0!==t.profile){const e=f;if("boolean"!=typeof t.profile){const e={params:{type:"boolean"}};null===p?p=[e]:p.push(e),f++}h=e===f}else h=!0;if(h){if(void 0!==t.readonly){const e=f;if("boolean"!=typeof t.readonly){const e={params:{type:"boolean"}};null===p?p=[e]:p.push(e),f++}h=e===f}else h=!0;if(h){if(void 0!==t.store){const e=f;if("pack"!==t.store){const e={params:{}};null===p?p=[e]:p.push(e),f++}h=e===f}else h=!0;if(h){if(void 0!==t.type){const e=f;if("filesystem"!==t.type){const e={params:{}};null===p?p=[e]:p.push(e),f++}h=e===f}else h=!0;if(h)if(void 0!==t.version){const e=f;if("string"!=typeof t.version){const e={params:{type:"string"}};null===p?p=[e]:p.push(e),f++}h=e===f}else h=!0}}}}}}}}}}}}}}}}}}}}}else{const e={params:{type:"object"}};null===p?p=[e]:p.push(e),f++}m=o===f,c=c||m}}if(!c){const e={params:{}};return null===p?p=[e]:p.push(e),f++,o.errors=p,!1}return f=u,null!==p&&(u?p.length=u:p=null),o.errors=p,0===f}function s(e,{instancePath:t="",parentData:n,parentDataProperty:r,rootData:i=e}={}){let a=null,l=0;const p=l;let f=!1;const u=l;if(!0!==e){const e={params:{}};null===a?a=[e]:a.push(e),l++}var c=u===l;if(f=f||c,!f){const s=l;o(e,{instancePath:t,parentData:n,parentDataProperty:r,rootData:i})||(a=null===a?o.errors:a.concat(o.errors),l=a.length),c=s===l,f=f||c}if(!f){const e={params:{}};return null===a?a=[e]:a.push(e),l++,s.errors=a,!1}return l=p,null!==a&&(p?a.length=p:a=null),s.errors=a,0===l}const i={type:"object",additionalProperties:!1,properties:{asyncChunks:{type:"boolean"},baseUri:{type:"string"},chunkLoading:{$ref:"#/definitions/ChunkLoading"},dependOn:{anyOf:[{type:"array",items:{type:"string",minLength:1},minItems:1,uniqueItems:!0},{type:"string",minLength:1}]},filename:{$ref:"#/definitions/EntryFilename"},import:{$ref:"#/definitions/EntryItem"},layer:{$ref:"#/definitions/Layer"},library:{$ref:"#/definitions/LibraryOptions"},publicPath:{$ref:"#/definitions/PublicPath"},runtime:{$ref:"#/definitions/EntryRuntime"},wasmLoading:{$ref:"#/definitions/WasmLoading"}},required:["import"]};function a(e,{instancePath:t="",parentData:n,parentDataProperty:r,rootData:o=e}={}){let s=null,i=0;const l=i;let p=!1;const f=i;if(!1!==e){const e={params:{}};null===s?s=[e]:s.push(e),i++}var u=f===i;if(p=p||u,!p){const t=i,n=i;let r=!1;const o=i;if("jsonp"!==e&&"import-scripts"!==e&&"require"!==e&&"async-node"!==e&&"import"!==e){const e={params:{}};null===s?s=[e]:s.push(e),i++}var c=o===i;if(r=r||c,!r){const t=i;if("string"!=typeof e){const e={params:{type:"string"}};null===s?s=[e]:s.push(e),i++}c=t===i,r=r||c}if(r)i=n,null!==s&&(n?s.length=n:s=null);else{const e={params:{}};null===s?s=[e]:s.push(e),i++}u=t===i,p=p||u}if(!p){const e={params:{}};return null===s?s=[e]:s.push(e),i++,a.errors=s,!1}return i=l,null!==s&&(l?s.length=l:s=null),a.errors=s,0===i}function l(t,{instancePath:n="",parentData:r,parentDataProperty:o,rootData:s=t}={}){let i=null,a=0;const p=a;let f=!1,u=null;const c=a,y=a;let m=!1;const d=a;if(a===d)if("string"==typeof t){if(t.includes("!")||!1!==e.test(t)){const e={params:{}};null===i?i=[e]:i.push(e),a++}else if(t.length<1){const e={params:{}};null===i?i=[e]:i.push(e),a++}}else{const e={params:{type:"string"}};null===i?i=[e]:i.push(e),a++}var h=d===a;if(m=m||h,!m){const e=a;if(!(t instanceof Function)){const e={params:{}};null===i?i=[e]:i.push(e),a++}h=e===a,m=m||h}if(m)a=y,null!==i&&(y?i.length=y:i=null);else{const e={params:{}};null===i?i=[e]:i.push(e),a++}if(c===a&&(f=!0,u=0),!f){const e={params:{passingSchemas:u}};return null===i?i=[e]:i.push(e),a++,l.errors=i,!1}return a=p,null!==i&&(p?i.length=p:i=null),l.errors=i,0===a}function p(e,{instancePath:t="",parentData:n,parentDataProperty:r,rootData:o=e}={}){let s=null,i=0;const a=i;let l=!1;const f=i;if("string"!=typeof e){const e={params:{type:"string"}};null===s?s=[e]:s.push(e),i++}var u=f===i;if(l=l||u,!l){const t=i;if(i==i)if(e&&"object"==typeof e&&!Array.isArray(e)){const t=i;for(const t in e)if("amd"!==t&&"commonjs"!==t&&"commonjs2"!==t&&"root"!==t){const e={params:{additionalProperty:t}};null===s?s=[e]:s.push(e),i++;break}if(t===i){if(void 0!==e.amd){const t=i;if("string"!=typeof e.amd){const e={params:{type:"string"}};null===s?s=[e]:s.push(e),i++}var c=t===i}else c=!0;if(c){if(void 0!==e.commonjs){const t=i;if("string"!=typeof e.commonjs){const e={params:{type:"string"}};null===s?s=[e]:s.push(e),i++}c=t===i}else c=!0;if(c){if(void 0!==e.commonjs2){const t=i;if("string"!=typeof e.commonjs2){const e={params:{type:"string"}};null===s?s=[e]:s.push(e),i++}c=t===i}else c=!0;if(c)if(void 0!==e.root){const t=i;if("string"!=typeof e.root){const e={params:{type:"string"}};null===s?s=[e]:s.push(e),i++}c=t===i}else c=!0}}}}else{const e={params:{type:"object"}};null===s?s=[e]:s.push(e),i++}u=t===i,l=l||u}if(!l){const e={params:{}};return null===s?s=[e]:s.push(e),i++,p.errors=s,!1}return i=a,null!==s&&(a?s.length=a:s=null),p.errors=s,0===i}function f(e,{instancePath:t="",parentData:n,parentDataProperty:r,rootData:o=e}={}){let s=null,i=0;const a=i;let l=!1;const p=i;if(i===p)if(Array.isArray(e))if(e.length<1){const e={params:{limit:1}};null===s?s=[e]:s.push(e),i++}else{const t=e.length;for(let n=0;n1){const r={};for(;n--;){let o=t[n];if("string"==typeof o){if("number"==typeof r[o]){e=r[o];const t={params:{i:n,j:e}};null===p?p=[t]:p.push(t),f++;break}r[o]=n}}}}}else{const e={params:{type:"array"}};null===p?p=[e]:p.push(e),f++}var b=s===f;if(o=o||b,!o){const e=f;if(f===e)if("string"==typeof t){if(t.length<1){const e={params:{}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"string"}};null===p?p=[e]:p.push(e),f++}b=e===f,o=o||b}if(!o){const e={params:{}};return null===p?p=[e]:p.push(e),f++,m.errors=p,!1}f=r,null!==p&&(r?p.length=r:p=null),d=n===f}else d=!0;if(d){if(void 0!==e.filename){const n=f;l(e.filename,{instancePath:t+"/filename",parentData:e,parentDataProperty:"filename",rootData:s})||(p=null===p?l.errors:p.concat(l.errors),f=p.length),d=n===f}else d=!0;if(d){if(void 0!==e.import){let t=e.import;const n=f,r=f;let o=!1;const s=f;if(f===s)if(Array.isArray(t))if(t.length<1){const e={params:{limit:1}};null===p?p=[e]:p.push(e),f++}else{var g=!0;const e=t.length;for(let n=0;n1){const r={};for(;n--;){let o=t[n];if("string"==typeof o){if("number"==typeof r[o]){e=r[o];const t={params:{i:n,j:e}};null===p?p=[t]:p.push(t),f++;break}r[o]=n}}}}}else{const e={params:{type:"array"}};null===p?p=[e]:p.push(e),f++}var v=s===f;if(o=o||v,!o){const e=f;if(f===e)if("string"==typeof t){if(t.length<1){const e={params:{}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"string"}};null===p?p=[e]:p.push(e),f++}v=e===f,o=o||v}if(!o){const e={params:{}};return null===p?p=[e]:p.push(e),f++,m.errors=p,!1}f=r,null!==p&&(r?p.length=r:p=null),d=n===f}else d=!0;if(d){if(void 0!==e.layer){let t=e.layer;const n=f,r=f;let o=!1;const s=f;if(null!==t){const e={params:{}};null===p?p=[e]:p.push(e),f++}var P=s===f;if(o=o||P,!o){const e=f;if(f===e)if("string"==typeof t){if(t.length<1){const e={params:{}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"string"}};null===p?p=[e]:p.push(e),f++}P=e===f,o=o||P}if(!o){const e={params:{}};return null===p?p=[e]:p.push(e),f++,m.errors=p,!1}f=r,null!==p&&(r?p.length=r:p=null),d=n===f}else d=!0;if(d){if(void 0!==e.library){const n=f;u(e.library,{instancePath:t+"/library",parentData:e,parentDataProperty:"library",rootData:s})||(p=null===p?u.errors:p.concat(u.errors),f=p.length),d=n===f}else d=!0;if(d){if(void 0!==e.publicPath){const n=f;c(e.publicPath,{instancePath:t+"/publicPath",parentData:e,parentDataProperty:"publicPath",rootData:s})||(p=null===p?c.errors:p.concat(c.errors),f=p.length),d=n===f}else d=!0;if(d){if(void 0!==e.runtime){let t=e.runtime;const n=f,r=f;let o=!1;const s=f;if(!1!==t){const e={params:{}};null===p?p=[e]:p.push(e),f++}var D=s===f;if(o=o||D,!o){const e=f;if(f===e)if("string"==typeof t){if(t.length<1){const e={params:{}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"string"}};null===p?p=[e]:p.push(e),f++}D=e===f,o=o||D}if(!o){const e={params:{}};return null===p?p=[e]:p.push(e),f++,m.errors=p,!1}f=r,null!==p&&(r?p.length=r:p=null),d=n===f}else d=!0;if(d)if(void 0!==e.wasmLoading){const n=f;y(e.wasmLoading,{instancePath:t+"/wasmLoading",parentData:e,parentDataProperty:"wasmLoading",rootData:s})||(p=null===p?y.errors:p.concat(y.errors),f=p.length),d=n===f}else d=!0}}}}}}}}}}}}}return m.errors=p,0===f}function d(e,{instancePath:t="",parentData:n,parentDataProperty:r,rootData:o=e}={}){let s=null,i=0;if(0===i){if(!e||"object"!=typeof e||Array.isArray(e))return d.errors=[{params:{type:"object"}}],!1;for(const n in e){let r=e[n];const f=i,u=i;let c=!1;const y=i,h=i;let b=!1;const g=i;if(i===g)if(Array.isArray(r))if(r.length<1){const e={params:{limit:1}};null===s?s=[e]:s.push(e),i++}else{var a=!0;const e=r.length;for(let t=0;t1){const n={};for(;t--;){let o=r[t];if("string"==typeof o){if("number"==typeof n[o]){e=n[o];const r={params:{i:t,j:e}};null===s?s=[r]:s.push(r),i++;break}n[o]=t}}}}}else{const e={params:{type:"array"}};null===s?s=[e]:s.push(e),i++}var l=g===i;if(b=b||l,!b){const e=i;if(i===e)if("string"==typeof r){if(r.length<1){const e={params:{}};null===s?s=[e]:s.push(e),i++}}else{const e={params:{type:"string"}};null===s?s=[e]:s.push(e),i++}l=e===i,b=b||l}if(b)i=h,null!==s&&(h?s.length=h:s=null);else{const e={params:{}};null===s?s=[e]:s.push(e),i++}var p=y===i;if(c=c||p,!c){const a=i;m(r,{instancePath:t+"/"+n.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:n,rootData:o})||(s=null===s?m.errors:s.concat(m.errors),i=s.length),p=a===i,c=c||p}if(!c){const e={params:{}};return null===s?s=[e]:s.push(e),i++,d.errors=s,!1}if(i=u,null!==s&&(u?s.length=u:s=null),f!==i)break}}return d.errors=s,0===i}function h(e,{instancePath:t="",parentData:n,parentDataProperty:r,rootData:o=e}={}){let s=null,i=0;const a=i;let l=!1,p=null;const f=i,u=i;let c=!1;const y=i;if(i===y)if(Array.isArray(e))if(e.length<1){const e={params:{limit:1}};null===s?s=[e]:s.push(e),i++}else{var m=!0;const t=e.length;for(let n=0;n1){const r={};for(;n--;){let o=e[n];if("string"==typeof o){if("number"==typeof r[o]){t=r[o];const e={params:{i:n,j:t}};null===s?s=[e]:s.push(e),i++;break}r[o]=n}}}}}else{const e={params:{type:"array"}};null===s?s=[e]:s.push(e),i++}var d=y===i;if(c=c||d,!c){const t=i;if(i===t)if("string"==typeof e){if(e.length<1){const e={params:{}};null===s?s=[e]:s.push(e),i++}}else{const e={params:{type:"string"}};null===s?s=[e]:s.push(e),i++}d=t===i,c=c||d}if(c)i=u,null!==s&&(u?s.length=u:s=null);else{const e={params:{}};null===s?s=[e]:s.push(e),i++}if(f===i&&(l=!0,p=0),!l){const e={params:{passingSchemas:p}};return null===s?s=[e]:s.push(e),i++,h.errors=s,!1}return i=a,null!==s&&(a?s.length=a:s=null),h.errors=s,0===i}function b(e,{instancePath:t="",parentData:n,parentDataProperty:r,rootData:o=e}={}){let s=null,i=0;const a=i;let l=!1;const p=i;d(e,{instancePath:t,parentData:n,parentDataProperty:r,rootData:o})||(s=null===s?d.errors:s.concat(d.errors),i=s.length);var f=p===i;if(l=l||f,!l){const a=i;h(e,{instancePath:t,parentData:n,parentDataProperty:r,rootData:o})||(s=null===s?h.errors:s.concat(h.errors),i=s.length),f=a===i,l=l||f}if(!l){const e={params:{}};return null===s?s=[e]:s.push(e),i++,b.errors=s,!1}return i=a,null!==s&&(a?s.length=a:s=null),b.errors=s,0===i}function g(e,{instancePath:t="",parentData:n,parentDataProperty:r,rootData:o=e}={}){let s=null,i=0;const a=i;let l=!1;const p=i;if(!(e instanceof Function)){const e={params:{}};null===s?s=[e]:s.push(e),i++}var f=p===i;if(l=l||f,!l){const a=i;b(e,{instancePath:t,parentData:n,parentDataProperty:r,rootData:o})||(s=null===s?b.errors:s.concat(b.errors),i=s.length),f=a===i,l=l||f}if(!l){const e={params:{}};return null===s?s=[e]:s.push(e),i++,g.errors=s,!1}return i=a,null!==s&&(a?s.length=a:s=null),g.errors=s,0===i}const v={type:"object",additionalProperties:!1,properties:{asyncWebAssembly:{type:"boolean"},backCompat:{type:"boolean"},buildHttp:{anyOf:[{$ref:"#/definitions/HttpUriAllowedUris"},{$ref:"#/definitions/HttpUriOptions"}]},cacheUnaffected:{type:"boolean"},css:{type:"boolean"},deferImport:{type:"boolean"},futureDefaults:{type:"boolean"},layers:{type:"boolean"},lazyCompilation:{anyOf:[{type:"boolean"},{$ref:"#/definitions/LazyCompilationOptions"}]},outputModule:{type:"boolean"},syncWebAssembly:{type:"boolean"},topLevelAwait:{type:"boolean"}}},P=new RegExp("^https?://","u");function D(e,{instancePath:t="",parentData:n,parentDataProperty:r,rootData:o=e}={}){let s=null,i=0;const a=i;let l=!1,p=null;const f=i;if(i==i)if(Array.isArray(e)){const t=e.length;for(let n=0;n=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var u=y===l;if(c=c||u,!c){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}u=t===l,c=c||u}if(c)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.filename){let n=t.filename;const r=l,o=l;let s=!1;const i=l;if(l===i)if("string"==typeof n){if(n.includes("!")||!1!==e.test(n)){const e={params:{}};null===a?a=[e]:a.push(e),l++}else if(n.length<1){const e={params:{}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"string"}};null===a?a=[e]:a.push(e),l++}var c=i===l;if(s=s||c,!s){const e=l;if(!(n instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}c=e===l,s=s||c}if(!s){const e={params:{}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=o,null!==a&&(o?a.length=o:a=null),p=r===l}else p=!0;if(p){if(void 0!==t.idHint){const e=l;if("string"!=typeof t.idHint)return De.errors=[{params:{type:"string"}}],!1;p=e===l}else p=!0;if(p){if(void 0!==t.layer){let e=t.layer;const n=l,r=l;let o=!1;const s=l;if(!(e instanceof RegExp)){const e={params:{}};null===a?a=[e]:a.push(e),l++}var y=s===l;if(o=o||y,!o){const t=l;if("string"!=typeof e){const e={params:{type:"string"}};null===a?a=[e]:a.push(e),l++}if(y=t===l,o=o||y,!o){const t=l;if(!(e instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}y=t===l,o=o||y}}if(!o){const e={params:{}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.maxAsyncRequests){let e=t.maxAsyncRequests;const n=l;if(l===n){if("number"!=typeof e)return De.errors=[{params:{type:"number"}}],!1;if(e<1||isNaN(e))return De.errors=[{params:{comparison:">=",limit:1}}],!1}p=n===l}else p=!0;if(p){if(void 0!==t.maxAsyncSize){let e=t.maxAsyncSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var m=c===l;if(u=u||m,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}m=t===l,u=u||m}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.maxInitialRequests){let e=t.maxInitialRequests;const n=l;if(l===n){if("number"!=typeof e)return De.errors=[{params:{type:"number"}}],!1;if(e<1||isNaN(e))return De.errors=[{params:{comparison:">=",limit:1}}],!1}p=n===l}else p=!0;if(p){if(void 0!==t.maxInitialSize){let e=t.maxInitialSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var d=c===l;if(u=u||d,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}d=t===l,u=u||d}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.maxSize){let e=t.maxSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var h=c===l;if(u=u||h,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}h=t===l,u=u||h}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.minChunks){let e=t.minChunks;const n=l;if(l===n){if("number"!=typeof e)return De.errors=[{params:{type:"number"}}],!1;if(e<1||isNaN(e))return De.errors=[{params:{comparison:">=",limit:1}}],!1}p=n===l}else p=!0;if(p){if(void 0!==t.minRemainingSize){let e=t.minRemainingSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var b=c===l;if(u=u||b,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}b=t===l,u=u||b}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.minSize){let e=t.minSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var g=c===l;if(u=u||g,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}g=t===l,u=u||g}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.minSizeReduction){let e=t.minSizeReduction;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var v=c===l;if(u=u||v,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}v=t===l,u=u||v}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.name){let e=t.name;const n=l,r=l;let o=!1;const s=l;if(!1!==e){const e={params:{}};null===a?a=[e]:a.push(e),l++}var P=s===l;if(o=o||P,!o){const t=l;if("string"!=typeof e){const e={params:{type:"string"}};null===a?a=[e]:a.push(e),l++}if(P=t===l,o=o||P,!o){const t=l;if(!(e instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}P=t===l,o=o||P}}if(!o){const e={params:{}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.priority){const e=l;if("number"!=typeof t.priority)return De.errors=[{params:{type:"number"}}],!1;p=e===l}else p=!0;if(p){if(void 0!==t.reuseExistingChunk){const e=l;if("boolean"!=typeof t.reuseExistingChunk)return De.errors=[{params:{type:"boolean"}}],!1;p=e===l}else p=!0;if(p){if(void 0!==t.test){let e=t.test;const n=l,r=l;let o=!1;const s=l;if(!(e instanceof RegExp)){const e={params:{}};null===a?a=[e]:a.push(e),l++}var D=s===l;if(o=o||D,!o){const t=l;if("string"!=typeof e){const e={params:{type:"string"}};null===a?a=[e]:a.push(e),l++}if(D=t===l,o=o||D,!o){const t=l;if(!(e instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}D=t===l,o=o||D}}if(!o){const e={params:{}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.type){let e=t.type;const n=l,r=l;let o=!1;const s=l;if(!(e instanceof RegExp)){const e={params:{}};null===a?a=[e]:a.push(e),l++}var O=s===l;if(o=o||O,!o){const t=l;if("string"!=typeof e){const e={params:{type:"string"}};null===a?a=[e]:a.push(e),l++}if(O=t===l,o=o||O,!o){const t=l;if(!(e instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}O=t===l,o=o||O}}if(!o){const e={params:{}};return null===a?a=[e]:a.push(e),l++,De.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p)if(void 0!==t.usedExports){const e=l;if("boolean"!=typeof t.usedExports)return De.errors=[{params:{type:"boolean"}}],!1;p=e===l}else p=!0}}}}}}}}}}}}}}}}}}}}}}}return De.errors=a,0===l}function Oe(t,{instancePath:r="",parentData:o,parentDataProperty:s,rootData:i=t}={}){let a=null,l=0;if(0===l){if(!t||"object"!=typeof t||Array.isArray(t))return Oe.errors=[{params:{type:"object"}}],!1;{const o=l;for(const e in t)if(!n.call(ve.properties,e))return Oe.errors=[{params:{additionalProperty:e}}],!1;if(o===l){if(void 0!==t.automaticNameDelimiter){let e=t.automaticNameDelimiter;const n=l;if(l===n){if("string"!=typeof e)return Oe.errors=[{params:{type:"string"}}],!1;if(e.length<1)return Oe.errors=[{params:{}}],!1}var p=n===l}else p=!0;if(p){if(void 0!==t.cacheGroups){let e=t.cacheGroups;const n=l,o=l,s=l;if(l===s)if(e&&"object"==typeof e&&!Array.isArray(e)){let t;if(void 0===e.test&&(t="test")){const e={};null===a?a=[e]:a.push(e),l++}else if(void 0!==e.test){let t=e.test;const n=l;let r=!1;const o=l;if(!(t instanceof RegExp)){const e={};null===a?a=[e]:a.push(e),l++}var f=o===l;if(r=r||f,!r){const e=l;if("string"!=typeof t){const e={};null===a?a=[e]:a.push(e),l++}if(f=e===l,r=r||f,!r){const e=l;if(!(t instanceof Function)){const e={};null===a?a=[e]:a.push(e),l++}f=e===l,r=r||f}}if(r)l=n,null!==a&&(n?a.length=n:a=null);else{const e={};null===a?a=[e]:a.push(e),l++}}}else{const e={};null===a?a=[e]:a.push(e),l++}if(s===l)return Oe.errors=[{params:{}}],!1;if(l=o,null!==a&&(o?a.length=o:a=null),l===n){if(!e||"object"!=typeof e||Array.isArray(e))return Oe.errors=[{params:{type:"object"}}],!1;for(const t in e){let n=e[t];const o=l,s=l;let p=!1;const f=l;if(!1!==n){const e={params:{}};null===a?a=[e]:a.push(e),l++}var u=f===l;if(p=p||u,!p){const o=l;if(!(n instanceof RegExp)){const e={params:{}};null===a?a=[e]:a.push(e),l++}if(u=o===l,p=p||u,!p){const o=l;if("string"!=typeof n){const e={params:{type:"string"}};null===a?a=[e]:a.push(e),l++}if(u=o===l,p=p||u,!p){const o=l;if(!(n instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}if(u=o===l,p=p||u,!p){const o=l;De(n,{instancePath:r+"/cacheGroups/"+t.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:t,rootData:i})||(a=null===a?De.errors:a.concat(De.errors),l=a.length),u=o===l,p=p||u}}}}if(!p){const e={params:{}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}if(l=s,null!==a&&(s?a.length=s:a=null),o!==l)break}}p=n===l}else p=!0;if(p){if(void 0!==t.chunks){let e=t.chunks;const n=l,r=l;let o=!1;const s=l;if("initial"!==e&&"async"!==e&&"all"!==e){const e={params:{}};null===a?a=[e]:a.push(e),l++}var c=s===l;if(o=o||c,!o){const t=l;if(!(e instanceof RegExp)){const e={params:{}};null===a?a=[e]:a.push(e),l++}if(c=t===l,o=o||c,!o){const t=l;if(!(e instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}c=t===l,o=o||c}}if(!o){const e={params:{}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.defaultSizeTypes){let e=t.defaultSizeTypes;const n=l;if(l===n){if(!Array.isArray(e))return Oe.errors=[{params:{type:"array"}}],!1;if(e.length<1)return Oe.errors=[{params:{limit:1}}],!1;{const t=e.length;for(let n=0;n=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var y=c===l;if(u=u||y,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}y=t===l,u=u||y}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.fallbackCacheGroup){let e=t.fallbackCacheGroup;const n=l;if(l===n){if(!e||"object"!=typeof e||Array.isArray(e))return Oe.errors=[{params:{type:"object"}}],!1;{const t=l;for(const t in e)if("automaticNameDelimiter"!==t&&"chunks"!==t&&"maxAsyncSize"!==t&&"maxInitialSize"!==t&&"maxSize"!==t&&"minSize"!==t&&"minSizeReduction"!==t)return Oe.errors=[{params:{additionalProperty:t}}],!1;if(t===l){if(void 0!==e.automaticNameDelimiter){let t=e.automaticNameDelimiter;const n=l;if(l===n){if("string"!=typeof t)return Oe.errors=[{params:{type:"string"}}],!1;if(t.length<1)return Oe.errors=[{params:{}}],!1}var m=n===l}else m=!0;if(m){if(void 0!==e.chunks){let t=e.chunks;const n=l,r=l;let o=!1;const s=l;if("initial"!==t&&"async"!==t&&"all"!==t){const e={params:{}};null===a?a=[e]:a.push(e),l++}var d=s===l;if(o=o||d,!o){const e=l;if(!(t instanceof RegExp)){const e={params:{}};null===a?a=[e]:a.push(e),l++}if(d=e===l,o=o||d,!o){const e=l;if(!(t instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}d=e===l,o=o||d}}if(!o){const e={params:{}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),m=n===l}else m=!0;if(m){if(void 0!==e.maxAsyncSize){let t=e.maxAsyncSize;const n=l,r=l;let o=!1,s=null;const i=l,p=l;let f=!1;const u=l;if(l===u)if("number"==typeof t){if(t<0||isNaN(t)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var h=u===l;if(f=f||h,!f){const e=l;if(l===e)if(t&&"object"==typeof t&&!Array.isArray(t))for(const e in t){const n=l;if("number"!=typeof t[e]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}h=e===l,f=f||h}if(f)l=p,null!==a&&(p?a.length=p:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),m=n===l}else m=!0;if(m){if(void 0!==e.maxInitialSize){let t=e.maxInitialSize;const n=l,r=l;let o=!1,s=null;const i=l,p=l;let f=!1;const u=l;if(l===u)if("number"==typeof t){if(t<0||isNaN(t)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var b=u===l;if(f=f||b,!f){const e=l;if(l===e)if(t&&"object"==typeof t&&!Array.isArray(t))for(const e in t){const n=l;if("number"!=typeof t[e]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}b=e===l,f=f||b}if(f)l=p,null!==a&&(p?a.length=p:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),m=n===l}else m=!0;if(m){if(void 0!==e.maxSize){let t=e.maxSize;const n=l,r=l;let o=!1,s=null;const i=l,p=l;let f=!1;const u=l;if(l===u)if("number"==typeof t){if(t<0||isNaN(t)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var g=u===l;if(f=f||g,!f){const e=l;if(l===e)if(t&&"object"==typeof t&&!Array.isArray(t))for(const e in t){const n=l;if("number"!=typeof t[e]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}g=e===l,f=f||g}if(f)l=p,null!==a&&(p?a.length=p:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),m=n===l}else m=!0;if(m){if(void 0!==e.minSize){let t=e.minSize;const n=l,r=l;let o=!1,s=null;const i=l,p=l;let f=!1;const u=l;if(l===u)if("number"==typeof t){if(t<0||isNaN(t)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var v=u===l;if(f=f||v,!f){const e=l;if(l===e)if(t&&"object"==typeof t&&!Array.isArray(t))for(const e in t){const n=l;if("number"!=typeof t[e]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}v=e===l,f=f||v}if(f)l=p,null!==a&&(p?a.length=p:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),m=n===l}else m=!0;if(m)if(void 0!==e.minSizeReduction){let t=e.minSizeReduction;const n=l,r=l;let o=!1,s=null;const i=l,p=l;let f=!1;const u=l;if(l===u)if("number"==typeof t){if(t<0||isNaN(t)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var P=u===l;if(f=f||P,!f){const e=l;if(l===e)if(t&&"object"==typeof t&&!Array.isArray(t))for(const e in t){const n=l;if("number"!=typeof t[e]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}P=e===l,f=f||P}if(f)l=p,null!==a&&(p?a.length=p:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),m=n===l}else m=!0}}}}}}}}p=n===l}else p=!0;if(p){if(void 0!==t.filename){let n=t.filename;const r=l,o=l;let s=!1;const i=l;if(l===i)if("string"==typeof n){if(n.includes("!")||!1!==e.test(n)){const e={params:{}};null===a?a=[e]:a.push(e),l++}else if(n.length<1){const e={params:{}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"string"}};null===a?a=[e]:a.push(e),l++}var D=i===l;if(s=s||D,!s){const e=l;if(!(n instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}D=e===l,s=s||D}if(!s){const e={params:{}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=o,null!==a&&(o?a.length=o:a=null),p=r===l}else p=!0;if(p){if(void 0!==t.hidePathInfo){const e=l;if("boolean"!=typeof t.hidePathInfo)return Oe.errors=[{params:{type:"boolean"}}],!1;p=e===l}else p=!0;if(p){if(void 0!==t.maxAsyncRequests){let e=t.maxAsyncRequests;const n=l;if(l===n){if("number"!=typeof e)return Oe.errors=[{params:{type:"number"}}],!1;if(e<1||isNaN(e))return Oe.errors=[{params:{comparison:">=",limit:1}}],!1}p=n===l}else p=!0;if(p){if(void 0!==t.maxAsyncSize){let e=t.maxAsyncSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var O=c===l;if(u=u||O,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}O=t===l,u=u||O}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.maxInitialRequests){let e=t.maxInitialRequests;const n=l;if(l===n){if("number"!=typeof e)return Oe.errors=[{params:{type:"number"}}],!1;if(e<1||isNaN(e))return Oe.errors=[{params:{comparison:">=",limit:1}}],!1}p=n===l}else p=!0;if(p){if(void 0!==t.maxInitialSize){let e=t.maxInitialSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var C=c===l;if(u=u||C,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}C=t===l,u=u||C}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.maxSize){let e=t.maxSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var x=c===l;if(u=u||x,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}x=t===l,u=u||x}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.minChunks){let e=t.minChunks;const n=l;if(l===n){if("number"!=typeof e)return Oe.errors=[{params:{type:"number"}}],!1;if(e<1||isNaN(e))return Oe.errors=[{params:{comparison:">=",limit:1}}],!1}p=n===l}else p=!0;if(p){if(void 0!==t.minRemainingSize){let e=t.minRemainingSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var $=c===l;if(u=u||$,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}$=t===l,u=u||$}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.minSize){let e=t.minSize;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var A=c===l;if(u=u||A,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}A=t===l,u=u||A}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.minSizeReduction){let e=t.minSizeReduction;const n=l,r=l;let o=!1,s=null;const i=l,f=l;let u=!1;const c=l;if(l===c)if("number"==typeof e){if(e<0||isNaN(e)){const e={params:{comparison:">=",limit:0}};null===a?a=[e]:a.push(e),l++}}else{const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}var k=c===l;if(u=u||k,!u){const t=l;if(l===t)if(e&&"object"==typeof e&&!Array.isArray(e))for(const t in e){const n=l;if("number"!=typeof e[t]){const e={params:{type:"number"}};null===a?a=[e]:a.push(e),l++}if(n!==l)break}else{const e={params:{type:"object"}};null===a?a=[e]:a.push(e),l++}k=t===l,u=u||k}if(u)l=f,null!==a&&(f?a.length=f:a=null);else{const e={params:{}};null===a?a=[e]:a.push(e),l++}if(i===l&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p){if(void 0!==t.name){let e=t.name;const n=l,r=l;let o=!1;const s=l;if(!1!==e){const e={params:{}};null===a?a=[e]:a.push(e),l++}var j=s===l;if(o=o||j,!o){const t=l;if("string"!=typeof e){const e={params:{type:"string"}};null===a?a=[e]:a.push(e),l++}if(j=t===l,o=o||j,!o){const t=l;if(!(e instanceof Function)){const e={params:{}};null===a?a=[e]:a.push(e),l++}j=t===l,o=o||j}}if(!o){const e={params:{}};return null===a?a=[e]:a.push(e),l++,Oe.errors=a,!1}l=r,null!==a&&(r?a.length=r:a=null),p=n===l}else p=!0;if(p)if(void 0!==t.usedExports){const e=l;if("boolean"!=typeof t.usedExports)return Oe.errors=[{params:{type:"boolean"}}],!1;p=e===l}else p=!0}}}}}}}}}}}}}}}}}}}}return Oe.errors=a,0===l}function Ce(e,{instancePath:t="",parentData:r,parentDataProperty:o,rootData:s=e}={}){let i=null,a=0;if(0===a){if(!e||"object"!=typeof e||Array.isArray(e))return Ce.errors=[{params:{type:"object"}}],!1;{const r=a;for(const t in e)if(!n.call(ge.properties,t))return Ce.errors=[{params:{additionalProperty:t}}],!1;if(r===a){if(void 0!==e.avoidEntryIife){const t=a;if("boolean"!=typeof e.avoidEntryIife)return Ce.errors=[{params:{type:"boolean"}}],!1;var l=t===a}else l=!0;if(l){if(void 0!==e.checkWasmTypes){const t=a;if("boolean"!=typeof e.checkWasmTypes)return Ce.errors=[{params:{type:"boolean"}}],!1;l=t===a}else l=!0;if(l){if(void 0!==e.chunkIds){let t=e.chunkIds;const n=a;if("natural"!==t&&"named"!==t&&"deterministic"!==t&&"size"!==t&&"total-size"!==t&&!1!==t)return Ce.errors=[{params:{}}],!1;l=n===a}else l=!0;if(l){if(void 0!==e.concatenateModules){const t=a;if("boolean"!=typeof e.concatenateModules)return Ce.errors=[{params:{type:"boolean"}}],!1;l=t===a}else l=!0;if(l){if(void 0!==e.emitOnErrors){const t=a;if("boolean"!=typeof e.emitOnErrors)return Ce.errors=[{params:{type:"boolean"}}],!1;l=t===a}else l=!0;if(l){if(void 0!==e.flagIncludedChunks){const t=a;if("boolean"!=typeof e.flagIncludedChunks)return Ce.errors=[{params:{type:"boolean"}}],!1;l=t===a}else l=!0;if(l){if(void 0!==e.innerGraph){const t=a;if("boolean"!=typeof e.innerGraph)return Ce.errors=[{params:{type:"boolean"}}],!1;l=t===a}else l=!0;if(l){if(void 0!==e.mangleExports){let t=e.mangleExports;const n=a,r=a;let o=!1;const s=a;if("size"!==t&&"deterministic"!==t){const e={params:{}};null===i?i=[e]:i.push(e),a++}var p=s===a;if(o=o||p,!o){const e=a;if("boolean"!=typeof t){const e={params:{type:"boolean"}};null===i?i=[e]:i.push(e),a++}p=e===a,o=o||p}if(!o){const e={params:{}};return null===i?i=[e]:i.push(e),a++,Ce.errors=i,!1}a=r,null!==i&&(r?i.length=r:i=null),l=n===a}else l=!0;if(l){if(void 0!==e.mangleWasmImports){const t=a;if("boolean"!=typeof e.mangleWasmImports)return Ce.errors=[{params:{type:"boolean"}}],!1;l=t===a}else l=!0;if(l){if(void 0!==e.mergeDuplicateChunks){const t=a;if("boolean"!=typeof e.mergeDuplicateChunks)return Ce.errors=[{params:{type:"boolean"}}],!1;l=t===a}else l=!0;if(l){if(void 0!==e.minimize){const t=a;if("boolean"!=typeof e.minimize)return Ce.errors=[{params:{type:"boolean"}}],!1;l=t===a}else l=!0;if(l){if(void 0!==e.minimizer){let t=e.minimizer;const n=a;if(a===n){if(!Array.isArray(t))return Ce.errors=[{params:{type:"array"}}],!1;{const e=t.length;for(let n=0;n=",limit:1}}],!1}u=n===f}else u=!0;if(u){if(void 0!==t.hashFunction){let e=t.hashFunction;const n=f,r=f;let o=!1;const s=f;if(f===s)if("string"==typeof e){if(e.length<1){const e={params:{}};null===l?l=[e]:l.push(e),f++}}else{const e={params:{type:"string"}};null===l?l=[e]:l.push(e),f++}var v=s===f;if(o=o||v,!o){const t=f;if(!(e instanceof Function)){const e={params:{}};null===l?l=[e]:l.push(e),f++}v=t===f,o=o||v}if(!o){const e={params:{}};return null===l?l=[e]:l.push(e),f++,Me.errors=l,!1}f=r,null!==l&&(r?l.length=r:l=null),u=n===f}else u=!0;if(u){if(void 0!==t.hashSalt){let e=t.hashSalt;const n=f;if(f==f){if("string"!=typeof e)return Me.errors=[{params:{type:"string"}}],!1;if(e.length<1)return Me.errors=[{params:{}}],!1}u=n===f}else u=!0;if(u){if(void 0!==t.hotUpdateChunkFilename){let n=t.hotUpdateChunkFilename;const r=f;if(f==f){if("string"!=typeof n)return Me.errors=[{params:{type:"string"}}],!1;if(n.includes("!")||!1!==e.test(n))return Me.errors=[{params:{}}],!1}u=r===f}else u=!0;if(u){if(void 0!==t.hotUpdateGlobal){const e=f;if("string"!=typeof t.hotUpdateGlobal)return Me.errors=[{params:{type:"string"}}],!1;u=e===f}else u=!0;if(u){if(void 0!==t.hotUpdateMainFilename){let n=t.hotUpdateMainFilename;const r=f;if(f==f){if("string"!=typeof n)return Me.errors=[{params:{type:"string"}}],!1;if(n.includes("!")||!1!==e.test(n))return Me.errors=[{params:{}}],!1}u=r===f}else u=!0;if(u){if(void 0!==t.ignoreBrowserWarnings){const e=f;if("boolean"!=typeof t.ignoreBrowserWarnings)return Me.errors=[{params:{type:"boolean"}}],!1;u=e===f}else u=!0;if(u){if(void 0!==t.iife){const e=f;if("boolean"!=typeof t.iife)return Me.errors=[{params:{type:"boolean"}}],!1;u=e===f}else u=!0;if(u){if(void 0!==t.importFunctionName){const e=f;if("string"!=typeof t.importFunctionName)return Me.errors=[{params:{type:"string"}}],!1;u=e===f}else u=!0;if(u){if(void 0!==t.importMetaName){const e=f;if("string"!=typeof t.importMetaName)return Me.errors=[{params:{type:"string"}}],!1;u=e===f}else u=!0;if(u){if(void 0!==t.library){const e=f;ze(t.library,{instancePath:r+"/library",parentData:t,parentDataProperty:"library",rootData:i})||(l=null===l?ze.errors:l.concat(ze.errors),f=l.length),u=e===f}else u=!0;if(u){if(void 0!==t.libraryExport){let e=t.libraryExport;const n=f,r=f;let o=!1,s=null;const i=f,a=f;let p=!1;const c=f;if(f===c)if(Array.isArray(e)){const t=e.length;for(let n=0;n=",limit:1}}],!1}c=t===f}else c=!0;if(c){if(void 0!==r.performance){const e=f;we(r.performance,{instancePath:o+"/performance",parentData:r,parentDataProperty:"performance",rootData:l})||(p=null===p?we.errors:p.concat(we.errors),f=p.length),c=e===f}else c=!0;if(c){if(void 0!==r.plugins){const e=f;Ie(r.plugins,{instancePath:o+"/plugins",parentData:r,parentDataProperty:"plugins",rootData:l})||(p=null===p?Ie.errors:p.concat(Ie.errors),f=p.length),c=e===f}else c=!0;if(c){if(void 0!==r.profile){const e=f;if("boolean"!=typeof r.profile)return _e.errors=[{params:{type:"boolean"}}],!1;c=e===f}else c=!0;if(c){if(void 0!==r.recordsInputPath){let t=r.recordsInputPath;const n=f,o=f;let s=!1;const i=f;if(!1!==t){const e={params:{}};null===p?p=[e]:p.push(e),f++}var v=i===f;if(s=s||v,!s){const n=f;if(f===n)if("string"==typeof t){if(t.includes("!")||!0!==e.test(t)){const e={params:{}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"string"}};null===p?p=[e]:p.push(e),f++}v=n===f,s=s||v}if(!s){const e={params:{}};return null===p?p=[e]:p.push(e),f++,_e.errors=p,!1}f=o,null!==p&&(o?p.length=o:p=null),c=n===f}else c=!0;if(c){if(void 0!==r.recordsOutputPath){let t=r.recordsOutputPath;const n=f,o=f;let s=!1;const i=f;if(!1!==t){const e={params:{}};null===p?p=[e]:p.push(e),f++}var P=i===f;if(s=s||P,!s){const n=f;if(f===n)if("string"==typeof t){if(t.includes("!")||!0!==e.test(t)){const e={params:{}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"string"}};null===p?p=[e]:p.push(e),f++}P=n===f,s=s||P}if(!s){const e={params:{}};return null===p?p=[e]:p.push(e),f++,_e.errors=p,!1}f=o,null!==p&&(o?p.length=o:p=null),c=n===f}else c=!0;if(c){if(void 0!==r.recordsPath){let t=r.recordsPath;const n=f,o=f;let s=!1;const i=f;if(!1!==t){const e={params:{}};null===p?p=[e]:p.push(e),f++}var D=i===f;if(s=s||D,!s){const n=f;if(f===n)if("string"==typeof t){if(t.includes("!")||!0!==e.test(t)){const e={params:{}};null===p?p=[e]:p.push(e),f++}}else{const e={params:{type:"string"}};null===p?p=[e]:p.push(e),f++}D=n===f,s=s||D}if(!s){const e={params:{}};return null===p?p=[e]:p.push(e),f++,_e.errors=p,!1}f=o,null!==p&&(o?p.length=o:p=null),c=n===f}else c=!0;if(c){if(void 0!==r.resolve){const e=f;Te(r.resolve,{instancePath:o+"/resolve",parentData:r,parentDataProperty:"resolve",rootData:l})||(p=null===p?Te.errors:p.concat(Te.errors),f=p.length),c=e===f}else c=!0;if(c){if(void 0!==r.resolveLoader){const e=f;Ne(r.resolveLoader,{instancePath:o+"/resolveLoader",parentData:r,parentDataProperty:"resolveLoader",rootData:l})||(p=null===p?Ne.errors:p.concat(Ne.errors),f=p.length),c=e===f}else c=!0;if(c){if(void 0!==r.snapshot){let t=r.snapshot;const n=f;if(f==f){if(!t||"object"!=typeof t||Array.isArray(t))return _e.errors=[{params:{type:"object"}}],!1;{const n=f;for(const e in t)if("buildDependencies"!==e&&"immutablePaths"!==e&&"managedPaths"!==e&&"module"!==e&&"resolve"!==e&&"resolveBuildDependencies"!==e&&"unmanagedPaths"!==e)return _e.errors=[{params:{additionalProperty:e}}],!1;if(n===f){if(void 0!==t.buildDependencies){let e=t.buildDependencies;const n=f;if(f===n){if(!e||"object"!=typeof e||Array.isArray(e))return _e.errors=[{params:{type:"object"}}],!1;{const t=f;for(const t in e)if("hash"!==t&&"timestamp"!==t)return _e.errors=[{params:{additionalProperty:t}}],!1;if(t===f){if(void 0!==e.hash){const t=f;if("boolean"!=typeof e.hash)return _e.errors=[{params:{type:"boolean"}}],!1;var O=t===f}else O=!0;if(O)if(void 0!==e.timestamp){const t=f;if("boolean"!=typeof e.timestamp)return _e.errors=[{params:{type:"boolean"}}],!1;O=t===f}else O=!0}}}var C=n===f}else C=!0;if(C){if(void 0!==t.immutablePaths){let n=t.immutablePaths;const r=f;if(f===r){if(!Array.isArray(n))return _e.errors=[{params:{type:"array"}}],!1;{const t=n.length;for(let r=0;r boolean)" + } + ] + }, + "AssetFilterTypes": { + "description": "Filtering modules.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "type": "array", + "items": { + "description": "Rule to filter.", + "cli": { + "helper": true + }, + "oneOf": [ + { + "$ref": "#/definitions/AssetFilterItemTypes" + } + ] + } + }, + { + "$ref": "#/definitions/AssetFilterItemTypes" + } + ] + }, + "AssetGeneratorDataUrl": { + "description": "The options for data url generator.", + "anyOf": [ + { + "$ref": "#/definitions/AssetGeneratorDataUrlOptions" + }, + { + "$ref": "#/definitions/AssetGeneratorDataUrlFunction" + } + ] + }, + "AssetGeneratorDataUrlFunction": { + "description": "Function that executes for module and should return an DataUrl string. It can have a string as 'ident' property which contributes to the module hash.", + "instanceof": "Function", + "tsType": "((source: string | Buffer, context: { filename: string, module: import('../lib/Module') }) => string)" + }, + "AssetGeneratorDataUrlOptions": { + "description": "Options object for data url generation.", + "type": "object", + "additionalProperties": false, + "properties": { + "encoding": { + "description": "Asset encoding (defaults to base64).", + "enum": [false, "base64"] + }, + "mimetype": { + "description": "Asset mimetype (getting from file extension by default).", + "type": "string" + } + } + }, + "AssetGeneratorOptions": { + "description": "Generator options for asset modules.", + "type": "object", + "implements": [ + "#/definitions/AssetInlineGeneratorOptions", + "#/definitions/AssetResourceGeneratorOptions" + ], + "additionalProperties": false, + "properties": { + "binary": { + "description": "Whether or not this asset module should be considered binary. This can be set to 'false' to treat this asset module as text.", + "type": "boolean" + }, + "dataUrl": { + "$ref": "#/definitions/AssetGeneratorDataUrl" + }, + "emit": { + "description": "Emit an output asset from this asset module. This can be set to 'false' to omit emitting e. g. for SSR.", + "type": "boolean" + }, + "filename": { + "$ref": "#/definitions/FilenameTemplate" + }, + "outputPath": { + "$ref": "#/definitions/AssetModuleOutputPath" + }, + "publicPath": { + "$ref": "#/definitions/RawPublicPath" + } + } + }, + "AssetInlineGeneratorOptions": { + "description": "Generator options for asset/inline modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "binary": { + "description": "Whether or not this asset module should be considered binary. This can be set to 'false' to treat this asset module as text.", + "type": "boolean" + }, + "dataUrl": { + "$ref": "#/definitions/AssetGeneratorDataUrl" + } + } + }, + "AssetModuleFilename": { + "description": "The filename of asset modules as relative path inside the 'output.path' directory.", + "anyOf": [ + { + "type": "string", + "absolutePath": false + }, + { + "instanceof": "Function", + "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + } + ] + }, + "AssetModuleOutputPath": { + "description": "Emit the asset in the specified folder relative to 'output.path'. This should only be needed when custom 'publicPath' is specified to match the folder structure there.", + "anyOf": [ + { + "type": "string", + "absolutePath": false + }, + { + "instanceof": "Function", + "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + } + ] + }, + "AssetParserDataUrlFunction": { + "description": "Function that executes for module and should return whenever asset should be inlined as DataUrl.", + "instanceof": "Function", + "tsType": "((source: string | Buffer, context: { filename: string, module: import('../lib/Module') }) => boolean)" + }, + "AssetParserDataUrlOptions": { + "description": "Options object for DataUrl condition.", + "type": "object", + "additionalProperties": false, + "properties": { + "maxSize": { + "description": "Maximum size of asset that should be inline as modules. Default: 8kb.", + "type": "number" + } + } + }, + "AssetParserOptions": { + "description": "Parser options for asset modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "dataUrlCondition": { + "description": "The condition for inlining the asset as DataUrl.", + "anyOf": [ + { + "$ref": "#/definitions/AssetParserDataUrlOptions" + }, + { + "$ref": "#/definitions/AssetParserDataUrlFunction" + } + ] + } + } + }, + "AssetResourceGeneratorOptions": { + "description": "Generator options for asset/resource modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "binary": { + "description": "Whether or not this asset module should be considered binary. This can be set to 'false' to treat this asset module as text.", + "type": "boolean" + }, + "emit": { + "description": "Emit an output asset from this asset module. This can be set to 'false' to omit emitting e. g. for SSR.", + "type": "boolean" + }, + "filename": { + "$ref": "#/definitions/FilenameTemplate" + }, + "outputPath": { + "$ref": "#/definitions/AssetModuleOutputPath" + }, + "publicPath": { + "$ref": "#/definitions/RawPublicPath" + } + } + }, + "AuxiliaryComment": { + "description": "Add a comment in the UMD wrapper.", + "anyOf": [ + { + "description": "Append the same comment above each import style.", + "type": "string" + }, + { + "$ref": "#/definitions/LibraryCustomUmdCommentObject" + } + ] + }, + "Bail": { + "description": "Report the first error as a hard error instead of tolerating it.", + "type": "boolean" + }, + "CacheOptions": { + "description": "Cache generated modules and chunks to improve performance for multiple incremental builds.", + "anyOf": [ + { + "description": "Enable in memory caching.", + "enum": [true] + }, + { + "$ref": "#/definitions/CacheOptionsNormalized" + } + ] + }, + "CacheOptionsNormalized": { + "description": "Cache generated modules and chunks to improve performance for multiple incremental builds.", + "anyOf": [ + { + "description": "Disable caching.", + "enum": [false] + }, + { + "$ref": "#/definitions/MemoryCacheOptions" + }, + { + "$ref": "#/definitions/FileCacheOptions" + } + ] + }, + "Charset": { + "description": "Add charset attribute for script tag.", + "type": "boolean" + }, + "ChunkFilename": { + "description": "Specifies the filename template of output files of non-initial chunks on disk. You must **not** specify an absolute path here, but the path may contain folders separated by '/'! The specified path is joined with the value of the 'output.path' option to determine the location on disk.", + "oneOf": [ + { + "$ref": "#/definitions/FilenameTemplate" + } + ] + }, + "ChunkFormat": { + "description": "The format of chunks (formats included by default are 'array-push' (web/WebWorker), 'commonjs' (node.js), 'module' (ESM), but others might be added by plugins).", + "anyOf": [ + { + "enum": ["array-push", "commonjs", "module", false] + }, + { + "type": "string" + } + ] + }, + "ChunkLoadTimeout": { + "description": "Number of milliseconds before chunk request expires.", + "type": "number" + }, + "ChunkLoading": { + "description": "The method of loading chunks (methods included by default are 'jsonp' (web), 'import' (ESM), 'importScripts' (WebWorker), 'require' (sync node.js), 'async-node' (async node.js), but others might be added by plugins).", + "anyOf": [ + { + "enum": [false] + }, + { + "$ref": "#/definitions/ChunkLoadingType" + } + ] + }, + "ChunkLoadingGlobal": { + "description": "The global variable used by webpack for loading of chunks.", + "type": "string" + }, + "ChunkLoadingType": { + "description": "The method of loading chunks (methods included by default are 'jsonp' (web), 'import' (ESM), 'importScripts' (WebWorker), 'require' (sync node.js), 'async-node' (async node.js), but others might be added by plugins).", + "anyOf": [ + { + "enum": ["jsonp", "import-scripts", "require", "async-node", "import"] + }, + { + "type": "string" + } + ] + }, + "Clean": { + "description": "Clean the output directory before emit.", + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "#/definitions/CleanOptions" + } + ] + }, + "CleanOptions": { + "description": "Advanced options for cleaning assets.", + "type": "object", + "additionalProperties": false, + "properties": { + "dry": { + "description": "Log the assets that should be removed instead of deleting them.", + "type": "boolean" + }, + "keep": { + "description": "Keep these assets.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string", + "absolutePath": false + }, + { + "instanceof": "Function", + "tsType": "((filename: string) => boolean)" + } + ] + } + } + }, + "CompareBeforeEmit": { + "description": "Check if to be emitted file already exists and have the same content before writing to output filesystem.", + "type": "boolean" + }, + "Context": { + "description": "The base directory (absolute path!) for resolving the `entry` option. If `output.pathinfo` is set, the included pathinfo is shortened to this directory.", + "type": "string", + "absolutePath": true + }, + "CrossOriginLoading": { + "description": "This option enables cross-origin loading of chunks.", + "enum": [false, "anonymous", "use-credentials"] + }, + "CssAutoGeneratorOptions": { + "description": "Generator options for css/auto modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "esModule": { + "$ref": "#/definitions/CssGeneratorEsModule" + }, + "exportsConvention": { + "$ref": "#/definitions/CssGeneratorExportsConvention" + }, + "exportsOnly": { + "$ref": "#/definitions/CssGeneratorExportsOnly" + }, + "localIdentName": { + "$ref": "#/definitions/CssGeneratorLocalIdentName" + } + } + }, + "CssAutoParserOptions": { + "description": "Parser options for css/auto modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "import": { + "$ref": "#/definitions/CssParserImport" + }, + "namedExports": { + "$ref": "#/definitions/CssParserNamedExports" + }, + "url": { + "$ref": "#/definitions/CssParserUrl" + } + } + }, + "CssChunkFilename": { + "description": "Specifies the filename template of non-initial output css files on disk. You must **not** specify an absolute path here, but the path may contain folders separated by '/'! The specified path is joined with the value of the 'output.path' option to determine the location on disk.", + "oneOf": [ + { + "$ref": "#/definitions/FilenameTemplate" + } + ] + }, + "CssFilename": { + "description": "Specifies the filename template of output css files on disk. You must **not** specify an absolute path here, but the path may contain folders separated by '/'! The specified path is joined with the value of the 'output.path' option to determine the location on disk.", + "oneOf": [ + { + "$ref": "#/definitions/FilenameTemplate" + } + ] + }, + "CssGeneratorEsModule": { + "description": "Configure the generated JS modules that use the ES modules syntax.", + "type": "boolean" + }, + "CssGeneratorExportsConvention": { + "description": "Specifies the convention of exported names.", + "anyOf": [ + { + "enum": [ + "as-is", + "camel-case", + "camel-case-only", + "dashes", + "dashes-only" + ] + }, + { + "instanceof": "Function", + "tsType": "((name: string) => string)" + } + ] + }, + "CssGeneratorExportsOnly": { + "description": "Avoid generating and loading a stylesheet and only embed exports from css into output javascript files.", + "type": "boolean" + }, + "CssGeneratorLocalIdentName": { + "description": "Configure the generated local ident name.", + "type": "string" + }, + "CssGeneratorOptions": { + "description": "Generator options for css modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "esModule": { + "$ref": "#/definitions/CssGeneratorEsModule" + }, + "exportsOnly": { + "$ref": "#/definitions/CssGeneratorExportsOnly" + } + } + }, + "CssGlobalGeneratorOptions": { + "description": "Generator options for css/global modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "esModule": { + "$ref": "#/definitions/CssGeneratorEsModule" + }, + "exportsConvention": { + "$ref": "#/definitions/CssGeneratorExportsConvention" + }, + "exportsOnly": { + "$ref": "#/definitions/CssGeneratorExportsOnly" + }, + "localIdentName": { + "$ref": "#/definitions/CssGeneratorLocalIdentName" + } + } + }, + "CssGlobalParserOptions": { + "description": "Parser options for css/global modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "import": { + "$ref": "#/definitions/CssParserImport" + }, + "namedExports": { + "$ref": "#/definitions/CssParserNamedExports" + }, + "url": { + "$ref": "#/definitions/CssParserUrl" + } + } + }, + "CssModuleGeneratorOptions": { + "description": "Generator options for css/module modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "esModule": { + "$ref": "#/definitions/CssGeneratorEsModule" + }, + "exportsConvention": { + "$ref": "#/definitions/CssGeneratorExportsConvention" + }, + "exportsOnly": { + "$ref": "#/definitions/CssGeneratorExportsOnly" + }, + "localIdentName": { + "$ref": "#/definitions/CssGeneratorLocalIdentName" + } + } + }, + "CssModuleParserOptions": { + "description": "Parser options for css/module modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "import": { + "$ref": "#/definitions/CssParserImport" + }, + "namedExports": { + "$ref": "#/definitions/CssParserNamedExports" + }, + "url": { + "$ref": "#/definitions/CssParserUrl" + } + } + }, + "CssParserImport": { + "description": "Enable/disable `@import` at-rules handling.", + "type": "boolean" + }, + "CssParserNamedExports": { + "description": "Use ES modules named export for css exports.", + "type": "boolean" + }, + "CssParserOptions": { + "description": "Parser options for css modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "import": { + "$ref": "#/definitions/CssParserImport" + }, + "namedExports": { + "$ref": "#/definitions/CssParserNamedExports" + }, + "url": { + "$ref": "#/definitions/CssParserUrl" + } + } + }, + "CssParserUrl": { + "description": "Enable/disable `url()`/`image-set()`/`src()`/`image()` functions handling.", + "type": "boolean" + }, + "DeferImportExperimentOptions": { + "description": "Options for defer import.", + "type": "boolean", + "required": ["asyncModule"] + }, + "Dependencies": { + "description": "References to other configurations to depend on.", + "type": "array", + "items": { + "description": "References to another configuration to depend on.", + "type": "string" + } + }, + "DevServer": { + "description": "Options for the webpack-dev-server.", + "anyOf": [ + { + "description": "Disable dev server.", + "enum": [false] + }, + { + "description": "Options for the webpack-dev-server.", + "type": "object" + } + ] + }, + "DevTool": { + "description": "A developer tool to enhance debugging (false | eval | [inline-|hidden-|eval-][nosources-][cheap-[module-]]source-map).", + "anyOf": [ + { + "enum": [false, "eval"] + }, + { + "type": "string", + "pattern": "^(inline-|hidden-|eval-)?(nosources-)?(cheap-(module-)?)?source-map(-debugids)?$" + } + ] + }, + "DevtoolFallbackModuleFilenameTemplate": { + "description": "Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers.", + "anyOf": [ + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "((context: TODO) => string)" + } + ] + }, + "DevtoolModuleFilenameTemplate": { + "description": "Filename template string of function for the sources array in a generated SourceMap.", + "anyOf": [ + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "import('../lib/ModuleFilenameHelpers').ModuleFilenameTemplateFunction" + } + ] + }, + "DevtoolNamespace": { + "description": "Module namespace to use when interpolating filename template string for the sources array in a generated SourceMap. Defaults to `output.library` if not set. It's useful for avoiding runtime collisions in sourcemaps from multiple webpack projects built as libraries.", + "type": "string" + }, + "EmptyGeneratorOptions": { + "description": "No generator options are supported for this module type.", + "type": "object", + "additionalProperties": false + }, + "EmptyParserOptions": { + "description": "No parser options are supported for this module type.", + "type": "object", + "additionalProperties": false + }, + "EnabledChunkLoadingTypes": { + "description": "List of chunk loading types enabled for use by entry points.", + "type": "array", + "items": { + "$ref": "#/definitions/ChunkLoadingType" + } + }, + "EnabledLibraryTypes": { + "description": "List of library types enabled for use by entry points.", + "type": "array", + "items": { + "$ref": "#/definitions/LibraryType" + } + }, + "EnabledWasmLoadingTypes": { + "description": "List of wasm loading types enabled for use by entry points.", + "type": "array", + "items": { + "$ref": "#/definitions/WasmLoadingType" + } + }, + "Entry": { + "description": "The entry point(s) of the compilation.", + "anyOf": [ + { + "$ref": "#/definitions/EntryDynamic" + }, + { + "$ref": "#/definitions/EntryStatic" + } + ] + }, + "EntryDescription": { + "description": "An object with entry point description.", + "type": "object", + "additionalProperties": false, + "properties": { + "asyncChunks": { + "description": "Enable/disable creating async chunks that are loaded on demand.", + "type": "boolean" + }, + "baseUri": { + "description": "Base uri for this entry.", + "type": "string" + }, + "chunkLoading": { + "$ref": "#/definitions/ChunkLoading" + }, + "dependOn": { + "description": "The entrypoints that the current entrypoint depend on. They must be loaded when this entrypoint is loaded.", + "anyOf": [ + { + "description": "The entrypoints that the current entrypoint depend on. They must be loaded when this entrypoint is loaded.", + "type": "array", + "items": { + "description": "An entrypoint that the current entrypoint depend on. It must be loaded when this entrypoint is loaded.", + "type": "string", + "minLength": 1 + }, + "minItems": 1, + "uniqueItems": true + }, + { + "description": "An entrypoint that the current entrypoint depend on. It must be loaded when this entrypoint is loaded.", + "type": "string", + "minLength": 1 + } + ] + }, + "filename": { + "$ref": "#/definitions/EntryFilename" + }, + "import": { + "$ref": "#/definitions/EntryItem" + }, + "layer": { + "$ref": "#/definitions/Layer" + }, + "library": { + "$ref": "#/definitions/LibraryOptions" + }, + "publicPath": { + "$ref": "#/definitions/PublicPath" + }, + "runtime": { + "$ref": "#/definitions/EntryRuntime" + }, + "wasmLoading": { + "$ref": "#/definitions/WasmLoading" + } + }, + "required": ["import"] + }, + "EntryDescriptionNormalized": { + "description": "An object with entry point description.", + "type": "object", + "additionalProperties": false, + "properties": { + "asyncChunks": { + "description": "Enable/disable creating async chunks that are loaded on demand.", + "type": "boolean" + }, + "baseUri": { + "description": "Base uri for this entry.", + "type": "string" + }, + "chunkLoading": { + "$ref": "#/definitions/ChunkLoading" + }, + "dependOn": { + "description": "The entrypoints that the current entrypoint depend on. They must be loaded when this entrypoint is loaded.", + "type": "array", + "items": { + "description": "An entrypoint that the current entrypoint depend on. It must be loaded when this entrypoint is loaded.", + "type": "string", + "minLength": 1 + }, + "minItems": 1, + "uniqueItems": true + }, + "filename": { + "$ref": "#/definitions/Filename" + }, + "import": { + "description": "Module(s) that are loaded upon startup. The last one is exported.", + "type": "array", + "items": { + "description": "Module that is loaded upon startup. Only the last one is exported.", + "type": "string", + "minLength": 1 + }, + "minItems": 1, + "uniqueItems": true + }, + "layer": { + "$ref": "#/definitions/Layer" + }, + "library": { + "$ref": "#/definitions/LibraryOptions" + }, + "publicPath": { + "$ref": "#/definitions/PublicPath" + }, + "runtime": { + "$ref": "#/definitions/EntryRuntime" + }, + "wasmLoading": { + "$ref": "#/definitions/WasmLoading" + } + } + }, + "EntryDynamic": { + "description": "A Function returning an entry object, an entry string, an entry array or a promise to these things.", + "instanceof": "Function", + "tsType": "(() => EntryStatic | Promise)" + }, + "EntryDynamicNormalized": { + "description": "A Function returning a Promise resolving to a normalized entry.", + "instanceof": "Function", + "tsType": "(() => Promise)" + }, + "EntryFilename": { + "description": "Specifies the filename of the output file on disk. You must **not** specify an absolute path here, but the path may contain folders separated by '/'! The specified path is joined with the value of the 'output.path' option to determine the location on disk.", + "oneOf": [ + { + "$ref": "#/definitions/FilenameTemplate" + } + ] + }, + "EntryItem": { + "description": "Module(s) that are loaded upon startup.", + "anyOf": [ + { + "description": "All modules are loaded upon startup. The last one is exported.", + "type": "array", + "items": { + "description": "A module that is loaded upon startup. Only the last one is exported.", + "type": "string", + "minLength": 1 + }, + "minItems": 1, + "uniqueItems": true + }, + { + "description": "The string is resolved to a module which is loaded upon startup.", + "type": "string", + "minLength": 1 + } + ] + }, + "EntryNormalized": { + "description": "The entry point(s) of the compilation.", + "anyOf": [ + { + "$ref": "#/definitions/EntryDynamicNormalized" + }, + { + "$ref": "#/definitions/EntryStaticNormalized" + } + ] + }, + "EntryObject": { + "description": "Multiple entry bundles are created. The key is the entry name. The value can be a string, an array or an entry description object.", + "type": "object", + "additionalProperties": { + "description": "An entry point with name.", + "anyOf": [ + { + "$ref": "#/definitions/EntryItem" + }, + { + "$ref": "#/definitions/EntryDescription" + } + ] + } + }, + "EntryRuntime": { + "description": "The name of the runtime chunk. If set a runtime chunk with this name is created or an existing entrypoint is used as runtime.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string", + "minLength": 1 + } + ] + }, + "EntryStatic": { + "description": "A static entry description.", + "anyOf": [ + { + "$ref": "#/definitions/EntryObject" + }, + { + "$ref": "#/definitions/EntryUnnamed" + } + ] + }, + "EntryStaticNormalized": { + "description": "Multiple entry bundles are created. The key is the entry name. The value is an entry description object.", + "type": "object", + "additionalProperties": { + "description": "An object with entry point description.", + "oneOf": [ + { + "$ref": "#/definitions/EntryDescriptionNormalized" + } + ] + } + }, + "EntryUnnamed": { + "description": "An entry point without name.", + "oneOf": [ + { + "$ref": "#/definitions/EntryItem" + } + ] + }, + "Environment": { + "description": "The abilities of the environment where the webpack generated code should run.", + "type": "object", + "additionalProperties": false, + "properties": { + "arrowFunction": { + "description": "The environment supports arrow functions ('() => { ... }').", + "type": "boolean" + }, + "asyncFunction": { + "description": "The environment supports async function and await ('async function () { await ... }').", + "type": "boolean" + }, + "bigIntLiteral": { + "description": "The environment supports BigInt as literal (123n).", + "type": "boolean" + }, + "const": { + "description": "The environment supports const and let for variable declarations.", + "type": "boolean" + }, + "destructuring": { + "description": "The environment supports destructuring ('{ a, b } = obj').", + "type": "boolean" + }, + "document": { + "description": "The environment supports 'document'.", + "type": "boolean" + }, + "dynamicImport": { + "description": "The environment supports an async import() function to import EcmaScript modules.", + "type": "boolean" + }, + "dynamicImportInWorker": { + "description": "The environment supports an async import() is available when creating a worker.", + "type": "boolean" + }, + "forOf": { + "description": "The environment supports 'for of' iteration ('for (const x of array) { ... }').", + "type": "boolean" + }, + "globalThis": { + "description": "The environment supports 'globalThis'.", + "type": "boolean" + }, + "module": { + "description": "The environment supports EcmaScript Module syntax to import EcmaScript modules (import ... from '...').", + "type": "boolean" + }, + "nodePrefixForCoreModules": { + "description": "The environment supports `node:` prefix for Node.js core modules.", + "type": "boolean" + }, + "optionalChaining": { + "description": "The environment supports optional chaining ('obj?.a' or 'obj?.()').", + "type": "boolean" + }, + "templateLiteral": { + "description": "The environment supports template literals.", + "type": "boolean" + } + } + }, + "Experiments": { + "description": "Enables/Disables experiments (experimental features with relax SemVer compatibility).", + "type": "object", + "implements": ["#/definitions/ExperimentsCommon"], + "additionalProperties": false, + "properties": { + "asyncWebAssembly": { + "description": "Support WebAssembly as asynchronous EcmaScript Module.", + "type": "boolean" + }, + "backCompat": { + "description": "Enable backward-compat layer with deprecation warnings for many webpack 4 APIs.", + "type": "boolean" + }, + "buildHttp": { + "description": "Build http(s): urls using a lockfile and resource content cache.", + "anyOf": [ + { + "$ref": "#/definitions/HttpUriAllowedUris" + }, + { + "$ref": "#/definitions/HttpUriOptions" + } + ] + }, + "cacheUnaffected": { + "description": "Enable additional in memory caching of modules that are unchanged and reference only unchanged modules.", + "type": "boolean" + }, + "css": { + "description": "Enable css support.", + "type": "boolean" + }, + "deferImport": { + "description": "Enable experimental tc39 proposal https://github.com/tc39/proposal-defer-import-eval. This allows to defer execution of a module until it's first use.", + "type": "boolean" + }, + "futureDefaults": { + "description": "Apply defaults of next major version.", + "type": "boolean" + }, + "layers": { + "description": "Enable module layers.", + "type": "boolean" + }, + "lazyCompilation": { + "description": "Compile entrypoints and import()s only when they are accessed.", + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "#/definitions/LazyCompilationOptions" + } + ] + }, + "outputModule": { + "description": "Allow output javascript files as module source type.", + "type": "boolean" + }, + "syncWebAssembly": { + "description": "Support WebAssembly as synchronous EcmaScript Module (outdated).", + "type": "boolean" + }, + "topLevelAwait": { + "description": "Allow using top-level-await in EcmaScript Modules.", + "type": "boolean" + } + } + }, + "ExperimentsCommon": { + "description": "Enables/Disables experiments (experimental features with relax SemVer compatibility).", + "type": "object", + "additionalProperties": false, + "properties": { + "asyncWebAssembly": { + "description": "Support WebAssembly as asynchronous EcmaScript Module.", + "type": "boolean" + }, + "backCompat": { + "description": "Enable backward-compat layer with deprecation warnings for many webpack 4 APIs.", + "type": "boolean" + }, + "cacheUnaffected": { + "description": "Enable additional in memory caching of modules that are unchanged and reference only unchanged modules.", + "type": "boolean" + }, + "futureDefaults": { + "description": "Apply defaults of next major version.", + "type": "boolean" + }, + "layers": { + "description": "Enable module layers.", + "type": "boolean" + }, + "outputModule": { + "description": "Allow output javascript files as module source type.", + "type": "boolean" + }, + "syncWebAssembly": { + "description": "Support WebAssembly as synchronous EcmaScript Module (outdated).", + "type": "boolean" + }, + "topLevelAwait": { + "description": "Allow using top-level-await in EcmaScript Modules.", + "type": "boolean" + } + } + }, + "ExperimentsNormalized": { + "description": "Enables/Disables experiments (experimental features with relax SemVer compatibility).", + "type": "object", + "implements": ["#/definitions/ExperimentsCommon"], + "additionalProperties": false, + "properties": { + "asyncWebAssembly": { + "description": "Support WebAssembly as asynchronous EcmaScript Module.", + "type": "boolean" + }, + "backCompat": { + "description": "Enable backward-compat layer with deprecation warnings for many webpack 4 APIs.", + "type": "boolean" + }, + "buildHttp": { + "description": "Build http(s): urls using a lockfile and resource content cache.", + "oneOf": [ + { + "$ref": "#/definitions/HttpUriOptions" + } + ] + }, + "cacheUnaffected": { + "description": "Enable additional in memory caching of modules that are unchanged and reference only unchanged modules.", + "type": "boolean" + }, + "css": { + "description": "Enable css support.", + "type": "boolean" + }, + "deferImport": { + "description": "Enable experimental tc39 proposal https://github.com/tc39/proposal-defer-import-eval. This allows to defer execution of a module until it's first use.", + "type": "boolean" + }, + "futureDefaults": { + "description": "Apply defaults of next major version.", + "type": "boolean" + }, + "layers": { + "description": "Enable module layers.", + "type": "boolean" + }, + "lazyCompilation": { + "description": "Compile entrypoints and import()s only when they are accessed.", + "anyOf": [ + { + "enum": [false] + }, + { + "$ref": "#/definitions/LazyCompilationOptions" + } + ] + }, + "outputModule": { + "description": "Allow output javascript files as module source type.", + "type": "boolean" + }, + "syncWebAssembly": { + "description": "Support WebAssembly as synchronous EcmaScript Module (outdated).", + "type": "boolean" + }, + "topLevelAwait": { + "description": "Allow using top-level-await in EcmaScript Modules.", + "type": "boolean" + } + } + }, + "Extends": { + "description": "Extend configuration from another configuration (only works when using webpack-cli).", + "anyOf": [ + { + "type": "array", + "items": { + "$ref": "#/definitions/ExtendsItem" + } + }, + { + "$ref": "#/definitions/ExtendsItem" + } + ] + }, + "ExtendsItem": { + "description": "Path to the configuration to be extended (only works when using webpack-cli).", + "type": "string" + }, + "ExternalItem": { + "description": "Specify dependency that shouldn't be resolved by webpack, but should become dependencies of the resulting bundle. The kind of the dependency depends on `output.libraryTarget`.", + "anyOf": [ + { + "description": "Every matched dependency becomes external.", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "An exact matched dependency becomes external. The same string is used as external dependency.", + "type": "string" + }, + { + "description": "If an dependency matches exactly a property of the object, the property value is used as dependency.", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/ExternalItemValue" + }, + "properties": { + "byLayer": { + "description": "Specify externals depending on the layer.", + "anyOf": [ + { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/ExternalItem" + } + }, + { + "instanceof": "Function", + "tsType": "((layer: string | null) => ExternalItem)" + } + ] + } + } + }, + { + "$ref": "#/definitions/ExternalItemFunction" + } + ] + }, + "ExternalItemFunction": { + "description": "The function is called on each dependency.", + "anyOf": [ + { + "$ref": "#/definitions/ExternalItemFunctionCallback" + }, + { + "$ref": "#/definitions/ExternalItemFunctionPromise" + } + ] + }, + "ExternalItemFunctionCallback": { + "description": "The function is called on each dependency (`function(context, request, callback(err, result))`).", + "instanceof": "Function", + "tsType": "((data: ExternalItemFunctionData, callback: (err?: (Error | null), result?: ExternalItemValue) => void) => void)" + }, + "ExternalItemFunctionData": { + "description": "Data object passed as argument when a function is set for 'externals'.", + "type": "object", + "additionalProperties": false, + "properties": { + "context": { + "description": "The directory in which the request is placed.", + "type": "string" + }, + "contextInfo": { + "description": "Contextual information.", + "type": "object", + "tsType": "import('../lib/ModuleFactory').ModuleFactoryCreateDataContextInfo" + }, + "dependencyType": { + "description": "The category of the referencing dependencies.", + "type": "string" + }, + "getResolve": { + "$ref": "#/definitions/ExternalItemFunctionDataGetResolve" + }, + "request": { + "description": "The request as written by the user in the require/import expression/statement.", + "type": "string" + } + } + }, + "ExternalItemFunctionDataGetResolve": { + "description": "Get a resolve function with the current resolver options.", + "instanceof": "Function", + "tsType": "((options?: ResolveOptions) => ExternalItemFunctionDataGetResolveCallbackResult | ExternalItemFunctionDataGetResolveResult)" + }, + "ExternalItemFunctionDataGetResolveCallbackResult": { + "description": "Result of get a resolve function with the current resolver options.", + "instanceof": "Function", + "tsType": "((context: string, request: string, callback: (err?: Error | null, result?: string | false, resolveRequest?: import('enhanced-resolve').ResolveRequest) => void) => void)" + }, + "ExternalItemFunctionDataGetResolveResult": { + "description": "Callback result of get a resolve function with the current resolver options.", + "instanceof": "Function", + "tsType": "((context: string, request: string) => Promise)" + }, + "ExternalItemFunctionPromise": { + "description": "The function is called on each dependency (`function(context, request)`).", + "instanceof": "Function", + "tsType": "((data: ExternalItemFunctionData) => Promise)" + }, + "ExternalItemValue": { + "description": "The dependency used for the external.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "A part of the target of the external.", + "type": "string", + "minLength": 1 + } + }, + { + "description": "`true`: The dependency name is used as target of the external.", + "type": "boolean" + }, + { + "description": "The target of the external.", + "type": "string" + }, + { + "type": "object" + } + ] + }, + "Externals": { + "description": "Specify dependencies that shouldn't be resolved by webpack, but should become dependencies of the resulting bundle. The kind of the dependency depends on `output.libraryTarget`.", + "anyOf": [ + { + "type": "array", + "items": { + "$ref": "#/definitions/ExternalItem" + } + }, + { + "$ref": "#/definitions/ExternalItem" + } + ] + }, + "ExternalsPresets": { + "description": "Enable presets of externals for specific targets.", + "type": "object", + "additionalProperties": false, + "properties": { + "electron": { + "description": "Treat common electron built-in modules in main and preload context like 'electron', 'ipc' or 'shell' as external and load them via require() when used.", + "type": "boolean" + }, + "electronMain": { + "description": "Treat electron built-in modules in the main context like 'app', 'ipc-main' or 'shell' as external and load them via require() when used.", + "type": "boolean" + }, + "electronPreload": { + "description": "Treat electron built-in modules in the preload context like 'web-frame', 'ipc-renderer' or 'shell' as external and load them via require() when used.", + "type": "boolean" + }, + "electronRenderer": { + "description": "Treat electron built-in modules in the renderer context like 'web-frame', 'ipc-renderer' or 'shell' as external and load them via require() when used.", + "type": "boolean" + }, + "node": { + "description": "Treat node.js built-in modules like fs, path or vm as external and load them via require() when used.", + "type": "boolean" + }, + "nwjs": { + "description": "Treat NW.js legacy nw.gui module as external and load it via require() when used.", + "type": "boolean" + }, + "web": { + "description": "Treat references to 'http(s)://...' and 'std:...' as external and load them via import when used (Note that this changes execution order as externals are executed before any other code in the chunk).", + "type": "boolean" + }, + "webAsync": { + "description": "Treat references to 'http(s)://...' and 'std:...' as external and load them via async import() when used (Note that this external type is an async module, which has various effects on the execution).", + "type": "boolean" + } + } + }, + "ExternalsType": { + "description": "Specifies the default type of externals ('amd*', 'umd*', 'system' and 'jsonp' depend on output.libraryTarget set to the same value).", + "enum": [ + "var", + "module", + "assign", + "this", + "window", + "self", + "global", + "commonjs", + "commonjs2", + "commonjs-module", + "commonjs-static", + "amd", + "amd-require", + "umd", + "umd2", + "jsonp", + "system", + "promise", + "import", + "module-import", + "script", + "node-commonjs" + ] + }, + "Falsy": { + "description": "These values will be ignored by webpack and created to be used with '&&' or '||' to improve readability of configurations.", + "cli": { + "exclude": true + }, + "enum": [false, 0, "", null], + "undefinedAsNull": true, + "tsType": "false | 0 | '' | null | undefined" + }, + "FileCacheOptions": { + "description": "Options object for persistent file-based caching.", + "type": "object", + "additionalProperties": false, + "properties": { + "allowCollectingMemory": { + "description": "Allows to collect unused memory allocated during deserialization. This requires copying data into smaller buffers and has a performance cost.", + "type": "boolean" + }, + "buildDependencies": { + "description": "Dependencies the build depends on (in multiple categories, default categories: 'defaultWebpack').", + "type": "object", + "additionalProperties": { + "description": "List of dependencies the build depends on.", + "type": "array", + "items": { + "description": "Request to a dependency (resolved as directory relative to the context directory).", + "type": "string", + "minLength": 1 + } + } + }, + "cacheDirectory": { + "description": "Base directory for the cache (defaults to node_modules/.cache/webpack).", + "type": "string", + "absolutePath": true + }, + "cacheLocation": { + "description": "Locations for the cache (defaults to cacheDirectory / name).", + "type": "string", + "absolutePath": true + }, + "compression": { + "description": "Compression type used for the cache files.", + "enum": [false, "gzip", "brotli"] + }, + "hashAlgorithm": { + "description": "Algorithm used for generation the hash (see node.js crypto package).", + "type": "string" + }, + "idleTimeout": { + "description": "Time in ms after which idle period the cache storing should happen.", + "type": "number", + "minimum": 0 + }, + "idleTimeoutAfterLargeChanges": { + "description": "Time in ms after which idle period the cache storing should happen when larger changes has been detected (cumulative build time > 2 x avg cache store time).", + "type": "number", + "minimum": 0 + }, + "idleTimeoutForInitialStore": { + "description": "Time in ms after which idle period the initial cache storing should happen.", + "type": "number", + "minimum": 0 + }, + "immutablePaths": { + "description": "List of paths that are managed by a package manager and contain a version or hash in its path so all files are immutable.", + "type": "array", + "items": { + "description": "List of paths that are managed by a package manager and contain a version or hash in its path so all files are immutable.", + "anyOf": [ + { + "description": "A RegExp matching an immutable directory (usually a package manager cache directory, including the tailing slash)", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "A path to an immutable directory (usually a package manager cache directory).", + "type": "string", + "absolutePath": true, + "minLength": 1 + } + ] + } + }, + "managedPaths": { + "description": "List of paths that are managed by a package manager and can be trusted to not be modified otherwise.", + "type": "array", + "items": { + "description": "List of paths that are managed by a package manager and can be trusted to not be modified otherwise.", + "anyOf": [ + { + "description": "A RegExp matching a managed directory (usually a node_modules directory, including the tailing slash)", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "A path to a managed directory (usually a node_modules directory).", + "type": "string", + "absolutePath": true, + "minLength": 1 + } + ] + } + }, + "maxAge": { + "description": "Time for which unused cache entries stay in the filesystem cache at minimum (in milliseconds).", + "type": "number", + "minimum": 0 + }, + "maxMemoryGenerations": { + "description": "Number of generations unused cache entries stay in memory cache at minimum (0 = no memory cache used, 1 = may be removed after unused for a single compilation, ..., Infinity: kept forever). Cache entries will be deserialized from disk when removed from memory cache.", + "type": "number", + "minimum": 0 + }, + "memoryCacheUnaffected": { + "description": "Additionally cache computation of modules that are unchanged and reference only unchanged modules in memory.", + "type": "boolean" + }, + "name": { + "description": "Name for the cache. Different names will lead to different coexisting caches.", + "type": "string" + }, + "profile": { + "description": "Track and log detailed timing information for individual cache items.", + "type": "boolean" + }, + "readonly": { + "description": "Enable/disable readonly mode.", + "type": "boolean" + }, + "store": { + "description": "When to store data to the filesystem. (pack: Store data when compiler is idle in a single file).", + "enum": ["pack"] + }, + "type": { + "description": "Filesystem caching.", + "enum": ["filesystem"] + }, + "version": { + "description": "Version of the cache data. Different versions won't allow to reuse the cache and override existing content. Update the version when config changed in a way which doesn't allow to reuse cache. This will invalidate the cache.", + "type": "string" + } + }, + "required": ["type"] + }, + "Filename": { + "description": "Specifies the filename of output files on disk. You must **not** specify an absolute path here, but the path may contain folders separated by '/'! The specified path is joined with the value of the 'output.path' option to determine the location on disk.", + "oneOf": [ + { + "$ref": "#/definitions/FilenameTemplate" + } + ] + }, + "FilenameTemplate": { + "description": "Specifies the filename template of output files on disk. You must **not** specify an absolute path here, but the path may contain folders separated by '/'! The specified path is joined with the value of the 'output.path' option to determine the location on disk.", + "anyOf": [ + { + "type": "string", + "absolutePath": false, + "minLength": 1 + }, + { + "instanceof": "Function", + "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + } + ] + }, + "FilterItemTypes": { + "description": "Filtering value, regexp or function.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string", + "absolutePath": false + }, + { + "instanceof": "Function", + "tsType": "((value: string) => boolean)" + } + ] + }, + "FilterTypes": { + "description": "Filtering values.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "type": "array", + "items": { + "description": "Rule to filter.", + "cli": { + "helper": true + }, + "oneOf": [ + { + "$ref": "#/definitions/FilterItemTypes" + } + ] + } + }, + { + "$ref": "#/definitions/FilterItemTypes" + } + ] + }, + "GeneratorOptionsByModuleType": { + "description": "Specify options for each generator.", + "type": "object", + "additionalProperties": { + "description": "Options for generating.", + "type": "object", + "additionalProperties": true + }, + "properties": { + "asset": { + "$ref": "#/definitions/AssetGeneratorOptions" + }, + "asset/inline": { + "$ref": "#/definitions/AssetInlineGeneratorOptions" + }, + "asset/resource": { + "$ref": "#/definitions/AssetResourceGeneratorOptions" + }, + "css": { + "$ref": "#/definitions/CssGeneratorOptions" + }, + "css/auto": { + "$ref": "#/definitions/CssAutoGeneratorOptions" + }, + "css/global": { + "$ref": "#/definitions/CssGlobalGeneratorOptions" + }, + "css/module": { + "$ref": "#/definitions/CssModuleGeneratorOptions" + }, + "javascript": { + "$ref": "#/definitions/EmptyGeneratorOptions" + }, + "javascript/auto": { + "$ref": "#/definitions/EmptyGeneratorOptions" + }, + "javascript/dynamic": { + "$ref": "#/definitions/EmptyGeneratorOptions" + }, + "javascript/esm": { + "$ref": "#/definitions/EmptyGeneratorOptions" + }, + "json": { + "$ref": "#/definitions/JsonGeneratorOptions" + } + } + }, + "GlobalObject": { + "description": "An expression which is used to address the global object/scope in runtime code.", + "type": "string", + "minLength": 1 + }, + "HashDigest": { + "description": "Digest type used for the hash.", + "type": "string" + }, + "HashDigestLength": { + "description": "Number of chars which are used for the hash.", + "type": "number", + "minimum": 1 + }, + "HashFunction": { + "description": "Algorithm used for generation the hash (see node.js crypto package).", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "Function", + "tsType": "typeof import('../lib/util/Hash')" + } + ] + }, + "HashSalt": { + "description": "Any string which is added to the hash to salt it.", + "type": "string", + "minLength": 1 + }, + "HotUpdateChunkFilename": { + "description": "The filename of the Hot Update Chunks. They are inside the output.path directory.", + "type": "string", + "absolutePath": false + }, + "HotUpdateGlobal": { + "description": "The global variable used by webpack for loading of hot update chunks.", + "type": "string" + }, + "HotUpdateMainFilename": { + "description": "The filename of the Hot Update Main File. It is inside the 'output.path' directory.", + "type": "string", + "absolutePath": false + }, + "HttpUriAllowedUris": { + "description": "List of allowed URIs for building http resources.", + "cli": { + "exclude": true + }, + "oneOf": [ + { + "$ref": "#/definitions/HttpUriOptionsAllowedUris" + } + ] + }, + "HttpUriOptions": { + "description": "Options for building http resources.", + "type": "object", + "additionalProperties": false, + "properties": { + "allowedUris": { + "$ref": "#/definitions/HttpUriOptionsAllowedUris" + }, + "cacheLocation": { + "description": "Location where resource content is stored for lockfile entries. It's also possible to disable storing by passing false.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string", + "absolutePath": true + } + ] + }, + "frozen": { + "description": "When set, anything that would lead to a modification of the lockfile or any resource content, will result in an error.", + "type": "boolean" + }, + "lockfileLocation": { + "description": "Location of the lockfile.", + "type": "string", + "absolutePath": true + }, + "proxy": { + "description": "Proxy configuration, which can be used to specify a proxy server to use for HTTP requests.", + "type": "string" + }, + "upgrade": { + "description": "When set, resources of existing lockfile entries will be fetched and entries will be upgraded when resource content has changed.", + "type": "boolean" + } + }, + "required": ["allowedUris"] + }, + "HttpUriOptionsAllowedUris": { + "description": "List of allowed URIs (resp. the beginning of them).", + "type": "array", + "items": { + "description": "List of allowed URIs (resp. the beginning of them).", + "anyOf": [ + { + "description": "Allowed URI pattern.", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "Allowed URI (resp. the beginning of it).", + "type": "string", + "pattern": "^https?://" + }, + { + "description": "Allowed URI filter function.", + "instanceof": "Function", + "tsType": "((uri: string) => boolean)" + } + ] + } + }, + "IgnoreWarnings": { + "description": "Ignore specific warnings.", + "type": "array", + "items": { + "description": "Ignore specific warnings.", + "anyOf": [ + { + "description": "A RegExp to select the warning message.", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "file": { + "description": "A RegExp to select the origin file for the warning.", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + "message": { + "description": "A RegExp to select the warning message.", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + "module": { + "description": "A RegExp to select the origin module for the warning.", + "instanceof": "RegExp", + "tsType": "RegExp" + } + } + }, + { + "description": "A custom function to select warnings based on the raw warning instance.", + "instanceof": "Function", + "tsType": "((warning: Error, compilation: import('../lib/Compilation')) => boolean)" + } + ] + } + }, + "IgnoreWarningsNormalized": { + "description": "Ignore specific warnings.", + "type": "array", + "items": { + "description": "A function to select warnings based on the raw warning instance.", + "instanceof": "Function", + "tsType": "((warning: Error, compilation: import('../lib/Compilation')) => boolean)" + } + }, + "Iife": { + "description": "Wrap javascript code into IIFE's to avoid leaking into global scope.", + "type": "boolean" + }, + "ImportFunctionName": { + "description": "The name of the native import() function (can be exchanged for a polyfill).", + "type": "string" + }, + "ImportMetaName": { + "description": "The name of the native import.meta object (can be exchanged for a polyfill).", + "type": "string" + }, + "InfrastructureLogging": { + "description": "Options for infrastructure level logging.", + "type": "object", + "additionalProperties": false, + "properties": { + "appendOnly": { + "description": "Only appends lines to the output. Avoids updating existing output e. g. for status messages. This option is only used when no custom console is provided.", + "type": "boolean" + }, + "colors": { + "description": "Enables/Disables colorful output. This option is only used when no custom console is provided.", + "type": "boolean" + }, + "console": { + "description": "Custom console used for logging.", + "tsType": "Console" + }, + "debug": { + "description": "Enable debug logging for specific loggers.", + "anyOf": [ + { + "description": "Enable/Disable debug logging for all loggers.", + "type": "boolean" + }, + { + "$ref": "#/definitions/FilterTypes" + } + ] + }, + "level": { + "description": "Log level.", + "enum": ["none", "error", "warn", "info", "log", "verbose"] + }, + "stream": { + "description": "Stream used for logging output. Defaults to process.stderr. This option is only used when no custom console is provided.", + "tsType": "NodeJS.WritableStream & { isTTY?: boolean, columns?: number, rows?: number }" + } + } + }, + "JavascriptParserOptions": { + "description": "Parser options for javascript modules.", + "type": "object", + "additionalProperties": true, + "properties": { + "amd": { + "$ref": "#/definitions/Amd" + }, + "browserify": { + "description": "Enable/disable special handling for browserify bundles.", + "type": "boolean" + }, + "commonjs": { + "description": "Enable/disable parsing of CommonJs syntax.", + "type": "boolean" + }, + "commonjsMagicComments": { + "description": "Enable/disable parsing of magic comments in CommonJs syntax.", + "type": "boolean" + }, + "createRequire": { + "description": "Enable/disable parsing \"import { createRequire } from \"module\"\" and evaluating createRequire().", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string" + } + ] + }, + "deferImport": { + "description": "Enable experimental tc39 proposal https://github.com/tc39/proposal-defer-import-eval. This allows to defer execution of a module until it's first use.", + "type": "boolean" + }, + "dynamicImportFetchPriority": { + "description": "Specifies global fetchPriority for dynamic import.", + "enum": ["low", "high", "auto", false] + }, + "dynamicImportMode": { + "description": "Specifies global mode for dynamic import.", + "enum": ["eager", "weak", "lazy", "lazy-once"] + }, + "dynamicImportPrefetch": { + "description": "Specifies global prefetch for dynamic import.", + "anyOf": [ + { + "type": "number" + }, + { + "type": "boolean" + } + ] + }, + "dynamicImportPreload": { + "description": "Specifies global preload for dynamic import.", + "anyOf": [ + { + "type": "number" + }, + { + "type": "boolean" + } + ] + }, + "dynamicUrl": { + "description": "Enable/disable parsing of dynamic URL.", + "type": "boolean" + }, + "exportsPresence": { + "description": "Specifies the behavior of invalid export names in \"import ... from ...\" and \"export ... from ...\".", + "enum": ["error", "warn", "auto", false] + }, + "exprContextCritical": { + "description": "Enable warnings for full dynamic dependencies.", + "type": "boolean" + }, + "exprContextRecursive": { + "description": "Enable recursive directory lookup for full dynamic dependencies.", + "type": "boolean" + }, + "exprContextRegExp": { + "description": "Sets the default regular expression for full dynamic dependencies.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "boolean" + } + ] + }, + "exprContextRequest": { + "description": "Set the default request for full dynamic dependencies.", + "type": "string" + }, + "harmony": { + "description": "Enable/disable parsing of EcmaScript Modules syntax.", + "type": "boolean" + }, + "import": { + "description": "Enable/disable parsing of import() syntax.", + "type": "boolean" + }, + "importExportsPresence": { + "description": "Specifies the behavior of invalid export names in \"import ... from ...\".", + "enum": ["error", "warn", "auto", false] + }, + "importMeta": { + "description": "Enable/disable evaluating import.meta.", + "type": "boolean" + }, + "importMetaContext": { + "description": "Enable/disable evaluating import.meta.webpackContext.", + "type": "boolean" + }, + "node": { + "$ref": "#/definitions/Node" + }, + "overrideStrict": { + "description": "Override the module to strict or non-strict. This may affect the behavior of the module (some behaviors differ between strict and non-strict), so please configure this option carefully.", + "enum": ["strict", "non-strict"] + }, + "reexportExportsPresence": { + "description": "Specifies the behavior of invalid export names in \"export ... from ...\". This might be useful to disable during the migration from \"export ... from ...\" to \"export type ... from ...\" when reexporting types in TypeScript.", + "enum": ["error", "warn", "auto", false] + }, + "requireContext": { + "description": "Enable/disable parsing of require.context syntax.", + "type": "boolean" + }, + "requireEnsure": { + "description": "Enable/disable parsing of require.ensure syntax.", + "type": "boolean" + }, + "requireInclude": { + "description": "Enable/disable parsing of require.include syntax.", + "type": "boolean" + }, + "requireJs": { + "description": "Enable/disable parsing of require.js special syntax like require.config, requirejs.config, require.version and requirejs.onError.", + "type": "boolean" + }, + "strictExportPresence": { + "description": "Deprecated in favor of \"exportsPresence\". Emit errors instead of warnings when imported names don't exist in imported module.", + "type": "boolean" + }, + "strictThisContextOnImports": { + "description": "Handle the this context correctly according to the spec for namespace objects.", + "type": "boolean" + }, + "system": { + "description": "Enable/disable parsing of System.js special syntax like System.import, System.get, System.set and System.register.", + "type": "boolean" + }, + "unknownContextCritical": { + "description": "Enable warnings when using the require function in a not statically analyse-able way.", + "type": "boolean" + }, + "unknownContextRecursive": { + "description": "Enable recursive directory lookup when using the require function in a not statically analyse-able way.", + "type": "boolean" + }, + "unknownContextRegExp": { + "description": "Sets the regular expression when using the require function in a not statically analyse-able way.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "boolean" + } + ] + }, + "unknownContextRequest": { + "description": "Sets the request when using the require function in a not statically analyse-able way.", + "type": "string" + }, + "url": { + "description": "Enable/disable parsing of new URL() syntax.", + "anyOf": [ + { + "enum": ["relative"] + }, + { + "type": "boolean" + } + ] + }, + "worker": { + "description": "Disable or configure parsing of WebWorker syntax like new Worker() or navigator.serviceWorker.register().", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Specify a syntax that should be parsed as WebWorker reference. 'Abc' handles 'new Abc()', 'Abc from xyz' handles 'import { Abc } from \"xyz\"; new Abc()', 'abc()' handles 'abc()', and combinations are also possible.", + "type": "string", + "minLength": 1 + } + }, + { + "type": "boolean" + } + ] + }, + "wrappedContextCritical": { + "description": "Enable warnings for partial dynamic dependencies.", + "type": "boolean" + }, + "wrappedContextRecursive": { + "description": "Enable recursive directory lookup for partial dynamic dependencies.", + "type": "boolean" + }, + "wrappedContextRegExp": { + "description": "Set the inner regular expression for partial dynamic dependencies.", + "instanceof": "RegExp", + "tsType": "RegExp" + } + } + }, + "JsonGeneratorOptions": { + "description": "Generator options for json modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "JSONParse": { + "description": "Use `JSON.parse` when the JSON string is longer than 20 characters.", + "type": "boolean" + } + } + }, + "JsonParserOptions": { + "description": "Parser options for JSON modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "exportsDepth": { + "description": "The depth of json dependency flagged as `exportInfo`.", + "type": "number" + }, + "parse": { + "description": "Function to parser content and return JSON.", + "instanceof": "Function", + "tsType": "((input: string) => Buffer | import('../lib/json/JsonParser').JsonValue)" + } + } + }, + "Layer": { + "description": "Specifies the layer in which modules of this entrypoint are placed.", + "anyOf": [ + { + "enum": [null] + }, + { + "type": "string", + "minLength": 1 + } + ] + }, + "LazyCompilationDefaultBackendOptions": { + "description": "Options for the default backend.", + "type": "object", + "additionalProperties": false, + "properties": { + "client": { + "description": "A custom client.", + "type": "string" + }, + "listen": { + "description": "Specifies where to listen to from the server.", + "anyOf": [ + { + "description": "A port.", + "type": "number" + }, + { + "description": "Listen options.", + "type": "object", + "additionalProperties": true, + "properties": { + "host": { + "description": "A host.", + "type": "string" + }, + "port": { + "description": "A port.", + "type": "number" + } + }, + "tsType": "import(\"net\").ListenOptions" + }, + { + "description": "A custom listen function.", + "instanceof": "Function", + "tsType": "((server: import(\"net\").Server) => void)" + } + ] + }, + "protocol": { + "description": "Specifies the protocol the client should use to connect to the server.", + "enum": ["http", "https"] + }, + "server": { + "description": "Specifies how to create the server handling the EventSource requests.", + "anyOf": [ + { + "description": "ServerOptions for the http or https createServer call.", + "type": "object", + "additionalProperties": true, + "properties": {}, + "tsType": "(import(\"../lib/hmr/lazyCompilationBackend\").HttpsServerOptions | import(\"../lib/hmr/lazyCompilationBackend\").HttpServerOptions)" + }, + { + "description": "A custom create server function.", + "instanceof": "Function", + "tsType": "(() => import(\"../lib/hmr/lazyCompilationBackend\").Server)" + } + ] + } + } + }, + "LazyCompilationOptions": { + "description": "Options for compiling entrypoints and import()s only when they are accessed.", + "type": "object", + "additionalProperties": false, + "properties": { + "backend": { + "description": "Specifies the backend that should be used for handling client keep alive.", + "anyOf": [ + { + "description": "A custom backend.", + "instanceof": "Function", + "tsType": "(((compiler: import('../lib/Compiler'), callback: (err: Error | null, api?: import(\"../lib/hmr/LazyCompilationPlugin\").BackendApi) => void) => void) | ((compiler: import('../lib/Compiler')) => Promise))" + }, + { + "$ref": "#/definitions/LazyCompilationDefaultBackendOptions" + } + ] + }, + "entries": { + "description": "Enable/disable lazy compilation for entries.", + "type": "boolean" + }, + "imports": { + "description": "Enable/disable lazy compilation for import() modules.", + "type": "boolean" + }, + "test": { + "description": "Specify which entrypoints or import()ed modules should be lazily compiled. This is matched with the imported module and not the entrypoint name.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "((module: import('../lib/Module')) => boolean)" + } + ] + } + } + }, + "Library": { + "description": "Make the output files a library, exporting the exports of the entry point.", + "anyOf": [ + { + "$ref": "#/definitions/LibraryName" + }, + { + "$ref": "#/definitions/LibraryOptions" + } + ] + }, + "LibraryCustomUmdCommentObject": { + "description": "Set explicit comments for `commonjs`, `commonjs2`, `amd`, and `root`.", + "type": "object", + "additionalProperties": false, + "properties": { + "amd": { + "description": "Set comment for `amd` section in UMD.", + "type": "string" + }, + "commonjs": { + "description": "Set comment for `commonjs` (exports) section in UMD.", + "type": "string" + }, + "commonjs2": { + "description": "Set comment for `commonjs2` (module.exports) section in UMD.", + "type": "string" + }, + "root": { + "description": "Set comment for `root` (global variable) section in UMD.", + "type": "string" + } + } + }, + "LibraryCustomUmdObject": { + "description": "Description object for all UMD variants of the library name.", + "type": "object", + "additionalProperties": false, + "properties": { + "amd": { + "description": "Name of the exposed AMD library in the UMD.", + "type": "string", + "minLength": 1 + }, + "commonjs": { + "description": "Name of the exposed commonjs export in the UMD.", + "type": "string", + "minLength": 1 + }, + "root": { + "description": "Name of the property exposed globally by a UMD library.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Part of the name of the property exposed globally by a UMD library.", + "type": "string", + "minLength": 1 + } + }, + { + "type": "string", + "minLength": 1 + } + ] + } + } + }, + "LibraryExport": { + "description": "Specify which export should be exposed as library.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Part of the export that should be exposed as library.", + "type": "string", + "minLength": 1 + } + }, + { + "type": "string", + "minLength": 1 + } + ] + }, + "LibraryName": { + "description": "The name of the library (some types allow unnamed libraries too).", + "anyOf": [ + { + "type": "array", + "items": { + "description": "A part of the library name.", + "type": "string", + "minLength": 1 + }, + "minItems": 1 + }, + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/LibraryCustomUmdObject" + } + ] + }, + "LibraryOptions": { + "description": "Options for library.", + "type": "object", + "additionalProperties": false, + "properties": { + "amdContainer": { + "$ref": "#/definitions/AmdContainer" + }, + "auxiliaryComment": { + "$ref": "#/definitions/AuxiliaryComment" + }, + "export": { + "$ref": "#/definitions/LibraryExport" + }, + "name": { + "$ref": "#/definitions/LibraryName" + }, + "type": { + "$ref": "#/definitions/LibraryType" + }, + "umdNamedDefine": { + "$ref": "#/definitions/UmdNamedDefine" + } + }, + "required": ["type"] + }, + "LibraryType": { + "description": "Type of library (types included by default are 'var', 'module', 'assign', 'assign-properties', 'this', 'window', 'self', 'global', 'commonjs', 'commonjs2', 'commonjs-module', 'commonjs-static', 'amd', 'amd-require', 'umd', 'umd2', 'jsonp', 'system', but others might be added by plugins).", + "anyOf": [ + { + "enum": [ + "var", + "module", + "assign", + "assign-properties", + "this", + "window", + "self", + "global", + "commonjs", + "commonjs2", + "commonjs-module", + "commonjs-static", + "amd", + "amd-require", + "umd", + "umd2", + "jsonp", + "system" + ] + }, + { + "type": "string" + } + ] + }, + "Loader": { + "description": "Custom values available in the loader context.", + "type": "object" + }, + "MemoryCacheOptions": { + "description": "Options object for in-memory caching.", + "type": "object", + "additionalProperties": false, + "properties": { + "cacheUnaffected": { + "description": "Additionally cache computation of modules that are unchanged and reference only unchanged modules.", + "type": "boolean" + }, + "maxGenerations": { + "description": "Number of generations unused cache entries stay in memory cache at minimum (1 = may be removed after unused for a single compilation, ..., Infinity: kept forever).", + "type": "number", + "minimum": 1 + }, + "type": { + "description": "In memory caching.", + "enum": ["memory"] + } + }, + "required": ["type"] + }, + "Mode": { + "description": "Enable production optimizations or development hints.", + "enum": ["development", "production", "none"] + }, + "ModuleFilterItemTypes": { + "description": "Filtering value, regexp or function.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string", + "absolutePath": false + }, + { + "instanceof": "Function", + "tsType": "((name: string, module: import('../lib/stats/DefaultStatsFactoryPlugin').StatsModule, type: 'module' | 'chunk' | 'root-of-chunk' | 'nested') => boolean)" + } + ] + }, + "ModuleFilterTypes": { + "description": "Filtering modules.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "type": "array", + "items": { + "description": "Rule to filter.", + "cli": { + "helper": true + }, + "oneOf": [ + { + "$ref": "#/definitions/ModuleFilterItemTypes" + } + ] + } + }, + { + "$ref": "#/definitions/ModuleFilterItemTypes" + } + ] + }, + "ModuleOptions": { + "description": "Options affecting the normal modules (`NormalModuleFactory`).", + "type": "object", + "additionalProperties": false, + "properties": { + "defaultRules": { + "description": "An array of rules applied by default for modules.", + "cli": { + "exclude": true + }, + "oneOf": [ + { + "$ref": "#/definitions/RuleSetRules" + } + ] + }, + "exprContextCritical": { + "description": "Enable warnings for full dynamic dependencies.", + "type": "boolean" + }, + "exprContextRecursive": { + "description": "Enable recursive directory lookup for full dynamic dependencies. Deprecated: This option has moved to 'module.parser.javascript.exprContextRecursive'.", + "type": "boolean" + }, + "exprContextRegExp": { + "description": "Sets the default regular expression for full dynamic dependencies. Deprecated: This option has moved to 'module.parser.javascript.exprContextRegExp'.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "boolean" + } + ] + }, + "exprContextRequest": { + "description": "Set the default request for full dynamic dependencies. Deprecated: This option has moved to 'module.parser.javascript.exprContextRequest'.", + "type": "string" + }, + "generator": { + "$ref": "#/definitions/GeneratorOptionsByModuleType" + }, + "noParse": { + "$ref": "#/definitions/NoParse" + }, + "parser": { + "$ref": "#/definitions/ParserOptionsByModuleType" + }, + "rules": { + "description": "An array of rules applied for modules.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetRules" + } + ] + }, + "strictExportPresence": { + "description": "Emit errors instead of warnings when imported names don't exist in imported module. Deprecated: This option has moved to 'module.parser.javascript.strictExportPresence'.", + "type": "boolean" + }, + "strictThisContextOnImports": { + "description": "Handle the this context correctly according to the spec for namespace objects. Deprecated: This option has moved to 'module.parser.javascript.strictThisContextOnImports'.", + "type": "boolean" + }, + "unknownContextCritical": { + "description": "Enable warnings when using the require function in a not statically analyse-able way. Deprecated: This option has moved to 'module.parser.javascript.unknownContextCritical'.", + "type": "boolean" + }, + "unknownContextRecursive": { + "description": "Enable recursive directory lookup when using the require function in a not statically analyse-able way. Deprecated: This option has moved to 'module.parser.javascript.unknownContextRecursive'.", + "type": "boolean" + }, + "unknownContextRegExp": { + "description": "Sets the regular expression when using the require function in a not statically analyse-able way. Deprecated: This option has moved to 'module.parser.javascript.unknownContextRegExp'.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "boolean" + } + ] + }, + "unknownContextRequest": { + "description": "Sets the request when using the require function in a not statically analyse-able way. Deprecated: This option has moved to 'module.parser.javascript.unknownContextRequest'.", + "type": "string" + }, + "unsafeCache": { + "description": "Cache the resolving of module requests.", + "anyOf": [ + { + "type": "boolean" + }, + { + "instanceof": "Function", + "tsType": "((module: import('../lib/Module')) => boolean)" + } + ] + }, + "wrappedContextCritical": { + "description": "Enable warnings for partial dynamic dependencies. Deprecated: This option has moved to 'module.parser.javascript.wrappedContextCritical'.", + "type": "boolean" + }, + "wrappedContextRecursive": { + "description": "Enable recursive directory lookup for partial dynamic dependencies. Deprecated: This option has moved to 'module.parser.javascript.wrappedContextRecursive'.", + "type": "boolean" + }, + "wrappedContextRegExp": { + "description": "Set the inner regular expression for partial dynamic dependencies. Deprecated: This option has moved to 'module.parser.javascript.wrappedContextRegExp'.", + "instanceof": "RegExp", + "tsType": "RegExp" + } + } + }, + "ModuleOptionsNormalized": { + "description": "Options affecting the normal modules (`NormalModuleFactory`).", + "type": "object", + "additionalProperties": false, + "properties": { + "defaultRules": { + "description": "An array of rules applied by default for modules.", + "cli": { + "exclude": true + }, + "oneOf": [ + { + "$ref": "#/definitions/RuleSetRules" + } + ] + }, + "generator": { + "$ref": "#/definitions/GeneratorOptionsByModuleType" + }, + "noParse": { + "$ref": "#/definitions/NoParse" + }, + "parser": { + "$ref": "#/definitions/ParserOptionsByModuleType" + }, + "rules": { + "description": "An array of rules applied for modules.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetRules" + } + ] + }, + "unsafeCache": { + "description": "Cache the resolving of module requests.", + "anyOf": [ + { + "type": "boolean" + }, + { + "instanceof": "Function", + "tsType": "((module: import('../lib/Module')) => boolean)" + } + ] + } + }, + "required": ["defaultRules", "generator", "parser", "rules"] + }, + "Name": { + "description": "Name of the configuration. Used when loading multiple configurations.", + "type": "string" + }, + "NoParse": { + "description": "Don't parse files matching. It's matched against the full resolved request.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Don't parse files matching. It's matched against the full resolved request.", + "anyOf": [ + { + "description": "A regular expression, when matched the module is not parsed.", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "An absolute path, when the module starts with this path it is not parsed.", + "type": "string", + "absolutePath": true + }, + { + "instanceof": "Function", + "tsType": "((content: string) => boolean)" + } + ] + }, + "minItems": 1 + }, + { + "description": "A regular expression, when matched the module is not parsed.", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "An absolute path, when the module starts with this path it is not parsed.", + "type": "string", + "absolutePath": true + }, + { + "instanceof": "Function", + "tsType": "((content: string) => boolean)" + } + ] + }, + "Node": { + "description": "Include polyfills or mocks for various node stuff.", + "anyOf": [ + { + "enum": [false] + }, + { + "$ref": "#/definitions/NodeOptions" + } + ] + }, + "NodeOptions": { + "description": "Options object for node compatibility features.", + "type": "object", + "additionalProperties": false, + "properties": { + "__dirname": { + "description": "Include a polyfill for the '__dirname' variable.", + "enum": [false, true, "warn-mock", "mock", "node-module", "eval-only"] + }, + "__filename": { + "description": "Include a polyfill for the '__filename' variable.", + "enum": [false, true, "warn-mock", "mock", "node-module", "eval-only"] + }, + "global": { + "description": "Include a polyfill for the 'global' variable.", + "enum": [false, true, "warn"] + } + } + }, + "Optimization": { + "description": "Enables/Disables integrated optimizations.", + "type": "object", + "additionalProperties": false, + "properties": { + "avoidEntryIife": { + "description": "Avoid wrapping the entry module in an IIFE.", + "type": "boolean" + }, + "checkWasmTypes": { + "description": "Check for incompatible wasm types when importing/exporting from/to ESM.", + "type": "boolean" + }, + "chunkIds": { + "description": "Define the algorithm to choose chunk ids (named: readable ids for better debugging, deterministic: numeric hash ids for better long term caching, size: numeric ids focused on minimal initial download size, total-size: numeric ids focused on minimal total download size, false: no algorithm used, as custom one can be provided via plugin).", + "enum": [ + "natural", + "named", + "deterministic", + "size", + "total-size", + false + ] + }, + "concatenateModules": { + "description": "Concatenate modules when possible to generate less modules, more efficient code and enable more optimizations by the minimizer.", + "type": "boolean" + }, + "emitOnErrors": { + "description": "Emit assets even when errors occur. Critical errors are emitted into the generated code and will cause errors at runtime.", + "type": "boolean" + }, + "flagIncludedChunks": { + "description": "Also flag chunks as loaded which contain a subset of the modules.", + "type": "boolean" + }, + "innerGraph": { + "description": "Creates a module-internal dependency graph for top level symbols, exports and imports, to improve unused exports detection.", + "type": "boolean" + }, + "mangleExports": { + "description": "Rename exports when possible to generate shorter code (depends on optimization.usedExports and optimization.providedExports, true/\"deterministic\": generate short deterministic names optimized for caching, \"size\": generate the shortest possible names).", + "anyOf": [ + { + "enum": ["size", "deterministic"] + }, + { + "type": "boolean" + } + ] + }, + "mangleWasmImports": { + "description": "Reduce size of WASM by changing imports to shorter strings.", + "type": "boolean" + }, + "mergeDuplicateChunks": { + "description": "Merge chunks which contain the same modules.", + "type": "boolean" + }, + "minimize": { + "description": "Enable minimizing the output. Uses optimization.minimizer.", + "type": "boolean" + }, + "minimizer": { + "description": "Minimizer(s) to use for minimizing the output.", + "type": "array", + "cli": { + "exclude": true + }, + "items": { + "description": "Plugin of type object or instanceof Function.", + "anyOf": [ + { + "enum": ["..."] + }, + { + "$ref": "#/definitions/Falsy" + }, + { + "$ref": "#/definitions/WebpackPluginInstance" + }, + { + "$ref": "#/definitions/WebpackPluginFunction" + } + ] + } + }, + "moduleIds": { + "description": "Define the algorithm to choose module ids (natural: numeric ids in order of usage, named: readable ids for better debugging, hashed: (deprecated) short hashes as ids for better long term caching, deterministic: numeric hash ids for better long term caching, size: numeric ids focused on minimal initial download size, false: no algorithm used, as custom one can be provided via plugin).", + "enum": ["natural", "named", "hashed", "deterministic", "size", false] + }, + "noEmitOnErrors": { + "description": "Avoid emitting assets when errors occur (deprecated: use 'emitOnErrors' instead).", + "type": "boolean", + "cli": { + "exclude": true + } + }, + "nodeEnv": { + "description": "Set process.env.NODE_ENV to a specific value.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string" + } + ] + }, + "portableRecords": { + "description": "Generate records with relative paths to be able to move the context folder.", + "type": "boolean" + }, + "providedExports": { + "description": "Figure out which exports are provided by modules to generate more efficient code.", + "type": "boolean" + }, + "realContentHash": { + "description": "Use real [contenthash] based on final content of the assets.", + "type": "boolean" + }, + "removeAvailableModules": { + "description": "Removes modules from chunks when these modules are already included in all parents.", + "type": "boolean" + }, + "removeEmptyChunks": { + "description": "Remove chunks which are empty.", + "type": "boolean" + }, + "runtimeChunk": { + "$ref": "#/definitions/OptimizationRuntimeChunk" + }, + "sideEffects": { + "description": "Skip over modules which contain no side effects when exports are not used (false: disabled, 'flag': only use manually placed side effects flag, true: also analyse source code for side effects).", + "anyOf": [ + { + "enum": ["flag"] + }, + { + "type": "boolean" + } + ] + }, + "splitChunks": { + "description": "Optimize duplication and caching by splitting chunks by shared modules and cache group.", + "anyOf": [ + { + "enum": [false] + }, + { + "$ref": "#/definitions/OptimizationSplitChunksOptions" + } + ] + }, + "usedExports": { + "description": "Figure out which exports are used by modules to mangle export names, omit unused exports and generate more efficient code (true: analyse used exports for each runtime, \"global\": analyse exports globally for all runtimes combined).", + "anyOf": [ + { + "enum": ["global"] + }, + { + "type": "boolean" + } + ] + } + } + }, + "OptimizationNormalized": { + "description": "Enables/Disables integrated optimizations.", + "type": "object", + "additionalProperties": false, + "properties": { + "avoidEntryIife": { + "description": "Avoid wrapping the entry module in an IIFE.", + "type": "boolean" + }, + "checkWasmTypes": { + "description": "Check for incompatible wasm types when importing/exporting from/to ESM.", + "type": "boolean" + }, + "chunkIds": { + "description": "Define the algorithm to choose chunk ids (named: readable ids for better debugging, deterministic: numeric hash ids for better long term caching, size: numeric ids focused on minimal initial download size, total-size: numeric ids focused on minimal total download size, false: no algorithm used, as custom one can be provided via plugin).", + "enum": [ + "natural", + "named", + "deterministic", + "size", + "total-size", + false + ] + }, + "concatenateModules": { + "description": "Concatenate modules when possible to generate less modules, more efficient code and enable more optimizations by the minimizer.", + "type": "boolean" + }, + "emitOnErrors": { + "description": "Emit assets even when errors occur. Critical errors are emitted into the generated code and will cause errors at runtime.", + "type": "boolean" + }, + "flagIncludedChunks": { + "description": "Also flag chunks as loaded which contain a subset of the modules.", + "type": "boolean" + }, + "innerGraph": { + "description": "Creates a module-internal dependency graph for top level symbols, exports and imports, to improve unused exports detection.", + "type": "boolean" + }, + "mangleExports": { + "description": "Rename exports when possible to generate shorter code (depends on optimization.usedExports and optimization.providedExports, true/\"deterministic\": generate short deterministic names optimized for caching, \"size\": generate the shortest possible names).", + "anyOf": [ + { + "enum": ["size", "deterministic"] + }, + { + "type": "boolean" + } + ] + }, + "mangleWasmImports": { + "description": "Reduce size of WASM by changing imports to shorter strings.", + "type": "boolean" + }, + "mergeDuplicateChunks": { + "description": "Merge chunks which contain the same modules.", + "type": "boolean" + }, + "minimize": { + "description": "Enable minimizing the output. Uses optimization.minimizer.", + "type": "boolean" + }, + "minimizer": { + "description": "Minimizer(s) to use for minimizing the output.", + "type": "array", + "cli": { + "exclude": true + }, + "items": { + "description": "Plugin of type object or instanceof Function.", + "anyOf": [ + { + "enum": ["..."] + }, + { + "$ref": "#/definitions/Falsy" + }, + { + "$ref": "#/definitions/WebpackPluginInstance" + }, + { + "$ref": "#/definitions/WebpackPluginFunction" + } + ] + } + }, + "moduleIds": { + "description": "Define the algorithm to choose module ids (natural: numeric ids in order of usage, named: readable ids for better debugging, hashed: (deprecated) short hashes as ids for better long term caching, deterministic: numeric hash ids for better long term caching, size: numeric ids focused on minimal initial download size, false: no algorithm used, as custom one can be provided via plugin).", + "enum": ["natural", "named", "hashed", "deterministic", "size", false] + }, + "noEmitOnErrors": { + "description": "Avoid emitting assets when errors occur (deprecated: use 'emitOnErrors' instead).", + "type": "boolean", + "cli": { + "exclude": true + } + }, + "nodeEnv": { + "description": "Set process.env.NODE_ENV to a specific value.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string" + } + ] + }, + "portableRecords": { + "description": "Generate records with relative paths to be able to move the context folder.", + "type": "boolean" + }, + "providedExports": { + "description": "Figure out which exports are provided by modules to generate more efficient code.", + "type": "boolean" + }, + "realContentHash": { + "description": "Use real [contenthash] based on final content of the assets.", + "type": "boolean" + }, + "removeAvailableModules": { + "description": "Removes modules from chunks when these modules are already included in all parents.", + "type": "boolean" + }, + "removeEmptyChunks": { + "description": "Remove chunks which are empty.", + "type": "boolean" + }, + "runtimeChunk": { + "$ref": "#/definitions/OptimizationRuntimeChunkNormalized" + }, + "sideEffects": { + "description": "Skip over modules which contain no side effects when exports are not used (false: disabled, 'flag': only use manually placed side effects flag, true: also analyse source code for side effects).", + "anyOf": [ + { + "enum": ["flag"] + }, + { + "type": "boolean" + } + ] + }, + "splitChunks": { + "description": "Optimize duplication and caching by splitting chunks by shared modules and cache group.", + "anyOf": [ + { + "enum": [false] + }, + { + "$ref": "#/definitions/OptimizationSplitChunksOptions" + } + ] + }, + "usedExports": { + "description": "Figure out which exports are used by modules to mangle export names, omit unused exports and generate more efficient code (true: analyse used exports for each runtime, \"global\": analyse exports globally for all runtimes combined).", + "anyOf": [ + { + "enum": ["global"] + }, + { + "type": "boolean" + } + ] + } + } + }, + "OptimizationRuntimeChunk": { + "description": "Create an additional chunk which contains only the webpack runtime and chunk hash maps.", + "anyOf": [ + { + "enum": ["single", "multiple"] + }, + { + "type": "boolean" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "description": "The name or name factory for the runtime chunks.", + "anyOf": [ + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "import('../lib/optimize/RuntimeChunkPlugin').RuntimeChunkFunction" + } + ] + } + } + } + ] + }, + "OptimizationRuntimeChunkNormalized": { + "description": "Create an additional chunk which contains only the webpack runtime and chunk hash maps.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "description": "The name factory for the runtime chunks.", + "instanceof": "Function", + "tsType": "import('../lib/optimize/RuntimeChunkPlugin').RuntimeChunkFunction" + } + } + } + ] + }, + "OptimizationSplitChunksCacheGroup": { + "description": "Options object for describing behavior of a cache group selecting modules that should be cached together.", + "type": "object", + "additionalProperties": false, + "properties": { + "automaticNameDelimiter": { + "description": "Sets the name delimiter for created chunks.", + "type": "string", + "minLength": 1 + }, + "chunks": { + "description": "Select chunks for determining cache group content (defaults to \"initial\", \"initial\" and \"all\" requires adding these chunks to the HTML).", + "anyOf": [ + { + "enum": ["initial", "async", "all"] + }, + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "instanceof": "Function", + "tsType": "((chunk: import('../lib/Chunk')) => boolean)" + } + ] + }, + "enforce": { + "description": "Ignore minimum size, minimum chunks and maximum requests and always create chunks for this cache group.", + "type": "boolean" + }, + "enforceSizeThreshold": { + "description": "Size threshold at which splitting is enforced and other restrictions (minRemainingSize, maxAsyncRequests, maxInitialRequests) are ignored.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "filename": { + "description": "Sets the template for the filename for created chunks.", + "anyOf": [ + { + "type": "string", + "absolutePath": false, + "minLength": 1 + }, + { + "instanceof": "Function", + "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + } + ] + }, + "idHint": { + "description": "Sets the hint for chunk id.", + "type": "string" + }, + "layer": { + "description": "Assign modules to a cache group by module layer.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "((layer: string | null) => boolean)" + } + ] + }, + "maxAsyncRequests": { + "description": "Maximum number of requests which are accepted for on-demand loading.", + "type": "number", + "minimum": 1 + }, + "maxAsyncSize": { + "description": "Maximal size hint for the on-demand chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "maxInitialRequests": { + "description": "Maximum number of initial chunks which are accepted for an entry point.", + "type": "number", + "minimum": 1 + }, + "maxInitialSize": { + "description": "Maximal size hint for the initial chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "maxSize": { + "description": "Maximal size hint for the created chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "minChunks": { + "description": "Minimum number of times a module has to be duplicated until it's considered for splitting.", + "type": "number", + "minimum": 1 + }, + "minRemainingSize": { + "description": "Minimal size for the chunks the stay after moving the modules to a new chunk.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "minSize": { + "description": "Minimal size for the created chunk.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "minSizeReduction": { + "description": "Minimum size reduction due to the created chunk.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "name": { + "description": "Give chunks for this cache group a name (chunks with equal name are merged).", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "((module: import('../lib/Module'), chunks: import('../lib/Chunk')[], key: string) => string | undefined)" + } + ] + }, + "priority": { + "description": "Priority of this cache group.", + "type": "number" + }, + "reuseExistingChunk": { + "description": "Try to reuse existing chunk (with name) when it has matching modules.", + "type": "boolean" + }, + "test": { + "description": "Assign modules to a cache group by module name.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "((module: import('../lib/Module'), context: import('../lib/optimize/SplitChunksPlugin').CacheGroupsContext) => boolean)" + } + ] + }, + "type": { + "description": "Assign modules to a cache group by module type.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "((type: string) => boolean)" + } + ] + }, + "usedExports": { + "description": "Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal.", + "type": "boolean" + } + } + }, + "OptimizationSplitChunksGetCacheGroups": { + "description": "A function returning cache groups.", + "instanceof": "Function", + "tsType": "((module: import('../lib/Module')) => OptimizationSplitChunksCacheGroup | OptimizationSplitChunksCacheGroup[] | void)" + }, + "OptimizationSplitChunksOptions": { + "description": "Options object for splitting chunks into smaller chunks.", + "type": "object", + "additionalProperties": false, + "properties": { + "automaticNameDelimiter": { + "description": "Sets the name delimiter for created chunks.", + "type": "string", + "minLength": 1 + }, + "cacheGroups": { + "description": "Assign modules to a cache group (modules from different cache groups are tried to keep in separate chunks, default categories: 'default', 'defaultVendors').", + "type": "object", + "additionalProperties": { + "description": "Configuration for a cache group.", + "anyOf": [ + { + "enum": [false] + }, + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string" + }, + { + "$ref": "#/definitions/OptimizationSplitChunksGetCacheGroups" + }, + { + "$ref": "#/definitions/OptimizationSplitChunksCacheGroup" + } + ] + }, + "not": { + "description": "Using the cacheGroup shorthand syntax with a cache group named 'test' is a potential config error\nDid you intent to define a cache group with a test instead?\ncacheGroups: {\n : {\n test: ...\n }\n}.", + "type": "object", + "additionalProperties": true, + "properties": { + "test": { + "description": "The test property is a cache group name, but using the test option of the cache group could be intended instead.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string" + }, + { + "$ref": "#/definitions/OptimizationSplitChunksGetCacheGroups" + } + ] + } + }, + "required": ["test"] + } + }, + "chunks": { + "description": "Select chunks for determining shared modules (defaults to \"async\", \"initial\" and \"all\" requires adding these chunks to the HTML).", + "anyOf": [ + { + "enum": ["initial", "async", "all"] + }, + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "instanceof": "Function", + "tsType": "((chunk: import('../lib/Chunk')) => boolean)" + } + ] + }, + "defaultSizeTypes": { + "description": "Sets the size types which are used when a number is used for sizes.", + "type": "array", + "items": { + "description": "Size type, like 'javascript', 'webassembly'.", + "type": "string" + }, + "minItems": 1 + }, + "enforceSizeThreshold": { + "description": "Size threshold at which splitting is enforced and other restrictions (minRemainingSize, maxAsyncRequests, maxInitialRequests) are ignored.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "fallbackCacheGroup": { + "description": "Options for modules not selected by any other cache group.", + "type": "object", + "additionalProperties": false, + "properties": { + "automaticNameDelimiter": { + "description": "Sets the name delimiter for created chunks.", + "type": "string", + "minLength": 1 + }, + "chunks": { + "description": "Select chunks for determining shared modules (defaults to \"async\", \"initial\" and \"all\" requires adding these chunks to the HTML).", + "anyOf": [ + { + "enum": ["initial", "async", "all"] + }, + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "instanceof": "Function", + "tsType": "((chunk: import('../lib/Chunk')) => boolean)" + } + ] + }, + "maxAsyncSize": { + "description": "Maximal size hint for the on-demand chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "maxInitialSize": { + "description": "Maximal size hint for the initial chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "maxSize": { + "description": "Maximal size hint for the created chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "minSize": { + "description": "Minimal size for the created chunk.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "minSizeReduction": { + "description": "Minimum size reduction due to the created chunk.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + } + } + }, + "filename": { + "description": "Sets the template for the filename for created chunks.", + "anyOf": [ + { + "type": "string", + "absolutePath": false, + "minLength": 1 + }, + { + "instanceof": "Function", + "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + } + ] + }, + "hidePathInfo": { + "description": "Prevents exposing path info when creating names for parts splitted by maxSize.", + "type": "boolean" + }, + "maxAsyncRequests": { + "description": "Maximum number of requests which are accepted for on-demand loading.", + "type": "number", + "minimum": 1 + }, + "maxAsyncSize": { + "description": "Maximal size hint for the on-demand chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "maxInitialRequests": { + "description": "Maximum number of initial chunks which are accepted for an entry point.", + "type": "number", + "minimum": 1 + }, + "maxInitialSize": { + "description": "Maximal size hint for the initial chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "maxSize": { + "description": "Maximal size hint for the created chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "minChunks": { + "description": "Minimum number of times a module has to be duplicated until it's considered for splitting.", + "type": "number", + "minimum": 1 + }, + "minRemainingSize": { + "description": "Minimal size for the chunks the stay after moving the modules to a new chunk.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "minSize": { + "description": "Minimal size for the created chunks.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "minSizeReduction": { + "description": "Minimum size reduction due to the created chunk.", + "oneOf": [ + { + "$ref": "#/definitions/OptimizationSplitChunksSizes" + } + ] + }, + "name": { + "description": "Give chunks created a name (chunks with equal name are merged).", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "((module: import('../lib/Module'), chunks: import('../lib/Chunk')[], key: string) => string | undefined)" + } + ] + }, + "usedExports": { + "description": "Compare used exports when checking common modules. Modules will only be put in the same chunk when exports are equal.", + "type": "boolean" + } + } + }, + "OptimizationSplitChunksSizes": { + "description": "Size description for limits.", + "anyOf": [ + { + "description": "Size of the javascript part of the chunk.", + "type": "number", + "minimum": 0 + }, + { + "description": "Specify size limits per size type.", + "type": "object", + "additionalProperties": { + "description": "Size of the part of the chunk with the type of the key.", + "type": "number" + } + } + ] + }, + "Output": { + "description": "Options affecting the output of the compilation. `output` options tell webpack how to write the compiled files to disk.", + "type": "object", + "additionalProperties": false, + "properties": { + "amdContainer": { + "cli": { + "exclude": true + }, + "oneOf": [ + { + "$ref": "#/definitions/AmdContainer" + } + ] + }, + "assetModuleFilename": { + "$ref": "#/definitions/AssetModuleFilename" + }, + "asyncChunks": { + "description": "Enable/disable creating async chunks that are loaded on demand.", + "type": "boolean" + }, + "auxiliaryComment": { + "cli": { + "exclude": true + }, + "oneOf": [ + { + "$ref": "#/definitions/AuxiliaryComment" + } + ] + }, + "charset": { + "$ref": "#/definitions/Charset" + }, + "chunkFilename": { + "$ref": "#/definitions/ChunkFilename" + }, + "chunkFormat": { + "$ref": "#/definitions/ChunkFormat" + }, + "chunkLoadTimeout": { + "$ref": "#/definitions/ChunkLoadTimeout" + }, + "chunkLoading": { + "$ref": "#/definitions/ChunkLoading" + }, + "chunkLoadingGlobal": { + "$ref": "#/definitions/ChunkLoadingGlobal" + }, + "clean": { + "$ref": "#/definitions/Clean" + }, + "compareBeforeEmit": { + "$ref": "#/definitions/CompareBeforeEmit" + }, + "crossOriginLoading": { + "$ref": "#/definitions/CrossOriginLoading" + }, + "cssChunkFilename": { + "$ref": "#/definitions/CssChunkFilename" + }, + "cssFilename": { + "$ref": "#/definitions/CssFilename" + }, + "devtoolFallbackModuleFilenameTemplate": { + "$ref": "#/definitions/DevtoolFallbackModuleFilenameTemplate" + }, + "devtoolModuleFilenameTemplate": { + "$ref": "#/definitions/DevtoolModuleFilenameTemplate" + }, + "devtoolNamespace": { + "$ref": "#/definitions/DevtoolNamespace" + }, + "enabledChunkLoadingTypes": { + "$ref": "#/definitions/EnabledChunkLoadingTypes" + }, + "enabledLibraryTypes": { + "$ref": "#/definitions/EnabledLibraryTypes" + }, + "enabledWasmLoadingTypes": { + "$ref": "#/definitions/EnabledWasmLoadingTypes" + }, + "environment": { + "$ref": "#/definitions/Environment" + }, + "filename": { + "$ref": "#/definitions/Filename" + }, + "globalObject": { + "$ref": "#/definitions/GlobalObject" + }, + "hashDigest": { + "$ref": "#/definitions/HashDigest" + }, + "hashDigestLength": { + "$ref": "#/definitions/HashDigestLength" + }, + "hashFunction": { + "$ref": "#/definitions/HashFunction" + }, + "hashSalt": { + "$ref": "#/definitions/HashSalt" + }, + "hotUpdateChunkFilename": { + "$ref": "#/definitions/HotUpdateChunkFilename" + }, + "hotUpdateGlobal": { + "$ref": "#/definitions/HotUpdateGlobal" + }, + "hotUpdateMainFilename": { + "$ref": "#/definitions/HotUpdateMainFilename" + }, + "ignoreBrowserWarnings": { + "description": "Ignore warnings in the browser.", + "type": "boolean" + }, + "iife": { + "$ref": "#/definitions/Iife" + }, + "importFunctionName": { + "$ref": "#/definitions/ImportFunctionName" + }, + "importMetaName": { + "$ref": "#/definitions/ImportMetaName" + }, + "library": { + "$ref": "#/definitions/Library" + }, + "libraryExport": { + "cli": { + "exclude": true + }, + "oneOf": [ + { + "$ref": "#/definitions/LibraryExport" + } + ] + }, + "libraryTarget": { + "cli": { + "exclude": true + }, + "oneOf": [ + { + "$ref": "#/definitions/LibraryType" + } + ] + }, + "module": { + "$ref": "#/definitions/OutputModule" + }, + "path": { + "$ref": "#/definitions/Path" + }, + "pathinfo": { + "$ref": "#/definitions/Pathinfo" + }, + "publicPath": { + "$ref": "#/definitions/PublicPath" + }, + "scriptType": { + "$ref": "#/definitions/ScriptType" + }, + "sourceMapFilename": { + "$ref": "#/definitions/SourceMapFilename" + }, + "sourcePrefix": { + "$ref": "#/definitions/SourcePrefix" + }, + "strictModuleErrorHandling": { + "$ref": "#/definitions/StrictModuleErrorHandling" + }, + "strictModuleExceptionHandling": { + "$ref": "#/definitions/StrictModuleExceptionHandling" + }, + "trustedTypes": { + "description": "Use a Trusted Types policy to create urls for chunks. 'output.uniqueName' is used a default policy name. Passing a string sets a custom policy name.", + "anyOf": [ + { + "enum": [true] + }, + { + "description": "The name of the Trusted Types policy created by webpack to serve bundle chunks.", + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/TrustedTypes" + } + ] + }, + "umdNamedDefine": { + "cli": { + "exclude": true + }, + "oneOf": [ + { + "$ref": "#/definitions/UmdNamedDefine" + } + ] + }, + "uniqueName": { + "$ref": "#/definitions/UniqueName" + }, + "wasmLoading": { + "$ref": "#/definitions/WasmLoading" + }, + "webassemblyModuleFilename": { + "$ref": "#/definitions/WebassemblyModuleFilename" + }, + "workerChunkLoading": { + "$ref": "#/definitions/ChunkLoading" + }, + "workerPublicPath": { + "$ref": "#/definitions/WorkerPublicPath" + }, + "workerWasmLoading": { + "$ref": "#/definitions/WasmLoading" + } + } + }, + "OutputModule": { + "description": "Output javascript files as module source type.", + "type": "boolean" + }, + "OutputNormalized": { + "description": "Normalized options affecting the output of the compilation. `output` options tell webpack how to write the compiled files to disk.", + "type": "object", + "additionalProperties": false, + "properties": { + "assetModuleFilename": { + "$ref": "#/definitions/AssetModuleFilename" + }, + "asyncChunks": { + "description": "Enable/disable creating async chunks that are loaded on demand.", + "type": "boolean" + }, + "charset": { + "$ref": "#/definitions/Charset" + }, + "chunkFilename": { + "$ref": "#/definitions/ChunkFilename" + }, + "chunkFormat": { + "$ref": "#/definitions/ChunkFormat" + }, + "chunkLoadTimeout": { + "$ref": "#/definitions/ChunkLoadTimeout" + }, + "chunkLoading": { + "$ref": "#/definitions/ChunkLoading" + }, + "chunkLoadingGlobal": { + "$ref": "#/definitions/ChunkLoadingGlobal" + }, + "clean": { + "$ref": "#/definitions/Clean" + }, + "compareBeforeEmit": { + "$ref": "#/definitions/CompareBeforeEmit" + }, + "crossOriginLoading": { + "$ref": "#/definitions/CrossOriginLoading" + }, + "cssChunkFilename": { + "$ref": "#/definitions/CssChunkFilename" + }, + "cssFilename": { + "$ref": "#/definitions/CssFilename" + }, + "devtoolFallbackModuleFilenameTemplate": { + "$ref": "#/definitions/DevtoolFallbackModuleFilenameTemplate" + }, + "devtoolModuleFilenameTemplate": { + "$ref": "#/definitions/DevtoolModuleFilenameTemplate" + }, + "devtoolNamespace": { + "$ref": "#/definitions/DevtoolNamespace" + }, + "enabledChunkLoadingTypes": { + "$ref": "#/definitions/EnabledChunkLoadingTypes" + }, + "enabledLibraryTypes": { + "$ref": "#/definitions/EnabledLibraryTypes" + }, + "enabledWasmLoadingTypes": { + "$ref": "#/definitions/EnabledWasmLoadingTypes" + }, + "environment": { + "$ref": "#/definitions/Environment" + }, + "filename": { + "$ref": "#/definitions/Filename" + }, + "globalObject": { + "$ref": "#/definitions/GlobalObject" + }, + "hashDigest": { + "$ref": "#/definitions/HashDigest" + }, + "hashDigestLength": { + "$ref": "#/definitions/HashDigestLength" + }, + "hashFunction": { + "$ref": "#/definitions/HashFunction" + }, + "hashSalt": { + "$ref": "#/definitions/HashSalt" + }, + "hotUpdateChunkFilename": { + "$ref": "#/definitions/HotUpdateChunkFilename" + }, + "hotUpdateGlobal": { + "$ref": "#/definitions/HotUpdateGlobal" + }, + "hotUpdateMainFilename": { + "$ref": "#/definitions/HotUpdateMainFilename" + }, + "ignoreBrowserWarnings": { + "description": "Ignore warnings in the browser.", + "type": "boolean" + }, + "iife": { + "$ref": "#/definitions/Iife" + }, + "importFunctionName": { + "$ref": "#/definitions/ImportFunctionName" + }, + "importMetaName": { + "$ref": "#/definitions/ImportMetaName" + }, + "library": { + "$ref": "#/definitions/LibraryOptions" + }, + "module": { + "$ref": "#/definitions/OutputModule" + }, + "path": { + "$ref": "#/definitions/Path" + }, + "pathinfo": { + "$ref": "#/definitions/Pathinfo" + }, + "publicPath": { + "$ref": "#/definitions/PublicPath" + }, + "scriptType": { + "$ref": "#/definitions/ScriptType" + }, + "sourceMapFilename": { + "$ref": "#/definitions/SourceMapFilename" + }, + "sourcePrefix": { + "$ref": "#/definitions/SourcePrefix" + }, + "strictModuleErrorHandling": { + "$ref": "#/definitions/StrictModuleErrorHandling" + }, + "strictModuleExceptionHandling": { + "$ref": "#/definitions/StrictModuleExceptionHandling" + }, + "trustedTypes": { + "$ref": "#/definitions/TrustedTypes" + }, + "uniqueName": { + "$ref": "#/definitions/UniqueName" + }, + "wasmLoading": { + "$ref": "#/definitions/WasmLoading" + }, + "webassemblyModuleFilename": { + "$ref": "#/definitions/WebassemblyModuleFilename" + }, + "workerChunkLoading": { + "$ref": "#/definitions/ChunkLoading" + }, + "workerPublicPath": { + "$ref": "#/definitions/WorkerPublicPath" + }, + "workerWasmLoading": { + "$ref": "#/definitions/WasmLoading" + } + }, + "required": [ + "environment", + "enabledChunkLoadingTypes", + "enabledLibraryTypes", + "enabledWasmLoadingTypes" + ] + }, + "Parallelism": { + "description": "The number of parallel processed modules in the compilation.", + "type": "number", + "minimum": 1 + }, + "ParserOptionsByModuleType": { + "description": "Specify options for each parser.", + "type": "object", + "additionalProperties": { + "description": "Options for parsing.", + "type": "object", + "additionalProperties": true + }, + "properties": { + "asset": { + "$ref": "#/definitions/AssetParserOptions" + }, + "asset/inline": { + "$ref": "#/definitions/EmptyParserOptions" + }, + "asset/resource": { + "$ref": "#/definitions/EmptyParserOptions" + }, + "asset/source": { + "$ref": "#/definitions/EmptyParserOptions" + }, + "css": { + "$ref": "#/definitions/CssParserOptions" + }, + "css/auto": { + "$ref": "#/definitions/CssAutoParserOptions" + }, + "css/global": { + "$ref": "#/definitions/CssGlobalParserOptions" + }, + "css/module": { + "$ref": "#/definitions/CssModuleParserOptions" + }, + "javascript": { + "$ref": "#/definitions/JavascriptParserOptions" + }, + "javascript/auto": { + "$ref": "#/definitions/JavascriptParserOptions" + }, + "javascript/dynamic": { + "$ref": "#/definitions/JavascriptParserOptions" + }, + "javascript/esm": { + "$ref": "#/definitions/JavascriptParserOptions" + }, + "json": { + "$ref": "#/definitions/JsonParserOptions" + } + } + }, + "Path": { + "description": "The output directory as **absolute path** (required).", + "type": "string", + "absolutePath": true + }, + "Pathinfo": { + "description": "Include comments with information about the modules.", + "anyOf": [ + { + "enum": ["verbose"] + }, + { + "type": "boolean" + } + ] + }, + "Performance": { + "description": "Configuration for web performance recommendations.", + "anyOf": [ + { + "enum": [false] + }, + { + "$ref": "#/definitions/PerformanceOptions" + } + ] + }, + "PerformanceOptions": { + "description": "Configuration object for web performance recommendations.", + "type": "object", + "additionalProperties": false, + "properties": { + "assetFilter": { + "description": "Filter function to select assets that are checked.", + "instanceof": "Function", + "tsType": "((name: import('../lib/Compilation').Asset['name'], source: import('../lib/Compilation').Asset['source'], assetInfo: import('../lib/Compilation').Asset['info']) => boolean)" + }, + "hints": { + "description": "Sets the format of the hints: warnings, errors or nothing at all.", + "enum": [false, "warning", "error"] + }, + "maxAssetSize": { + "description": "File size limit (in bytes) when exceeded, that webpack will provide performance hints.", + "type": "number" + }, + "maxEntrypointSize": { + "description": "Total size of an entry point (in bytes).", + "type": "number" + } + } + }, + "Plugins": { + "description": "Add additional plugins to the compiler.", + "type": "array", + "items": { + "description": "Plugin of type object or instanceof Function.", + "anyOf": [ + { + "$ref": "#/definitions/Falsy" + }, + { + "$ref": "#/definitions/WebpackPluginInstance" + }, + { + "$ref": "#/definitions/WebpackPluginFunction" + } + ] + } + }, + "Profile": { + "description": "Capture timing information for each module.", + "type": "boolean" + }, + "PublicPath": { + "description": "The 'publicPath' specifies the public URL address of the output files when referenced in a browser.", + "anyOf": [ + { + "enum": ["auto"] + }, + { + "$ref": "#/definitions/RawPublicPath" + } + ] + }, + "RawPublicPath": { + "description": "The 'publicPath' specifies the public URL address of the output files when referenced in a browser.", + "anyOf": [ + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "((pathData: import(\"../lib/Compilation\").PathData, assetInfo?: import(\"../lib/Compilation\").AssetInfo) => string)" + } + ] + }, + "RecordsInputPath": { + "description": "Store compiler state to a json file.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string", + "absolutePath": true + } + ] + }, + "RecordsOutputPath": { + "description": "Load compiler state from a json file.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string", + "absolutePath": true + } + ] + }, + "RecordsPath": { + "description": "Store/Load compiler state from/to a json file. This will result in persistent ids of modules and chunks. An absolute path is expected. `recordsPath` is used for `recordsInputPath` and `recordsOutputPath` if they left undefined.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string", + "absolutePath": true + } + ] + }, + "Resolve": { + "description": "Options for the resolver.", + "oneOf": [ + { + "$ref": "#/definitions/ResolveOptions" + } + ] + }, + "ResolveAlias": { + "description": "Redirect module requests.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Alias configuration.", + "type": "object", + "additionalProperties": false, + "properties": { + "alias": { + "description": "New request.", + "anyOf": [ + { + "description": "Multiple alternative requests.", + "type": "array", + "items": { + "description": "One choice of request.", + "type": "string", + "minLength": 1 + } + }, + { + "description": "Ignore request (replace with empty module).", + "enum": [false] + }, + { + "description": "New request.", + "type": "string", + "minLength": 1 + } + ] + }, + "name": { + "description": "Request to be redirected.", + "type": "string" + }, + "onlyModule": { + "description": "Redirect only exact matching request.", + "type": "boolean" + } + }, + "required": ["alias", "name"] + } + }, + { + "type": "object", + "additionalProperties": { + "description": "New request.", + "anyOf": [ + { + "description": "Multiple alternative requests.", + "type": "array", + "items": { + "description": "One choice of request.", + "type": "string", + "minLength": 1 + } + }, + { + "description": "Ignore request (replace with empty module).", + "enum": [false] + }, + { + "description": "New request.", + "type": "string", + "minLength": 1 + } + ] + } + } + ] + }, + "ResolveLoader": { + "description": "Options for the resolver when resolving loaders.", + "oneOf": [ + { + "$ref": "#/definitions/ResolveOptions" + } + ] + }, + "ResolveOptions": { + "description": "Options object for resolving requests.", + "type": "object", + "additionalProperties": false, + "properties": { + "alias": { + "$ref": "#/definitions/ResolveAlias" + }, + "aliasFields": { + "description": "Fields in the description file (usually package.json) which are used to redirect requests inside the module.", + "type": "array", + "items": { + "description": "Field in the description file (usually package.json) which are used to redirect requests inside the module.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Part of the field path in the description file (usually package.json) which are used to redirect requests inside the module.", + "type": "string", + "minLength": 1 + } + }, + { + "type": "string", + "minLength": 1 + } + ] + } + }, + "byDependency": { + "description": "Extra resolve options per dependency category. Typical categories are \"commonjs\", \"amd\", \"esm\".", + "type": "object", + "additionalProperties": { + "description": "Options object for resolving requests.", + "oneOf": [ + { + "$ref": "#/definitions/ResolveOptions" + } + ] + } + }, + "cache": { + "description": "Enable caching of successfully resolved requests (cache entries are revalidated).", + "type": "boolean" + }, + "cachePredicate": { + "description": "Predicate function to decide which requests should be cached.", + "instanceof": "Function", + "tsType": "((request: import('enhanced-resolve').ResolveRequest) => boolean)" + }, + "cacheWithContext": { + "description": "Include the context information in the cache identifier when caching.", + "type": "boolean" + }, + "conditionNames": { + "description": "Condition names for exports field entry point.", + "type": "array", + "items": { + "description": "Condition names for exports field entry point.", + "type": "string" + } + }, + "descriptionFiles": { + "description": "Filenames used to find a description file (like a package.json).", + "type": "array", + "items": { + "description": "Filename used to find a description file (like a package.json).", + "type": "string", + "minLength": 1 + } + }, + "enforceExtension": { + "description": "Enforce the resolver to use one of the extensions from the extensions option (User must specify requests without extension).", + "type": "boolean" + }, + "exportsFields": { + "description": "Field names from the description file (usually package.json) which are used to provide entry points of a package.", + "type": "array", + "items": { + "description": "Field name from the description file (usually package.json) which is used to provide entry points of a package.", + "type": "string" + } + }, + "extensionAlias": { + "description": "An object which maps extension to extension aliases.", + "type": "object", + "additionalProperties": { + "description": "Extension alias.", + "anyOf": [ + { + "description": "Multiple extensions.", + "type": "array", + "items": { + "description": "Aliased extension.", + "type": "string", + "minLength": 1 + } + }, + { + "description": "Aliased extension.", + "type": "string", + "minLength": 1 + } + ] + } + }, + "extensions": { + "description": "Extensions added to the request when trying to find the file.", + "type": "array", + "items": { + "description": "Extension added to the request when trying to find the file.", + "type": "string" + } + }, + "fallback": { + "description": "Redirect module requests when normal resolving fails.", + "oneOf": [ + { + "$ref": "#/definitions/ResolveAlias" + } + ] + }, + "fileSystem": { + "description": "Filesystem for the resolver.", + "tsType": "(import('../lib/util/fs').InputFileSystem)" + }, + "fullySpecified": { + "description": "Treats the request specified by the user as fully specified, meaning no extensions are added and the mainFiles in directories are not resolved (This doesn't affect requests from mainFields, aliasFields or aliases).", + "type": "boolean" + }, + "importsFields": { + "description": "Field names from the description file (usually package.json) which are used to provide internal request of a package (requests starting with # are considered as internal).", + "type": "array", + "items": { + "description": "Field name from the description file (usually package.json) which is used to provide internal request of a package (requests starting with # are considered as internal).", + "type": "string" + } + }, + "mainFields": { + "description": "Field names from the description file (package.json) which are used to find the default entry point.", + "type": "array", + "items": { + "description": "Field name from the description file (package.json) which are used to find the default entry point.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Part of the field path from the description file (package.json) which are used to find the default entry point.", + "type": "string", + "minLength": 1 + } + }, + { + "type": "string", + "minLength": 1 + } + ] + } + }, + "mainFiles": { + "description": "Filenames used to find the default entry point if there is no description file or main field.", + "type": "array", + "items": { + "description": "Filename used to find the default entry point if there is no description file or main field.", + "type": "string", + "minLength": 1 + } + }, + "modules": { + "description": "Folder names or directory paths where to find modules.", + "type": "array", + "items": { + "description": "Folder name or directory path where to find modules.", + "type": "string", + "minLength": 1 + } + }, + "plugins": { + "description": "Plugins for the resolver.", + "type": "array", + "cli": { + "exclude": true + }, + "items": { + "description": "Plugin of type object or instanceof Function.", + "anyOf": [ + { + "enum": ["..."] + }, + { + "$ref": "#/definitions/Falsy" + }, + { + "$ref": "#/definitions/ResolvePluginInstance" + } + ] + } + }, + "preferAbsolute": { + "description": "Prefer to resolve server-relative URLs (starting with '/') as absolute paths before falling back to resolve in 'resolve.roots'.", + "type": "boolean" + }, + "preferRelative": { + "description": "Prefer to resolve module requests as relative request and fallback to resolving as module.", + "type": "boolean" + }, + "resolver": { + "description": "Custom resolver.", + "tsType": "(import('enhanced-resolve').Resolver)" + }, + "restrictions": { + "description": "A list of resolve restrictions. Resolve results must fulfill all of these restrictions to resolve successfully. Other resolve paths are taken when restrictions are not met.", + "type": "array", + "items": { + "description": "Resolve restriction. Resolve result must fulfill this restriction.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string", + "absolutePath": true, + "minLength": 1 + } + ] + } + }, + "roots": { + "description": "A list of directories in which requests that are server-relative URLs (starting with '/') are resolved.", + "type": "array", + "items": { + "description": "Directory in which requests that are server-relative URLs (starting with '/') are resolved.", + "type": "string" + } + }, + "symlinks": { + "description": "Enable resolving symlinks to the original location.", + "type": "boolean" + }, + "unsafeCache": { + "description": "Enable caching of successfully resolved requests (cache entries are not revalidated).", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "object", + "additionalProperties": true + } + ] + }, + "useSyncFileSystemCalls": { + "description": "Use synchronous filesystem calls for the resolver.", + "type": "boolean" + } + } + }, + "ResolvePluginInstance": { + "description": "Plugin instance.", + "anyOf": [ + { + "type": "object", + "additionalProperties": true, + "properties": { + "apply": { + "description": "The run point of the plugin, required method.", + "instanceof": "Function", + "tsType": "(arg0: import('enhanced-resolve').Resolver) => void" + } + }, + "required": ["apply"] + }, + { + "instanceof": "Function", + "tsType": "((this: import('enhanced-resolve').Resolver, arg1: import('enhanced-resolve').Resolver) => void)" + } + ] + }, + "RuleSetCondition": { + "description": "A condition matcher.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string" + }, + { + "instanceof": "Function", + "tsType": "((value: string) => boolean)" + }, + { + "$ref": "#/definitions/RuleSetLogicalConditions" + }, + { + "$ref": "#/definitions/RuleSetConditions" + } + ] + }, + "RuleSetConditionAbsolute": { + "description": "A condition matcher matching an absolute path.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string", + "absolutePath": true + }, + { + "instanceof": "Function", + "tsType": "((value: string) => boolean)" + }, + { + "$ref": "#/definitions/RuleSetLogicalConditionsAbsolute" + }, + { + "$ref": "#/definitions/RuleSetConditionsAbsolute" + } + ] + }, + "RuleSetConditionOrConditions": { + "description": "One or multiple rule conditions.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "$ref": "#/definitions/RuleSetCondition" + }, + { + "$ref": "#/definitions/RuleSetConditions" + } + ] + }, + "RuleSetConditionOrConditionsAbsolute": { + "description": "One or multiple rule conditions matching an absolute path.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "$ref": "#/definitions/RuleSetConditionAbsolute" + }, + { + "$ref": "#/definitions/RuleSetConditionsAbsolute" + } + ] + }, + "RuleSetConditions": { + "description": "A list of rule conditions.", + "type": "array", + "items": { + "description": "A rule condition.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetCondition" + } + ] + } + }, + "RuleSetConditionsAbsolute": { + "description": "A list of rule conditions matching an absolute path.", + "type": "array", + "items": { + "description": "A rule condition matching an absolute path.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionAbsolute" + } + ] + } + }, + "RuleSetLoader": { + "description": "A loader request.", + "type": "string", + "minLength": 1 + }, + "RuleSetLoaderOptions": { + "description": "Options passed to a loader.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "object" + } + ] + }, + "RuleSetLogicalConditions": { + "description": "Logic operators used in a condition matcher.", + "type": "object", + "additionalProperties": false, + "properties": { + "and": { + "description": "Logical AND.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditions" + } + ] + }, + "not": { + "description": "Logical NOT.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetCondition" + } + ] + }, + "or": { + "description": "Logical OR.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditions" + } + ] + } + } + }, + "RuleSetLogicalConditionsAbsolute": { + "description": "Logic operators used in a condition matcher.", + "type": "object", + "additionalProperties": false, + "properties": { + "and": { + "description": "Logical AND.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionsAbsolute" + } + ] + }, + "not": { + "description": "Logical NOT.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionAbsolute" + } + ] + }, + "or": { + "description": "Logical OR.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionsAbsolute" + } + ] + } + } + }, + "RuleSetRule": { + "description": "A rule description with conditions and effects for modules.", + "type": "object", + "additionalProperties": false, + "properties": { + "assert": { + "description": "Match on import assertions of the dependency.", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + }, + "compiler": { + "description": "Match the child compiler name.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + ] + }, + "dependency": { + "description": "Match dependency type.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + ] + }, + "descriptionData": { + "description": "Match values of properties in the description file (usually package.json).", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + }, + "enforce": { + "description": "Enforce this rule as pre or post step.", + "enum": ["pre", "post"] + }, + "exclude": { + "description": "Shortcut for resource.exclude.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" + } + ] + }, + "generator": { + "description": "The options for the module generator.", + "type": "object" + }, + "include": { + "description": "Shortcut for resource.include.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" + } + ] + }, + "issuer": { + "description": "Match the issuer of the module (The module pointing to this module).", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" + } + ] + }, + "issuerLayer": { + "description": "Match layer of the issuer of this module (The module pointing to this module).", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + ] + }, + "layer": { + "description": "Specifies the layer in which the module should be placed in.", + "type": "string" + }, + "loader": { + "description": "Shortcut for use.loader.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetLoader" + } + ] + }, + "mimetype": { + "description": "Match module mimetype when load from Data URI.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + ] + }, + "oneOf": { + "description": "Only execute the first matching rule in this array.", + "type": "array", + "items": { + "description": "A rule.", + "anyOf": [ + { + "$ref": "#/definitions/Falsy" + }, + { + "$ref": "#/definitions/RuleSetRule" + } + ] + } + }, + "options": { + "description": "Shortcut for use.options.", + "cli": { + "exclude": true + }, + "oneOf": [ + { + "$ref": "#/definitions/RuleSetLoaderOptions" + } + ] + }, + "parser": { + "description": "Options for parsing.", + "type": "object", + "additionalProperties": true + }, + "realResource": { + "description": "Match the real resource path of the module.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" + } + ] + }, + "resolve": { + "description": "Options for the resolver.", + "type": "object", + "oneOf": [ + { + "$ref": "#/definitions/ResolveOptions" + } + ] + }, + "resource": { + "description": "Match the resource path of the module.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" + } + ] + }, + "resourceFragment": { + "description": "Match the resource fragment of the module.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + ] + }, + "resourceQuery": { + "description": "Match the resource query of the module.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + ] + }, + "rules": { + "description": "Match and execute these rules when this rule is matched.", + "type": "array", + "items": { + "description": "A rule.", + "anyOf": [ + { + "$ref": "#/definitions/Falsy" + }, + { + "$ref": "#/definitions/RuleSetRule" + } + ] + } + }, + "scheme": { + "description": "Match module scheme.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + ] + }, + "sideEffects": { + "description": "Flags a module as with or without side effects.", + "type": "boolean" + }, + "test": { + "description": "Shortcut for resource.test.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetConditionOrConditionsAbsolute" + } + ] + }, + "type": { + "description": "Module type to use for the module.", + "type": "string" + }, + "use": { + "description": "Modifiers applied to the module when rule is matched.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetUse" + } + ] + }, + "with": { + "description": "Match on import attributes of the dependency.", + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/RuleSetConditionOrConditions" + } + } + } + }, + "RuleSetRules": { + "description": "A list of rules.", + "type": "array", + "items": { + "description": "A rule.", + "anyOf": [ + { + "cli": { + "exclude": true + }, + "enum": ["..."] + }, + { + "$ref": "#/definitions/Falsy" + }, + { + "$ref": "#/definitions/RuleSetRule" + } + ] + } + }, + "RuleSetUse": { + "description": "A list of descriptions of loaders applied.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "An use item.", + "anyOf": [ + { + "$ref": "#/definitions/Falsy" + }, + { + "$ref": "#/definitions/RuleSetUseItem" + } + ] + } + }, + { + "$ref": "#/definitions/RuleSetUseFunction" + }, + { + "$ref": "#/definitions/RuleSetUseItem" + } + ] + }, + "RuleSetUseFunction": { + "description": "The function is called on each data and return rule set item.", + "instanceof": "Function", + "tsType": "((data: import('../lib/rules/RuleSetCompiler').EffectData) => (RuleSetUseItem | (Falsy | RuleSetUseItem)[]))" + }, + "RuleSetUseItem": { + "description": "A description of an applied loader.", + "anyOf": [ + { + "type": "object", + "additionalProperties": false, + "properties": { + "ident": { + "description": "Unique loader options identifier.", + "type": "string" + }, + "loader": { + "description": "Loader name.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetLoader" + } + ] + }, + "options": { + "description": "Loader options.", + "oneOf": [ + { + "$ref": "#/definitions/RuleSetLoaderOptions" + } + ] + } + } + }, + { + "$ref": "#/definitions/RuleSetUseFunction" + }, + { + "$ref": "#/definitions/RuleSetLoader" + } + ] + }, + "ScriptType": { + "description": "This option enables loading async chunks via a custom script type, such as script type=\"module\".", + "enum": [false, "text/javascript", "module"] + }, + "SnapshotOptions": { + "description": "Options affecting how file system snapshots are created and validated.", + "type": "object", + "additionalProperties": false, + "properties": { + "buildDependencies": { + "description": "Options for snapshotting build dependencies to determine if the whole cache need to be invalidated.", + "type": "object", + "additionalProperties": false, + "properties": { + "hash": { + "description": "Use hashes of the content of the files/directories to determine invalidation.", + "type": "boolean" + }, + "timestamp": { + "description": "Use timestamps of the files/directories to determine invalidation.", + "type": "boolean" + } + } + }, + "immutablePaths": { + "description": "List of paths that are managed by a package manager and contain a version or hash in its path so all files are immutable.", + "type": "array", + "items": { + "description": "List of paths that are managed by a package manager and contain a version or hash in its path so all files are immutable.", + "anyOf": [ + { + "description": "A RegExp matching an immutable directory (usually a package manager cache directory, including the tailing slash)", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "A path to an immutable directory (usually a package manager cache directory).", + "type": "string", + "absolutePath": true, + "minLength": 1 + } + ] + } + }, + "managedPaths": { + "description": "List of paths that are managed by a package manager and can be trusted to not be modified otherwise.", + "type": "array", + "items": { + "description": "List of paths that are managed by a package manager and can be trusted to not be modified otherwise.", + "anyOf": [ + { + "description": "A RegExp matching a managed directory (usually a node_modules directory, including the tailing slash)", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "A path to a managed directory (usually a node_modules directory).", + "type": "string", + "absolutePath": true, + "minLength": 1 + } + ] + } + }, + "module": { + "description": "Options for snapshotting dependencies of modules to determine if they need to be built again.", + "type": "object", + "additionalProperties": false, + "properties": { + "hash": { + "description": "Use hashes of the content of the files/directories to determine invalidation.", + "type": "boolean" + }, + "timestamp": { + "description": "Use timestamps of the files/directories to determine invalidation.", + "type": "boolean" + } + } + }, + "resolve": { + "description": "Options for snapshotting dependencies of request resolving to determine if requests need to be re-resolved.", + "type": "object", + "additionalProperties": false, + "properties": { + "hash": { + "description": "Use hashes of the content of the files/directories to determine invalidation.", + "type": "boolean" + }, + "timestamp": { + "description": "Use timestamps of the files/directories to determine invalidation.", + "type": "boolean" + } + } + }, + "resolveBuildDependencies": { + "description": "Options for snapshotting the resolving of build dependencies to determine if the build dependencies need to be re-resolved.", + "type": "object", + "additionalProperties": false, + "properties": { + "hash": { + "description": "Use hashes of the content of the files/directories to determine invalidation.", + "type": "boolean" + }, + "timestamp": { + "description": "Use timestamps of the files/directories to determine invalidation.", + "type": "boolean" + } + } + }, + "unmanagedPaths": { + "description": "List of paths that are not managed by a package manager and the contents are subject to change.", + "type": "array", + "items": { + "description": "List of paths that are not managed by a package manager and the contents are subject to change.", + "anyOf": [ + { + "description": "A RegExp matching an unmanaged directory.", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "A path to an unmanaged directory.", + "type": "string", + "absolutePath": true, + "minLength": 1 + } + ] + } + } + } + }, + "SourceMapFilename": { + "description": "The filename of the SourceMaps for the JavaScript files. They are inside the 'output.path' directory.", + "type": "string", + "absolutePath": false + }, + "SourcePrefix": { + "description": "Prefixes every line of the source in the bundle with this string.", + "type": "string" + }, + "StatsOptions": { + "description": "Stats options object.", + "type": "object", + "additionalProperties": false, + "properties": { + "all": { + "description": "Fallback value for stats options when an option is not defined (has precedence over local webpack defaults).", + "type": "boolean" + }, + "assets": { + "description": "Add assets information.", + "type": "boolean" + }, + "assetsSort": { + "description": "Sort the assets by that field.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string" + } + ] + }, + "assetsSpace": { + "description": "Space to display assets (groups will be collapsed to fit this space).", + "type": "number" + }, + "builtAt": { + "description": "Add built at time information.", + "type": "boolean" + }, + "cached": { + "description": "Add information about cached (not built) modules (deprecated: use 'cachedModules' instead).", + "type": "boolean" + }, + "cachedAssets": { + "description": "Show cached assets (setting this to `false` only shows emitted files).", + "type": "boolean" + }, + "cachedModules": { + "description": "Add information about cached (not built) modules.", + "type": "boolean" + }, + "children": { + "description": "Add children information.", + "type": "boolean" + }, + "chunkGroupAuxiliary": { + "description": "Display auxiliary assets in chunk groups.", + "type": "boolean" + }, + "chunkGroupChildren": { + "description": "Display children of chunk groups.", + "type": "boolean" + }, + "chunkGroupMaxAssets": { + "description": "Limit of assets displayed in chunk groups.", + "type": "number" + }, + "chunkGroups": { + "description": "Display all chunk groups with the corresponding bundles.", + "type": "boolean" + }, + "chunkModules": { + "description": "Add built modules information to chunk information.", + "type": "boolean" + }, + "chunkModulesSpace": { + "description": "Space to display chunk modules (groups will be collapsed to fit this space, value is in number of modules/group).", + "type": "number" + }, + "chunkOrigins": { + "description": "Add the origins of chunks and chunk merging info.", + "type": "boolean" + }, + "chunkRelations": { + "description": "Add information about parent, children and sibling chunks to chunk information.", + "type": "boolean" + }, + "chunks": { + "description": "Add chunk information.", + "type": "boolean" + }, + "chunksSort": { + "description": "Sort the chunks by that field.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string" + } + ] + }, + "colors": { + "description": "Enables/Disables colorful output.", + "anyOf": [ + { + "description": "Enables/Disables colorful output.", + "type": "boolean" + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "bold": { + "description": "Custom color for bold text.", + "type": "string" + }, + "cyan": { + "description": "Custom color for cyan text.", + "type": "string" + }, + "green": { + "description": "Custom color for green text.", + "type": "string" + }, + "magenta": { + "description": "Custom color for magenta text.", + "type": "string" + }, + "red": { + "description": "Custom color for red text.", + "type": "string" + }, + "yellow": { + "description": "Custom color for yellow text.", + "type": "string" + } + } + } + ] + }, + "context": { + "description": "Context directory for request shortening.", + "type": "string", + "absolutePath": true + }, + "dependentModules": { + "description": "Show chunk modules that are dependencies of other modules of the chunk.", + "type": "boolean" + }, + "depth": { + "description": "Add module depth in module graph.", + "type": "boolean" + }, + "entrypoints": { + "description": "Display the entry points with the corresponding bundles.", + "anyOf": [ + { + "enum": ["auto"] + }, + { + "type": "boolean" + } + ] + }, + "env": { + "description": "Add --env information.", + "type": "boolean" + }, + "errorCause": { + "description": "Add cause to errors.", + "anyOf": [ + { + "enum": ["auto"] + }, + { + "type": "boolean" + } + ] + }, + "errorDetails": { + "description": "Add details to errors (like resolving log).", + "anyOf": [ + { + "enum": ["auto"] + }, + { + "type": "boolean" + } + ] + }, + "errorErrors": { + "description": "Add nested errors to errors (like in AggregateError).", + "anyOf": [ + { + "enum": ["auto"] + }, + { + "type": "boolean" + } + ] + }, + "errorStack": { + "description": "Add internal stack trace to errors.", + "type": "boolean" + }, + "errors": { + "description": "Add errors.", + "type": "boolean" + }, + "errorsCount": { + "description": "Add errors count.", + "type": "boolean" + }, + "errorsSpace": { + "description": "Space to display errors (value is in number of lines).", + "type": "number" + }, + "exclude": { + "description": "Please use excludeModules instead.", + "cli": { + "exclude": true + }, + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "#/definitions/ModuleFilterTypes" + } + ] + }, + "excludeAssets": { + "description": "Suppress assets that match the specified filters. Filters can be Strings, RegExps or Functions.", + "oneOf": [ + { + "$ref": "#/definitions/AssetFilterTypes" + } + ] + }, + "excludeModules": { + "description": "Suppress modules that match the specified filters. Filters can be Strings, RegExps, Booleans or Functions.", + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "#/definitions/ModuleFilterTypes" + } + ] + }, + "groupAssetsByChunk": { + "description": "Group assets by how their are related to chunks.", + "type": "boolean" + }, + "groupAssetsByEmitStatus": { + "description": "Group assets by their status (emitted, compared for emit or cached).", + "type": "boolean" + }, + "groupAssetsByExtension": { + "description": "Group assets by their extension.", + "type": "boolean" + }, + "groupAssetsByInfo": { + "description": "Group assets by their asset info (immutable, development, hotModuleReplacement, etc).", + "type": "boolean" + }, + "groupAssetsByPath": { + "description": "Group assets by their path.", + "type": "boolean" + }, + "groupModulesByAttributes": { + "description": "Group modules by their attributes (errors, warnings, assets, optional, orphan, or dependent).", + "type": "boolean" + }, + "groupModulesByCacheStatus": { + "description": "Group modules by their status (cached or built and cacheable).", + "type": "boolean" + }, + "groupModulesByExtension": { + "description": "Group modules by their extension.", + "type": "boolean" + }, + "groupModulesByLayer": { + "description": "Group modules by their layer.", + "type": "boolean" + }, + "groupModulesByPath": { + "description": "Group modules by their path.", + "type": "boolean" + }, + "groupModulesByType": { + "description": "Group modules by their type.", + "type": "boolean" + }, + "groupReasonsByOrigin": { + "description": "Group reasons by their origin module.", + "type": "boolean" + }, + "hash": { + "description": "Add the hash of the compilation.", + "type": "boolean" + }, + "ids": { + "description": "Add ids.", + "type": "boolean" + }, + "logging": { + "description": "Add logging output.", + "anyOf": [ + { + "description": "Specify log level of logging output.", + "enum": ["none", "error", "warn", "info", "log", "verbose"] + }, + { + "description": "Enable/disable logging output (`true`: shows normal logging output, loglevel: log).", + "type": "boolean" + } + ] + }, + "loggingDebug": { + "description": "Include debug logging of specified loggers (i. e. for plugins or loaders). Filters can be Strings, RegExps or Functions.", + "anyOf": [ + { + "description": "Enable/Disable debug logging for all loggers.", + "type": "boolean" + }, + { + "$ref": "#/definitions/FilterTypes" + } + ] + }, + "loggingTrace": { + "description": "Add stack traces to logging output.", + "type": "boolean" + }, + "moduleAssets": { + "description": "Add information about assets inside modules.", + "type": "boolean" + }, + "moduleTrace": { + "description": "Add dependencies and origin of warnings/errors.", + "type": "boolean" + }, + "modules": { + "description": "Add built modules information.", + "type": "boolean" + }, + "modulesSort": { + "description": "Sort the modules by that field.", + "anyOf": [ + { + "enum": [false] + }, + { + "type": "string" + } + ] + }, + "modulesSpace": { + "description": "Space to display modules (groups will be collapsed to fit this space, value is in number of modules/groups).", + "type": "number" + }, + "nestedModules": { + "description": "Add information about modules nested in other modules (like with module concatenation).", + "type": "boolean" + }, + "nestedModulesSpace": { + "description": "Space to display modules nested within other modules (groups will be collapsed to fit this space, value is in number of modules/group).", + "type": "number" + }, + "optimizationBailout": { + "description": "Show reasons why optimization bailed out for modules.", + "type": "boolean" + }, + "orphanModules": { + "description": "Add information about orphan modules.", + "type": "boolean" + }, + "outputPath": { + "description": "Add output path information.", + "type": "boolean" + }, + "performance": { + "description": "Add performance hint flags.", + "type": "boolean" + }, + "preset": { + "description": "Preset for the default values.", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string" + } + ] + }, + "providedExports": { + "description": "Show exports provided by modules.", + "type": "boolean" + }, + "publicPath": { + "description": "Add public path information.", + "type": "boolean" + }, + "reasons": { + "description": "Add information about the reasons why modules are included.", + "type": "boolean" + }, + "reasonsSpace": { + "description": "Space to display reasons (groups will be collapsed to fit this space).", + "type": "number" + }, + "relatedAssets": { + "description": "Add information about assets that are related to other assets (like SourceMaps for assets).", + "type": "boolean" + }, + "runtime": { + "description": "Add information about runtime modules (deprecated: use 'runtimeModules' instead).", + "type": "boolean" + }, + "runtimeModules": { + "description": "Add information about runtime modules.", + "type": "boolean" + }, + "source": { + "description": "Add the source code of modules.", + "type": "boolean" + }, + "timings": { + "description": "Add timing information.", + "type": "boolean" + }, + "usedExports": { + "description": "Show exports used by modules.", + "type": "boolean" + }, + "version": { + "description": "Add webpack version information.", + "type": "boolean" + }, + "warnings": { + "description": "Add warnings.", + "type": "boolean" + }, + "warningsCount": { + "description": "Add warnings count.", + "type": "boolean" + }, + "warningsFilter": { + "description": "Suppress listing warnings that match the specified filters (they will still be counted). Filters can be Strings, RegExps or Functions.", + "oneOf": [ + { + "$ref": "#/definitions/WarningFilterTypes" + } + ] + }, + "warningsSpace": { + "description": "Space to display warnings (value is in number of lines).", + "type": "number" + } + } + }, + "StatsValue": { + "description": "Stats options object or preset name.", + "anyOf": [ + { + "enum": [ + "none", + "summary", + "errors-only", + "errors-warnings", + "minimal", + "normal", + "detailed", + "verbose" + ] + }, + { + "type": "boolean" + }, + { + "$ref": "#/definitions/StatsOptions" + } + ] + }, + "StrictModuleErrorHandling": { + "description": "Handles error in module loading correctly at a performance cost. This will handle module error compatible with the EcmaScript Modules spec.", + "type": "boolean" + }, + "StrictModuleExceptionHandling": { + "description": "Handles exceptions in module loading correctly at a performance cost (Deprecated). This will handle module error compatible with the Node.js CommonJS way.", + "type": "boolean" + }, + "Target": { + "description": "Environment to build for. An array of environments to build for all of them when possible.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Environment to build for.", + "type": "string", + "minLength": 1 + }, + "minItems": 1 + }, + { + "enum": [false] + }, + { + "type": "string", + "minLength": 1 + } + ] + }, + "TrustedTypes": { + "description": "Use a Trusted Types policy to create urls for chunks.", + "type": "object", + "additionalProperties": false, + "properties": { + "onPolicyCreationFailure": { + "description": "If the call to `trustedTypes.createPolicy(...)` fails -- e.g., due to the policy name missing from the CSP `trusted-types` list, or it being a duplicate name, etc. -- controls whether to continue with loading in the hope that `require-trusted-types-for 'script'` isn't enforced yet, versus fail immediately. Default behavior is 'stop'.", + "enum": ["continue", "stop"] + }, + "policyName": { + "description": "The name of the Trusted Types policy created by webpack to serve bundle chunks.", + "type": "string", + "minLength": 1 + } + } + }, + "UmdNamedDefine": { + "description": "If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module.", + "type": "boolean" + }, + "UniqueName": { + "description": "A unique name of the webpack build to avoid multiple webpack runtimes to conflict when using globals.", + "type": "string", + "minLength": 1 + }, + "WarningFilterItemTypes": { + "description": "Filtering value, regexp or function.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string", + "absolutePath": false + }, + { + "instanceof": "Function", + "tsType": "((warning: import('../lib/stats/DefaultStatsFactoryPlugin').StatsError, value: string) => boolean)" + } + ] + }, + "WarningFilterTypes": { + "description": "Filtering warnings.", + "cli": { + "helper": true + }, + "anyOf": [ + { + "type": "array", + "items": { + "description": "Rule to filter.", + "cli": { + "helper": true + }, + "oneOf": [ + { + "$ref": "#/definitions/WarningFilterItemTypes" + } + ] + } + }, + { + "$ref": "#/definitions/WarningFilterItemTypes" + } + ] + }, + "WasmLoading": { + "description": "The method of loading WebAssembly Modules (methods included by default are 'fetch' (web/WebWorker), 'async-node' (node.js), but others might be added by plugins).", + "anyOf": [ + { + "enum": [false] + }, + { + "$ref": "#/definitions/WasmLoadingType" + } + ] + }, + "WasmLoadingType": { + "description": "The method of loading WebAssembly Modules (methods included by default are 'fetch' (web/WebWorker), 'async-node' (node.js), but others might be added by plugins).", + "anyOf": [ + { + "enum": ["fetch", "async-node"] + }, + { + "type": "string" + } + ] + }, + "Watch": { + "description": "Enter watch mode, which rebuilds on file change.", + "type": "boolean" + }, + "WatchOptions": { + "description": "Options for the watcher.", + "type": "object", + "additionalProperties": false, + "properties": { + "aggregateTimeout": { + "description": "Delay the rebuilt after the first change. Value is a time in ms.", + "type": "number" + }, + "followSymlinks": { + "description": "Resolve symlinks and watch symlink and real file. This is usually not needed as webpack already resolves symlinks ('resolve.symlinks').", + "type": "boolean" + }, + "ignored": { + "description": "Ignore some files from watching (glob pattern or regexp).", + "anyOf": [ + { + "type": "array", + "items": { + "description": "A glob pattern for files that should be ignored from watching.", + "type": "string", + "minLength": 1 + } + }, + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "description": "A single glob pattern for files that should be ignored from watching.", + "type": "string", + "minLength": 1 + } + ] + }, + "poll": { + "description": "Enable polling mode for watching.", + "anyOf": [ + { + "description": "`number`: use polling with specified interval.", + "type": "number" + }, + { + "description": "`true`: use polling.", + "type": "boolean" + } + ] + }, + "stdin": { + "description": "Stop watching when stdin stream has ended.", + "type": "boolean" + } + } + }, + "WebassemblyModuleFilename": { + "description": "The filename of WebAssembly modules as relative path inside the 'output.path' directory.", + "type": "string", + "absolutePath": false + }, + "WebpackOptionsNormalized": { + "description": "Normalized webpack options object.", + "type": "object", + "additionalProperties": false, + "properties": { + "amd": { + "$ref": "#/definitions/Amd" + }, + "bail": { + "$ref": "#/definitions/Bail" + }, + "cache": { + "$ref": "#/definitions/CacheOptionsNormalized" + }, + "context": { + "$ref": "#/definitions/Context" + }, + "dependencies": { + "$ref": "#/definitions/Dependencies" + }, + "devServer": { + "$ref": "#/definitions/DevServer" + }, + "devtool": { + "$ref": "#/definitions/DevTool" + }, + "entry": { + "$ref": "#/definitions/EntryNormalized" + }, + "experiments": { + "$ref": "#/definitions/ExperimentsNormalized" + }, + "externals": { + "$ref": "#/definitions/Externals" + }, + "externalsPresets": { + "$ref": "#/definitions/ExternalsPresets" + }, + "externalsType": { + "$ref": "#/definitions/ExternalsType" + }, + "ignoreWarnings": { + "$ref": "#/definitions/IgnoreWarningsNormalized" + }, + "infrastructureLogging": { + "$ref": "#/definitions/InfrastructureLogging" + }, + "loader": { + "$ref": "#/definitions/Loader" + }, + "mode": { + "$ref": "#/definitions/Mode" + }, + "module": { + "$ref": "#/definitions/ModuleOptionsNormalized" + }, + "name": { + "$ref": "#/definitions/Name" + }, + "node": { + "$ref": "#/definitions/Node" + }, + "optimization": { + "$ref": "#/definitions/OptimizationNormalized" + }, + "output": { + "$ref": "#/definitions/OutputNormalized" + }, + "parallelism": { + "$ref": "#/definitions/Parallelism" + }, + "performance": { + "$ref": "#/definitions/Performance" + }, + "plugins": { + "$ref": "#/definitions/Plugins" + }, + "profile": { + "$ref": "#/definitions/Profile" + }, + "recordsInputPath": { + "$ref": "#/definitions/RecordsInputPath" + }, + "recordsOutputPath": { + "$ref": "#/definitions/RecordsOutputPath" + }, + "resolve": { + "$ref": "#/definitions/Resolve" + }, + "resolveLoader": { + "$ref": "#/definitions/ResolveLoader" + }, + "snapshot": { + "$ref": "#/definitions/SnapshotOptions" + }, + "stats": { + "$ref": "#/definitions/StatsValue" + }, + "target": { + "$ref": "#/definitions/Target" + }, + "watch": { + "$ref": "#/definitions/Watch" + }, + "watchOptions": { + "$ref": "#/definitions/WatchOptions" + } + }, + "required": [ + "cache", + "snapshot", + "entry", + "experiments", + "externals", + "externalsPresets", + "infrastructureLogging", + "module", + "node", + "optimization", + "output", + "plugins", + "resolve", + "resolveLoader", + "stats", + "watchOptions" + ] + }, + "WebpackPluginFunction": { + "description": "Function acting as plugin.", + "instanceof": "Function", + "tsType": "(this: import('../lib/Compiler'), compiler: import('../lib/Compiler')) => void" + }, + "WebpackPluginInstance": { + "description": "Plugin instance.", + "type": "object", + "additionalProperties": true, + "properties": { + "apply": { + "description": "The run point of the plugin, required method.", + "instanceof": "Function", + "tsType": "(compiler: import('../lib/Compiler')) => void" + } + }, + "required": ["apply"] + }, + "WorkerPublicPath": { + "description": "Worker public path. Much like the public path, this sets the location where the worker script file is intended to be found. If not set, webpack will use the publicPath. Don't set this option unless your worker scripts are located at a different path from your other script files.", + "type": "string" + } + }, + "title": "WebpackOptions", + "description": "Options object as provided by the user.", + "type": "object", + "additionalProperties": false, + "properties": { + "amd": { + "$ref": "#/definitions/Amd" + }, + "bail": { + "$ref": "#/definitions/Bail" + }, + "cache": { + "$ref": "#/definitions/CacheOptions" + }, + "context": { + "$ref": "#/definitions/Context" + }, + "dependencies": { + "$ref": "#/definitions/Dependencies" + }, + "devServer": { + "$ref": "#/definitions/DevServer" + }, + "devtool": { + "$ref": "#/definitions/DevTool" + }, + "entry": { + "$ref": "#/definitions/Entry" + }, + "experiments": { + "$ref": "#/definitions/Experiments" + }, + "extends": { + "$ref": "#/definitions/Extends" + }, + "externals": { + "$ref": "#/definitions/Externals" + }, + "externalsPresets": { + "$ref": "#/definitions/ExternalsPresets" + }, + "externalsType": { + "$ref": "#/definitions/ExternalsType" + }, + "ignoreWarnings": { + "$ref": "#/definitions/IgnoreWarnings" + }, + "infrastructureLogging": { + "$ref": "#/definitions/InfrastructureLogging" + }, + "loader": { + "$ref": "#/definitions/Loader" + }, + "mode": { + "$ref": "#/definitions/Mode" + }, + "module": { + "$ref": "#/definitions/ModuleOptions" + }, + "name": { + "$ref": "#/definitions/Name" + }, + "node": { + "$ref": "#/definitions/Node" + }, + "optimization": { + "$ref": "#/definitions/Optimization" + }, + "output": { + "$ref": "#/definitions/Output" + }, + "parallelism": { + "$ref": "#/definitions/Parallelism" + }, + "performance": { + "$ref": "#/definitions/Performance" + }, + "plugins": { + "$ref": "#/definitions/Plugins" + }, + "profile": { + "$ref": "#/definitions/Profile" + }, + "recordsInputPath": { + "$ref": "#/definitions/RecordsInputPath" + }, + "recordsOutputPath": { + "$ref": "#/definitions/RecordsOutputPath" + }, + "recordsPath": { + "$ref": "#/definitions/RecordsPath" + }, + "resolve": { + "$ref": "#/definitions/Resolve" + }, + "resolveLoader": { + "$ref": "#/definitions/ResolveLoader" + }, + "snapshot": { + "$ref": "#/definitions/SnapshotOptions" + }, + "stats": { + "$ref": "#/definitions/StatsValue" + }, + "target": { + "$ref": "#/definitions/Target" + }, + "watch": { + "$ref": "#/definitions/Watch" + }, + "watchOptions": { + "$ref": "#/definitions/WatchOptions" + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/_container.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/_container.json new file mode 100644 index 0000000000000000000000000000000000000000..e333f1db0c5517973709dcd40fc9d8da8176d2b2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/_container.json @@ -0,0 +1,155 @@ +{ + "definitions": { + "Exposes": { + "description": "Modules that should be exposed by this container. When provided, property name is used as public name, otherwise public name is automatically inferred from request.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Modules that should be exposed by this container.", + "anyOf": [ + { + "$ref": "#/definitions/ExposesItem" + }, + { + "$ref": "#/definitions/ExposesObject" + } + ] + } + }, + { + "$ref": "#/definitions/ExposesObject" + } + ] + }, + "ExposesConfig": { + "description": "Advanced configuration for modules that should be exposed by this container.", + "type": "object", + "additionalProperties": false, + "properties": { + "import": { + "description": "Request to a module that should be exposed by this container.", + "anyOf": [ + { + "$ref": "#/definitions/ExposesItem" + }, + { + "$ref": "#/definitions/ExposesItems" + } + ] + }, + "name": { + "description": "Custom chunk name for the exposed module.", + "type": "string" + } + }, + "required": ["import"] + }, + "ExposesItem": { + "description": "Module that should be exposed by this container.", + "type": "string", + "minLength": 1 + }, + "ExposesItems": { + "description": "Modules that should be exposed by this container.", + "type": "array", + "items": { + "$ref": "#/definitions/ExposesItem" + } + }, + "ExposesObject": { + "description": "Modules that should be exposed by this container. Property names are used as public paths.", + "type": "object", + "additionalProperties": { + "description": "Modules that should be exposed by this container.", + "anyOf": [ + { + "$ref": "#/definitions/ExposesConfig" + }, + { + "$ref": "#/definitions/ExposesItem" + }, + { + "$ref": "#/definitions/ExposesItems" + } + ] + } + }, + "Remotes": { + "description": "Container locations and request scopes from which modules should be resolved and loaded at runtime. When provided, property name is used as request scope, otherwise request scope is automatically inferred from container location.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Container locations and request scopes from which modules should be resolved and loaded at runtime.", + "anyOf": [ + { + "$ref": "#/definitions/RemotesItem" + }, + { + "$ref": "#/definitions/RemotesObject" + } + ] + } + }, + { + "$ref": "#/definitions/RemotesObject" + } + ] + }, + "RemotesConfig": { + "description": "Advanced configuration for container locations from which modules should be resolved and loaded at runtime.", + "type": "object", + "additionalProperties": false, + "properties": { + "external": { + "description": "Container locations from which modules should be resolved and loaded at runtime.", + "anyOf": [ + { + "$ref": "#/definitions/RemotesItem" + }, + { + "$ref": "#/definitions/RemotesItems" + } + ] + }, + "shareScope": { + "description": "The name of the share scope shared with this remote.", + "type": "string", + "minLength": 1 + } + }, + "required": ["external"] + }, + "RemotesItem": { + "description": "Container location from which modules should be resolved and loaded at runtime.", + "type": "string", + "minLength": 1 + }, + "RemotesItems": { + "description": "Container locations from which modules should be resolved and loaded at runtime.", + "type": "array", + "items": { + "$ref": "#/definitions/RemotesItem" + } + }, + "RemotesObject": { + "description": "Container locations from which modules should be resolved and loaded at runtime. Property names are used as request scopes.", + "type": "object", + "additionalProperties": { + "description": "Container locations from which modules should be resolved and loaded at runtime.", + "anyOf": [ + { + "$ref": "#/definitions/RemotesConfig" + }, + { + "$ref": "#/definitions/RemotesItem" + }, + { + "$ref": "#/definitions/RemotesItems" + } + ] + } + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/_sharing.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/_sharing.json new file mode 100644 index 0000000000000000000000000000000000000000..02c1eedb7051adf7e3c0d8d2ca269896c6ae7148 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/_sharing.json @@ -0,0 +1,118 @@ +{ + "definitions": { + "Shared": { + "description": "Modules that should be shared in the share scope. When provided, property names are used to match requested modules in this compilation.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "Modules that should be shared in the share scope.", + "anyOf": [ + { + "$ref": "#/definitions/SharedItem" + }, + { + "$ref": "#/definitions/SharedObject" + } + ] + } + }, + { + "$ref": "#/definitions/SharedObject" + } + ] + }, + "SharedConfig": { + "description": "Advanced configuration for modules that should be shared in the share scope.", + "type": "object", + "additionalProperties": false, + "properties": { + "eager": { + "description": "Include the provided and fallback module directly instead behind an async request. This allows to use this shared module in initial load too. All possible shared modules need to be eager too.", + "type": "boolean" + }, + "import": { + "description": "Provided module that should be provided to share scope. Also acts as fallback module if no shared module is found in share scope or version isn't valid. Defaults to the property name.", + "anyOf": [ + { + "description": "No provided or fallback module.", + "enum": [false] + }, + { + "$ref": "#/definitions/SharedItem" + } + ] + }, + "packageName": { + "description": "Package name to determine required version from description file. This is only needed when package name can't be automatically determined from request.", + "type": "string", + "minLength": 1 + }, + "requiredVersion": { + "description": "Version requirement from module in share scope.", + "anyOf": [ + { + "description": "No version requirement check.", + "enum": [false] + }, + { + "description": "Version as string. Can be prefixed with '^' or '~' for minimum matches. Each part of the version should be separated by a dot '.'.", + "type": "string" + } + ] + }, + "shareKey": { + "description": "Module is looked up under this key from the share scope.", + "type": "string", + "minLength": 1 + }, + "shareScope": { + "description": "Share scope name.", + "type": "string", + "minLength": 1 + }, + "singleton": { + "description": "Allow only a single version of the shared module in share scope (disabled by default).", + "type": "boolean" + }, + "strictVersion": { + "description": "Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).", + "type": "boolean" + }, + "version": { + "description": "Version of the provided module. Will replace lower matching versions, but not higher.", + "anyOf": [ + { + "description": "Don't provide a version.", + "enum": [false] + }, + { + "description": "Version as string. Each part of the version should be separated by a dot '.'.", + "type": "string" + } + ] + } + } + }, + "SharedItem": { + "description": "A module that should be shared in the share scope.", + "type": "string", + "minLength": 1 + }, + "SharedObject": { + "description": "Modules that should be shared in the share scope. Property names are used to match requested modules in this compilation. Relative requests are resolved, module requests are matched unresolved, absolute paths will match resolved requests. A trailing slash will match all requests with this prefix. In this case shareKey must also have a trailing slash.", + "type": "object", + "additionalProperties": { + "description": "Modules that should be shared in the share scope.", + "anyOf": [ + { + "$ref": "#/definitions/SharedConfig" + }, + { + "$ref": "#/definitions/SharedItem" + } + ] + } + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/BannerPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/BannerPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..389d72d7ed5d90377fed575f860d7425227ac188 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/BannerPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../declarations/plugins/BannerPlugin").BannerPluginArgument) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/BannerPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/BannerPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..c97c9b19b4d23f638305af72908dad6f6583cf87 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/BannerPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function n(t,{instancePath:e="",parentData:s,parentDataProperty:l,rootData:a=t}={}){let r=null,o=0;const u=o;let i=!1;const p=o;if(o===p)if(Array.isArray(t)){const n=t.length;for(let e=0;e string" + }, + "Rule": { + "description": "Filtering rule as regex or string.", + "anyOf": [ + { + "instanceof": "RegExp", + "tsType": "RegExp" + }, + { + "type": "string", + "minLength": 1 + } + ] + }, + "Rules": { + "description": "Filtering rules.", + "anyOf": [ + { + "type": "array", + "items": { + "description": "A rule condition.", + "oneOf": [ + { + "$ref": "#/definitions/Rule" + } + ] + } + }, + { + "$ref": "#/definitions/Rule" + } + ] + } + }, + "title": "BannerPluginArgument", + "anyOf": [ + { + "description": "The banner as string, it will be wrapped in a comment.", + "type": "string", + "minLength": 1 + }, + { + "title": "BannerPluginOptions", + "type": "object", + "additionalProperties": false, + "properties": { + "banner": { + "description": "Specifies the banner.", + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/definitions/BannerFunction" + } + ] + }, + "entryOnly": { + "description": "If true, the banner will only be added to the entry chunks.", + "type": "boolean" + }, + "exclude": { + "description": "Exclude all modules matching any of these conditions.", + "oneOf": [ + { + "$ref": "#/definitions/Rules" + } + ] + }, + "footer": { + "description": "If true, banner will be placed at the end of the output.", + "type": "boolean" + }, + "include": { + "description": "Include all modules matching any of these conditions.", + "oneOf": [ + { + "$ref": "#/definitions/Rules" + } + ] + }, + "raw": { + "description": "If true, banner will not be wrapped in a comment.", + "type": "boolean" + }, + "stage": { + "description": "Specifies the stage when add a banner.", + "type": "number" + }, + "test": { + "description": "Include all modules that pass test assertion.", + "oneOf": [ + { + "$ref": "#/definitions/Rules" + } + ] + } + }, + "required": ["banner"] + }, + { + "$ref": "#/definitions/BannerFunction" + } + ] +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..99ba2990316f653e2a6581043664e7d04f75489a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../declarations/plugins/DllPlugin").DllPluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..238b5107adcdcf8b39ab6ed0de7d6bbdc52a8f10 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function r(e,{instancePath:t="",parentData:o,parentDataProperty:n,rootData:a=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return r.errors=[{params:{type:"object"}}],!1;{let t;if(void 0===e.path&&(t="path"))return r.errors=[{params:{missingProperty:t}}],!1;{const t=0;for(const t in e)if("context"!==t&&"entryOnly"!==t&&"format"!==t&&"name"!==t&&"path"!==t&&"type"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(0===t){if(void 0!==e.context){let t=e.context;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}var s=0===o}else s=!0;if(s){if(void 0!==e.entryOnly){const t=0;if("boolean"!=typeof e.entryOnly)return r.errors=[{params:{type:"boolean"}}],!1;s=0===t}else s=!0;if(s){if(void 0!==e.format){const t=0;if("boolean"!=typeof e.format)return r.errors=[{params:{type:"boolean"}}],!1;s=0===t}else s=!0;if(s){if(void 0!==e.name){let t=e.name;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}s=0===o}else s=!0;if(s){if(void 0!==e.path){let t=e.path;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}s=0===o}else s=!0;if(s)if(void 0!==e.type){let t=e.type;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}s=0===o}else s=!0}}}}}}}return r.errors=null,!0}module.exports=r,module.exports.default=r; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllPlugin.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllPlugin.json new file mode 100644 index 0000000000000000000000000000000000000000..9e5b999252f8faf988b25a7c3c4ceb62fd06cdf8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllPlugin.json @@ -0,0 +1,36 @@ +{ + "title": "DllPluginOptions", + "type": "object", + "additionalProperties": false, + "properties": { + "context": { + "description": "Context of requests in the manifest file (defaults to the webpack context).", + "type": "string", + "minLength": 1 + }, + "entryOnly": { + "description": "If true, only entry points will be exposed (default: true).", + "type": "boolean" + }, + "format": { + "description": "If true, manifest json file (output) will be formatted.", + "type": "boolean" + }, + "name": { + "description": "Name of the exposed dll function (external name, use value of 'output.library').", + "type": "string", + "minLength": 1 + }, + "path": { + "description": "Absolute path to the manifest json file (output).", + "type": "string", + "minLength": 1 + }, + "type": { + "description": "Type of the dll bundle (external type, use value of 'output.libraryTarget').", + "type": "string", + "minLength": 1 + } + }, + "required": ["path"] +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllReferencePlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllReferencePlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e156ef45be845363117232730606b5aca03df061 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllReferencePlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllReferencePlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllReferencePlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..5a05b48f61463ebe808ddb25058b1aa2902247ad --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/DllReferencePlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +const s=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;function t(s,{instancePath:e="",parentData:n,parentDataProperty:l,rootData:o=s}={}){let r=null,i=0;if(0===i){if(!s||"object"!=typeof s||Array.isArray(s))return t.errors=[{params:{type:"object"}}],!1;{let e;if(void 0===s.content&&(e="content"))return t.errors=[{params:{missingProperty:e}}],!1;{const e=i;for(const e in s)if("content"!==e&&"name"!==e&&"type"!==e)return t.errors=[{params:{additionalProperty:e}}],!1;if(e===i){if(void 0!==s.content){let e=s.content;const n=i,l=i;let o=!1,f=null;const m=i;if(i==i)if(e&&"object"==typeof e&&!Array.isArray(e))if(Object.keys(e).length<1){const s={params:{limit:1}};null===r?r=[s]:r.push(s),i++}else for(const s in e){let t=e[s];const n=i;if(i===n)if(t&&"object"==typeof t&&!Array.isArray(t)){let s;if(void 0===t.id&&(s="id")){const t={params:{missingProperty:s}};null===r?r=[t]:r.push(t),i++}else{const s=i;for(const s in t)if("buildMeta"!==s&&"exports"!==s&&"id"!==s){const t={params:{additionalProperty:s}};null===r?r=[t]:r.push(t),i++;break}if(s===i){if(void 0!==t.buildMeta){let s=t.buildMeta;const e=i;if(!s||"object"!=typeof s||Array.isArray(s)){const s={params:{type:"object"}};null===r?r=[s]:r.push(s),i++}var a=e===i}else a=!0;if(a){if(void 0!==t.exports){let s=t.exports;const e=i,n=i;let l=!1;const o=i;if(i===o)if(Array.isArray(s)){const t=s.length;for(let e=0;e boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/HashedModuleIdsPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/HashedModuleIdsPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..ddf0827a426aadf3a0eca818d05c2ac734ccc5de --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/HashedModuleIdsPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +const t=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;function e(r,{instancePath:s="",parentData:n,parentDataProperty:a,rootData:i=r}={}){let o=null,l=0;if(0===l){if(!r||"object"!=typeof r||Array.isArray(r))return e.errors=[{params:{type:"object"}}],!1;{const s=l;for(const t in r)if("context"!==t&&"hashDigest"!==t&&"hashDigestLength"!==t&&"hashFunction"!==t)return e.errors=[{params:{additionalProperty:t}}],!1;if(s===l){if(void 0!==r.context){let s=r.context;const n=l;if(l===n){if("string"!=typeof s)return e.errors=[{params:{type:"string"}}],!1;if(s.includes("!")||!0!==t.test(s))return e.errors=[{params:{}}],!1}var u=n===l}else u=!0;if(u){if(void 0!==r.hashDigest){let t=r.hashDigest;const s=l;if("hex"!==t&&"latin1"!==t&&"base64"!==t)return e.errors=[{params:{}}],!1;u=s===l}else u=!0;if(u){if(void 0!==r.hashDigestLength){let t=r.hashDigestLength;const s=l;if(l===s){if("number"!=typeof t)return e.errors=[{params:{type:"number"}}],!1;if(t<1||isNaN(t))return e.errors=[{params:{comparison:">=",limit:1}}],!1}u=s===l}else u=!0;if(u)if(void 0!==r.hashFunction){let t=r.hashFunction;const s=l,n=l;let a=!1,i=null;const p=l,h=l;let c=!1;const m=l;if(l===m)if("string"==typeof t){if(t.length<1){const t={params:{}};null===o?o=[t]:o.push(t),l++}}else{const t={params:{type:"string"}};null===o?o=[t]:o.push(t),l++}var f=m===l;if(c=c||f,!c){const e=l;if(!(t instanceof Function)){const t={params:{}};null===o?o=[t]:o.push(t),l++}f=e===l,c=c||f}if(c)l=h,null!==o&&(h?o.length=h:o=null);else{const t={params:{}};null===o?o=[t]:o.push(t),l++}if(p===l&&(a=!0,i=0),!a){const t={params:{passingSchemas:i}};return null===o?o=[t]:o.push(t),l++,e.errors=o,!1}l=n,null!==o&&(n?o.length=n:o=null),u=s===l}else u=!0}}}}}return e.errors=o,0===l}module.exports=e,module.exports.default=e; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/HashedModuleIdsPlugin.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/HashedModuleIdsPlugin.json new file mode 100644 index 0000000000000000000000000000000000000000..1b4efc40b5ebb97df43219e6df9ef47238e54ed8 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/HashedModuleIdsPlugin.json @@ -0,0 +1,44 @@ +{ + "definitions": { + "HashFunction": { + "description": "Algorithm used for generation the hash (see node.js crypto package).", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "instanceof": "Function", + "tsType": "typeof import('../../lib/util/Hash')" + } + ] + } + }, + "title": "HashedModuleIdsPluginOptions", + "type": "object", + "additionalProperties": false, + "properties": { + "context": { + "description": "The context directory for creating names.", + "type": "string", + "absolutePath": true + }, + "hashDigest": { + "description": "The encoding to use when generating the hash, defaults to 'base64'. All encodings from Node.JS' hash.digest are supported.", + "enum": ["hex", "latin1", "base64"] + }, + "hashDigestLength": { + "description": "The prefix length of the hash digest to use, defaults to 4.", + "type": "number", + "minimum": 1 + }, + "hashFunction": { + "description": "The hashing algorithm to use, defaults to 'md4'. All functions from Node.JS' crypto.createHash are supported.", + "oneOf": [ + { + "$ref": "#/definitions/HashFunction" + } + ] + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/IgnorePlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/IgnorePlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7291efb3a26e23f1af1d1f44c5393e0ea3ae4b7b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/IgnorePlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../declarations/plugins/IgnorePlugin").IgnorePluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/IgnorePlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/IgnorePlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..6018579813344a904ecd62908909768dd3eb38fb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/IgnorePlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function e(s,{instancePath:o="",parentData:r,parentDataProperty:t,rootData:n=s}={}){let c=null,a=0;const p=a;let l=!1;const i=a;if(a===i)if(s&&"object"==typeof s&&!Array.isArray(s)){let e;if(void 0===s.resourceRegExp&&(e="resourceRegExp")){const s={params:{missingProperty:e}};null===c?c=[s]:c.push(s),a++}else{const e=a;for(const e in s)if("contextRegExp"!==e&&"resourceRegExp"!==e){const s={params:{additionalProperty:e}};null===c?c=[s]:c.push(s),a++;break}if(e===a){if(void 0!==s.contextRegExp){const e=a;if(!(s.contextRegExp instanceof RegExp)){const e={params:{}};null===c?c=[e]:c.push(e),a++}var u=e===a}else u=!0;if(u)if(void 0!==s.resourceRegExp){const e=a;if(!(s.resourceRegExp instanceof RegExp)){const e={params:{}};null===c?c=[e]:c.push(e),a++}u=e===a}else u=!0}}}else{const e={params:{type:"object"}};null===c?c=[e]:c.push(e),a++}var f=i===a;if(l=l||f,!l){const e=a;if(a===e)if(s&&"object"==typeof s&&!Array.isArray(s)){let e;if(void 0===s.checkResource&&(e="checkResource")){const s={params:{missingProperty:e}};null===c?c=[s]:c.push(s),a++}else{const e=a;for(const e in s)if("checkResource"!==e){const s={params:{additionalProperty:e}};null===c?c=[s]:c.push(s),a++;break}if(e===a&&void 0!==s.checkResource&&!(s.checkResource instanceof Function)){const e={params:{}};null===c?c=[e]:c.push(e),a++}}}else{const e={params:{type:"object"}};null===c?c=[e]:c.push(e),a++}f=e===a,l=l||f}if(!l){const s={params:{}};return null===c?c=[s]:c.push(s),a++,e.errors=c,!1}return a=p,null!==c&&(p?c.length=p:c=null),e.errors=c,0===a}module.exports=e,module.exports.default=e; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/IgnorePlugin.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/IgnorePlugin.json new file mode 100644 index 0000000000000000000000000000000000000000..58c1d2c50c564244eea82df995f6214366dca4c5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/IgnorePlugin.json @@ -0,0 +1,34 @@ +{ + "title": "IgnorePluginOptions", + "anyOf": [ + { + "type": "object", + "additionalProperties": false, + "properties": { + "contextRegExp": { + "description": "A RegExp to test the context (directory) against.", + "instanceof": "RegExp", + "tsType": "RegExp" + }, + "resourceRegExp": { + "description": "A RegExp to test the request against.", + "instanceof": "RegExp", + "tsType": "RegExp" + } + }, + "required": ["resourceRegExp"] + }, + { + "type": "object", + "additionalProperties": false, + "properties": { + "checkResource": { + "description": "A filter function for resource and context.", + "instanceof": "Function", + "tsType": "((resource: string, context: string) => boolean)" + } + }, + "required": ["checkResource"] + } + ] +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/LoaderOptionsPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/LoaderOptionsPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea1d3a60a81bc25dea26781120f924025df66315 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/LoaderOptionsPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/LoaderOptionsPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/LoaderOptionsPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..80fb3af14d5bf00e59841858eb22c53690115aa2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/LoaderOptionsPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +const r=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;function e(t,{instancePath:o="",parentData:a,parentDataProperty:i,rootData:n=t}={}){if(!t||"object"!=typeof t||Array.isArray(t))return e.errors=[{params:{type:"object"}}],!1;if(void 0!==t.debug){const r=0;if("boolean"!=typeof t.debug)return e.errors=[{params:{type:"boolean"}}],!1;var s=0===r}else s=!0;if(s){if(void 0!==t.minimize){const r=0;if("boolean"!=typeof t.minimize)return e.errors=[{params:{type:"boolean"}}],!1;s=0===r}else s=!0;if(s)if(void 0!==t.options){let o=t.options;const a=0;if(0===a){if(!o||"object"!=typeof o||Array.isArray(o))return e.errors=[{params:{type:"object"}}],!1;if(void 0!==o.context){let t=o.context;if("string"!=typeof t)return e.errors=[{params:{type:"string"}}],!1;if(t.includes("!")||!0!==r.test(t))return e.errors=[{params:{}}],!1}}s=0===a}else s=!0}return e.errors=null,!0}module.exports=e,module.exports.default=e; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/LoaderOptionsPlugin.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/LoaderOptionsPlugin.json new file mode 100644 index 0000000000000000000000000000000000000000..912095c597573f7464c60ab81c32d086d4ac8a1b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/LoaderOptionsPlugin.json @@ -0,0 +1,27 @@ +{ + "title": "LoaderOptionsPluginOptions", + "type": "object", + "additionalProperties": true, + "properties": { + "debug": { + "description": "Whether loaders should be in debug mode or not. debug will be removed as of webpack 3.", + "type": "boolean" + }, + "minimize": { + "description": "Where loaders can be switched to minimize mode.", + "type": "boolean" + }, + "options": { + "description": "A configuration object that can be used to configure older loaders.", + "type": "object", + "additionalProperties": true, + "properties": { + "context": { + "description": "The context that can be used to configure older loaders.", + "type": "string", + "absolutePath": true + } + } + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/ProgressPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/ProgressPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0be4363ea363e52551f012f5c6b8fee1d5ac3f5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/ProgressPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../declarations/plugins/ProgressPlugin").ProgressPluginArgument) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/ProgressPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/ProgressPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..09819f1d453c141208be86a6bb5b00fa96083aa5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/ProgressPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";module.exports=t,module.exports.default=t;const e={type:"object",additionalProperties:!1,properties:{activeModules:{type:"boolean"},dependencies:{type:"boolean"},dependenciesCount:{type:"number"},entries:{type:"boolean"},handler:{oneOf:[{$ref:"#/definitions/HandlerFunction"}]},modules:{type:"boolean"},modulesCount:{type:"number"},percentBy:{enum:["entries","modules","dependencies",null]},profile:{enum:[!0,!1,null]}}},r=Object.prototype.hasOwnProperty;function n(t,{instancePath:o="",parentData:s,parentDataProperty:a,rootData:l=t}={}){let i=null,p=0;if(0===p){if(!t||"object"!=typeof t||Array.isArray(t))return n.errors=[{params:{type:"object"}}],!1;{const o=p;for(const o in t)if(!r.call(e.properties,o))return n.errors=[{params:{additionalProperty:o}}],!1;if(o===p){if(void 0!==t.activeModules){const e=p;if("boolean"!=typeof t.activeModules)return n.errors=[{params:{type:"boolean"}}],!1;var u=e===p}else u=!0;if(u){if(void 0!==t.dependencies){const e=p;if("boolean"!=typeof t.dependencies)return n.errors=[{params:{type:"boolean"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.dependenciesCount){const e=p;if("number"!=typeof t.dependenciesCount)return n.errors=[{params:{type:"number"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.entries){const e=p;if("boolean"!=typeof t.entries)return n.errors=[{params:{type:"boolean"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.handler){const e=p,r=p;let o=!1,s=null;const a=p;if(!(t.handler instanceof Function)){const e={params:{}};null===i?i=[e]:i.push(e),p++}if(a===p&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===i?i=[e]:i.push(e),p++,n.errors=i,!1}p=r,null!==i&&(r?i.length=r:i=null),u=e===p}else u=!0;if(u){if(void 0!==t.modules){const e=p;if("boolean"!=typeof t.modules)return n.errors=[{params:{type:"boolean"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.modulesCount){const e=p;if("number"!=typeof t.modulesCount)return n.errors=[{params:{type:"number"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.percentBy){let e=t.percentBy;const r=p;if("entries"!==e&&"modules"!==e&&"dependencies"!==e&&null!==e)return n.errors=[{params:{}}],!1;u=r===p}else u=!0;if(u)if(void 0!==t.profile){let e=t.profile;const r=p;if(!0!==e&&!1!==e&&null!==e)return n.errors=[{params:{}}],!1;u=r===p}else u=!0}}}}}}}}}}return n.errors=i,0===p}function t(e,{instancePath:r="",parentData:o,parentDataProperty:s,rootData:a=e}={}){let l=null,i=0;const p=i;let u=!1;const c=i;n(e,{instancePath:r,parentData:o,parentDataProperty:s,rootData:a})||(l=null===l?n.errors:l.concat(n.errors),i=l.length);var f=c===i;if(u=u||f,!u){const r=i;if(!(e instanceof Function)){const e={params:{}};null===l?l=[e]:l.push(e),i++}f=r===i,u=u||f}if(!u){const e={params:{}};return null===l?l=[e]:l.push(e),i++,t.errors=l,!1}return i=p,null!==l&&(p?l.length=p:l=null),t.errors=l,0===i} \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/ProgressPlugin.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/ProgressPlugin.json new file mode 100644 index 0000000000000000000000000000000000000000..2867de45e10d282f0228c062b8ea102bbcc185cc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/ProgressPlugin.json @@ -0,0 +1,65 @@ +{ + "definitions": { + "HandlerFunction": { + "description": "Function that executes for every progress step.", + "instanceof": "Function", + "tsType": "((percentage: number, msg: string, ...args: string[]) => void)" + }, + "ProgressPluginOptions": { + "description": "Options object for the ProgressPlugin.", + "type": "object", + "additionalProperties": false, + "properties": { + "activeModules": { + "description": "Show active modules count and one active module in progress message.", + "type": "boolean" + }, + "dependencies": { + "description": "Show dependencies count in progress message.", + "type": "boolean" + }, + "dependenciesCount": { + "description": "Minimum dependencies count to start with. For better progress calculation. Default: 10000.", + "type": "number" + }, + "entries": { + "description": "Show entries count in progress message.", + "type": "boolean" + }, + "handler": { + "description": "Function that executes for every progress step.", + "oneOf": [ + { + "$ref": "#/definitions/HandlerFunction" + } + ] + }, + "modules": { + "description": "Show modules count in progress message.", + "type": "boolean" + }, + "modulesCount": { + "description": "Minimum modules count to start with. For better progress calculation. Default: 5000.", + "type": "number" + }, + "percentBy": { + "description": "Collect percent algorithm. By default it calculates by a median from modules, entries and dependencies percent.", + "enum": ["entries", "modules", "dependencies", null] + }, + "profile": { + "description": "Collect profile data for progress steps. Default: false.", + "enum": [true, false, null] + } + } + } + }, + "title": "ProgressPluginArgument", + "anyOf": [ + { + "$ref": "#/definitions/ProgressPluginOptions" + }, + { + "$ref": "#/definitions/HandlerFunction" + } + ] +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/SourceMapDevToolPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/SourceMapDevToolPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..61d2440ef0b89b53508ba5ab5d18aa61cc0eb1ff --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/SourceMapDevToolPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/SourceMapDevToolPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/SourceMapDevToolPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..de73840e28ecd20d4267abf89b698d79de593044 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/SourceMapDevToolPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +const e=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;module.exports=l,module.exports.default=l;const n={definitions:{rule:{anyOf:[{instanceof:"RegExp"},{type:"string",minLength:1}]},rules:{anyOf:[{type:"array",items:{oneOf:[{$ref:"#/definitions/rule"}]}},{$ref:"#/definitions/rule"}]}},type:"object",additionalProperties:!1,properties:{append:{anyOf:[{enum:[!1,null]},{type:"string",minLength:1},{instanceof:"Function"}]},columns:{type:"boolean"},debugIds:{type:"boolean"},exclude:{oneOf:[{$ref:"#/definitions/rules"}]},fallbackModuleFilenameTemplate:{anyOf:[{type:"string",minLength:1},{instanceof:"Function"}]},fileContext:{type:"string"},filename:{anyOf:[{enum:[!1,null]},{type:"string",absolutePath:!1,minLength:1}]},include:{oneOf:[{$ref:"#/definitions/rules"}]},module:{type:"boolean"},moduleFilenameTemplate:{anyOf:[{type:"string",minLength:1},{instanceof:"Function"}]},namespace:{type:"string"},noSources:{type:"boolean"},publicPath:{type:"string"},sourceRoot:{type:"string"},test:{$ref:"#/definitions/rules"}}},t=Object.prototype.hasOwnProperty;function s(e,{instancePath:n="",parentData:t,parentDataProperty:l,rootData:r=e}={}){let o=null,a=0;const i=a;let u=!1;const p=a;if(a===p)if(Array.isArray(e)){const n=e.length;for(let t=0;t string)" + } + ] + }, + "columns": { + "description": "Indicates whether column mappings should be used (defaults to true).", + "type": "boolean" + }, + "debugIds": { + "description": "Emit debug IDs into source and SourceMap.", + "type": "boolean" + }, + "exclude": { + "description": "Exclude modules that match the given value from source map generation.", + "oneOf": [ + { + "$ref": "#/definitions/rules" + } + ] + }, + "fallbackModuleFilenameTemplate": { + "description": "Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap used only if 'moduleFilenameTemplate' would result in a conflict.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "description": "Custom function generating the identifier.", + "instanceof": "Function", + "tsType": "import('../../lib/ModuleFilenameHelpers').ModuleFilenameTemplateFunction" + } + ] + }, + "fileContext": { + "description": "Path prefix to which the [file] placeholder is relative to.", + "type": "string" + }, + "filename": { + "description": "Defines the output filename of the SourceMap (will be inlined if no value is provided).", + "anyOf": [ + { + "description": "Disable separate SourceMap file and inline SourceMap as DataUrl.", + "enum": [false, null] + }, + { + "type": "string", + "absolutePath": false, + "minLength": 1 + } + ] + }, + "include": { + "description": "Include source maps for module paths that match the given value.", + "oneOf": [ + { + "$ref": "#/definitions/rules" + } + ] + }, + "module": { + "description": "Indicates whether SourceMaps from loaders should be used (defaults to true).", + "type": "boolean" + }, + "moduleFilenameTemplate": { + "description": "Generator string or function to create identifiers of modules for the 'sources' array in the SourceMap.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "description": "Custom function generating the identifier.", + "instanceof": "Function", + "tsType": "import('../../lib/ModuleFilenameHelpers').ModuleFilenameTemplateFunction" + } + ] + }, + "namespace": { + "description": "Namespace prefix to allow multiple webpack roots in the devtools.", + "type": "string" + }, + "noSources": { + "description": "Omit the 'sourceContents' array from the SourceMap.", + "type": "boolean" + }, + "publicPath": { + "description": "Provide a custom public path for the SourceMapping comment.", + "type": "string" + }, + "sourceRoot": { + "description": "Provide a custom value for the 'sourceRoot' property in the SourceMap.", + "type": "string" + }, + "test": { + "$ref": "#/definitions/rules" + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/WatchIgnorePlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/WatchIgnorePlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..41baee25378a6c99a248ef8f4dc7d90d91ea0600 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/WatchIgnorePlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/WatchIgnorePlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/WatchIgnorePlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..60bd0be7312426a352109215c7eeb753d6278e30 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/WatchIgnorePlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function r(t,{instancePath:e="",parentData:s,parentDataProperty:a,rootData:n=t}={}){let o=null,i=0;if(0===i){if(!t||"object"!=typeof t||Array.isArray(t))return r.errors=[{params:{type:"object"}}],!1;{let e;if(void 0===t.paths&&(e="paths"))return r.errors=[{params:{missingProperty:e}}],!1;{const e=i;for(const e in t)if("paths"!==e)return r.errors=[{params:{additionalProperty:e}}],!1;if(e===i&&void 0!==t.paths){let e=t.paths;if(i==i){if(!Array.isArray(e))return r.errors=[{params:{type:"array"}}],!1;if(e.length<1)return r.errors=[{params:{limit:1}}],!1;{const t=e.length;for(let s=0;s boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetGeneratorOptions.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetGeneratorOptions.check.js new file mode 100644 index 0000000000000000000000000000000000000000..c835a70e5e431b4aae5165e92e51dd5792da47ef --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetGeneratorOptions.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +const t=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;function n(t,{instancePath:r="",parentData:e,parentDataProperty:a,rootData:s=t}={}){let o=null,l=0;const i=l;let p=!1;const u=l;if(l==l)if(t&&"object"==typeof t&&!Array.isArray(t)){const n=l;for(const n in t)if("encoding"!==n&&"mimetype"!==n){const t={params:{additionalProperty:n}};null===o?o=[t]:o.push(t),l++;break}if(n===l){if(void 0!==t.encoding){let n=t.encoding;const r=l;if(!1!==n&&"base64"!==n){const t={params:{}};null===o?o=[t]:o.push(t),l++}var c=r===l}else c=!0;if(c)if(void 0!==t.mimetype){const n=l;if("string"!=typeof t.mimetype){const t={params:{type:"string"}};null===o?o=[t]:o.push(t),l++}c=n===l}else c=!0}}else{const t={params:{type:"object"}};null===o?o=[t]:o.push(t),l++}var f=u===l;if(p=p||f,!p){const n=l;if(!(t instanceof Function)){const t={params:{}};null===o?o=[t]:o.push(t),l++}f=n===l,p=p||f}if(!p){const t={params:{}};return null===o?o=[t]:o.push(t),l++,n.errors=o,!1}return l=i,null!==o&&(i?o.length=i:o=null),n.errors=o,0===l}function r(e,{instancePath:a="",parentData:s,parentDataProperty:o,rootData:l=e}={}){let i=null,p=0;if(0===p){if(!e||"object"!=typeof e||Array.isArray(e))return r.errors=[{params:{type:"object"}}],!1;{const s=p;for(const t in e)if("binary"!==t&&"dataUrl"!==t&&"emit"!==t&&"filename"!==t&&"outputPath"!==t&&"publicPath"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(s===p){if(void 0!==e.binary){const t=p;if("boolean"!=typeof e.binary)return r.errors=[{params:{type:"boolean"}}],!1;var u=t===p}else u=!0;if(u){if(void 0!==e.dataUrl){const t=p;n(e.dataUrl,{instancePath:a+"/dataUrl",parentData:e,parentDataProperty:"dataUrl",rootData:l})||(i=null===i?n.errors:i.concat(n.errors),p=i.length),u=t===p}else u=!0;if(u){if(void 0!==e.emit){const t=p;if("boolean"!=typeof e.emit)return r.errors=[{params:{type:"boolean"}}],!1;u=t===p}else u=!0;if(u){if(void 0!==e.filename){let n=e.filename;const a=p,s=p;let o=!1;const l=p;if(p===l)if("string"==typeof n){if(n.includes("!")||!1!==t.test(n)){const t={params:{}};null===i?i=[t]:i.push(t),p++}else if(n.length<1){const t={params:{}};null===i?i=[t]:i.push(t),p++}}else{const t={params:{type:"string"}};null===i?i=[t]:i.push(t),p++}var c=l===p;if(o=o||c,!o){const t=p;if(!(n instanceof Function)){const t={params:{}};null===i?i=[t]:i.push(t),p++}c=t===p,o=o||c}if(!o){const t={params:{}};return null===i?i=[t]:i.push(t),p++,r.errors=i,!1}p=s,null!==i&&(s?i.length=s:i=null),u=a===p}else u=!0;if(u){if(void 0!==e.outputPath){let n=e.outputPath;const a=p,s=p;let o=!1;const l=p;if(p===l)if("string"==typeof n){if(n.includes("!")||!1!==t.test(n)){const t={params:{}};null===i?i=[t]:i.push(t),p++}}else{const t={params:{type:"string"}};null===i?i=[t]:i.push(t),p++}var f=l===p;if(o=o||f,!o){const t=p;if(!(n instanceof Function)){const t={params:{}};null===i?i=[t]:i.push(t),p++}f=t===p,o=o||f}if(!o){const t={params:{}};return null===i?i=[t]:i.push(t),p++,r.errors=i,!1}p=s,null!==i&&(s?i.length=s:i=null),u=a===p}else u=!0;if(u)if(void 0!==e.publicPath){let t=e.publicPath;const n=p,a=p;let s=!1;const o=p;if("string"!=typeof t){const t={params:{type:"string"}};null===i?i=[t]:i.push(t),p++}var h=o===p;if(s=s||h,!s){const n=p;if(!(t instanceof Function)){const t={params:{}};null===i?i=[t]:i.push(t),p++}h=n===p,s=s||h}if(!s){const t={params:{}};return null===i?i=[t]:i.push(t),p++,r.errors=i,!1}p=a,null!==i&&(a?i.length=a:i=null),u=n===p}else u=!0}}}}}}}return r.errors=i,0===p}function e(t,{instancePath:n="",parentData:a,parentDataProperty:s,rootData:o=t}={}){let l=null,i=0;return r(t,{instancePath:n,parentData:a,parentDataProperty:s,rootData:o})||(l=null===l?r.errors:l.concat(r.errors),i=l.length),e.errors=l,0===i}module.exports=e,module.exports.default=e; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetGeneratorOptions.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetGeneratorOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..c00fc87197f29d58833afc1bbe56675e0cc9f67d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetGeneratorOptions.json @@ -0,0 +1,3 @@ +{ + "$ref": "../../WebpackOptions.json#/definitions/AssetGeneratorOptions" +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetInlineGeneratorOptions.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetInlineGeneratorOptions.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8710226a8f47ef50493ae7a80d3540fad36ccd2d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetInlineGeneratorOptions.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: any) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetInlineGeneratorOptions.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetInlineGeneratorOptions.check.js new file mode 100644 index 0000000000000000000000000000000000000000..e5496307f4321ac50f3c13537ba1becf469aa649 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetInlineGeneratorOptions.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function t(r,{instancePath:a="",parentData:e,parentDataProperty:n,rootData:o=r}={}){let s=null,i=0;const l=i;let p=!1;const c=i;if(i==i)if(r&&"object"==typeof r&&!Array.isArray(r)){const t=i;for(const t in r)if("encoding"!==t&&"mimetype"!==t){const r={params:{additionalProperty:t}};null===s?s=[r]:s.push(r),i++;break}if(t===i){if(void 0!==r.encoding){let t=r.encoding;const a=i;if(!1!==t&&"base64"!==t){const t={params:{}};null===s?s=[t]:s.push(t),i++}var u=a===i}else u=!0;if(u)if(void 0!==r.mimetype){const t=i;if("string"!=typeof r.mimetype){const t={params:{type:"string"}};null===s?s=[t]:s.push(t),i++}u=t===i}else u=!0}}else{const t={params:{type:"object"}};null===s?s=[t]:s.push(t),i++}var f=c===i;if(p=p||f,!p){const t=i;if(!(r instanceof Function)){const t={params:{}};null===s?s=[t]:s.push(t),i++}f=t===i,p=p||f}if(!p){const r={params:{}};return null===s?s=[r]:s.push(r),i++,t.errors=s,!1}return i=l,null!==s&&(l?s.length=l:s=null),t.errors=s,0===i}function r(a,{instancePath:e="",parentData:n,parentDataProperty:o,rootData:s=a}={}){let i=null,l=0;if(0===l){if(!a||"object"!=typeof a||Array.isArray(a))return r.errors=[{params:{type:"object"}}],!1;{const n=l;for(const t in a)if("binary"!==t&&"dataUrl"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(n===l){if(void 0!==a.binary){const t=l;if("boolean"!=typeof a.binary)return r.errors=[{params:{type:"boolean"}}],!1;var p=t===l}else p=!0;if(p)if(void 0!==a.dataUrl){const r=l;t(a.dataUrl,{instancePath:e+"/dataUrl",parentData:a,parentDataProperty:"dataUrl",rootData:s})||(i=null===i?t.errors:i.concat(t.errors),l=i.length),p=r===l}else p=!0}}}return r.errors=i,0===l}function a(t,{instancePath:e="",parentData:n,parentDataProperty:o,rootData:s=t}={}){let i=null,l=0;return r(t,{instancePath:e,parentData:n,parentDataProperty:o,rootData:s})||(i=null===i?r.errors:i.concat(r.errors),l=i.length),a.errors=i,0===l}module.exports=a,module.exports.default=a; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetInlineGeneratorOptions.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetInlineGeneratorOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..a6fff2a170ae9e35c5f26c431e02999fe77215a6 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetInlineGeneratorOptions.json @@ -0,0 +1,3 @@ +{ + "$ref": "../../WebpackOptions.json#/definitions/AssetInlineGeneratorOptions" +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetParserOptions.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetParserOptions.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8710226a8f47ef50493ae7a80d3540fad36ccd2d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetParserOptions.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: any) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetParserOptions.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetParserOptions.check.js new file mode 100644 index 0000000000000000000000000000000000000000..33350819763eda033e6a1acd883d92220d774d59 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetParserOptions.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function t(r,{instancePath:a="",parentData:n,parentDataProperty:o,rootData:e=r}={}){let s=null,i=0;if(0===i){if(!r||"object"!=typeof r||Array.isArray(r))return t.errors=[{params:{type:"object"}}],!1;{const a=i;for(const a in r)if("dataUrlCondition"!==a)return t.errors=[{params:{additionalProperty:a}}],!1;if(a===i&&void 0!==r.dataUrlCondition){let a=r.dataUrlCondition;const n=i;let o=!1;const e=i;if(i==i)if(a&&"object"==typeof a&&!Array.isArray(a)){const t=i;for(const t in a)if("maxSize"!==t){const r={params:{additionalProperty:t}};null===s?s=[r]:s.push(r),i++;break}if(t===i&&void 0!==a.maxSize&&"number"!=typeof a.maxSize){const t={params:{type:"number"}};null===s?s=[t]:s.push(t),i++}}else{const t={params:{type:"object"}};null===s?s=[t]:s.push(t),i++}var l=e===i;if(o=o||l,!o){const t=i;if(!(a instanceof Function)){const t={params:{}};null===s?s=[t]:s.push(t),i++}l=t===i,o=o||l}if(!o){const r={params:{}};return null===s?s=[r]:s.push(r),i++,t.errors=s,!1}i=n,null!==s&&(n?s.length=n:s=null)}}}return t.errors=s,0===i}function r(a,{instancePath:n="",parentData:o,parentDataProperty:e,rootData:s=a}={}){let i=null,l=0;return t(a,{instancePath:n,parentData:o,parentDataProperty:e,rootData:s})||(i=null===i?t.errors:i.concat(t.errors),l=i.length),r.errors=i,0===l}module.exports=r,module.exports.default=r; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetParserOptions.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetParserOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..66bf562d6c1aca339394bdb0ecb7bbeba0d7d0e2 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetParserOptions.json @@ -0,0 +1,3 @@ +{ + "$ref": "../../WebpackOptions.json#/definitions/AssetParserOptions" +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetResourceGeneratorOptions.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetResourceGeneratorOptions.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8710226a8f47ef50493ae7a80d3540fad36ccd2d --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetResourceGeneratorOptions.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: any) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js new file mode 100644 index 0000000000000000000000000000000000000000..15921fa87d06c5f89d73ccb3d38eba0d07992e06 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +const t=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;function n(r,{instancePath:e="",parentData:a,parentDataProperty:s,rootData:o=r}={}){let l=null,i=0;if(0===i){if(!r||"object"!=typeof r||Array.isArray(r))return n.errors=[{params:{type:"object"}}],!1;{const e=i;for(const t in r)if("binary"!==t&&"emit"!==t&&"filename"!==t&&"outputPath"!==t&&"publicPath"!==t)return n.errors=[{params:{additionalProperty:t}}],!1;if(e===i){if(void 0!==r.binary){const t=i;if("boolean"!=typeof r.binary)return n.errors=[{params:{type:"boolean"}}],!1;var u=t===i}else u=!0;if(u){if(void 0!==r.emit){const t=i;if("boolean"!=typeof r.emit)return n.errors=[{params:{type:"boolean"}}],!1;u=t===i}else u=!0;if(u){if(void 0!==r.filename){let e=r.filename;const a=i,s=i;let o=!1;const f=i;if(i===f)if("string"==typeof e){if(e.includes("!")||!1!==t.test(e)){const t={params:{}};null===l?l=[t]:l.push(t),i++}else if(e.length<1){const t={params:{}};null===l?l=[t]:l.push(t),i++}}else{const t={params:{type:"string"}};null===l?l=[t]:l.push(t),i++}var p=f===i;if(o=o||p,!o){const t=i;if(!(e instanceof Function)){const t={params:{}};null===l?l=[t]:l.push(t),i++}p=t===i,o=o||p}if(!o){const t={params:{}};return null===l?l=[t]:l.push(t),i++,n.errors=l,!1}i=s,null!==l&&(s?l.length=s:l=null),u=a===i}else u=!0;if(u){if(void 0!==r.outputPath){let e=r.outputPath;const a=i,s=i;let o=!1;const p=i;if(i===p)if("string"==typeof e){if(e.includes("!")||!1!==t.test(e)){const t={params:{}};null===l?l=[t]:l.push(t),i++}}else{const t={params:{type:"string"}};null===l?l=[t]:l.push(t),i++}var f=p===i;if(o=o||f,!o){const t=i;if(!(e instanceof Function)){const t={params:{}};null===l?l=[t]:l.push(t),i++}f=t===i,o=o||f}if(!o){const t={params:{}};return null===l?l=[t]:l.push(t),i++,n.errors=l,!1}i=s,null!==l&&(s?l.length=s:l=null),u=a===i}else u=!0;if(u)if(void 0!==r.publicPath){let t=r.publicPath;const e=i,a=i;let s=!1;const o=i;if("string"!=typeof t){const t={params:{type:"string"}};null===l?l=[t]:l.push(t),i++}var c=o===i;if(s=s||c,!s){const n=i;if(!(t instanceof Function)){const t={params:{}};null===l?l=[t]:l.push(t),i++}c=n===i,s=s||c}if(!s){const t={params:{}};return null===l?l=[t]:l.push(t),i++,n.errors=l,!1}i=a,null!==l&&(a?l.length=a:l=null),u=e===i}else u=!0}}}}}}return n.errors=l,0===i}function r(t,{instancePath:e="",parentData:a,parentDataProperty:s,rootData:o=t}={}){let l=null,i=0;return n(t,{instancePath:e,parentData:a,parentDataProperty:s,rootData:o})||(l=null===l?n.errors:l.concat(n.errors),i=l.length),r.errors=l,0===i}module.exports=r,module.exports.default=r; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetResourceGeneratorOptions.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetResourceGeneratorOptions.json new file mode 100644 index 0000000000000000000000000000000000000000..8ae51d5ca91c1ccb0659f8d70bfcad9fc60d582c --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/asset/AssetResourceGeneratorOptions.json @@ -0,0 +1,3 @@ +{ + "$ref": "../../WebpackOptions.json#/definitions/AssetResourceGeneratorOptions" +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ContainerPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ContainerPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ace987f552947f3ac7ebc2aca548243f20eaee4 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ContainerPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../../declarations/plugins/container/ContainerPlugin").ContainerPluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ContainerPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ContainerPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..8bb1a53a45b8bb364be0be46169c6c65140137e1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ContainerPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +const r=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;function t(r,{instancePath:e="",parentData:n,parentDataProperty:s,rootData:a=r}={}){if(!Array.isArray(r))return t.errors=[{params:{type:"array"}}],!1;{const e=r.length;for(let n=0;n boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ContainerReferencePlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ContainerReferencePlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..8a902953c7a4bafa56134ea23266bfc892fde42f --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ContainerReferencePlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function r(t,{instancePath:e="",parentData:a,parentDataProperty:n,rootData:o=t}={}){if(!Array.isArray(t))return r.errors=[{params:{type:"array"}}],!1;{const e=t.length;for(let a=0;a boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ExternalsType.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ExternalsType.check.js new file mode 100644 index 0000000000000000000000000000000000000000..0ac3c98fffcca816e0c8e294a6cf8a2310dc99a1 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ExternalsType.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function o(m,{instancePath:r="",parentData:s,parentDataProperty:t,rootData:e=m}={}){return"var"!==m&&"module"!==m&&"assign"!==m&&"this"!==m&&"window"!==m&&"self"!==m&&"global"!==m&&"commonjs"!==m&&"commonjs2"!==m&&"commonjs-module"!==m&&"commonjs-static"!==m&&"amd"!==m&&"amd-require"!==m&&"umd"!==m&&"umd2"!==m&&"jsonp"!==m&&"system"!==m&&"promise"!==m&&"import"!==m&&"module-import"!==m&&"script"!==m&&"node-commonjs"!==m?(o.errors=[{params:{}}],!1):(o.errors=null,!0)}module.exports=o,module.exports.default=o; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ExternalsType.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ExternalsType.json new file mode 100644 index 0000000000000000000000000000000000000000..d5898583c6bf864d831ef9b3b6118bac859997bf --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ExternalsType.json @@ -0,0 +1,3 @@ +{ + "$ref": "./ModuleFederationPlugin.json#/definitions/ExternalsType" +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ModuleFederationPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ModuleFederationPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..66c94833a7885f7d9b90160bef37a61c911fe5bb --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ModuleFederationPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../../declarations/plugins/container/ModuleFederationPlugin").ModuleFederationPluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ModuleFederationPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ModuleFederationPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..cee2e81be582ba719f5f08eeb957854547b8c42a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/container/ModuleFederationPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +const t=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;module.exports=D,module.exports.default=D;const e={definitions:{AmdContainer:{type:"string",minLength:1},AuxiliaryComment:{anyOf:[{type:"string"},{$ref:"#/definitions/LibraryCustomUmdCommentObject"}]},EntryRuntime:{anyOf:[{enum:[!1]},{type:"string",minLength:1}]},Exposes:{anyOf:[{type:"array",items:{anyOf:[{$ref:"#/definitions/ExposesItem"},{$ref:"#/definitions/ExposesObject"}]}},{$ref:"#/definitions/ExposesObject"}]},ExposesConfig:{type:"object",additionalProperties:!1,properties:{import:{anyOf:[{$ref:"#/definitions/ExposesItem"},{$ref:"#/definitions/ExposesItems"}]},name:{type:"string"}},required:["import"]},ExposesItem:{type:"string",minLength:1},ExposesItems:{type:"array",items:{$ref:"#/definitions/ExposesItem"}},ExposesObject:{type:"object",additionalProperties:{anyOf:[{$ref:"#/definitions/ExposesConfig"},{$ref:"#/definitions/ExposesItem"},{$ref:"#/definitions/ExposesItems"}]}},ExternalsType:{enum:["var","module","assign","this","window","self","global","commonjs","commonjs2","commonjs-module","commonjs-static","amd","amd-require","umd","umd2","jsonp","system","promise","import","module-import","script","node-commonjs"]},LibraryCustomUmdCommentObject:{type:"object",additionalProperties:!1,properties:{amd:{type:"string"},commonjs:{type:"string"},commonjs2:{type:"string"},root:{type:"string"}}},LibraryCustomUmdObject:{type:"object",additionalProperties:!1,properties:{amd:{type:"string",minLength:1},commonjs:{type:"string",minLength:1},root:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{type:"string",minLength:1}]}}},LibraryExport:{anyOf:[{type:"array",items:{type:"string",minLength:1}},{type:"string",minLength:1}]},LibraryName:{anyOf:[{type:"array",items:{type:"string",minLength:1},minItems:1},{type:"string",minLength:1},{$ref:"#/definitions/LibraryCustomUmdObject"}]},LibraryOptions:{type:"object",additionalProperties:!1,properties:{amdContainer:{$ref:"#/definitions/AmdContainer"},auxiliaryComment:{$ref:"#/definitions/AuxiliaryComment"},export:{$ref:"#/definitions/LibraryExport"},name:{$ref:"#/definitions/LibraryName"},type:{$ref:"#/definitions/LibraryType"},umdNamedDefine:{$ref:"#/definitions/UmdNamedDefine"}},required:["type"]},LibraryType:{anyOf:[{enum:["var","module","assign","assign-properties","this","window","self","global","commonjs","commonjs2","commonjs-module","commonjs-static","amd","amd-require","umd","umd2","jsonp","system"]},{type:"string"}]},Remotes:{anyOf:[{type:"array",items:{anyOf:[{$ref:"#/definitions/RemotesItem"},{$ref:"#/definitions/RemotesObject"}]}},{$ref:"#/definitions/RemotesObject"}]},RemotesConfig:{type:"object",additionalProperties:!1,properties:{external:{anyOf:[{$ref:"#/definitions/RemotesItem"},{$ref:"#/definitions/RemotesItems"}]},shareScope:{type:"string",minLength:1}},required:["external"]},RemotesItem:{type:"string",minLength:1},RemotesItems:{type:"array",items:{$ref:"#/definitions/RemotesItem"}},RemotesObject:{type:"object",additionalProperties:{anyOf:[{$ref:"#/definitions/RemotesConfig"},{$ref:"#/definitions/RemotesItem"},{$ref:"#/definitions/RemotesItems"}]}},Shared:{anyOf:[{type:"array",items:{anyOf:[{$ref:"#/definitions/SharedItem"},{$ref:"#/definitions/SharedObject"}]}},{$ref:"#/definitions/SharedObject"}]},SharedConfig:{type:"object",additionalProperties:!1,properties:{eager:{type:"boolean"},import:{anyOf:[{enum:[!1]},{$ref:"#/definitions/SharedItem"}]},packageName:{type:"string",minLength:1},requiredVersion:{anyOf:[{enum:[!1]},{type:"string"}]},shareKey:{type:"string",minLength:1},shareScope:{type:"string",minLength:1},singleton:{type:"boolean"},strictVersion:{type:"boolean"},version:{anyOf:[{enum:[!1]},{type:"string"}]}}},SharedItem:{type:"string",minLength:1},SharedObject:{type:"object",additionalProperties:{anyOf:[{$ref:"#/definitions/SharedConfig"},{$ref:"#/definitions/SharedItem"}]}},UmdNamedDefine:{type:"boolean"}},type:"object",additionalProperties:!1,properties:{exposes:{$ref:"#/definitions/Exposes"},filename:{type:"string",absolutePath:!1},library:{$ref:"#/definitions/LibraryOptions"},name:{type:"string"},remoteType:{oneOf:[{$ref:"#/definitions/ExternalsType"}]},remotes:{$ref:"#/definitions/Remotes"},runtime:{$ref:"#/definitions/EntryRuntime"},shareScope:{type:"string",minLength:1},shared:{$ref:"#/definitions/Shared"}}},r=Object.prototype.hasOwnProperty;function n(t,{instancePath:e="",parentData:r,parentDataProperty:s,rootData:a=t}={}){if(!Array.isArray(t))return n.errors=[{params:{type:"array"}}],!1;{const e=t.length;for(let r=0;r boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/AggressiveSplittingPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/AggressiveSplittingPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..d74a152767025922bc2cf459799d348801d6debc --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/AggressiveSplittingPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function r(e,{instancePath:t="",parentData:n,parentDataProperty:i,rootData:o=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return r.errors=[{params:{type:"object"}}],!1;{const t=0;for(const t in e)if("chunkOverhead"!==t&&"entryChunkMultiplicator"!==t&&"maxSize"!==t&&"minSize"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(0===t){if(void 0!==e.chunkOverhead){const t=0;if("number"!=typeof e.chunkOverhead)return r.errors=[{params:{type:"number"}}],!1;var a=0===t}else a=!0;if(a){if(void 0!==e.entryChunkMultiplicator){const t=0;if("number"!=typeof e.entryChunkMultiplicator)return r.errors=[{params:{type:"number"}}],!1;a=0===t}else a=!0;if(a){if(void 0!==e.maxSize){const t=0;if("number"!=typeof e.maxSize)return r.errors=[{params:{type:"number"}}],!1;a=0===t}else a=!0;if(a)if(void 0!==e.minSize){const t=0;if("number"!=typeof e.minSize)return r.errors=[{params:{type:"number"}}],!1;a=0===t}else a=!0}}}}return r.errors=null,!0}module.exports=r,module.exports.default=r; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/AggressiveSplittingPlugin.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/AggressiveSplittingPlugin.json new file mode 100644 index 0000000000000000000000000000000000000000..8abcdd8ad5f613aa3c9236609dc6ca77f45b641b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/AggressiveSplittingPlugin.json @@ -0,0 +1,23 @@ +{ + "title": "AggressiveSplittingPluginOptions", + "type": "object", + "additionalProperties": false, + "properties": { + "chunkOverhead": { + "description": "Extra cost for each chunk (Default: 9.8kiB).", + "type": "number" + }, + "entryChunkMultiplicator": { + "description": "Extra cost multiplicator for entry chunks (Default: 10).", + "type": "number" + }, + "maxSize": { + "description": "Byte, max size of per file (Default: 50kiB).", + "type": "number" + }, + "minSize": { + "description": "Byte, split point. (Default: 30kiB).", + "type": "number" + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/LimitChunkCountPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/LimitChunkCountPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a133d633b5256ef3c210fba3508020b5439c830 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/LimitChunkCountPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/LimitChunkCountPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/LimitChunkCountPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..967ed872f888716e9ba3a74fcd05b3cfd9c993c0 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/LimitChunkCountPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function r(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return r.errors=[{params:{type:"object"}}],!1;{let t;if(void 0===e.maxChunks&&(t="maxChunks"))return r.errors=[{params:{missingProperty:t}}],!1;{const t=0;for(const t in e)if("chunkOverhead"!==t&&"entryChunkMultiplicator"!==t&&"maxChunks"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(0===t){if(void 0!==e.chunkOverhead){const t=0;if("number"!=typeof e.chunkOverhead)return r.errors=[{params:{type:"number"}}],!1;var s=0===t}else s=!0;if(s){if(void 0!==e.entryChunkMultiplicator){const t=0;if("number"!=typeof e.entryChunkMultiplicator)return r.errors=[{params:{type:"number"}}],!1;s=0===t}else s=!0;if(s)if(void 0!==e.maxChunks){let t=e.maxChunks;const n=0;if(0===n){if("number"!=typeof t)return r.errors=[{params:{type:"number"}}],!1;if(t<1||isNaN(t))return r.errors=[{params:{comparison:">=",limit:1}}],!1}s=0===n}else s=!0}}}}return r.errors=null,!0}module.exports=r,module.exports.default=r; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/LimitChunkCountPlugin.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/LimitChunkCountPlugin.json new file mode 100644 index 0000000000000000000000000000000000000000..3bbd39188f49fdfff98cda9c8dd6458490ff53b3 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/LimitChunkCountPlugin.json @@ -0,0 +1,21 @@ +{ + "title": "LimitChunkCountPluginOptions", + "type": "object", + "additionalProperties": false, + "properties": { + "chunkOverhead": { + "description": "Constant overhead for a chunk.", + "type": "number" + }, + "entryChunkMultiplicator": { + "description": "Multiplicator for initial chunks.", + "type": "number" + }, + "maxChunks": { + "description": "Limit the maximum number of chunks using a value greater greater than or equal to 1.", + "type": "number", + "minimum": 1 + } + }, + "required": ["maxChunks"] +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8003689a46751a58b91f7127f62fe2847daa853a --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../../declarations/plugins/optimize/MergeDuplicateChunksPlugin").MergeDuplicateChunksPluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..182b09ebe895bff65f0147145a8ed07b7778a209 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function r(t,{instancePath:e="",parentData:a,parentDataProperty:o,rootData:s=t}={}){if(!t||"object"!=typeof t||Array.isArray(t))return r.errors=[{params:{type:"object"}}],!1;{const e=0;for(const e in t)if("stage"!==e)return r.errors=[{params:{additionalProperty:e}}],!1;if(0===e&&void 0!==t.stage&&"number"!=typeof t.stage)return r.errors=[{params:{type:"number"}}],!1}return r.errors=null,!0}module.exports=r,module.exports.default=r; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MergeDuplicateChunksPlugin.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MergeDuplicateChunksPlugin.json new file mode 100644 index 0000000000000000000000000000000000000000..12f591a2cb2f425024f751fd1792b670a7c3dc33 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MergeDuplicateChunksPlugin.json @@ -0,0 +1,11 @@ +{ + "title": "MergeDuplicateChunksPluginOptions", + "type": "object", + "additionalProperties": false, + "properties": { + "stage": { + "description": "Specifies the stage for merging duplicate chunks.", + "type": "number" + } + } +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MinChunkSizePlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MinChunkSizePlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2da0f6e35315055a2c6d03f9cf0a0efb43a21340 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MinChunkSizePlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MinChunkSizePlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MinChunkSizePlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..8eb8dc9fccc7e952075316f910a521d977a940dd --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MinChunkSizePlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function r(e,{instancePath:t="",parentData:n,parentDataProperty:i,rootData:o=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return r.errors=[{params:{type:"object"}}],!1;{let t;if(void 0===e.minChunkSize&&(t="minChunkSize"))return r.errors=[{params:{missingProperty:t}}],!1;{const t=0;for(const t in e)if("chunkOverhead"!==t&&"entryChunkMultiplicator"!==t&&"minChunkSize"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(0===t){if(void 0!==e.chunkOverhead){const t=0;if("number"!=typeof e.chunkOverhead)return r.errors=[{params:{type:"number"}}],!1;var a=0===t}else a=!0;if(a){if(void 0!==e.entryChunkMultiplicator){const t=0;if("number"!=typeof e.entryChunkMultiplicator)return r.errors=[{params:{type:"number"}}],!1;a=0===t}else a=!0;if(a)if(void 0!==e.minChunkSize){const t=0;if("number"!=typeof e.minChunkSize)return r.errors=[{params:{type:"number"}}],!1;a=0===t}else a=!0}}}}return r.errors=null,!0}module.exports=r,module.exports.default=r; \ No newline at end of file diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MinChunkSizePlugin.json b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MinChunkSizePlugin.json new file mode 100644 index 0000000000000000000000000000000000000000..ba02156a0657cad5c8adbafe3cbbd7050832907b --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/optimize/MinChunkSizePlugin.json @@ -0,0 +1,20 @@ +{ + "title": "MinChunkSizePluginOptions", + "type": "object", + "additionalProperties": false, + "properties": { + "chunkOverhead": { + "description": "Constant overhead for a chunk.", + "type": "number" + }, + "entryChunkMultiplicator": { + "description": "Multiplicator for initial chunks.", + "type": "number" + }, + "minChunkSize": { + "description": "Minimum number of characters.", + "type": "number" + } + }, + "required": ["minChunkSize"] +} diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/ConsumeSharedPlugin.check.d.ts b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/ConsumeSharedPlugin.check.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a24ecdfb61d0d19513a26549197209b41926adf5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/ConsumeSharedPlugin.check.d.ts @@ -0,0 +1,7 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +declare const check: (options: import("../../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions) => boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/ConsumeSharedPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/ConsumeSharedPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..19b0e7da002f7db133afd6f24dfc368c189bff88 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/ConsumeSharedPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function r(e,{instancePath:t="",parentData:n,parentDataProperty:s,rootData:a=e}={}){let o=null,i=0;if(0===i){if(!e||"object"!=typeof e||Array.isArray(e))return r.errors=[{params:{type:"object"}}],!1;{const t=i;for(const t in e)if("eager"!==t&&"import"!==t&&"packageName"!==t&&"requiredVersion"!==t&&"shareKey"!==t&&"shareScope"!==t&&"singleton"!==t&&"strictVersion"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(t===i){if(void 0!==e.eager){const t=i;if("boolean"!=typeof e.eager)return r.errors=[{params:{type:"boolean"}}],!1;var l=t===i}else l=!0;if(l){if(void 0!==e.import){let t=e.import;const n=i,s=i;let a=!1;const f=i;if(!1!==t){const r={params:{}};null===o?o=[r]:o.push(r),i++}var p=f===i;if(a=a||p,!a){const r=i;if(i==i)if("string"==typeof t){if(t.length<1){const r={params:{}};null===o?o=[r]:o.push(r),i++}}else{const r={params:{type:"string"}};null===o?o=[r]:o.push(r),i++}p=r===i,a=a||p}if(!a){const e={params:{}};return null===o?o=[e]:o.push(e),i++,r.errors=o,!1}i=s,null!==o&&(s?o.length=s:o=null),l=n===i}else l=!0;if(l){if(void 0!==e.packageName){let t=e.packageName;const n=i;if(i===n){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}l=n===i}else l=!0;if(l){if(void 0!==e.requiredVersion){let t=e.requiredVersion;const n=i,s=i;let a=!1;const p=i;if(!1!==t){const r={params:{}};null===o?o=[r]:o.push(r),i++}var f=p===i;if(a=a||f,!a){const r=i;if("string"!=typeof t){const r={params:{type:"string"}};null===o?o=[r]:o.push(r),i++}f=r===i,a=a||f}if(!a){const e={params:{}};return null===o?o=[e]:o.push(e),i++,r.errors=o,!1}i=s,null!==o&&(s?o.length=s:o=null),l=n===i}else l=!0;if(l){if(void 0!==e.shareKey){let t=e.shareKey;const n=i;if(i===n){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}l=n===i}else l=!0;if(l){if(void 0!==e.shareScope){let t=e.shareScope;const n=i;if(i===n){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}l=n===i}else l=!0;if(l){if(void 0!==e.singleton){const t=i;if("boolean"!=typeof e.singleton)return r.errors=[{params:{type:"boolean"}}],!1;l=t===i}else l=!0;if(l)if(void 0!==e.strictVersion){const t=i;if("boolean"!=typeof e.strictVersion)return r.errors=[{params:{type:"boolean"}}],!1;l=t===i}else l=!0}}}}}}}}}return r.errors=o,0===i}function e(t,{instancePath:n="",parentData:s,parentDataProperty:a,rootData:o=t}={}){let i=null,l=0;if(0===l){if(!t||"object"!=typeof t||Array.isArray(t))return e.errors=[{params:{type:"object"}}],!1;for(const s in t){let a=t[s];const f=l,c=l;let u=!1;const y=l;r(a,{instancePath:n+"/"+s.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:t,parentDataProperty:s,rootData:o})||(i=null===i?r.errors:i.concat(r.errors),l=i.length);var p=y===l;if(u=u||p,!u){const r=l;if(l==l)if("string"==typeof a){if(a.length<1){const r={params:{}};null===i?i=[r]:i.push(r),l++}}else{const r={params:{type:"string"}};null===i?i=[r]:i.push(r),l++}p=r===l,u=u||p}if(!u){const r={params:{}};return null===i?i=[r]:i.push(r),l++,e.errors=i,!1}if(l=c,null!==i&&(c?i.length=c:i=null),f!==l)break}}return e.errors=i,0===l}function t(r,{instancePath:n="",parentData:s,parentDataProperty:a,rootData:o=r}={}){let i=null,l=0;const p=l;let f=!1;const c=l;if(l===c)if(Array.isArray(r)){const t=r.length;for(let s=0;s boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/ProvideSharedPlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/ProvideSharedPlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..2a6c5200091b2432f9a9d2a0f9954e6875d9b7f5 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/ProvideSharedPlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";function r(t,{instancePath:e="",parentData:s,parentDataProperty:n,rootData:a=t}={}){let o=null,l=0;if(0===l){if(!t||"object"!=typeof t||Array.isArray(t))return r.errors=[{params:{type:"object"}}],!1;for(const e in t){let s=t[e];const n=l,a=l;let f=!1;const u=l;if(l==l)if(s&&"object"==typeof s&&!Array.isArray(s)){const r=l;for(const r in s)if("eager"!==r&&"shareKey"!==r&&"shareScope"!==r&&"version"!==r){const t={params:{additionalProperty:r}};null===o?o=[t]:o.push(t),l++;break}if(r===l){if(void 0!==s.eager){const r=l;if("boolean"!=typeof s.eager){const r={params:{type:"boolean"}};null===o?o=[r]:o.push(r),l++}var i=r===l}else i=!0;if(i){if(void 0!==s.shareKey){let r=s.shareKey;const t=l;if(l===t)if("string"==typeof r){if(r.length<1){const r={params:{}};null===o?o=[r]:o.push(r),l++}}else{const r={params:{type:"string"}};null===o?o=[r]:o.push(r),l++}i=t===l}else i=!0;if(i){if(void 0!==s.shareScope){let r=s.shareScope;const t=l;if(l===t)if("string"==typeof r){if(r.length<1){const r={params:{}};null===o?o=[r]:o.push(r),l++}}else{const r={params:{type:"string"}};null===o?o=[r]:o.push(r),l++}i=t===l}else i=!0;if(i)if(void 0!==s.version){let r=s.version;const t=l,e=l;let n=!1;const a=l;if(!1!==r){const r={params:{}};null===o?o=[r]:o.push(r),l++}var p=a===l;if(n=n||p,!n){const t=l;if("string"!=typeof r){const r={params:{type:"string"}};null===o?o=[r]:o.push(r),l++}p=t===l,n=n||p}if(n)l=e,null!==o&&(e?o.length=e:o=null);else{const r={params:{}};null===o?o=[r]:o.push(r),l++}i=t===l}else i=!0}}}}else{const r={params:{type:"object"}};null===o?o=[r]:o.push(r),l++}var c=u===l;if(f=f||c,!f){const r=l;if(l==l)if("string"==typeof s){if(s.length<1){const r={params:{}};null===o?o=[r]:o.push(r),l++}}else{const r={params:{type:"string"}};null===o?o=[r]:o.push(r),l++}c=r===l,f=f||c}if(!f){const t={params:{}};return null===o?o=[t]:o.push(t),l++,r.errors=o,!1}if(l=a,null!==o&&(a?o.length=a:o=null),n!==l)break}}return r.errors=o,0===l}function t(e,{instancePath:s="",parentData:n,parentDataProperty:a,rootData:o=e}={}){let l=null,i=0;const p=i;let c=!1;const f=i;if(i===f)if(Array.isArray(e)){const t=e.length;for(let n=0;n boolean; +export = check; diff --git a/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/SharePlugin.check.js b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/SharePlugin.check.js new file mode 100644 index 0000000000000000000000000000000000000000..839423fff0cb17fc167677e616bb657ec6367a91 --- /dev/null +++ b/novas/novacore-zephyr/groq-code-cli/node_modules/webpack/schemas/plugins/sharing/SharePlugin.check.js @@ -0,0 +1,6 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ +"use strict";module.exports=a,module.exports.default=a;const r={type:"object",additionalProperties:!1,properties:{eager:{type:"boolean"},import:{anyOf:[{enum:[!1]},{$ref:"#/definitions/SharedItem"}]},packageName:{type:"string",minLength:1},requiredVersion:{anyOf:[{enum:[!1]},{type:"string"}]},shareKey:{type:"string",minLength:1},shareScope:{type:"string",minLength:1},singleton:{type:"boolean"},strictVersion:{type:"boolean"},version:{anyOf:[{enum:[!1]},{type:"string"}]}}},e=Object.prototype.hasOwnProperty;function t(n,{instancePath:s="",parentData:a,parentDataProperty:o,rootData:i=n}={}){let l=null,p=0;if(0===p){if(!n||"object"!=typeof n||Array.isArray(n))return t.errors=[{params:{type:"object"}}],!1;{const s=p;for(const s in n)if(!e.call(r.properties,s))return t.errors=[{params:{additionalProperty:s}}],!1;if(s===p){if(void 0!==n.eager){const r=p;if("boolean"!=typeof n.eager)return t.errors=[{params:{type:"boolean"}}],!1;var f=r===p}else f=!0;if(f){if(void 0!==n.import){let r=n.import;const e=p,s=p;let a=!1;const o=p;if(!1!==r){const r={params:{}};null===l?l=[r]:l.push(r),p++}var u=o===p;if(a=a||u,!a){const e=p;if(p==p)if("string"==typeof r){if(r.length<1){const r={params:{}};null===l?l=[r]:l.push(r),p++}}else{const r={params:{type:"string"}};null===l?l=[r]:l.push(r),p++}u=e===p,a=a||u}if(!a){const r={params:{}};return null===l?l=[r]:l.push(r),p++,t.errors=l,!1}p=s,null!==l&&(s?l.length=s:l=null),f=e===p}else f=!0;if(f){if(void 0!==n.packageName){let r=n.packageName;const e=p;if(p===e){if("string"!=typeof r)return t.errors=[{params:{type:"string"}}],!1;if(r.length<1)return t.errors=[{params:{}}],!1}f=e===p}else f=!0;if(f){if(void 0!==n.requiredVersion){let r=n.requiredVersion;const e=p,s=p;let a=!1;const o=p;if(!1!==r){const r={params:{}};null===l?l=[r]:l.push(r),p++}var c=o===p;if(a=a||c,!a){const e=p;if("string"!=typeof r){const r={params:{type:"string"}};null===l?l=[r]:l.push(r),p++}c=e===p,a=a||c}if(!a){const r={params:{}};return null===l?l=[r]:l.push(r),p++,t.errors=l,!1}p=s,null!==l&&(s?l.length=s:l=null),f=e===p}else f=!0;if(f){if(void 0!==n.shareKey){let r=n.shareKey;const e=p;if(p===e){if("string"!=typeof r)return t.errors=[{params:{type:"string"}}],!1;if(r.length<1)return t.errors=[{params:{}}],!1}f=e===p}else f=!0;if(f){if(void 0!==n.shareScope){let r=n.shareScope;const e=p;if(p===e){if("string"!=typeof r)return t.errors=[{params:{type:"string"}}],!1;if(r.length<1)return t.errors=[{params:{}}],!1}f=e===p}else f=!0;if(f){if(void 0!==n.singleton){const r=p;if("boolean"!=typeof n.singleton)return t.errors=[{params:{type:"boolean"}}],!1;f=r===p}else f=!0;if(f){if(void 0!==n.strictVersion){const r=p;if("boolean"!=typeof n.strictVersion)return t.errors=[{params:{type:"boolean"}}],!1;f=r===p}else f=!0;if(f)if(void 0!==n.version){let r=n.version;const e=p,s=p;let a=!1;const o=p;if(!1!==r){const r={params:{}};null===l?l=[r]:l.push(r),p++}var y=o===p;if(a=a||y,!a){const e=p;if("string"!=typeof r){const r={params:{type:"string"}};null===l?l=[r]:l.push(r),p++}y=e===p,a=a||y}if(!a){const r={params:{}};return null===l?l=[r]:l.push(r),p++,t.errors=l,!1}p=s,null!==l&&(s?l.length=s:l=null),f=e===p}else f=!0}}}}}}}}}}return t.errors=l,0===p}function n(r,{instancePath:e="",parentData:s,parentDataProperty:a,rootData:o=r}={}){let i=null,l=0;if(0===l){if(!r||"object"!=typeof r||Array.isArray(r))return n.errors=[{params:{type:"object"}}],!1;for(const s in r){let a=r[s];const f=l,u=l;let c=!1;const y=l;t(a,{instancePath:e+"/"+s.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:r,parentDataProperty:s,rootData:o})||(i=null===i?t.errors:i.concat(t.errors),l=i.length);var p=y===l;if(c=c||p,!c){const r=l;if(l==l)if("string"==typeof a){if(a.length<1){const r={params:{}};null===i?i=[r]:i.push(r),l++}}else{const r={params:{type:"string"}};null===i?i=[r]:i.push(r),l++}p=r===l,c=c||p}if(!c){const r={params:{}};return null===i?i=[r]:i.push(r),l++,n.errors=i,!1}if(l=u,null!==i&&(u?i.length=u:i=null),f!==l)break}}return n.errors=i,0===l}function s(r,{instancePath:e="",parentData:t,parentDataProperty:a,rootData:o=r}={}){let i=null,l=0;const p=l;let f=!1;const u=l;if(l===u)if(Array.isArray(r)){const t=r.length;for(let s=0;s