WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
"use strict";
var _object_without_properties_loose = require("./_object_without_properties_loose.cjs");
function _object_without_properties(source, excluded) {
if (source == null) return {};
var target = {}, sourceKeys, key, i;
if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
sourceKeys = Reflect.ownKeys(Object(source));
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
return target;
}
target = _object_without_properties_loose._(source, excluded);
if (Object.getOwnPropertySymbols) {
sourceKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
exports._ = _object_without_properties;

View File

@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImplicitLibVariable = void 0;
const ESLintScopeVariable_1 = require("./ESLintScopeVariable");
/**
* An variable implicitly defined by the TS Lib
*/
class ImplicitLibVariable extends ESLintScopeVariable_1.ESLintScopeVariable {
/**
* `true` if the variable is valid in a type context, false otherwise
*/
isTypeVariable;
/**
* `true` if the variable is valid in a value context, false otherwise
*/
isValueVariable;
constructor(scope, name, { eslintImplicitGlobalSetting, isTypeVariable, isValueVariable, writeable, }) {
super(name, scope);
this.isTypeVariable = isTypeVariable ?? false;
this.isValueVariable = isValueVariable ?? false;
this.writeable = writeable ?? false;
this.eslintImplicitGlobalSetting =
eslintImplicitGlobalSetting ?? 'readonly';
}
}
exports.ImplicitLibVariable = ImplicitLibVariable;

View File

@@ -0,0 +1 @@
{"version":3,"file":"hkdf.d.ts","sourceRoot":"","sources":["../src/hkdf.ts"],"names":[],"mappings":"AAMA,OAAO,EAAkB,KAAK,KAAK,EAAS,KAAK,KAAK,EAAW,MAAM,YAAY,CAAC;AAEpF;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,KAAK,GAAG,UAAU,CAOzE;AAKD;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,GAAE,MAAW,GAAG,UAAU,CA4B7F;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,IAAI,GACf,MAAM,KAAK,EACX,KAAK,KAAK,EACV,MAAM,KAAK,GAAG,SAAS,EACvB,MAAM,KAAK,GAAG,SAAS,EACvB,QAAQ,MAAM,KACb,UAAkE,CAAC"}

View File

@@ -0,0 +1,26 @@
function asyncGeneratorStep(n, t, e, r, o, a, c) {
try {
var i = n[a](c),
u = i.value;
} catch (n) {
return void e(n);
}
i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
return function () {
var t = this,
e = arguments;
return new Promise(function (r, o) {
var a = n.apply(t, e);
function _next(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
}
function _throw(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
}
_next(void 0);
});
};
}
module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,5 @@
import checkPrivateRedeclaration from "./checkPrivateRedeclaration.js";
function _classPrivateMethodInitSpec(e, a) {
checkPrivateRedeclaration(e, a), a.add(e);
}
export { _classPrivateMethodInitSpec as default };

View File

@@ -0,0 +1,689 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
const assertionFunctionUtils_1 = require("../util/assertionFunctionUtils");
// #region
const nullishFlag = ts.TypeFlags.Undefined | ts.TypeFlags.Null;
function isNullishType(type) {
return tsutils.isTypeFlagSet(type, nullishFlag);
}
function isAlwaysNullish(type) {
return tsutils.unionConstituents(type).every(isNullishType);
}
/**
* Note that this differs from {@link isNullableType} in that it doesn't consider
* `any` or `unknown` to be nullable.
*/
function isPossiblyNullish(type) {
return tsutils
.unionConstituents(type)
.some(t => isNullishType(t) || (0, util_1.isTypeFlagSet)(t, ts.TypeFlags.Void));
}
function toStaticValue(type) {
// type.isLiteral() only covers numbers/bigints and strings, hence the rest of the branches.
if (tsutils.isBooleanLiteralType(type)) {
return { value: tsutils.isTrueLiteralType(type) };
}
if (type.flags === ts.TypeFlags.Undefined) {
return { value: undefined };
}
if (type.flags === ts.TypeFlags.Null) {
return { value: null };
}
if (type.isLiteral()) {
return { value: (0, util_1.getValueOfLiteralType)(type) };
}
return undefined;
}
const BOOL_OPERATORS = new Set([
'<',
'>',
'<=',
'>=',
'==',
'===',
'!=',
'!==',
]);
function isBoolOperator(operator) {
return BOOL_OPERATORS.has(operator);
}
function booleanComparison(left, operator, right) {
switch (operator) {
case '!=':
// eslint-disable-next-line eqeqeq -- intentionally comparing with loose equality
return left != right;
case '!==':
return left !== right;
case '<':
// @ts-expect-error: we don't care if the comparison seems unintentional.
return left < right;
case '<=':
// @ts-expect-error: we don't care if the comparison seems unintentional.
return left <= right;
case '==':
// eslint-disable-next-line eqeqeq -- intentionally comparing with loose equality
return left == right;
case '===':
return left === right;
case '>':
// @ts-expect-error: we don't care if the comparison seems unintentional.
return left > right;
case '>=':
// @ts-expect-error: we don't care if the comparison seems unintentional.
return left >= right;
}
}
const constantLoopConditionsAllowedLiterals = new Set([
true,
false,
1,
0,
]);
exports.default = (0, util_1.createRule)({
name: 'no-unnecessary-condition',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow conditionals where the type is always truthy or always falsy',
recommended: 'strict',
requiresTypeChecking: true,
},
hasSuggestions: true,
messages: {
alwaysFalsy: 'Unnecessary conditional, value is always falsy.',
alwaysFalsyFunc: 'This callback should return a conditional, but return is always falsy.',
alwaysNullish: 'Unnecessary conditional, left-hand side of `??` operator is always `null` or `undefined`.',
alwaysTruthy: 'Unnecessary conditional, value is always truthy.',
alwaysTruthyFunc: 'This callback should return a conditional, but return is always truthy.',
comparisonBetweenLiteralTypes: 'Unnecessary conditional, comparison is always {{trueOrFalse}}, since `{{left}} {{operator}} {{right}}` is {{trueOrFalse}}.',
never: 'Unnecessary conditional, value is `never`.',
neverNullish: 'Unnecessary conditional, expected left-hand side of `??` operator to be possibly null or undefined.',
neverOptionalChain: 'Unnecessary optional chain on a non-nullish value.',
noOverlapBooleanExpression: 'Unnecessary conditional, the types have no overlap.',
noStrictNullCheck: 'This rule requires the `strictNullChecks` compiler option to be turned on to function correctly.',
suggestRemoveOptionalChain: 'Remove unnecessary optional chain',
typeGuardAlreadyIsType: 'Unnecessary conditional, expression already has the type being checked by the {{typeGuardOrAssertionFunction}}.',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowConstantLoopConditions: {
description: 'Whether to ignore constant loop conditions, such as `while (true)`.',
oneOf: [
{
type: 'boolean',
description: 'Always ignore or not ignore the loop conditions',
},
{
type: 'string',
description: 'Which situations to ignore constant conditions in.',
enum: ['always', 'never', 'only-allowed-literals'],
},
],
},
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: {
type: 'boolean',
description: 'Whether to not error when running with a tsconfig that has strictNullChecks turned.',
},
checkTypePredicates: {
type: 'boolean',
description: 'Whether to check the asserted argument of a type predicate function for unnecessary conditions',
},
},
},
],
},
defaultOptions: [
{
allowConstantLoopConditions: 'never',
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
checkTypePredicates: false,
},
],
create(context, [{ allowConstantLoopConditions, allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing, checkTypePredicates, },]) {
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
const compilerOptions = services.program.getCompilerOptions();
const isStrictNullChecks = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks');
const isNoUncheckedIndexedAccess = tsutils.isCompilerOptionEnabled(compilerOptions, 'noUncheckedIndexedAccess');
const allowConstantLoopConditionsOption = normalizeAllowConstantLoopConditions(
// https://github.com/typescript-eslint/typescript-eslint/issues/5439
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
allowConstantLoopConditions);
if (!isStrictNullChecks &&
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing !== true) {
context.report({
loc: {
start: { column: 0, line: 0 },
end: { column: 0, line: 0 },
},
messageId: 'noStrictNullCheck',
});
}
function nodeIsArrayType(node) {
const nodeType = (0, util_1.getConstrainedTypeAtLocation)(services, node);
return tsutils
.unionConstituents(nodeType)
.some(part => checker.isArrayType(part));
}
function nodeIsTupleType(node) {
const nodeType = (0, util_1.getConstrainedTypeAtLocation)(services, node);
return tsutils
.unionConstituents(nodeType)
.some(part => checker.isTupleType(part));
}
function isArrayIndexExpression(node) {
return (
// Is an index signature
node.type === utils_1.AST_NODE_TYPES.MemberExpression &&
node.computed &&
// ...into an array type
(nodeIsArrayType(node.object) ||
// ... or a tuple type
(nodeIsTupleType(node.object) &&
// Exception: literal index into a tuple - will have a sound type
node.property.type !== utils_1.AST_NODE_TYPES.Literal)));
}
// Conditional is always necessary if it involves:
// `any` or `unknown` or a naked type variable
function isConditionalAlwaysNecessary(type) {
return tsutils
.unionConstituents(type)
.some(part => (0, util_1.isTypeAnyType)(part) ||
(0, util_1.isTypeUnknownType)(part) ||
(0, util_1.isTypeFlagSet)(part, ts.TypeFlags.TypeVariable));
}
function isNullableMemberExpression(node) {
const objectType = services.getTypeAtLocation(node.object);
if (node.computed) {
const propertyType = services.getTypeAtLocation(node.property);
return isNullablePropertyType(objectType, propertyType);
}
const property = node.property;
// Get the actual property name, to account for private properties (this.#prop).
const propertyName = context.sourceCode.getText(property);
const propertyType = objectType
.getProperties()
.find(prop => prop.name === propertyName);
if (propertyType &&
tsutils.isSymbolFlagSet(propertyType, ts.SymbolFlags.Optional)) {
return true;
}
return false;
}
/**
* Checks if a conditional node is necessary:
* if the type of the node is always true or always false, it's not necessary.
*/
function checkNode(expression, isUnaryNotArgument = false, node = expression) {
// Check if the node is Unary Negation expression and handle it
if (expression.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
expression.operator === '!') {
return checkNode(expression.argument, !isUnaryNotArgument, node);
}
// Since typescript array index signature types don't represent the
// possibility of out-of-bounds access, if we're indexing into an array
// just skip the check, to avoid false positives
if (!isNoUncheckedIndexedAccess && isArrayIndexExpression(expression)) {
return;
}
// When checking logical expressions, only check the right side
// as the left side has been checked by checkLogicalExpressionForUnnecessaryConditionals
//
// Unless the node is nullish coalescing, as it's common to use patterns like `nullBool ?? true` to to strict
// boolean checks if we inspect the right here, it'll usually be a constant condition on purpose.
// In this case it's better to inspect the type of the expression as a whole.
if (expression.type === utils_1.AST_NODE_TYPES.LogicalExpression &&
expression.operator !== '??') {
return checkNode(expression.right);
}
const type = (0, util_1.getConstrainedTypeAtLocation)(services, expression);
if (isConditionalAlwaysNecessary(type)) {
return;
}
let messageId = null;
if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Never)) {
messageId = 'never';
}
else if (!(0, util_1.isPossiblyTruthy)(type)) {
messageId = !isUnaryNotArgument ? 'alwaysFalsy' : 'alwaysTruthy';
}
else if (!(0, util_1.isPossiblyFalsy)(type)) {
messageId = !isUnaryNotArgument ? 'alwaysTruthy' : 'alwaysFalsy';
}
if (messageId) {
context.report({ node, messageId });
}
}
function checkNodeForNullish(node) {
const type = (0, util_1.getConstrainedTypeAtLocation)(services, node);
// Conditional is always necessary if it involves `any`, `unknown` or a naked type parameter
if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Any |
ts.TypeFlags.Unknown |
ts.TypeFlags.TypeParameter |
ts.TypeFlags.TypeVariable)) {
return;
}
let messageId = null;
if ((0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Never)) {
messageId = 'never';
}
else if (!isPossiblyNullish(type) &&
!(node.type === utils_1.AST_NODE_TYPES.MemberExpression &&
isNullableMemberExpression(node))) {
// Since typescript array index signature types don't represent the
// possibility of out-of-bounds access, if we're indexing into an array
// just skip the check, to avoid false positives
if (isNoUncheckedIndexedAccess ||
(!isArrayIndexExpression(node) &&
!(node.type === utils_1.AST_NODE_TYPES.ChainExpression &&
node.expression.type !== utils_1.AST_NODE_TYPES.TSNonNullExpression &&
optionChainContainsOptionArrayIndex(node.expression)))) {
messageId = 'neverNullish';
}
}
else if (isAlwaysNullish(type)) {
messageId = 'alwaysNullish';
}
if (messageId) {
context.report({ node, messageId });
}
}
/**
* Checks that a binary expression is necessarily conditional, reports otherwise.
* If both sides of the binary expression are literal values, it's not a necessary condition.
*
* NOTE: It's also unnecessary if the types that don't overlap at all
* but that case is handled by the Typescript compiler itself.
* Known exceptions:
* - https://github.com/microsoft/TypeScript/issues/32627
* - https://github.com/microsoft/TypeScript/issues/37160 (handled)
*/
function checkIfBoolExpressionIsNecessaryConditional(node, left, right, operator) {
const leftType = (0, util_1.getConstrainedTypeAtLocation)(services, left);
const rightType = (0, util_1.getConstrainedTypeAtLocation)(services, right);
const leftStaticValue = toStaticValue(leftType);
const rightStaticValue = toStaticValue(rightType);
if (leftStaticValue != null && rightStaticValue != null) {
const conditionIsTrue = booleanComparison(leftStaticValue.value, operator, rightStaticValue.value);
context.report({
node,
messageId: 'comparisonBetweenLiteralTypes',
data: {
left: checker.typeToString(leftType),
operator,
right: checker.typeToString(rightType),
trueOrFalse: conditionIsTrue ? 'true' : 'false',
},
});
return;
}
// Workaround for https://github.com/microsoft/TypeScript/issues/37160
if (isStrictNullChecks) {
const UNDEFINED = ts.TypeFlags.Undefined;
const NULL = ts.TypeFlags.Null;
const VOID = ts.TypeFlags.Void;
const isComparable = (type, flag) => {
// Allow comparison to `any`, `unknown` or a naked type parameter.
flag |=
ts.TypeFlags.Any |
ts.TypeFlags.Unknown |
ts.TypeFlags.TypeParameter |
ts.TypeFlags.TypeVariable;
// Allow loose comparison to nullish values.
if (operator === '==' || operator === '!=') {
flag |= NULL | UNDEFINED | VOID;
}
return (0, util_1.isTypeFlagSet)(type, flag);
};
if ((leftType.flags === UNDEFINED &&
!isComparable(rightType, UNDEFINED | VOID)) ||
(rightType.flags === UNDEFINED &&
!isComparable(leftType, UNDEFINED | VOID)) ||
(leftType.flags === NULL && !isComparable(rightType, NULL)) ||
(rightType.flags === NULL && !isComparable(leftType, NULL))) {
context.report({ node, messageId: 'noOverlapBooleanExpression' });
return;
}
}
}
/**
* Checks that a logical expression contains a boolean, reports otherwise.
*/
function checkLogicalExpressionForUnnecessaryConditionals(node) {
if (node.operator === '??') {
checkNodeForNullish(node.left);
return;
}
// Only checks the left side, since the right side might not be "conditional" at all.
// The right side will be checked if the LogicalExpression is used in a conditional context
checkNode(node.left);
}
/**
* Checks that a testable expression of a loop is necessarily conditional, reports otherwise.
*/
function checkIfLoopIsNecessaryConditional(node) {
if (node.test == null) {
// e.g. `for(;;)`
return;
}
if (allowConstantLoopConditionsOption === 'only-allowed-literals' &&
node.test.type === utils_1.AST_NODE_TYPES.Literal &&
constantLoopConditionsAllowedLiterals.has(node.test.value)) {
return;
}
if (allowConstantLoopConditionsOption === 'always' &&
tsutils.isTrueLiteralType((0, util_1.getConstrainedTypeAtLocation)(services, node.test))) {
return;
}
checkNode(node.test);
}
function checkCallExpression(node) {
if (checkTypePredicates) {
const truthinessAssertedArgument = (0, assertionFunctionUtils_1.findTruthinessAssertedArgument)(services, node);
if (truthinessAssertedArgument != null) {
checkNode(truthinessAssertedArgument);
}
const typeGuardAssertedArgument = (0, assertionFunctionUtils_1.findTypeGuardAssertedArgument)(services, node);
if (typeGuardAssertedArgument != null) {
const typeOfArgument = (0, util_1.getConstrainedTypeAtLocation)(services, typeGuardAssertedArgument.argument);
if (
// Skip `any` — it is assignable to everything, producing
// false positives for meaningful runtime type guards.
!tsutils.isTypeFlagSet(typeOfArgument, ts.TypeFlags.Any | ts.TypeFlags.Unknown) &&
checker.isTypeAssignableTo(typeOfArgument, typeGuardAssertedArgument.type) &&
// Only flag if the types are mutually assignable (i.e. equivalent,
// like Narrower ↔ Wider with optional props) or the predicate type
// is a union that the argument is a strict subtype of. This avoids
// false positives with structural subtypes whose extra members are
// all optional in the *predicate* type (e.g. custom MappedType
// interfaces extending ts.Type).
(checker.isTypeAssignableTo(typeGuardAssertedArgument.type, typeOfArgument) ||
typeGuardAssertedArgument.type.isUnion())) {
context.report({
node: typeGuardAssertedArgument.argument,
messageId: 'typeGuardAlreadyIsType',
data: {
typeGuardOrAssertionFunction: typeGuardAssertedArgument.asserts
? 'assertion function'
: 'type guard',
},
});
}
}
}
// If this is something like arr.filter(x => /*condition*/), check `condition`
if ((0, util_1.isArrayMethodCallWithPredicate)(context, services, node) &&
node.arguments.length) {
const callback = node.arguments[0];
// Inline defined functions
if (callback.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression ||
callback.type === utils_1.AST_NODE_TYPES.FunctionExpression) {
// Two special cases, where we can directly check the node that's returned:
// () => something
if (callback.body.type !== utils_1.AST_NODE_TYPES.BlockStatement) {
return checkNode(callback.body);
}
// () => { return something; }
const callbackBody = callback.body.body;
if (callbackBody.length === 1 &&
callbackBody[0].type === utils_1.AST_NODE_TYPES.ReturnStatement &&
callbackBody[0].argument) {
return checkNode(callbackBody[0].argument);
}
// Potential enhancement: could use code-path analysis to check
// any function with a single return statement
// (Value to complexity ratio is dubious however)
}
// Otherwise just do type analysis on the function as a whole.
const returnTypes = tsutils
.getCallSignaturesOfType((0, util_1.getConstrainedTypeAtLocation)(services, callback))
.map(sig => sig.getReturnType());
if (returnTypes.length === 0) {
// Not a callable function, e.g. `any`
return;
}
let hasFalsyReturnTypes = false;
let hasTruthyReturnTypes = false;
for (const type of returnTypes) {
const { constraintType } = (0, util_1.getConstraintInfo)(checker, type);
// Predicate is always necessary if it involves `any` or `unknown`
if (!constraintType ||
(0, util_1.isTypeAnyType)(constraintType) ||
(0, util_1.isTypeUnknownType)(constraintType)) {
return;
}
if ((0, util_1.isPossiblyFalsy)(constraintType)) {
hasFalsyReturnTypes = true;
}
if ((0, util_1.isPossiblyTruthy)(constraintType)) {
hasTruthyReturnTypes = true;
}
// bail early if both a possibly-truthy and a possibly-falsy have been detected
if (hasFalsyReturnTypes && hasTruthyReturnTypes) {
return;
}
}
if (!hasFalsyReturnTypes) {
return context.report({
node: callback,
messageId: 'alwaysTruthyFunc',
});
}
if (!hasTruthyReturnTypes) {
return context.report({
node: callback,
messageId: 'alwaysFalsyFunc',
});
}
}
}
// Recursively searches an optional chain for an array index expression
// Has to search the entire chain, because an array index will "infect" the rest of the types
// Example:
// ```
// [{x: {y: "z"} }][n] // type is {x: {y: "z"}}
// ?.x // type is {y: "z"}
// ?.y // This access is considered "unnecessary" according to the types
// ```
function optionChainContainsOptionArrayIndex(node) {
const lhsNode = node.type === utils_1.AST_NODE_TYPES.CallExpression ? node.callee : node.object;
if (node.optional && isArrayIndexExpression(lhsNode)) {
return true;
}
if (lhsNode.type === utils_1.AST_NODE_TYPES.MemberExpression ||
lhsNode.type === utils_1.AST_NODE_TYPES.CallExpression) {
return optionChainContainsOptionArrayIndex(lhsNode);
}
return false;
}
function isNullablePropertyType(objType, propertyType) {
if (propertyType.isUnion()) {
return propertyType.types.some(type => isNullablePropertyType(objType, type));
}
if (propertyType.isNumberLiteral() || propertyType.isStringLiteral()) {
const propType = (0, util_1.getTypeOfPropertyOfName)(checker, objType, propertyType.value.toString());
if (propType) {
return (0, util_1.isNullableType)(propType);
}
}
const typeName = (0, util_1.getTypeName)(checker, propertyType);
return checker
.getIndexInfosOfType(objType)
.some(info => (0, util_1.getTypeName)(checker, info.keyType) === typeName);
}
// Checks whether a member expression is nullable or not regardless of it's previous node.
// Example:
// ```
// // 'bar' is nullable if 'foo' is null.
// // but this function checks regardless of 'foo' type, so returns 'true'.
// declare const foo: { bar : { baz: string } } | null
// foo?.bar;
// ```
function isMemberExpressionNullableOriginFromObject(node) {
const prevType = (0, util_1.getConstrainedTypeAtLocation)(services, node.object);
const property = node.property;
if (prevType.isUnion() && (0, util_1.isIdentifier)(property)) {
const isOwnNullable = prevType.types.some(type => {
if (node.computed) {
const propertyType = (0, util_1.getConstrainedTypeAtLocation)(services, node.property);
return isNullablePropertyType(type, propertyType);
}
const propType = (0, util_1.getTypeOfPropertyOfName)(checker, type, property.name);
if (propType) {
return (0, util_1.isNullableType)(propType);
}
const indexInfo = checker.getIndexInfosOfType(type);
return indexInfo.some(info => {
const isStringTypeName = (0, util_1.getTypeName)(checker, info.keyType) === 'string';
return (isStringTypeName &&
(isNoUncheckedIndexedAccess || (0, util_1.isNullableType)(info.type)));
});
});
return !isOwnNullable && (0, util_1.isNullableType)(prevType);
}
return false;
}
function isCallExpressionNullableOriginFromCallee(node) {
const prevType = (0, util_1.getConstrainedTypeAtLocation)(services, node.callee);
if (prevType.isUnion()) {
const isOwnNullable = prevType.types.some(type => {
const signatures = type.getCallSignatures();
return signatures.some(sig => (0, util_1.isNullableType)(sig.getReturnType()));
});
return !isOwnNullable && (0, util_1.isNullableType)(prevType);
}
return false;
}
function isOptionableExpression(node) {
const type = (0, util_1.getConstrainedTypeAtLocation)(services, node);
const isOwnNullable = node.type === utils_1.AST_NODE_TYPES.MemberExpression
? !isMemberExpressionNullableOriginFromObject(node)
: node.type === utils_1.AST_NODE_TYPES.CallExpression
? !isCallExpressionNullableOriginFromCallee(node)
: true;
return (isConditionalAlwaysNecessary(type) ||
(isOwnNullable && (0, util_1.isNullableType)(type)));
}
function checkOptionalChain(node, beforeOperator, fix) {
// We only care if this step in the chain is optional. If just descend
// from an optional chain, then that's fine.
if (!node.optional) {
return;
}
// Since typescript array index signature types don't represent the
// possibility of out-of-bounds access, if we're indexing into an array
// just skip the check, to avoid false positives
if (!isNoUncheckedIndexedAccess &&
optionChainContainsOptionArrayIndex(node)) {
return;
}
const nodeToCheck = node.type === utils_1.AST_NODE_TYPES.CallExpression ? node.callee : node.object;
if (isOptionableExpression(nodeToCheck)) {
return;
}
const questionDotOperator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(beforeOperator, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator && token.value === '?.'), util_1.NullThrowsReasons.MissingToken('operator', node.type));
context.report({
loc: questionDotOperator.loc,
node,
messageId: 'neverOptionalChain',
suggest: [
{
messageId: 'suggestRemoveOptionalChain',
fix(fixer) {
return fixer.replaceText(questionDotOperator, fix);
},
},
],
});
}
function checkOptionalMemberExpression(node) {
checkOptionalChain(node, node.object, node.computed ? '' : '.');
}
function checkOptionalCallExpression(node) {
checkOptionalChain(node, node.callee, '');
}
function checkAssignmentExpression(node) {
// Similar to checkLogicalExpressionForUnnecessaryConditionals, since
// a ||= b is equivalent to a || (a = b)
if (['&&=', '||='].includes(node.operator)) {
checkNode(node.left);
}
else if (node.operator === '??=') {
checkNodeForNullish(node.left);
}
}
return {
AssignmentExpression: checkAssignmentExpression,
BinaryExpression(node) {
const { operator } = node;
if (isBoolOperator(operator)) {
checkIfBoolExpressionIsNecessaryConditional(node, node.left, node.right, operator);
}
},
CallExpression: checkCallExpression,
'CallExpression[optional = true]': checkOptionalCallExpression,
ConditionalExpression: (node) => checkNode(node.test),
DoWhileStatement: checkIfLoopIsNecessaryConditional,
ForStatement: checkIfLoopIsNecessaryConditional,
IfStatement: (node) => checkNode(node.test),
LogicalExpression: checkLogicalExpressionForUnnecessaryConditionals,
'MemberExpression[optional = true]': checkOptionalMemberExpression,
SwitchCase({ parent, test }) {
// only check `case ...:`, not `default:`
if (test) {
checkIfBoolExpressionIsNecessaryConditional(test, parent.discriminant, test, '===');
}
},
WhileStatement: checkIfLoopIsNecessaryConditional,
};
},
});
function normalizeAllowConstantLoopConditions(allowConstantLoopConditions) {
if (allowConstantLoopConditions === true) {
return 'always';
}
if (allowConstantLoopConditions === false) {
return 'never';
}
return allowConstantLoopConditions;
}

View File

@@ -0,0 +1,5 @@
'use strict'
const compareBuild = require('./compare-build')
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort

View File

@@ -0,0 +1,147 @@
import { Console } from 'node:console';
import { relative } from 'node:path';
import { Writable } from 'node:stream';
import { getSafeTimers } from '@vitest/utils/timers';
import c from 'tinyrainbow';
import { R as RealDate } from './rpc.MzXet3jl.js';
import { g as getWorkerState } from './utils.BX5Fg8C4.js';
import './index.Chj8NDwU.js';
const UNKNOWN_TEST_ID = "__vitest__unknown_test__";
function getTaskIdByStack(root) {
const stack = (/* @__PURE__ */ new Error("STACK_TRACE_ERROR")).stack?.split("\n");
if (!stack) return UNKNOWN_TEST_ID;
const index = stack.findIndex((line) => line.includes("at Console.value"));
const line = index === -1 ? null : stack[index + 2];
if (!line) return UNKNOWN_TEST_ID;
const filepath = line.match(/at\s(.*)\s?/)?.[1];
if (filepath) return relative(root, filepath);
return UNKNOWN_TEST_ID;
}
function createCustomConsole(defaultState) {
const stdoutBuffer = /* @__PURE__ */ new Map();
const stderrBuffer = /* @__PURE__ */ new Map();
const timers = /* @__PURE__ */ new Map();
const { queueMicrotask } = getSafeTimers();
function queueCancelableMicrotask(callback) {
let canceled = false;
queueMicrotask(() => {
if (!canceled) callback();
});
return () => {
canceled = true;
};
}
const state = () => defaultState || getWorkerState();
// group sync console.log calls with micro task
function schedule(taskId) {
const timer = timers.get(taskId);
const { stdoutTime, stderrTime } = timer;
timer.cancel?.();
timer.cancel = queueCancelableMicrotask(() => {
if (stderrTime < stdoutTime) {
sendStderr(taskId);
sendStdout(taskId);
} else {
sendStdout(taskId);
sendStderr(taskId);
}
});
}
function sendStdout(taskId) {
sendBuffer("stdout", taskId);
}
function sendStderr(taskId) {
sendBuffer("stderr", taskId);
}
function sendBuffer(type, taskId) {
const buffers = type === "stdout" ? stdoutBuffer : stderrBuffer;
const buffer = buffers.get(taskId);
if (!buffer) return;
if (state().config.printConsoleTrace) buffer.forEach(([buffer, origin]) => {
sendLog(type, taskId, String(buffer), buffer.length, origin);
});
else sendLog(type, taskId, buffer.map((i) => String(i[0])).join(""), buffer.length);
const timer = timers.get(taskId);
buffers.delete(taskId);
if (type === "stderr") timer.stderrTime = 0;
else timer.stdoutTime = 0;
}
function sendLog(type, taskId, content, size, origin) {
const timer = timers.get(taskId);
const time = type === "stderr" ? timer.stderrTime : timer.stdoutTime;
state().rpc.onUserConsoleLog({
type,
content: content || "<empty line>",
taskId,
time: time || RealDate.now(),
size,
origin
});
}
return new Console({
stdout: new Writable({ write(data, encoding, callback) {
const s = state();
const id = s?.current?.id || s?.current?.suite?.id || s.current?.file.id || getTaskIdByStack(s.config.root);
let timer = timers.get(id);
if (timer) timer.stdoutTime = timer.stdoutTime || RealDate.now();
else {
timer = {
stdoutTime: RealDate.now(),
stderrTime: RealDate.now()
};
timers.set(id, timer);
}
let buffer = stdoutBuffer.get(id);
if (!buffer) {
buffer = [];
stdoutBuffer.set(id, buffer);
}
if (state().config.printConsoleTrace) {
const limit = Error.stackTraceLimit;
Error.stackTraceLimit = limit + 6;
const trace = (/* @__PURE__ */ new Error("STACK_TRACE")).stack?.split("\n").slice(7).join("\n");
Error.stackTraceLimit = limit;
buffer.push([data, trace]);
} else buffer.push([data, void 0]);
schedule(id);
callback();
} }),
stderr: new Writable({ write(data, encoding, callback) {
const s = state();
const id = s?.current?.id || s?.current?.suite?.id || s.current?.file.id || getTaskIdByStack(s.config.root);
let timer = timers.get(id);
if (timer) timer.stderrTime = timer.stderrTime || RealDate.now();
else {
timer = {
stderrTime: RealDate.now(),
stdoutTime: RealDate.now()
};
timers.set(id, timer);
}
let buffer = stderrBuffer.get(id);
if (!buffer) {
buffer = [];
stderrBuffer.set(id, buffer);
}
if (state().config.printConsoleTrace) {
const limit = Error.stackTraceLimit;
Error.stackTraceLimit = limit + 6;
const stack = (/* @__PURE__ */ new Error("STACK_TRACE")).stack?.split("\n");
Error.stackTraceLimit = limit;
if (stack?.some((line) => line.includes("at Console.trace"))) buffer.push([data, void 0]);
else {
const trace = stack?.slice(7).join("\n");
Error.stackTraceLimit = limit;
buffer.push([data, trace]);
}
} else buffer.push([data, void 0]);
schedule(id);
callback();
} }),
colorMode: c.isColorSupported,
groupIndentation: 2
});
}
export { UNKNOWN_TEST_ID, createCustomConsole };

View File

@@ -0,0 +1,118 @@
/**
* @fileoverview `Map` to load rules lazily.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
"use strict";
const debug = require("debug")("eslint:rules");
/** @typedef {import("../../types").Rule.RuleModule} Rule */
/**
* The `Map` object that loads each rule when it's accessed.
* @example
* const rules = new LazyLoadingRuleMap([
* ["eqeqeq", () => require("eqeqeq")],
* ["semi", () => require("semi")],
* ["no-unused-vars", () => require("no-unused-vars")]
* ]);
*
* rules.get("semi"); // call `() => require("semi")` here.
*
* @extends {Map<string, Rule>}
*/
class LazyLoadingRuleMap extends Map {
/**
* Initialize this map.
* @param {Array<[string, function(): Rule]>} loaders The rule loaders.
*/
constructor(loaders) {
let remaining = loaders.length;
super(
debug.enabled
? loaders.map(([ruleId, load]) => {
let cache = null;
return [
ruleId,
() => {
if (!cache) {
debug(
"Loading rule %o (remaining=%d)",
ruleId,
--remaining,
);
cache = load();
}
return cache;
},
];
})
: loaders,
);
// `super(...iterable)` uses `this.set()`, so disable it here.
Object.defineProperty(LazyLoadingRuleMap.prototype, "set", {
configurable: true,
value: void 0,
});
}
/**
* Get a rule.
* Each rule will be loaded on the first access.
* @param {string} ruleId The rule ID to get.
* @returns {Rule|undefined} The rule.
*/
get(ruleId) {
const load = super.get(ruleId);
return load && load();
}
/**
* Iterate rules.
* @returns {IterableIterator<Rule>} Rules.
*/
*values() {
for (const load of super.values()) {
yield load();
}
}
/**
* Iterate rules.
* @returns {IterableIterator<[string, Rule]>} Rules.
*/
*entries() {
for (const [ruleId, load] of super.entries()) {
yield [ruleId, load()];
}
}
/**
* Call a function with each rule.
* @param {Function} callbackFn The callback function.
* @param {any} [thisArg] The object to pass to `this` of the callback function.
* @returns {void}
*/
forEach(callbackFn, thisArg) {
for (const [ruleId, load] of super.entries()) {
callbackFn.call(thisArg, load(), ruleId, this);
}
}
}
// Forbid mutation.
Object.defineProperties(LazyLoadingRuleMap.prototype, {
clear: { configurable: true, value: void 0 },
delete: { configurable: true, value: void 0 },
[Symbol.iterator]: {
configurable: true,
writable: true,
value: LazyLoadingRuleMap.prototype.entries,
},
});
module.exports = { LazyLoadingRuleMap };

View File

@@ -0,0 +1,54 @@
{
"name": "p-locate",
"version": "5.0.0",
"description": "Get the first fulfilled promise that satisfies the provided testing function",
"license": "MIT",
"repository": "sindresorhus/p-locate",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"promise",
"locate",
"find",
"finder",
"search",
"searcher",
"test",
"array",
"collection",
"iterable",
"iterator",
"race",
"fulfilled",
"fastest",
"async",
"await",
"promises",
"bluebird"
],
"dependencies": {
"p-limit": "^3.0.2"
},
"devDependencies": {
"ava": "^2.4.0",
"delay": "^4.1.0",
"in-range": "^2.0.0",
"time-span": "^4.0.0",
"tsd": "^0.13.1",
"xo": "^0.32.1"
}
}

View File

@@ -0,0 +1,218 @@
import type { CacheDurationSeconds, DebugLevel, JSDocParsingMode, ProjectServiceOptions, SourceType } from '@typescript-eslint/types';
import type * as ts from 'typescript';
import type { TSESTree, TSESTreeToTSNode, TSNode, TSToken } from './ts-estree';
interface ParseOptions {
/**
* Specify the `sourceType`.
* For more details, see https://github.com/typescript-eslint/typescript-eslint/pull/9121
*/
sourceType?: SourceType;
/**
* Prevents the parser from throwing an error if it receives an invalid AST from TypeScript.
* This case only usually occurs when attempting to lint invalid code.
*/
allowInvalidAST?: boolean;
/**
* create a top-level comments array containing all comments
*/
comment?: boolean;
/**
* An array of modules to turn explicit debugging on for.
* - 'typescript-eslint' is the same as setting the env var `DEBUG=typescript-eslint:*`
* - 'eslint' is the same as setting the env var `DEBUG=eslint:*`
* - 'typescript' is the same as setting `extendedDiagnostics: true` in your tsconfig compilerOptions
*
* For convenience, also supports a boolean:
* - true === ['typescript-eslint']
* - false === []
*/
debugLevel?: DebugLevel;
/**
* Cause the parser to error if it encounters an unknown AST node type (useful for testing).
* This case only usually occurs when TypeScript releases new features.
*/
errorOnUnknownASTType?: boolean;
/**
* Absolute (or relative to `cwd`) path to the file being parsed.
*/
filePath?: string;
/**
* If you are using TypeScript version >=5.3 then this option can be used as a performance optimization.
*
* The valid values for this rule are:
* - `'all'` - parse all JSDoc comments, always.
* - `'none'` - parse no JSDoc comments, ever.
* - `'type-info'` - parse just JSDoc comments that are required to provide correct type-info. TS will always parse JSDoc in non-TS files, but never in TS files.
*
* If you do not rely on JSDoc tags from the TypeScript AST, then you can safely set this to `'none'` to improve performance.
*/
jsDocParsingMode?: JSDocParsingMode;
/**
* Enable parsing of JSX.
* For more details, see https://www.typescriptlang.org/docs/handbook/jsx.html
*
* NOTE: this setting does not effect known file types (.js, .cjs, .mjs, .jsx, .ts, .mts, .cts, .tsx, .json) because the
* TypeScript compiler has its own internal handling for known file extensions.
*
* For the exact behavior, see https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/parser#parseroptionsecmafeaturesjsx
*/
jsx?: boolean;
/**
* Controls whether the `loc` information to each node.
* The `loc` property is an object which contains the exact line/column the node starts/ends on.
* This is similar to the `range` property, except it is line/column relative.
*/
loc?: boolean;
loggerFn?: ((message: string) => void) | false;
/**
* Controls how the parser reacts when run with a TypeScript version that is
* not officially supported by typescript-eslint.
* - `'warn'` (default): log a warning via {@link loggerFn}.
* - `'error'`: throw, regardless of {@link loggerFn}.
* - `'ignore'`: do nothing.
*/
onUnsupportedTypeScriptVersion?: 'error' | 'ignore' | 'warn';
/**
* Controls whether the `range` property is included on AST nodes.
* The `range` property is a [number, number] which indicates the start/end index of the node in the file contents.
* This is similar to the `loc` property, except this is the absolute index.
*/
range?: boolean;
/**
* Set to true to create a top-level array containing all tokens from the file.
*/
tokens?: boolean;
/**
* Whether deprecated AST properties should skip calling console.warn on accesses.
*/
suppressDeprecatedPropertyWarnings?: boolean;
}
interface ParseAndGenerateServicesOptions extends ParseOptions {
/**
* Granular control of the expiry lifetime of our internal caches.
* You can specify the number of seconds as an integer number, or the string
* 'Infinity' if you never want the cache to expire.
*
* By default cache entries will be evicted after 30 seconds, or will persist
* indefinitely if `disallowAutomaticSingleRunInference = false` AND the parser
* infers that it is a single run.
*/
cacheLifetime?: {
/**
* Glob resolution for `parserOptions.project` values.
*/
glob?: CacheDurationSeconds;
};
/**
* ESLint (and therefore typescript-eslint) is used in both "single run"/one-time contexts,
* such as an ESLint CLI invocation, and long-running sessions (such as continuous feedback
* on a file in an IDE).
*
* When typescript-eslint handles TypeScript Program management behind the scenes, this distinction
* is important because there is significant overhead to managing the so called Watch Programs
* needed for the long-running use-case.
*
* By default, we will use common heuristics to infer whether ESLint is being
* used as part of a single run. This option disables those heuristics, and
* therefore the performance optimizations gained by them.
*
* In other words, typescript-eslint is faster by default, and this option
* disables an automatic performance optimization.
*
* This setting's default value can be specified by setting a `TSESTREE_SINGLE_RUN`
* environment variable to `"false"` or `"true"`.
* Otherwise, the default value is `false`.
*/
disallowAutomaticSingleRunInference?: boolean;
/**
* Causes the parser to error if the TypeScript compiler returns any unexpected syntax/semantic errors.
*/
errorOnTypeScriptSyntacticAndSemanticIssues?: boolean;
/**
* When `project` is provided, this controls the non-standard file extensions which will be parsed.
* It accepts an array of file extensions, each preceded by a `.`.
*
* NOTE: When used with {@link projectService}, full project reloads may occur.
*/
extraFileExtensions?: string[];
/**
* Absolute (or relative to `tsconfigRootDir`) path to the file being parsed.
* When `project` is provided, this is required, as it is used to fetch the file from the TypeScript compiler's cache.
*/
filePath?: string;
/**
* Allows the user to control whether or not two-way AST node maps are preserved
* during the AST conversion process.
*
* By default: the AST node maps are NOT preserved, unless `project` has been specified,
* in which case the maps are made available on the returned `parserServices`.
*
* NOTE: If `preserveNodeMaps` is explicitly set by the user, it will be respected,
* regardless of whether or not `project` is in use.
*/
preserveNodeMaps?: boolean;
/**
* Absolute (or relative to `tsconfigRootDir`) paths to the tsconfig(s),
* or `true` to find the nearest tsconfig.json to the file.
* If this is provided, type information will be returned.
*
* If set to `false`, `null` or `undefined` type information will not be returned.
*
* Note that {@link projectService} is now preferred.
*/
project?: boolean | string | string[] | null;
/**
* If you provide a glob (or globs) to the project option, you can use this option to ignore certain folders from
* being matched by the globs.
* This accepts an array of globs to ignore.
*
* By default, this is set to ["**\/node_modules/**"]
*/
projectFolderIgnoreList?: string[];
/**
* Whether to create a shared TypeScript project service to power program creation.
*/
projectService?: boolean | ProjectServiceOptions;
/**
* The absolute path to the root directory for all provided `project`s.
*/
tsconfigRootDir?: string;
/**
* An array of one or more instances of TypeScript Program objects to be used for type information.
* This overrides any program or programs that would have been computed from the `project` option.
* All linted files must be part of the provided program(s).
*/
programs?: ts.Program[] | null;
}
export type TSESTreeOptions = ParseAndGenerateServicesOptions;
export interface ParserWeakMap<Key, ValueBase> {
get<Value extends ValueBase>(key: Key): Value;
has(key: unknown): boolean;
}
export interface ParserWeakMapESTreeToTSNode<Key extends TSESTree.Node = TSESTree.Node> {
get<KeyBase extends Key>(key: KeyBase): TSESTreeToTSNode<KeyBase>;
has(key: unknown): boolean;
}
export interface ParserServicesBase {
emitDecoratorMetadata: boolean | undefined;
experimentalDecorators: boolean | undefined;
isolatedDeclarations: boolean | undefined;
}
export interface ParserServicesNodeMaps {
esTreeNodeToTSNodeMap: ParserWeakMapESTreeToTSNode;
tsNodeToESTreeNodeMap: ParserWeakMap<TSNode | TSToken, TSESTree.Node>;
}
export interface ParserServicesWithTypeInformation extends ParserServicesNodeMaps, ParserServicesBase {
getSymbolAtLocation: (node: TSESTree.Node) => ts.Symbol | undefined;
getTypeAtLocation: (node: TSESTree.Node) => ts.Type;
getContextualType: (node: TSESTree.Expression) => ts.Type | undefined;
getResolvedSignature: (node: TSESTree.CallExpression | TSESTree.NewExpression) => ts.Signature | undefined;
getTypeFromTypeNode: (node: TSESTree.TypeNode) => ts.Type;
getTypeOfSymbolAtLocation: (symbol: ts.Symbol, node: TSESTree.Node) => ts.Type;
program: ts.Program;
}
export interface ParserServicesWithoutTypeInformation extends ParserServicesNodeMaps, ParserServicesBase {
program: null;
}
export type ParserServices = ParserServicesWithoutTypeInformation | ParserServicesWithTypeInformation;
export {};

View File

@@ -0,0 +1,101 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
type FunctionNode = TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression;
/**
* Gets the location of the given function node for reporting.
*
* - `function foo() {}`
* ^^^^^^^^^^^^
* - `(function foo() {})`
* ^^^^^^^^^^^^
* - `(function() {})`
* ^^^^^^^^
* - `function* foo() {}`
* ^^^^^^^^^^^^^
* - `(function* foo() {})`
* ^^^^^^^^^^^^^
* - `(function*() {})`
* ^^^^^^^^^
* - `() => {}`
* ^^
* - `async () => {}`
* ^^
* - `({ foo: function foo() {} })`
* ^^^^^^^^^^^^^^^^^
* - `({ foo: function() {} })`
* ^^^^^^^^^^^^^
* - `({ ['foo']: function() {} })`
* ^^^^^^^^^^^^^^^^^
* - `({ [foo]: function() {} })`
* ^^^^^^^^^^^^^^^
* - `({ foo() {} })`
* ^^^
* - `({ foo: function* foo() {} })`
* ^^^^^^^^^^^^^^^^^^
* - `({ foo: function*() {} })`
* ^^^^^^^^^^^^^^
* - `({ ['foo']: function*() {} })`
* ^^^^^^^^^^^^^^^^^^
* - `({ [foo]: function*() {} })`
* ^^^^^^^^^^^^^^^^
* - `({ *foo() {} })`
* ^^^^
* - `({ foo: async function foo() {} })`
* ^^^^^^^^^^^^^^^^^^^^^^^
* - `({ foo: async function() {} })`
* ^^^^^^^^^^^^^^^^^^^
* - `({ ['foo']: async function() {} })`
* ^^^^^^^^^^^^^^^^^^^^^^^
* - `({ [foo]: async function() {} })`
* ^^^^^^^^^^^^^^^^^^^^^
* - `({ async foo() {} })`
* ^^^^^^^^^
* - `({ get foo() {} })`
* ^^^^^^^
* - `({ set foo(a) {} })`
* ^^^^^^^
* - `class A { constructor() {} }`
* ^^^^^^^^^^^
* - `class A { foo() {} }`
* ^^^
* - `class A { *foo() {} }`
* ^^^^
* - `class A { async foo() {} }`
* ^^^^^^^^^
* - `class A { ['foo']() {} }`
* ^^^^^^^
* - `class A { *['foo']() {} }`
* ^^^^^^^^
* - `class A { async ['foo']() {} }`
* ^^^^^^^^^^^^^
* - `class A { [foo]() {} }`
* ^^^^^
* - `class A { *[foo]() {} }`
* ^^^^^^
* - `class A { async [foo]() {} }`
* ^^^^^^^^^^^
* - `class A { get foo() {} }`
* ^^^^^^^
* - `class A { set foo(a) {} }`
* ^^^^^^^
* - `class A { static foo() {} }`
* ^^^^^^^^^^
* - `class A { static *foo() {} }`
* ^^^^^^^^^^^
* - `class A { static async foo() {} }`
* ^^^^^^^^^^^^^^^^
* - `class A { static get foo() {} }`
* ^^^^^^^^^^^^^^
* - `class A { static set foo(a) {} }`
* ^^^^^^^^^^^^^^
* - `class A { foo = function() {} }`
* ^^^^^^^^^^^^^^
* - `class A { static foo = function() {} }`
* ^^^^^^^^^^^^^^^^^^^^^
* - `class A { foo = (a, b) => {} }`
* ^^^^^^
* @param node The function node to get.
* @param sourceCode The source code object to get tokens.
* @returns The location of the function node for reporting.
*/
export declare function getFunctionHeadLoc(node: FunctionNode, sourceCode: TSESLint.SourceCode): TSESTree.SourceLocation;
export {};

View File

@@ -0,0 +1,8 @@
import arrayWithHoles from "./arrayWithHoles.js";
import iterableToArrayLimit from "./iterableToArrayLimit.js";
import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
import nonIterableRest from "./nonIterableRest.js";
function _slicedToArray(r, e) {
return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest();
}
export { _slicedToArray as default };

View File

@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
const getESLintCoreRule_1 = require("../util/getESLintCoreRule");
const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-useless-constructor');
/**
* Check if method with accessibility is not useless
*/
function checkAccessibility(node) {
switch (node.accessibility) {
case 'protected':
case 'private':
return false;
case 'public':
if (node.parent.parent.superClass) {
return false;
}
break;
}
return true;
}
/**
* Check if method is not useless due to typescript parameter properties and decorators
*/
function checkParams(node) {
return !node.value.params.some(param => param.type === utils_1.AST_NODE_TYPES.TSParameterProperty ||
param.decorators.length);
}
exports.default = (0, util_1.createRule)({
name: 'no-useless-constructor',
meta: {
type: 'problem',
// defaultOptions, -- base rule does not use defaultOptions
docs: {
description: 'Disallow unnecessary constructors',
extendsBaseRule: true,
recommended: 'strict',
},
hasSuggestions: baseRule.meta.hasSuggestions,
messages: baseRule.meta.messages,
schema: baseRule.meta.schema,
},
defaultOptions: [],
create(context) {
const rules = baseRule.create(context);
return {
MethodDefinition(node) {
if (node.value.type === utils_1.AST_NODE_TYPES.FunctionExpression &&
checkAccessibility(node) &&
checkParams(node)) {
rules.MethodDefinition(node);
}
},
};
},
});

View File

@@ -0,0 +1,32 @@
import { type KDFInput } from './utils.ts';
/**
* Argon2 options.
* * t: time cost, m: mem cost in kb, p: parallelization.
* * key: optional key. personalization: arbitrary extra data.
* * dkLen: desired number of output bytes.
*/
export type ArgonOpts = {
t: number;
m: number;
p: number;
version?: number;
key?: KDFInput;
personalization?: KDFInput;
dkLen?: number;
asyncTick?: number;
maxmem?: number;
onProgress?: (progress: number) => void;
};
/** argon2d GPU-resistant version. */
export declare const argon2d: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Uint8Array;
/** argon2i side-channel-resistant version. */
export declare const argon2i: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Uint8Array;
/** argon2id, combining i+d, the most popular version from RFC 9106 */
export declare const argon2id: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Uint8Array;
/** argon2d async GPU-resistant version. */
export declare const argon2dAsync: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Promise<Uint8Array>;
/** argon2i async side-channel-resistant version. */
export declare const argon2iAsync: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Promise<Uint8Array>;
/** argon2id async, combining i+d, the most popular version from RFC 9106 */
export declare const argon2idAsync: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Promise<Uint8Array>;
//# sourceMappingURL=argon2.d.ts.map

View File

@@ -0,0 +1,34 @@
'use strict';
const https = require('https');
const ClientHttp = require('./http');
/**
* Constructor for a Jayson HTTPS Client
* @class ClientHttps
* @constructor
* @extends ClientHttp
* @param {Object|String} [options] String interpreted as a URL
* @param {String} [options.encoding="utf8"] Encoding to use
* @return {ClientHttps}
*/
const ClientHttps = function(options) {
if(!(this instanceof ClientHttps)) {
return new ClientHttps(options);
}
// just proxy to constructor for ClientHttp
ClientHttp.call(this, options);
};
require('util').inherits(ClientHttps, ClientHttp);
module.exports = ClientHttps;
/**
* Gets a stream interface to a https server
* @param {Object} options An options object
* @return {require('https').ClientRequest}
* @private
*/
ClientHttps.prototype._getRequestStream = function(options) {
return https.request(options || {});
};

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.crypto = void 0;
/**
* Internal webcrypto alias.
* We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.
* Falls back to Node.js built-in crypto for Node.js <=v14.
* See utils.ts for details.
* @module
*/
// @ts-ignore
const nc = require("node:crypto");
exports.crypto = nc && typeof nc === 'object' && 'webcrypto' in nc
? nc.webcrypto
: nc && typeof nc === 'object' && 'randomBytes' in nc
? nc
: undefined;
//# sourceMappingURL=cryptoNode.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["src/crypto.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,MAAM,EAAE,GACqE,CAAC"}

View File

@@ -0,0 +1,83 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserMessageWriter = exports.BrowserMessageReader = void 0;
exports.createMessageConnection = createMessageConnection;
const ril_1 = __importDefault(require("./ril"));
// Install the browser runtime abstract.
ril_1.default.install();
const api_1 = require("../common/api");
__exportStar(require("../common/api"), exports);
class BrowserMessageReader extends api_1.AbstractMessageReader {
_onData;
_messageListener;
constructor(port) {
super();
this._onData = new api_1.Emitter();
this._messageListener = (event) => {
this._onData.fire(event.data);
};
port.addEventListener('error', (event) => this.fireError(event));
port.onmessage = this._messageListener;
}
listen(callback) {
return this._onData.event(callback);
}
}
exports.BrowserMessageReader = BrowserMessageReader;
class BrowserMessageWriter extends api_1.AbstractMessageWriter {
port;
errorCount;
constructor(port) {
super();
this.port = port;
this.errorCount = 0;
port.addEventListener('error', (event) => this.fireError(event));
}
write(msg) {
try {
this.port.postMessage(msg);
return Promise.resolve();
}
catch (error) {
this.handleError(error, msg);
return Promise.reject(error);
}
}
handleError(error, msg) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
end() {
}
}
exports.BrowserMessageWriter = BrowserMessageWriter;
function createMessageConnection(reader, writer, logger, options) {
if (logger === undefined) {
logger = api_1.NullLogger;
}
if (api_1.ConnectionStrategy.is(options)) {
options = { connectionStrategy: options };
}
return (0, api_1.createMessageConnection)(reader, writer, logger, options);
}

View File

@@ -0,0 +1,2 @@
import type { TSESTree } from '@typescript-eslint/utils';
export declare function skipChainExpression<T extends TSESTree.Node>(node: T): T | TSESTree.ChainElement;

View File

@@ -0,0 +1,64 @@
# yocto-queue [![](https://badgen.net/bundlephobia/minzip/yocto-queue)](https://bundlephobia.com/result?p=yocto-queue)
> Tiny queue data structure
You should use this package instead of an array if you do a lot of `Array#push()` and `Array#shift()` on large arrays, since `Array#shift()` has [linear time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(N)%E2%80%94Linear%20Time) *O(n)* while `Queue#dequeue()` has [constant time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(1)%20%E2%80%94%20Constant%20Time) *O(1)*. That makes a huge difference for large arrays.
> A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is an ordered list of elements where an element is inserted at the end of the queue and is removed from the front of the queue. A queue works based on the first-in, first-out ([FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics))) principle.
## Install
```
$ npm install yocto-queue
```
## Usage
```js
const Queue = require('yocto-queue');
const queue = new Queue();
queue.enqueue('🦄');
queue.enqueue('🌈');
console.log(queue.size);
//=> 2
console.log(...queue);
//=> '🦄 🌈'
console.log(queue.dequeue());
//=> '🦄'
console.log(queue.dequeue());
//=> '🌈'
```
## API
### `queue = new Queue()`
The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop, or use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow.
#### `.enqueue(value)`
Add a value to the queue.
#### `.dequeue()`
Remove the next value in the queue.
Returns the removed value or `undefined` if the queue is empty.
#### `.clear()`
Clear the queue.
#### `.size`
The size of the queue.
## Related
- [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple “Least Recently Used” (LRU) cache

View File

@@ -0,0 +1,49 @@
'use strict'
const Benchmark = require('benchmark')
const sjson = require('..')
const internals = {
text: '{ "a": 5, "b": 6, "c": { "d": 0, "e": "text", "f": { "g": 2 } } }',
proto: '{ "a": 5, "b": 6, "__proto__": { "x": 7 }, "c": { "d": 0, "e": "text", "__proto__": { "y": 8 }, "f": { "g": 2 } } }'
}
const suite = new Benchmark.Suite()
suite
.add('JSON.parse', () => {
JSON.parse(internals.text)
})
.add('JSON.parse proto', () => {
JSON.parse(internals.proto)
})
.add('secure-json-parse parse', () => {
sjson.parse(internals.text)
})
.add('secure-json-parse parse proto', () => {
sjson.parse(internals.text, { constructorAction: 'ignore', protoAction: 'ignore' })
})
.add('secure-json-parse safeParse', () => {
sjson.safeParse(internals.text)
})
.add('secure-json-parse safeParse proto', () => {
sjson.safeParse(internals.proto)
})
.add('JSON.parse reviver', () => {
JSON.parse(internals.text, internals.reviver)
})
.on('cycle', (event) => {
console.log(String(event.target))
})
.on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').map('name'))
})
.run({ async: true })
internals.reviver = function (key, value) {
if (key === '__proto__') {
return undefined
}
return value
}

View File

@@ -0,0 +1,33 @@
'use strict'
const { unregister, registerBeforeExit } = require('../..')
const assert = require('assert')
function setup () {
const obj = { foo: 'bar' }
registerBeforeExit(obj, shutdown)
}
let shutdownCalled = false
let timeoutFinished = false
function shutdown (obj, event) {
shutdownCalled = true
if (event === 'beforeExit') {
setTimeout(function () {
timeoutFinished = true
assert.strictEqual(obj.foo, 'bar')
unregister(obj)
}, 100)
process.on('beforeExit', function () {
assert.strictEqual(timeoutFinished, true)
})
} else {
throw new Error('different event')
}
}
setup()
process.on('exit', function () {
assert.strictEqual(shutdownCalled, true)
})

View File

@@ -0,0 +1,6 @@
"use strict";
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
exports._ = _interop_require_default;

View File

@@ -0,0 +1,189 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScopeManager = void 0;
const assert_1 = require("./assert");
const scope_1 = require("./scope");
const ClassFieldInitializerScope_1 = require("./scope/ClassFieldInitializerScope");
const ClassStaticBlockScope_1 = require("./scope/ClassStaticBlockScope");
/**
* @see https://eslint.org/docs/latest/developer-guide/scope-manager-interface#scopemanager-interface
*/
class ScopeManager {
#options;
currentScope;
declaredVariables;
/**
* The root scope
*/
globalScope;
nodeToScope;
/**
* All scopes
* @public
*/
scopes;
constructor(options) {
this.scopes = [];
this.globalScope = null;
this.nodeToScope = new WeakMap();
this.currentScope = null;
this.#options = options;
this.declaredVariables = new WeakMap();
}
isES6() {
return true;
}
isGlobalReturn() {
return this.#options.globalReturn === true;
}
isImpliedStrict() {
return this.#options.impliedStrict === true;
}
isModule() {
return this.#options.sourceType === 'module';
}
isStrictModeSupported() {
return true;
}
get variables() {
const variables = new Set();
function recurse(scope) {
scope.variables.forEach(v => variables.add(v));
scope.childScopes.forEach(recurse);
}
this.scopes.forEach(recurse);
return [...variables].sort((a, b) => a.$id - b.$id);
}
/**
* Get the variables that a given AST node defines. The gotten variables' `def[].node`/`def[].parent` property is the node.
* If the node does not define any variable, this returns an empty array.
* @param node An AST node to get their variables.
*/
getDeclaredVariables(node) {
return this.declaredVariables.get(node) ?? [];
}
/**
* Get the scope of a given AST node. The gotten scope's `block` property is the node.
* This method never returns `function-expression-name` scope. If the node does not have their scope, this returns `null`.
*
* @param node An AST node to get their scope.
* @param inner If the node has multiple scopes, this returns the outermost scope normally.
* If `inner` is `true` then this returns the innermost scope.
*/
acquire(node, inner = false) {
function predicate(testScope) {
if (testScope.type === scope_1.ScopeType.function &&
testScope.functionExpressionScope) {
return false;
}
return true;
}
const scopes = this.nodeToScope.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;
}
}
return null;
}
return scopes.find(predicate) ?? null;
}
/**
* Adds dynamically created globals to the global scope and resolve their references.
* This method is called by ESLint.
* @param names Names of the globals to create
*/
addGlobals(names) {
this.globalScope?.addVariables(names);
}
nestBlockScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.BlockScope(this, this.currentScope, node));
}
nestCatchScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.CatchScope(this, this.currentScope, node));
}
nestClassFieldInitializerScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new ClassFieldInitializerScope_1.ClassFieldInitializerScope(this, this.currentScope, node));
}
nestClassScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.ClassScope(this, this.currentScope, node));
}
nestClassStaticBlockScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new ClassStaticBlockScope_1.ClassStaticBlockScope(this, this.currentScope, node));
}
nestConditionalTypeScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.ConditionalTypeScope(this, this.currentScope, node));
}
nestForScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.ForScope(this, this.currentScope, node));
}
nestFunctionExpressionNameScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.FunctionExpressionNameScope(this, this.currentScope, node));
}
nestFunctionScope(node, isMethodDefinition) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.FunctionScope(this, this.currentScope, node, isMethodDefinition));
}
nestFunctionTypeScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.FunctionTypeScope(this, this.currentScope, node));
}
nestGlobalScope(node) {
return this.nestScope(new scope_1.GlobalScope(this, node));
}
nestMappedTypeScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.MappedTypeScope(this, this.currentScope, node));
}
nestModuleScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.ModuleScope(this, this.currentScope, node));
}
nestSwitchScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.SwitchScope(this, this.currentScope, node));
}
nestTSEnumScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.TSEnumScope(this, this.currentScope, node));
}
nestTSModuleScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.TSModuleScope(this, this.currentScope, node));
}
nestTypeScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.TypeScope(this, this.currentScope, node));
}
nestWithScope(node) {
(0, assert_1.assert)(this.currentScope);
return this.nestScope(new scope_1.WithScope(this, this.currentScope, node));
}
nestScope(scope) {
if (scope instanceof scope_1.GlobalScope) {
(0, assert_1.assert)(this.currentScope == null);
this.globalScope = scope;
}
this.currentScope = scope;
return scope;
}
}
exports.ScopeManager = ScopeManager;

View File

@@ -0,0 +1,106 @@
/**
* @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function
* @author James Allardice
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const {
CALL,
CONSTRUCT,
ReferenceTracker,
} = require("@eslint-community/eslint-utils");
const getPropertyName = require("./utils/ast-utils").getStaticPropertyName;
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const nonCallableGlobals = [
"Atomics",
"JSON",
"Math",
"Reflect",
"Intl",
"Temporal",
];
/**
* Returns the name of the node to report
* @param {ASTNode} node A node to report
* @returns {string} name to report
*/
function getReportNodeName(node) {
if (node.type === "ChainExpression") {
return getReportNodeName(node.expression);
}
if (node.type === "MemberExpression") {
return getPropertyName(node);
}
return node.name;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description:
"Disallow calling global object properties as functions",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-obj-calls",
},
schema: [],
messages: {
unexpectedCall: "'{{name}}' is not a function.",
unexpectedRefCall:
"'{{name}}' is reference to '{{ref}}', which is not a function.",
},
},
create(context) {
const sourceCode = context.sourceCode;
return {
Program(node) {
const scope = sourceCode.getScope(node);
const tracker = new ReferenceTracker(scope);
const traceMap = {};
for (const g of nonCallableGlobals) {
traceMap[g] = {
[CALL]: true,
[CONSTRUCT]: true,
};
}
for (const {
node: refNode,
path,
} of tracker.iterateGlobalReferences(traceMap)) {
const name = getReportNodeName(refNode.callee);
const ref = path[0];
const messageId =
name === ref ? "unexpectedCall" : "unexpectedRefCall";
context.report({
node: refNode,
messageId,
data: { name, ref },
});
}
},
};
},
};

View File

@@ -0,0 +1,52 @@
{
"name": "@vitest/expect",
"type": "module",
"version": "4.1.10",
"description": "Jest's expect matchers as a Chai plugin",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://vitest.dev/api/expect",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
"directory": "packages/expect"
},
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"chai",
"assertion"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./*": "./*"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"dependencies": {
"@standard-schema/spec": "^1.1.0",
"@types/chai": "^5.2.2",
"chai": "^6.2.2",
"tinyrainbow": "^3.1.0",
"@vitest/spy": "4.1.10",
"@vitest/utils": "4.1.10"
},
"devDependencies": {
"@vitest/runner": "4.1.10"
},
"scripts": {
"build": "premove dist && rollup -c",
"dev": "rollup -c --watch"
}
}

View File

@@ -0,0 +1,69 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.containsAllTypesByName = containsAllTypesByName;
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const typeFlagUtils_1 = require("./typeFlagUtils");
/**
* @param type Type being checked by name.
* @param allowAny Whether to consider `any` and `unknown` to match.
* @param allowedNames Symbol names checking on the type.
* @param matchAnyInstead Whether to instead just check if any parts match, rather than all parts.
* @returns Whether the type is, extends, or contains the allowed names (or all matches the allowed names, if mustMatchAll is true).
*/
function containsAllTypesByName(type, allowAny, allowedNames, matchAnyInstead = false) {
if ((0, typeFlagUtils_1.isTypeFlagSet)(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
return !allowAny;
}
if (tsutils.isTypeReference(type)) {
type = type.target;
}
const symbol = type.getSymbol();
if (symbol && allowedNames.has(symbol.name)) {
return true;
}
const predicate = (t) => containsAllTypesByName(t, allowAny, allowedNames, matchAnyInstead);
if (tsutils.isUnionOrIntersectionType(type)) {
return matchAnyInstead
? type.types.some(predicate)
: type.types.every(predicate);
}
const bases = type.getBaseTypes();
return (bases != null &&
(matchAnyInstead
? bases.some(predicate)
: bases.length > 0 && bases.every(predicate)));
}

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_set.cjs",
"module": "../../esm/_set.js"
}