docs: 仓库链接指向本镜像仓库
Dev Build / cleanup (push) Canceled after 0s
Dev Build / typecheck (push) Canceled after 0s
Dev Build / build (linux-arm64, ubuntu-24.04-arm, linux-arm64) (push) Canceled after 0s
Dev Build / build (linux-x64, ubuntu-latest, linux-x64) (push) Canceled after 0s
Dev Build / build (win-x64, windows-latest, win32-x64) (push) Canceled after 0s
Dev Build / dispatch-dev-docker (push) Skipped

This commit is contained in:
TanTan committed 2026-11-13 09:27:07 +08:00
1 parent fa9c73363d
commit 2a69b23b47
18210 files changed
+5101211 -16

No files matched your search

@@ -0,0 +1,882 @@
"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");
exports.default = (0, util_1.createRule)({
name: 'strict-boolean-expressions',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow certain types in boolean expressions',
requiresTypeChecking: true,
},
hasSuggestions: true,
messages: {
conditionErrorAny: 'Unexpected any value in {{context}}. ' +
'An explicit comparison or type conversion is required.',
conditionErrorNullableBoolean: 'Unexpected nullable boolean value in {{context}}. ' +
'Please handle the nullish case explicitly.',
conditionErrorNullableEnum: 'Unexpected nullable enum value in {{context}}. ' +
'Please handle the nullish/zero/NaN cases explicitly.',
conditionErrorNullableNumber: 'Unexpected nullable number value in {{context}}. ' +
'Please handle the nullish/zero/NaN cases explicitly.',
conditionErrorNullableObject: 'Unexpected nullable object value in {{context}}. ' +
'An explicit null check is required.',
conditionErrorNullableString: 'Unexpected nullable string value in {{context}}. ' +
'Please handle the nullish/empty cases explicitly.',
conditionErrorNullish: 'Unexpected nullish value in conditional. ' +
'The condition is always false.',
conditionErrorNumber: 'Unexpected number value in {{context}}. ' +
'An explicit zero/NaN check is required.',
conditionErrorObject: 'Unexpected object value in {{context}}. ' +
'The condition is always true.',
conditionErrorOther: 'Unexpected value in conditional. ' +
'A boolean expression is required.',
conditionErrorString: 'Unexpected string value in {{context}}. ' +
'An explicit empty string check is required.',
conditionFixCastBoolean: 'Explicitly convert value to a boolean (`Boolean(value)`)',
conditionFixCompareArrayLengthNonzero: "Change condition to check array's length (`value.length > 0`)",
conditionFixCompareArrayLengthZero: "Change condition to check array's length (`value.length === 0`)",
conditionFixCompareEmptyString: 'Change condition to check for empty string (`value !== ""`)',
conditionFixCompareFalse: 'Change condition to check if false (`value === false`)',
conditionFixCompareNaN: 'Change condition to check for NaN (`!Number.isNaN(value)`)',
conditionFixCompareNullish: 'Change condition to check for null/undefined (`value != null`)',
conditionFixCompareStringLength: "Change condition to check string's length (`value.length !== 0`)",
conditionFixCompareTrue: 'Change condition to check if true (`value === true`)',
conditionFixCompareZero: 'Change condition to check for 0 (`value !== 0`)',
conditionFixDefaultEmptyString: 'Explicitly treat nullish value the same as an empty string (`value ?? ""`)',
conditionFixDefaultFalse: 'Explicitly treat nullish value the same as false (`value ?? false`)',
conditionFixDefaultZero: 'Explicitly treat nullish value the same as 0 (`value ?? 0`)',
explicitBooleanReturnType: 'Add an explicit `boolean` return type annotation.',
noStrictNullCheck: 'This rule requires the `strictNullChecks` compiler option to be turned on to function correctly.',
predicateCannotBeAsync: "Predicate function should not be 'async'; expected a boolean return type.",
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowAny: {
type: 'boolean',
description: 'Whether to allow `any`s in a boolean context.',
},
allowNullableBoolean: {
type: 'boolean',
description: 'Whether to allow nullable `boolean`s in a boolean context.',
},
allowNullableEnum: {
type: 'boolean',
description: 'Whether to allow nullable `enum`s in a boolean context.',
},
allowNullableNumber: {
type: 'boolean',
description: 'Whether to allow nullable `number`s in a boolean context.',
},
allowNullableObject: {
type: 'boolean',
description: 'Whether to allow nullable `object`s, `symbol`s, and functions in a boolean context.',
},
allowNullableString: {
type: 'boolean',
description: 'Whether to allow nullable `string`s in a boolean context.',
},
allowNumber: {
type: 'boolean',
description: 'Whether to allow `number`s in a boolean context.',
},
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: {
type: 'boolean',
description: 'Unless this is set to `true`, the rule will error on every file whose `tsconfig.json` does _not_ have the `strictNullChecks` compiler option (or `strict`) set to `true`.',
},
allowString: {
type: 'boolean',
description: 'Whether to allow `string`s in a boolean context.',
},
},
},
],
},
defaultOptions: [
{
allowAny: false,
allowNullableBoolean: false,
allowNullableEnum: false,
allowNullableNumber: false,
allowNullableObject: true,
allowNullableString: false,
allowNumber: true,
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
allowString: true,
},
],
create(context, [options]) {
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
const compilerOptions = services.program.getCompilerOptions();
const isStrictNullChecks = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks');
if (!isStrictNullChecks &&
options.allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing !== true) {
context.report({
loc: {
start: { column: 0, line: 0 },
end: { column: 0, line: 0 },
},
messageId: 'noStrictNullCheck',
});
}
const traversedNodes = new Set();
return {
CallExpression: traverseCallExpression,
ConditionalExpression: traverseTestExpression,
DoWhileStatement: traverseTestExpression,
ForStatement: traverseTestExpression,
IfStatement: traverseTestExpression,
'LogicalExpression[operator!="??"]': traverseLogicalExpression,
'UnaryExpression[operator="!"]': traverseUnaryLogicalExpression,
WhileStatement: traverseTestExpression,
};
/**
* Inspects condition of a test expression. (`if`, `while`, `for`, etc.)
*/
function traverseTestExpression(node) {
if (node.test == null) {
return;
}
traverseNode(node.test, true);
}
/**
* Inspects the argument of a unary logical expression (`!`).
*/
function traverseUnaryLogicalExpression(node) {
traverseNode(node.argument, true);
}
/**
* Inspects the arguments of a logical expression (`&&`, `||`).
*
* If the logical expression is a descendant of a test expression,
* the `isCondition` flag should be set to true.
* Otherwise, if the logical expression is there on it's own,
* it's used for control flow and is not a condition itself.
*/
function traverseLogicalExpression(node, isCondition = false) {
// left argument is always treated as a condition
traverseNode(node.left, true);
// if the logical expression is used for control flow,
// then its right argument is used for its side effects only
traverseNode(node.right, isCondition);
}
function traverseCallExpression(node) {
const assertedArgument = (0, assertionFunctionUtils_1.findTruthinessAssertedArgument)(services, node);
if (assertedArgument != null) {
traverseNode(assertedArgument, true);
}
if ((0, util_1.isArrayMethodCallWithPredicate)(context, services, node)) {
const predicate = node.arguments.at(0);
if (predicate) {
checkArrayMethodCallPredicate(predicate);
}
}
}
/**
* Dedicated function to check array method predicate calls. Reports predicate
* arguments that don't return a boolean value.
*/
function checkArrayMethodCallPredicate(predicateNode) {
const isFunctionExpression = utils_1.ASTUtils.isFunction(predicateNode);
// custom message for accidental `async` function expressions
if (isFunctionExpression && predicateNode.async) {
return context.report({
node: predicateNode,
messageId: 'predicateCannotBeAsync',
});
}
const returnTypes = services
.getTypeAtLocation(predicateNode)
.getCallSignatures()
.map(signature => {
const type = signature.getReturnType();
if (tsutils.isTypeParameter(type)) {
return checker.getBaseConstraintOfType(type) ?? type;
}
return type;
});
const flattenTypes = [
...new Set(returnTypes.flatMap(type => tsutils.unionConstituents(type))),
];
const types = inspectVariantTypes(flattenTypes);
const reportType = determineReportType(types);
if (reportType == null) {
return;
}
const suggestions = [];
if (isFunctionExpression &&
predicateNode.body.type !== utils_1.AST_NODE_TYPES.BlockStatement) {
suggestions.push(...getSuggestionsForConditionError(predicateNode.body, reportType));
}
if (isFunctionExpression && !predicateNode.returnType) {
suggestions.push({
messageId: 'explicitBooleanReturnType',
fix: fixer => {
if (predicateNode.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression &&
(0, util_1.isParenlessArrowFunction)(predicateNode, context.sourceCode)) {
return [
fixer.insertTextBefore(predicateNode.params[0], '('),
fixer.insertTextAfter(predicateNode.params[0], '): boolean'),
];
}
if (predicateNode.params.length === 0) {
const closingBracket = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(predicateNode, token => token.value === ')'), 'function expression has to have a closing parenthesis.');
return fixer.insertTextAfter(closingBracket, ': boolean');
}
const lastClosingParenthesis = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(predicateNode.params[predicateNode.params.length - 1], token => token.value === ')'), 'function expression has to have a closing parenthesis.');
return fixer.insertTextAfter(lastClosingParenthesis, ': boolean');
},
});
}
return context.report({
node: predicateNode,
messageId: reportType,
data: {
context: 'array predicate return type',
},
suggest: suggestions,
});
}
/**
* Inspects any node.
*
* If it's a logical expression then it recursively traverses its arguments.
* If it's any other kind of node then it's type is finally checked against the rule,
* unless `isCondition` flag is set to false, in which case
* it's assumed to be used for side effects only and is skipped.
*/
function traverseNode(node, isCondition) {
// prevent checking the same node multiple times
if (traversedNodes.has(node)) {
return;
}
traversedNodes.add(node);
// for logical operator, we check its operands
if (node.type === utils_1.AST_NODE_TYPES.LogicalExpression &&
node.operator !== '??') {
traverseLogicalExpression(node, isCondition);
return;
}
// skip if node is not a condition
if (!isCondition) {
return;
}
checkNode(node);
}
function determineReportType(types) {
const is = (...wantedTypes) => types.size === wantedTypes.length &&
wantedTypes.every(type => types.has(type));
// boolean
if (is('boolean') || is('truthy boolean')) {
// boolean is always ok
return undefined;
}
// never
if (is('never')) {
// never is always okay
return undefined;
}
// nullish
if (is('nullish')) {
// condition is always false
return 'conditionErrorNullish';
}
// Known edge case: boolean `true` and nullish values are always valid boolean expressions
if (is('nullish', 'truthy boolean')) {
return;
}
// nullable boolean
if (is('nullish', 'boolean')) {
return !options.allowNullableBoolean
? 'conditionErrorNullableBoolean'
: undefined;
}
// Known edge case: truthy primitives and nullish values are always valid boolean expressions
if ((options.allowNumber && is('nullish', 'truthy number')) ||
(options.allowString && is('nullish', 'truthy string'))) {
return;
}
// string
if (is('string') || is('truthy string')) {
return !options.allowString ? 'conditionErrorString' : undefined;
}
// nullable string
if (is('nullish', 'string')) {
return !options.allowNullableString
? 'conditionErrorNullableString'
: undefined;
}
// number
if (is('number') || is('truthy number')) {
return !options.allowNumber ? 'conditionErrorNumber' : undefined;
}
// nullable number
if (is('nullish', 'number')) {
return !options.allowNullableNumber
? 'conditionErrorNullableNumber'
: undefined;
}
// object
if (is('object')) {
return 'conditionErrorObject';
}
// nullable object
if (is('nullish', 'object')) {
return !options.allowNullableObject
? 'conditionErrorNullableObject'
: undefined;
}
// nullable enum
if (is('nullish', 'number', 'enum') ||
is('nullish', 'string', 'enum') ||
is('nullish', 'truthy number', 'enum') ||
is('nullish', 'truthy string', 'enum') ||
// mixed enums
is('nullish', 'truthy number', 'truthy string', 'enum') ||
is('nullish', 'truthy number', 'string', 'enum') ||
is('nullish', 'truthy string', 'number', 'enum') ||
is('nullish', 'number', 'string', 'enum')) {
return !options.allowNullableEnum
? 'conditionErrorNullableEnum'
: undefined;
}
// any
if (is('any')) {
return !options.allowAny ? 'conditionErrorAny' : undefined;
}
return 'conditionErrorOther';
}
function getSuggestionsForConditionError(node, conditionError) {
switch (conditionError) {
case 'conditionErrorAny':
return [
{
messageId: 'conditionFixCastBoolean',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `Boolean(${code})`,
}),
},
];
case 'conditionErrorNullableBoolean':
if (isLogicalNegationExpression(node.parent)) {
// if (!nullableBoolean)
return [
{
messageId: 'conditionFixDefaultFalse',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} ?? false`,
}),
},
{
messageId: 'conditionFixCompareFalse',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `${code} === false`,
}),
},
];
}
// if (nullableBoolean)
return [
{
messageId: 'conditionFixDefaultFalse',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} ?? false`,
}),
},
{
messageId: 'conditionFixCompareTrue',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} === true`,
}),
},
];
case 'conditionErrorNullableEnum':
if (isLogicalNegationExpression(node.parent)) {
return [
{
messageId: 'conditionFixCompareNullish',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `${code} == null`,
}),
},
];
}
return [
{
messageId: 'conditionFixCompareNullish',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} != null`,
}),
},
];
case 'conditionErrorNullableNumber':
if (isLogicalNegationExpression(node.parent)) {
// if (!nullableNumber)
return [
{
messageId: 'conditionFixCompareNullish',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `${code} == null`,
}),
},
{
messageId: 'conditionFixDefaultZero',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} ?? 0`,
}),
},
{
messageId: 'conditionFixCastBoolean',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `!Boolean(${code})`,
}),
},
];
}
// if (nullableNumber)
return [
{
messageId: 'conditionFixCompareNullish',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} != null`,
}),
},
{
messageId: 'conditionFixDefaultZero',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} ?? 0`,
}),
},
{
messageId: 'conditionFixCastBoolean',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `Boolean(${code})`,
}),
},
];
case 'conditionErrorNullableObject':
if (isLogicalNegationExpression(node.parent)) {
// if (!nullableObject)
return [
{
messageId: 'conditionFixCompareNullish',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `${code} == null`,
}),
},
];
}
// if (nullableObject)
return [
{
messageId: 'conditionFixCompareNullish',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} != null`,
}),
},
];
case 'conditionErrorNullableString':
if (isLogicalNegationExpression(node.parent)) {
// if (!nullableString)
return [
{
messageId: 'conditionFixCompareNullish',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `${code} == null`,
}),
},
{
messageId: 'conditionFixDefaultEmptyString',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} ?? ""`,
}),
},
{
messageId: 'conditionFixCastBoolean',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `!Boolean(${code})`,
}),
},
];
}
// if (nullableString)
return [
{
messageId: 'conditionFixCompareNullish',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} != null`,
}),
},
{
messageId: 'conditionFixDefaultEmptyString',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} ?? ""`,
}),
},
{
messageId: 'conditionFixCastBoolean',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `Boolean(${code})`,
}),
},
];
case 'conditionErrorNumber':
if (isArrayLengthExpression(node, checker, services)) {
if (isLogicalNegationExpression(node.parent)) {
// if (!array.length)
return [
{
messageId: 'conditionFixCompareArrayLengthZero',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `${code} === 0`,
}),
},
];
}
// if (array.length)
return [
{
messageId: 'conditionFixCompareArrayLengthNonzero',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} > 0`,
}),
},
];
}
if (isLogicalNegationExpression(node.parent)) {
// if (!number)
return [
{
messageId: 'conditionFixCompareZero',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
// TODO: we have to compare to 0n if the type is bigint
wrap: code => `${code} === 0`,
}),
},
{
// TODO: don't suggest this for bigint because it can't be NaN
messageId: 'conditionFixCompareNaN',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `Number.isNaN(${code})`,
}),
},
{
messageId: 'conditionFixCastBoolean',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `!Boolean(${code})`,
}),
},
];
}
// if (number)
return [
{
messageId: 'conditionFixCompareZero',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} !== 0`,
}),
},
{
messageId: 'conditionFixCompareNaN',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `!Number.isNaN(${code})`,
}),
},
{
messageId: 'conditionFixCastBoolean',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `Boolean(${code})`,
}),
},
];
case 'conditionErrorString':
if (isLogicalNegationExpression(node.parent)) {
// if (!string)
return [
{
messageId: 'conditionFixCompareStringLength',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `${code}.length === 0`,
}),
},
{
messageId: 'conditionFixCompareEmptyString',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `${code} === ""`,
}),
},
{
messageId: 'conditionFixCastBoolean',
fix: (0, util_1.getWrappingFixer)({
node: node.parent,
innerNode: node,
sourceCode: context.sourceCode,
wrap: code => `!Boolean(${code})`,
}),
},
];
}
// if (string)
return [
{
messageId: 'conditionFixCompareStringLength',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code}.length > 0`,
}),
},
{
messageId: 'conditionFixCompareEmptyString',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `${code} !== ""`,
}),
},
{
messageId: 'conditionFixCastBoolean',
fix: (0, util_1.getWrappingFixer)({
node,
sourceCode: context.sourceCode,
wrap: code => `Boolean(${code})`,
}),
},
];
case 'conditionErrorObject':
case 'conditionErrorNullish':
case 'conditionErrorOther':
return [];
default:
conditionError;
throw new Error('Unreachable');
}
}
/**
* This function does the actual type check on a node.
* It analyzes the type of a node and checks if it is allowed in a boolean context.
*/
function checkNode(node) {
const type = (0, util_1.getConstrainedTypeAtLocation)(services, node);
const types = inspectVariantTypes(tsutils.unionConstituents(type));
const reportType = determineReportType(types);
if (reportType != null) {
context.report({
node,
messageId: reportType,
data: {
context: 'conditional',
},
suggest: getSuggestionsForConditionError(node, reportType),
});
}
}
/**
* Check union variants for the types we care about
*/
function inspectVariantTypes(types) {
const variantTypes = new Set();
if (types.some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.VoidLike))) {
variantTypes.add('nullish');
}
const booleans = types.filter(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.BooleanLike));
// If incoming type is either "true" or "false", there will be one type
// object with intrinsicName set accordingly
// If incoming type is boolean, there will be two type objects with
// intrinsicName set "true" and "false" each because of ts-api-utils.unionConstituents()
if (booleans.length === 1) {
variantTypes.add(tsutils.isTrueLiteralType(booleans[0]) ? 'truthy boolean' : 'boolean');
}
else if (booleans.length === 2) {
variantTypes.add('boolean');
}
const strings = types.filter(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.StringLike));
if (strings.length) {
if (strings.every(type => type.isStringLiteral() && type.value !== '')) {
variantTypes.add('truthy string');
}
else {
variantTypes.add('string');
}
}
const numbers = types.filter(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike));
if (numbers.length) {
if (numbers.every(type => type.isNumberLiteral() && type.value !== 0)) {
variantTypes.add('truthy number');
}
else {
variantTypes.add('number');
}
}
if (types.some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.EnumLike))) {
variantTypes.add('enum');
}
if (types.some(type => !tsutils.isTypeFlagSet(type, ts.TypeFlags.Null |
ts.TypeFlags.Undefined |
ts.TypeFlags.VoidLike |
ts.TypeFlags.BooleanLike |
ts.TypeFlags.StringLike |
ts.TypeFlags.NumberLike |
ts.TypeFlags.BigIntLike |
ts.TypeFlags.TypeParameter |
ts.TypeFlags.Any |
ts.TypeFlags.Unknown |
ts.TypeFlags.Never))) {
variantTypes.add(types.some(isBrandedBoolean) ? 'boolean' : 'object');
}
if (types.some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.TypeParameter |
ts.TypeFlags.Any |
ts.TypeFlags.Unknown))) {
variantTypes.add('any');
}
if (types.some(type => tsutils.isTypeFlagSet(type, ts.TypeFlags.Never))) {
variantTypes.add('never');
}
return variantTypes;
}
},
});
function isLogicalNegationExpression(node) {
return node.type === utils_1.AST_NODE_TYPES.UnaryExpression && node.operator === '!';
}
function isArrayLengthExpression(node, typeChecker, services) {
if (node.type !== utils_1.AST_NODE_TYPES.MemberExpression) {
return false;
}
if (node.computed) {
return false;
}
if (node.property.name !== 'length') {
return false;
}
const objectType = (0, util_1.getConstrainedTypeAtLocation)(services, node.object);
return (0, util_1.isTypeArrayTypeOrUnionOfArrayTypes)(objectType, typeChecker);
}
/**
* Verify is the type is a branded boolean (e.g. `type Foo = boolean & { __brand: 'Foo' }`)
*
* @param type The type checked
*/
function isBrandedBoolean(type) {
return (type.isIntersection() &&
type.types.some(childType => isBooleanType(childType)));
}
function isBooleanType(expressionType) {
return tsutils.isTypeFlagSet(expressionType, ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral);
}
@@ -0,0 +1,19 @@
import { DateInput } from './types';
/**
* Calculates the difference in months between two dates.
* 计算两个日期之间的月份差
*
* @param date - The first date to compare.
* @param input - The second date to compare.
* @param asFloat - Whether to return the result as a float.
* @returns The difference in months between the two dates.
* @example
* ```ts
* diffInYears(new Date(), new Date()); // 0
* diffInYears(new Date(), new Date(Date.now() + 1000 * 60 * 60 * 24 * 30)); // 1
* diffInYears(new Date(), new Date(Date.now() - 1000 * 60 * 60 * 24 * 30)); // -1
* diffInYears(new Date(), new Date(Date.now() - 1000 * 60 * 60 * 24 * 30 * 12)); // -1
* diffInYears(new Date(), new Date(Date.now() - 1000 * 60 * 60 * 24 * 30 * 12 * 2)); // -2
* ```
*/
export default function diffInYears(date: Date, input: DateInput, asFloat?: boolean): number;
@@ -0,0 +1 @@
{"version":3,"file":"plus.js","sources":["../../../src/icons/plus.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Plus\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNSAxMmgxNCIgLz4KICA8cGF0aCBkPSJNMTIgNXYxNCIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/plus\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Plus = createLucideIcon('Plus', [\n ['path', { d: 'M5 12h14', key: '1ays0h' }],\n ['path', { d: 'M12 5v14', key: 's699le' }],\n]);\n\nexport default Plus;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO,iBAAiB,MAAQ,CAAA,CAAA,CAAA;AAAA,CAAA,CACpC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC3C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,91 @@
/**
* JSON Web Token (JWT) Encryption (JWT is in JWE format)
*
* @module
*/
import type * as types from '../types.d.ts';
/**
* The EncryptJWT class is used to build and encrypt Compact JWE formatted JSON Web Tokens.
*
* This class is exported (as a named export) from the main `'jose'` module entry point as well as
* from its subpath export `'jose/jwt/encrypt'`.
*
*/
export declare class EncryptJWT implements types.ProduceJWT {
#private;
/**
* {@link EncryptJWT} constructor
*
* @param payload The JWT Claims Set object. Defaults to an empty object.
*/
constructor(payload?: types.JWTPayload);
setIssuer(issuer: string): this;
setSubject(subject: string): this;
setAudience(audience: string | string[]): this;
setJti(jwtId: string): this;
setNotBefore(input: number | string | Date): this;
setExpirationTime(input: number | string | Date): this;
setIssuedAt(input?: number | string | Date): this;
/**
* Sets the JWE Protected Header on the EncryptJWT object.
*
* @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc"
* (JWE Encryption Algorithm) properties.
*/
setProtectedHeader(protectedHeader: types.CompactJWEHeaderParameters): this;
/**
* Sets the JWE Key Management parameters to be used when encrypting.
*
* (ECDH-ES) Use of this method is needed for ECDH based algorithms to set the "apu" (Agreement
* PartyUInfo) or "apv" (Agreement PartyVInfo) parameters.
*
* @param parameters JWE Key Management parameters.
*/
setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this;
/**
* Sets a content encryption key to use, by default a random suitable one is generated for the JWE
* enc" (Encryption Algorithm) Header Parameter.
*
* @deprecated You should not use this method. It is only really intended for test and vector
* validation purposes.
*
* @param cek JWE Content Encryption Key.
*/
setContentEncryptionKey(cek: Uint8Array): this;
/**
* Sets the JWE Initialization Vector to use for content encryption, by default a random suitable
* one is generated for the JWE enc" (Encryption Algorithm) Header Parameter.
*
* @deprecated You should not use this method. It is only really intended for test and vector
* validation purposes.
*
* @param iv JWE Initialization Vector.
*/
setInitializationVector(iv: Uint8Array): this;
/**
* Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter.
*
* @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3}
*/
replicateIssuerAsHeader(): this;
/**
* Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter.
*
* @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3}
*/
replicateSubjectAsHeader(): this;
/**
* Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter.
*
* @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3}
*/
replicateAudienceAsHeader(): this;
/**
* Encrypts and returns the JWT.
*
* @param key Public Key or Secret to encrypt the JWT with. See
* {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
* @param options JWE Encryption options.
*/
encrypt(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.EncryptOptions): Promise<string>;
}
@@ -0,0 +1,179 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
const explicitReturnTypeUtils_1 = require("../util/explicitReturnTypeUtils");
exports.default = (0, util_1.createRule)({
name: 'explicit-function-return-type',
meta: {
type: 'problem',
docs: {
description: 'Require explicit return types on functions and class methods',
},
messages: {
missingReturnType: 'Missing return type on function.',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowConciseArrowFunctionExpressionsStartingWithVoid: {
type: 'boolean',
description: 'Whether to allow arrow functions that start with the `void` keyword.',
},
allowDirectConstAssertionInArrowFunctions: {
type: 'boolean',
description: 'Whether to ignore arrow functions immediately returning a `as const` value.',
},
allowedNames: {
type: 'array',
description: 'An array of function/method names that will not have their arguments or return values checked.',
items: {
type: 'string',
},
},
allowExpressions: {
type: 'boolean',
description: 'Whether to ignore function expressions (functions which are not part of a declaration).',
},
allowFunctionsWithoutTypeParameters: {
type: 'boolean',
description: "Whether to ignore functions that don't have generic type parameters.",
},
allowHigherOrderFunctions: {
type: 'boolean',
description: 'Whether to ignore functions immediately returning another function expression.',
},
allowIIFEs: {
type: 'boolean',
description: 'Whether to ignore immediately invoked function expressions (IIFEs).',
},
allowTypedFunctionExpressions: {
type: 'boolean',
description: 'Whether to ignore type annotations on the variable of function expressions.',
},
},
},
],
},
defaultOptions: [
{
allowConciseArrowFunctionExpressionsStartingWithVoid: false,
allowDirectConstAssertionInArrowFunctions: true,
allowedNames: [],
allowExpressions: false,
allowFunctionsWithoutTypeParameters: false,
allowHigherOrderFunctions: true,
allowIIFEs: false,
allowTypedFunctionExpressions: true,
},
],
create(context, [options]) {
const functionInfoStack = [];
function enterFunction(node) {
functionInfoStack.push({
node,
returns: [],
});
}
function popFunctionInfo(exitNodeType) {
return (0, util_1.nullThrows)(functionInfoStack.pop(), `Stack should exist on ${exitNodeType} exit`);
}
function isAllowedFunction(node) {
if (options.allowFunctionsWithoutTypeParameters && !node.typeParameters) {
return true;
}
if (options.allowIIFEs && isIIFE(node)) {
return true;
}
if (!options.allowedNames?.length) {
return false;
}
if (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression ||
node.type === utils_1.AST_NODE_TYPES.FunctionExpression) {
const parent = node.parent;
let funcName;
if (node.id?.name) {
funcName = node.id.name;
}
else {
switch (parent.type) {
case utils_1.AST_NODE_TYPES.VariableDeclarator: {
if (parent.id.type === utils_1.AST_NODE_TYPES.Identifier) {
funcName = parent.id.name;
}
break;
}
case utils_1.AST_NODE_TYPES.MethodDefinition:
case utils_1.AST_NODE_TYPES.PropertyDefinition:
case utils_1.AST_NODE_TYPES.Property: {
if (parent.key.type === utils_1.AST_NODE_TYPES.Identifier &&
!parent.computed) {
funcName = parent.key.name;
}
break;
}
}
}
if (!!funcName && options.allowedNames.includes(funcName)) {
return true;
}
}
if (node.type === utils_1.AST_NODE_TYPES.FunctionDeclaration &&
node.id &&
options.allowedNames.includes(node.id.name)) {
return true;
}
return false;
}
function isIIFE(node) {
return node.parent.type === utils_1.AST_NODE_TYPES.CallExpression;
}
function exitFunctionExpression(node) {
const info = popFunctionInfo('function expression');
if (options.allowConciseArrowFunctionExpressionsStartingWithVoid &&
node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression &&
node.expression &&
node.body.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
node.body.operator === 'void') {
return;
}
if (isAllowedFunction(node)) {
return;
}
if (options.allowTypedFunctionExpressions &&
((0, explicitReturnTypeUtils_1.isValidFunctionExpressionReturnType)(node, options) ||
(0, explicitReturnTypeUtils_1.ancestorHasReturnType)(node))) {
return;
}
(0, explicitReturnTypeUtils_1.checkFunctionReturnType)(info, options, context.sourceCode, loc => context.report({
loc,
node,
messageId: 'missingReturnType',
}));
}
return {
'ArrowFunctionExpression, FunctionExpression, FunctionDeclaration': enterFunction,
'ArrowFunctionExpression:exit': exitFunctionExpression,
'FunctionDeclaration:exit'(node) {
const info = popFunctionInfo('function declaration');
if (isAllowedFunction(node)) {
return;
}
if (options.allowTypedFunctionExpressions && node.returnType) {
return;
}
(0, explicitReturnTypeUtils_1.checkFunctionReturnType)(info, options, context.sourceCode, loc => context.report({
loc,
node,
messageId: 'missingReturnType',
}));
},
'FunctionExpression:exit': exitFunctionExpression,
ReturnStatement(node) {
functionInfoStack.at(-1)?.returns.push(node);
},
};
},
});
@@ -0,0 +1,8 @@
'use strict'
const parse = require('./parse')
const prerelease = (version, options) => {
const parsed = parse(version, options)
return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
module.exports = prerelease
@@ -0,0 +1,58 @@
let crypto = require('crypto')
let { urlAlphabet } = require('./url-alphabet/index.cjs')
const POOL_SIZE_MULTIPLIER = 128
let pool, poolOffset
let fillPool = bytes => {
if (bytes < 0 || bytes > 1024) throw new RangeError('Wrong ID size')
if (!pool || pool.length < bytes) {
pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
crypto.randomFillSync(pool)
poolOffset = 0
} else if (poolOffset + bytes > pool.length) {
crypto.randomFillSync(pool)
poolOffset = 0
}
poolOffset += bytes
}
let random = bytes => {
fillPool((bytes |= 0))
return pool.subarray(poolOffset - bytes, poolOffset)
}
let customRandom = (alphabet, defaultSize, getRandom) => {
let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
return (size = defaultSize) => {
if (size <= 0) return ''
let id = ''
while (true) {
let bytes = getRandom(step)
let i = step
while (i--) {
id += alphabet[bytes[i] & mask] || ''
if (id.length === size) return id
}
}
}
}
let customAlphabet = (alphabet, size = 21) =>
customRandom(alphabet, size, random)
let nanoid = (size = 21) => {
fillPool((size |= 0))
let id = ''
for (let i = poolOffset - size; i < poolOffset; i++) {
id += urlAlphabet[pool[i] & 63]
}
return id
}
module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _classPrivateFieldInitSpec;
var _checkPrivateRedeclaration = require("./checkPrivateRedeclaration.js");
function _classPrivateFieldInitSpec(obj, privateMap, value) {
(0, _checkPrivateRedeclaration.default)(obj, privateMap);
privateMap.set(obj, value);
}
//# sourceMappingURL=classPrivateFieldInitSpec.js.map
@@ -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"}
}
}
@@ -0,0 +1,44 @@
"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.PatternMatcher = void 0;
const eslintUtils = __importStar(require("@eslint-community/eslint-utils"));
/**
* The class to find a pattern in strings as handling escape sequences.
* It ignores the found pattern if it's escaped with `\`.
*
* @see {@link https://eslint-community.github.io/eslint-utils/api/ast-utils.html#patternmatcher-class}
*/
exports.PatternMatcher = eslintUtils.PatternMatcher;
@@ -0,0 +1,25 @@
// unix absolute paths are also absolute on win32, so we use this for both
import { win32 } from 'node:path';
const { isAbsolute, parse } = win32;
// returns [root, stripped]
// Note that windows will think that //x/y/z/a has a "root" of //x/y, and in
// those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip /
// explicitly if it's the first character.
// drive-specific relative paths on Windows get their root stripped off even
// though they are not absolute, so `c:../foo` becomes ['c:', '../foo']
export const stripAbsolutePath = (path) => {
let r = '';
let parsed = parse(path);
while (isAbsolute(path) || parsed.root) {
// windows will think that //x/y/z has a "root" of //x/y/
// but strip the //?/C:/ off of //?/C:/path
const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ?
'/'
: parsed.root;
path = path.slice(root.length);
r += root;
parsed = parse(path);
}
return [r, path];
};
//# sourceMappingURL=strip-absolute-path.js.map
@@ -0,0 +1,59 @@
# 0.9.0
- update dependencies, in particular `levn` and `type-check` - this could affect behaviour of argument parsing
# 0.8.3
- changes dependency from `wordwrap` to `word-wrap` due to license issue
- update dependencies
# 0.8.2
- fix bug #18 - detect missing value when flag is last item
- update dependencies
# 0.8.1
- update `fast-levenshtein` dependency
# 0.8.0
- update `levn` dependency - supplying a float value to an option with type `Int` now throws an error, instead of silently converting to an `Int`
# 0.7.1
- fix bug with use of `defaults` and `concatRepeatedArrays` or `mergeRepeatedObjects`
# 0.7.0
- added `concatrepeatedarrays` option: `oneValuePerFlag`, only allows one array value per flag
- added `typeAliases` option
- added `parseArgv` which takes an array and parses with the first two items sliced off
- changed enum help style
- bug fixes (#12)
- use of `concatRepeatedArrays` and `mergeRepeatedObjects` at the top level is deprecated, use it as either a per-option option, or set them in the `defaults` object to set them for all objects
# 0.6.0
- added `defaults` lib-option flag, allowing one to set default properties for all options
- added `concatRepeatedArrays` and `mergeRepeatedObjects` as option level properties, allowing you to turn this feature on for specific options only
# 0.5.0
- `Boolean` flags with `default: 'true'`, and no short aliases, will by default show the `--no` version in help
# 0.4.0
- add `mergeRepeatedObjects` setting
# 0.3.0
- add `concatRepeatedArrays` setting
- add `overrideRequired` option setting
- use just Levenshtein string compare algo rather than Levenshtein Damerau to due dependency license issue
# 0.2.2
- bug fixes
# 0.2.1
- improved interpolation
- added changelog
# 0.2.0
- add dependency checks to options - added `dependsOn` as an option property
- add interpolation for `prepend` and `append` text with new `generateHelp` option, `interpolate`
# 0.1.1
- update dependencies
# 0.1.0
- initial release
@@ -0,0 +1,17 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const MailMinus = createLucideIcon("MailMinus", [
["path", { d: "M22 15V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8", key: "fuxbkv" }],
["path", { d: "m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7", key: "1ocrg3" }],
["path", { d: "M16 19h6", key: "xwg31i" }]
]);
export { MailMinus as default };
//# sourceMappingURL=mail-minus.js.map
@@ -0,0 +1,261 @@
[![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree)
[![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree)
[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/js/espree/actions)
[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE)
# Espree
Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima.
## Usage
Install:
```
npm i espree
```
To use in an ESM file:
```js
import * as espree from "espree";
const ast = espree.parse(code);
```
To use in a Common JS file:
```js
const espree = require("espree");
const ast = espree.parse(code);
```
## API
### `parse()`
`parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters.
- `code` [string]() - the code which needs to be parsed.
- `options (Optional)` [Object]() - read more about this [here](#options).
```js
import * as espree from "espree";
const ast = espree.parse(code);
```
**Example :**
```js
const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 });
console.log(ast);
```
<details><summary>Output</summary>
<p>
```
Node {
type: 'Program',
start: 0,
end: 15,
body: [
Node {
type: 'VariableDeclaration',
start: 0,
end: 15,
declarations: [Array],
kind: 'let'
}
],
sourceType: 'script'
}
```
</p>
</details>
### `tokenize()`
`tokenize` returns the tokens of a given code. It takes two parameters.
- `code` [string]() - the code which needs to be parsed.
- `options (Optional)` [Object]() - read more about this [here](#options).
Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array
**Example :**
```js
import * as espree from "espree";
const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 });
console.log(tokens);
```
<details><summary>Output</summary>
<p>
```
Token { type: 'Keyword', value: 'let', start: 0, end: 3 },
Token { type: 'Identifier', value: 'foo', start: 4, end: 7 },
Token { type: 'Punctuator', value: '=', start: 8, end: 9 },
Token { type: 'String', value: '"bar"', start: 10, end: 15 }
```
</p>
</details>
### `version`
Returns the current `espree` version
### `VisitorKeys`
Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/js/tree/main/packages/eslint-visitor-keys)
### `latestEcmaVersion`
Returns the latest ECMAScript supported by `espree`
### `supportedEcmaVersions`
Returns an array of all supported ECMAScript versions
## Options
```js
const options = {
// attach range information to each node
range: false,
// attach line/column location information to each node
loc: false,
// create a top-level comments array containing all comments
comment: false,
// create a top-level tokens array containing all tokens
tokens: false,
// Set to 3, 5 (the default), 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 or 17 to specify the version of ECMAScript syntax you want to use.
// You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), 2022 (same as 13), 2023 (same as 14), 2024 (same as 15), 2025 (same as 16) or 2026 (same as 17) to use the year-based naming.
// You can also set "latest" to use the most recently supported version.
ecmaVersion: 3,
allowReserved: true, // only allowed when ecmaVersion is 3
// specify which type of script you're parsing ("script", "module", or "commonjs")
sourceType: "script",
// specify additional language features
ecmaFeatures: {
// enable JSX parsing
jsx: false,
// enable return in global scope (set to true automatically when sourceType is "commonjs")
globalReturn: false,
// enable implied strict mode (if ecmaVersion >= 5)
impliedStrict: false,
},
};
```
## Esprima Compatibility Going Forward
The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same.
Espree may also deviate from Esprima in the interface it exposes.
## 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/js/issues).
Espree is licensed under a permissive BSD 2-clause license.
## Security Policy
We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md).
## Build Commands
- `npm test` - run all tests
- `npm run lint` - run all linting
## Differences from Espree 2.x
- The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics.
- Trailing whitespace no longer is counted as part of a node.
- `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`.
- The `esparse` and `esvalidate` binary scripts have been removed.
- There is no `tolerant` option. We will investigate adding this back in the future.
## Known Incompatibilities
In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change.
### Esprima 1.2.2
- Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs.
- Espree does not parse `let` and `const` declarations by default.
- Error messages returned for parsing errors are different.
- There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn.
### Esprima 2.x
- Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2.
## Frequently Asked Questions
### Why another parser
[ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration.
We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API.
With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima.
### Have you tried working with Esprima?
Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support.
### Why don't you just use Acorn?
Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint.
We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better.
### What ECMAScript features do you support?
Espree supports all ECMAScript 2025 features and partially supports ECMAScript 2026 features.
Because ECMAScript 2026 is still under development, we are implementing features as they are finalized. Currently, Espree supports:
- [Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management)
See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized.
### How do you determine which experimental features to support?
In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features.
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/d472863/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/2d6c3b6/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://opensource.sap.com"><img src="https://avatars.githubusercontent.com/u/2531208" alt="SAP" height="32"></a> <a href="https://www.crawljobs.com/"><img src="https://images.opencollective.com/crawljobs-poland/fa43a17/logo.png" alt="CrawlJobs" height="32"></a> <a href="https://depot.dev"><img src="https://images.opencollective.com/depot/39125a1/logo.png" alt="Depot" height="32"></a> <a href="https://www.n-ix.com/"><img src="https://images.opencollective.com/n-ix-ltd/575a7a5/logo.png" alt="N-iX Ltd" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="TestMu AI Open Source Office (Formerly LambdaTest)" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->
@@ -0,0 +1 @@
{"version":3,"names":["_toSetter","fn","args","thisArg","l","length","Object","defineProperty","set","v","apply"],"sources":["../../src/helpers/toSetter.ts"],"sourcesContent":["/* @minVersion 7.24.0 */\n\nexport default function _toSetter(fn: Function, args: any[], thisArg: any) {\n if (!args) args = [];\n var l = args.length++;\n return Object.defineProperty({}, \"_\", {\n set: function (v) {\n args[l] = v;\n fn.apply(thisArg, args);\n },\n });\n}\n"],"mappings":";;;;;;AAEe,SAASA,SAASA,CAACC,EAAY,EAAEC,IAAW,EAAEC,OAAY,EAAE;EACzE,IAAI,CAACD,IAAI,EAAEA,IAAI,GAAG,EAAE;EACpB,IAAIE,CAAC,GAAGF,IAAI,CAACG,MAAM,EAAE;EACrB,OAAOC,MAAM,CAACC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE;IACpCC,GAAG,EAAE,SAAAA,CAAUC,CAAC,EAAE;MAChBP,IAAI,CAACE,CAAC,CAAC,GAAGK,CAAC;MACXR,EAAE,CAACS,KAAK,CAACP,OAAO,EAAED,IAAI,CAAC;IACzB;EACF,CAAC,CAAC;AACJ","ignoreList":[]}
@@ -0,0 +1,25 @@
import { handle } from "./handler.js";
//#region src/adapter/service-worker/index.ts
/**
* Registers a Hono app to handle fetch events in a service worker.
* This sets up `addEventListener('fetch', handle(app, options))` for the provided app.
*
* @param app - The Hono application instance
* @param options - Options for handling requests (fetch defaults to undefined)
* @example
* ```ts
* import { Hono } from 'hono'
* import { fire } from 'hono/service-worker'
*
* const app = new Hono()
*
* app.get('/', (c) => c.text('Hi'))
*
* fire(app)
* ```
*/
const fire = (app, options) => {
addEventListener("fetch", handle(app, options));
};
//#endregion
export { fire, handle };
@@ -0,0 +1,49 @@
<?xml version="1.0"?>
<!-- http://cyber.law.harvard.edu/rss/examples/rss2sample.xml -->
<rss version="2.0">
<channel>
<title>Liftoff News</title>
<link>http://liftoff.msfc.nasa.gov/</link>
<description>Liftoff to Space Exploration.</description>
<language>en-us</language>
<pubDate>Tue, 10 Jun 2003 04:00:00 GMT</pubDate>
<lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
<docs>http://blogs.law.harvard.edu/tech/rss</docs>
<generator>Weblog Editor 2.0</generator>
<managingEditor>editor@example.com</managingEditor>
<webMaster>webmaster@example.com</webMaster>
<item>
<title>Star City</title>
<link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link>
<description>How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's &lt;a href="http://howe.iki.rssi.ru/GCTC/gctc_e.htm"&gt;Star City&lt;/a&gt;.</description>
<pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate>
<guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid>
</item>
<item>
<description>Sky watchers in Europe, Asia, and parts of Alaska and Canada will experience a &lt;a href="http://science.nasa.gov/headlines/y2003/30may_solareclipse.htm"&gt;partial eclipse of the Sun&lt;/a&gt; on Saturday, May 31st.</description>
<pubDate>Fri, 30 May 2003 11:06:42 GMT</pubDate>
<guid>http://liftoff.msfc.nasa.gov/2003/05/30.html#item572</guid>
</item>
<item>
<title>The Engine That Does More</title>
<link>http://liftoff.msfc.nasa.gov/news/2003/news-VASIMR.asp</link>
<description>Before man travels to Mars, NASA hopes to design new engines that will let us fly through the Solar System more quickly. The proposed VASIMR engine would do that.</description>
<pubDate>Tue, 27 May 2003 08:37:32 GMT</pubDate>
<guid>http://liftoff.msfc.nasa.gov/2003/05/27.html#item571</guid>
</item>
<item>
<title>Astronauts' Dirty Laundry</title>
<link>http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp</link>
<description>Compared to earlier spacecraft, the International Space Station has many luxuries, but laundry facilities are not one of them. Instead, astronauts have other options.</description>
<pubDate>Tue, 20 May 2003 08:56:02 GMT</pubDate>
<guid>http://liftoff.msfc.nasa.gov/2003/05/20.html#item570</guid>
<media:content height="200" medium="image" url="https://picsum.photos/200" width="200"/>
</item>
</channel>
</rss>
@@ -0,0 +1 @@
{"version":3,"names":["shallowEqual","actual","expected","keys","Object","key"],"sources":["../../src/utils/shallowEqual.ts"],"sourcesContent":["export default function shallowEqual<T extends object>(\n actual: object,\n expected: T,\n): actual is T {\n const keys = Object.keys(expected) as (keyof T)[];\n\n for (const key of keys) {\n if (\n // @ts-expect-error maybe we should check whether key exists first\n actual[key] !== expected[key]\n ) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;AAAe,SAASA,YAAYA,CAClCC,MAAc,EACdC,QAAW,EACE;EACb,MAAMC,IAAI,GAAGC,MAAM,CAACD,IAAI,CAACD,QAAQ,CAAgB;EAEjD,KAAK,MAAMG,GAAG,IAAIF,IAAI,EAAE;IACtB,IAEEF,MAAM,CAACI,GAAG,CAAC,KAAKH,QAAQ,CAACG,GAAG,CAAC,EAC7B;MACA,OAAO,KAAK;IACd;EACF;EAEA,OAAO,IAAI;AACb","ignoreList":[]}
@@ -0,0 +1,15 @@
# Installation
> `npm install --save @types/chai`
# Summary
This package contains type definitions for chai (http://chaijs.com/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/chai.
### Additional Details
* Last updated: Mon, 20 Oct 2025 23:32:35 GMT
* Dependencies: [@types/deep-eql](https://npmjs.com/package/@types/deep-eql), [assertion-error](https://npmjs.com/package/assertion-error)
# Credits
These definitions were written by [Bart van der Schoor](https://github.com/Bartvds), [Andrew Brown](https://github.com/AGBrown), [Olivier Chevet](https://github.com/olivr70), [Matt Wistrand](https://github.com/mwistrand), [Shaun Luttin](https://github.com/shaunluttin), [Satana Charuwichitratana](https://github.com/micksatana), [Erik Schierboom](https://github.com/ErikSchierboom), [Bogdan Paranytsia](https://github.com/bparan), [CXuesong](https://github.com/CXuesong), and [Joey Kilpatrick](https://github.com/joeykilpatrick).
@@ -0,0 +1,16 @@
type ModeWriter = (doc: Doc, modes: {
execution: "sync" | "async";
}) => void;
export declare class Doc {
args: string[];
/** Bindings the compiled function closes over, by name. */
closed: Record<string, unknown>;
content: string[];
indent: number;
constructor(args?: string[], closed?: Record<string, unknown>);
indented(fn: (doc: Doc) => void): void;
write(fn: ModeWriter): void;
write(line: string): void;
compile(): any;
}
export {};
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../node_modules/minipass/src/index.ts", "../../node_modules/@isaacs/fs-minipass/src/index.ts", "../../src/options.ts", "../../src/make-command.ts", "../../node_modules/minizlib/src/constants.ts", "../../node_modules/minizlib/src/index.ts", "../../src/large-numbers.ts", "../../src/types.ts", "../../src/header.ts", "../../src/pax.ts", "../../src/normalize-windows-path.ts", "../../src/read-entry.ts", "../../src/warn-method.ts", "../../src/parse.ts", "../../src/strip-trailing-slashes.ts", "../../src/list.ts", "../../src/mode-fix.ts", "../../src/strip-absolute-path.ts", "../../src/winchars.ts", "../../src/write-entry.ts", "../../node_modules/yallist/src/index.ts", "../../src/pack.ts", "../../src/create.ts", "../../src/get-write-flag.ts", "../../node_modules/chownr/src/index.ts", "../../src/cwd-error.ts", "../../src/symlink-error.ts", "../../src/mkdir.ts", "../../src/normalize-unicode.ts", "../../src/path-reservations.ts", "../../src/process-umask.ts", "../../src/unpack.ts", "../../src/extract.ts", "../../src/replace.ts", "../../src/update.ts", "../../src/index.ts"],
"sourcesContent": ["const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrorsLine truncated
"mappings": "4RAAA,IAAMA,GACJ,OAAO,SAAY,UAAY,QAC3B,QACA,CACE,OAAQ,KACR,OAAQ,MAEhBC,GAAA,QAAA,aAAA,EACAC,GAAAC,GAAA,QAAA,aAAA,CAAA,EACAC,GAAA,QAAA,qBAAA,EAaaC,GACX,GAEA,CAAC,CAAC,GACF,OAAO,GAAM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K,EAEzBA,EAAQ,OAAO,KACbA,EAAM,OACNA,EAAM,WACNA,EAAM,UAAU,UAETpB,GAAkBoB,CAAK,EAEhCA,EAAQ,OAAO,KAAKA,CAAK,UAChB,OAAOA,GAAU,SAC1B,MAAM,IAAI,MACR,sDAAsD,EAO5D,OAAI,KAAKrC,CAAU,GAGb,KAAKR,CAAO,GAAK,KAAKK,CAAY,IAAM,GAAG,KAAKT,EAAK,EAAE,EAAI,EAG3D,KAAKI,CAAO,EAAG,KAAK,KAAK,OAAQ6C,CAAyB,EACzD,KAAKvC,EAAU,EAAEuC,CAAyB,EAE3C,KAAKxC,CAAY,IAAM,GAAG,KAAK,KAAK,UAAU,EAE9C0C,GAAI1B,EAAG0B,CAAE,EAEN,KAAK/C,CAAO,GAKf6C,EAAkC,QAStC,OAAOA,GAAU,UAEjB,EAAEC,IAAa,KAAKhD,CAAQ,GAAK,CAAC,KAAKC,EAAO,GAAG,YAGjD8C,EAAQ,OAAO,KAAKA,EAAOC,CAAQ,GAGjC,OAAO,SAASD,CAAK,GAAK,KAAK/C,CAAQ,IAEzC+C,EAAQ,KAAK9C,EAAO,EAALine truncated
"names": ["proc", "node_events_1", "node_stream_1", "__importDefault", "node_string_decoder_1", "isStream", "Minipass", "exports", "isReadable", "isWritable", "EOF", "MAYBE_EMIT_END", "EMITTED_END", "EMITTING_END", "EMITTED_ERROR", "CLOSED", "READ", "FLUSH", "FLUSHCHUNK", "ENCODING", "DECODER", "FLOWING", "PAUSED", "RESUME", "BUFFER", "PIPES", "BUFFERLENGTH", "BUFFERPUSH", "BUFFERSHIFT", "OBJECTMODE", "DESTROYED", "ERROR", "EMITDATA", "EMITEND", "EMITEND2", "ASYNC", "ABORT", "ABORTED", "SIGNAL", "DATALISTENERS", "DISCARDED", "defer", "fn", "nodefer", "isEndish", "ev", "isArrayBufferLike", "b", "isArrayBufferView", "Pipe", "src", "dest", "opts", "_er", "PipeProxyErrors", "er", "isObjectModeOptions", "o", "isEncodingOptions", "args", "options", "signal", "_enc", "_om", "a", "_", "chunk", "encoding", "cb", "n", "ret", "c", "noDrain", "ended", "p", "handler", "h", "data", "buf", "resolve", "reject", "stopped", "stop", "res", "onerr", "ondata", "onend", "ondestroy", "value", "rej", "next", "wc", "events_1", "__importDefault", "fs_1", "minipass_1", "writev", "_autoClose", "_close", "_ended", "_fd", "_finished", "_flags", "_flush", "_handleChunk", "_makeBuf", "_mode", "_needDrain", "_onerror", "_onopen", "_onread", "_onwrite", "_open", "_path", "_pos", "_queue", "_read", "_readSize", "_reading", "_remain", "_size", "_write", "_writing", "_defaultFlag", "_errored", "ReadStream", "path", "opt", "er", "fd", "buf", "br", "b", "ret", "ev", "args", "exports", "ReadStreamSync", "threw", "WriteStream", "defaultFlag", "enc", "bw", "iovec", "WriteStreamSync", "argmap", "isSyncFile", "o", "exports", "isAsyncFile", "isSyncNoFile", "isAsyncNoFile", "isSync", "isAsync", "isFile", "isNoFile", "dealiasKey", "k", "d", "dealias", "opt", "result", "key", "v", "options_js_1", "makeCommand", "syncFile", "asyncFile", "syncNoFile", "asyncNoFile", "validate", "opt_", "entries", "cb", "opt", "p", "exports", "zlib_1", "__importDefault", "realZlibConstants", "exports", "assert_1", "__importDefault", "buffer_1", "minipass_1", "realZlib", "__importStar", "constants_js_1", "constants_js_2", "exports", "OriginalBufferConcat", "desc", "noop", "args", "passthroughBufferConcat", "makeNoOp", "_", "_superWrite", "ZlibError", "err", "origin", "_flushFlag", "ZlibBase", "#sawError", "#ended", "#flushFlag", "#finishFlushFlag", "#fullFlushFlag", "#handle", "#onError", "opts", "mode", "er", "flushFlag", "chunk", "encoding", "cb", "data", "nativeHandle", "originalNativeClose", "originalClose", "result", "writeReturn", "r", "i", "Zlib", "#level", "#strategy", "level", "strategy", "origFlush", "Deflate", "Inflate", "Gzip", "#portable", "Gunzip", "DeflateRaw", "InflateRaw", "Unzip", "Brotli", "BrotliCompress", "BrotliDecompress", "Zstd", "ZstdCompress", "ZstdDecompress", "encode", "num", "buf", "encodeNegative", "encodePositive", "exports", "i", "flipped", "byte", "onesComp", "twosComp", "parse", "pre", "value", "pos", "twos", "len", "sum", "f", "isCode", "c", "exports", "isName", "kv", "node_path_1", "large", "__importStar", "types", "notNegative", "n", "Header", "#type", "data", "off", "ex", "gex", "#slurp", "buf", "t", "decString", "isNormalFS", "exForFields", "gexForFields", "decNumber", "decDate", "prefix", "sum", "i", "k", "v", "prefixSize", "split", "splitPrefix", "path", "encString", "encNumber", "encDate", "type", "c", "exports", "p", "pp", "ret", "root", "size", "numToDate", "num", "decSmallNumber", "nanUndef", "value", "MAXNUM", "encSmallNumber", "octalString", "padOctal", "str", "date", "NULLS", "node_path_1", "header_js_1", "Pax", "_Pax", "obj", "global", "body", "bodyLen", "bufLen", "buf", "i", "field", "r", "v", "s", "byteLen", "digits", "str", "ex", "g", "merge", "parseKV", "exports", "a", "b", "parseKVLine", "set", "line", "n", "kv", "k", "platform", "exports", "p", "minipass_1", "normalize_windows_path_js_1", "ReadEntry", "header", "ex", "gex", "#slurp", "data", "writeLen", "r", "br", "k", "v", "exports", "warnMethod", "self", "code", "message", "data", "exports", "events_1", "minizlib_1", "header_js_1", "pax_js_1", "read_entry_js_1", "warn_method_js_1", "maxMetaEntrySize", "gzipHeader", "zstdHeader", "ZIP_HEADER_LEN", "STATE", "WRITEENTRY", "READENTRY", "NEXTENTRY", "PROCESSENTRY", "EX", "GEX", "META", "EMITMETA", "BUFFER", "QUEUE", "ENDED", "EMITTEDEND", "EMIT", "UNZIP", "CONSUMECHUNK", "CONSUMECHUNKSUB", "CONSUMEBODY", "CONSUMEMETA", "CONSUMEHEADER", "CONSUMING", "BUFFERCONCAT", "MAYBEEND", "WRITING", "ABORTED", "DONE", "SAW_VALID_ENTRY", "SAW_NULL_BLOCK", "SAW_EOF", "CLOSESTREAM", "MAX_DECOMPRESSION_RATIO", "COMPRESSEDBYTESREAD", "DECOMPRESSEDBYTESREAD", "CHECKDECOMPRESSIONRATIO", "noop", "Parser", "opt", "isTBR", "isTZST", "code", "message", "data", "chunk", "position", "header", "er", "type", "entry", "onend", "c", "go", "ev", "args", "re", "br", "ret", "extra", "ex", "error", "u", "ratio", "encoding", "cb", "i", "isZstd", "maybeBrotli", "ended", "have", "length", "exports", "stripTrailingSlashes", "str", "i", "slashesStart", "exporLine truncated
}
@@ -0,0 +1,46 @@
"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.isHigherPrecedenceThanAwait = isHigherPrecedenceThanAwait;
const ts = __importStar(require("typescript"));
const getOperatorPrecedence_1 = require("./getOperatorPrecedence");
function isHigherPrecedenceThanAwait(tsNode) {
const operator = ts.isBinaryExpression(tsNode)
? tsNode.operatorToken.kind
: ts.SyntaxKind.Unknown;
const nodePrecedence = (0, getOperatorPrecedence_1.getOperatorPrecedence)(tsNode.kind, operator);
const awaitPrecedence = (0, getOperatorPrecedence_1.getOperatorPrecedence)(ts.SyntaxKind.AwaitExpression, ts.SyntaxKind.Unknown);
return nodePrecedence > awaitPrecedence;
}
@@ -0,0 +1,63 @@
/**
* @fileoverview Utilities to operate on option objects.
* @author Josh Goldberg
*/
"use strict";
/**
* Determines whether any of input's properties are different
* from values that already exist in original.
* @template T
* @param {Partial<T>} input New value.
* @param {T} original Original value.
* @returns {boolean} Whether input includes an explicit difference.
*/
function containsDifferentProperty(input, original) {
if (input === original) {
return false;
}
if (
typeof input !== typeof original ||
Array.isArray(input) !== Array.isArray(original)
) {
return true;
}
if (Array.isArray(input)) {
return (
input.length !== original.length ||
input.some((value, i) =>
containsDifferentProperty(value, original[i]),
)
);
}
if (typeof input === "object") {
if (input === null || original === null) {
return true;
}
const inputKeys = Object.keys(input);
const originalKeys = Object.keys(original);
return (
inputKeys.length !== originalKeys.length ||
inputKeys.some(
inputKey =>
!Object.hasOwn(original, inputKey) ||
containsDifferentProperty(
input[inputKey],
original[inputKey],
),
)
);
}
return true;
}
module.exports = {
containsDifferentProperty,
};
@@ -0,0 +1,47 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Resolver")} Resolver */
/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
/** @typedef {string | string[] | false} Alias */
/** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */
const { aliasResolveHandler } = require("./AliasUtils");
module.exports = class AliasPlugin {
/**
* @param {string | ResolveStepHook} source source
* @param {AliasOption | AliasOption[]} options options
* @param {string | ResolveStepHook} target target
*/
constructor(source, options, target) {
this.source = source;
this.options = Array.isArray(options) ? options : [options];
this.target = target;
}
/**
* @param {Resolver} resolver the resolver
* @returns {void}
*/
apply(resolver) {
const target = resolver.ensureHook(this.target);
resolver
.getHook(this.source)
.tapAsync("AliasPlugin", (request, resolveContext, callback) => {
aliasResolveHandler(
resolver,
this.options,
target,
request,
resolveContext,
callback,
);
});
}
};
@@ -0,0 +1,18 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const ArrowRightLeft = createLucideIcon("ArrowRightLeft", [
["path", { d: "m16 3 4 4-4 4", key: "1x1c3m" }],
["path", { d: "M20 7H4", key: "zbl0bi" }],
["path", { d: "m8 21-4-4 4-4", key: "h9nckh" }],
["path", { d: "M4 17h16", key: "g4d7ey" }]
]);
export { ArrowRightLeft as default };
//# sourceMappingURL=arrow-right-left.js.map
@@ -0,0 +1,36 @@
'use strict'
const fs = require('../fs')
const u = require('universalify').fromPromise
async function utimesMillis (path, atime, mtime) {
// if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
const fd = await fs.open(path, 'r+')
let closeErr = null
try {
await fs.futimes(fd, atime, mtime)
} finally {
try {
await fs.close(fd)
} catch (e) {
closeErr = e
}
}
if (closeErr) {
throw closeErr
}
}
function utimesMillisSync (path, atime, mtime) {
const fd = fs.openSync(path, 'r+')
fs.futimesSync(fd, atime, mtime)
return fs.closeSync(fd)
}
module.exports = {
utimesMillis: u(utimesMillis),
utimesMillisSync
}
@@ -0,0 +1 @@
{"version":3,"file":"blake2.js","sourceRoot":"","sources":["src/blake2.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrC,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,kBAAkB;AAClB,OAAO,EACL,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EACjC,KAAK,EAAE,YAAY,EACnB,UAAU,EAAE,SAAS,EACrB,GAAG,EAKJ,MAAM,YAAY,CAAC;AAkBpB,+EAA+E;AAC/E,qCAAqC;AACrC,MAAM,MAAM,GAAG,eAAe,CAAC,WAAW,CAAC,IAAI,CAAC;IAC9C,UAAU,EAAE,UAAU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AAC,CAAC;IAC1E,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;IAC7C,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;IAC7C,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAALine truncated
@@ -0,0 +1,138 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
Root: () => Slot,
Slot: () => Slot,
Slottable: () => Slottable,
createSlot: () => createSlot,
createSlottable: () => createSlottable
});
module.exports = __toCommonJS(index_exports);
// src/slot.tsx
var React = __toESM(require("react"));
var import_react_compose_refs = require("@radix-ui/react-compose-refs");
var import_jsx_runtime = require("react/jsx-runtime");
// @__NO_SIDE_EFFECTS__
function createSlot(ownerName) {
const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);
const Slot2 = React.forwardRef((props, forwardedRef) => {
const { children, ...slotProps } = props;
const childrenArray = React.Children.toArray(children);
const slottable = childrenArray.find(isSlottable);
if (slottable) {
const newElement = slottable.props.children;
const newChildren = childrenArray.map((child) => {
if (child === slottable) {
if (React.Children.count(newElement) > 1) return React.Children.only(null);
return React.isValidElement(newElement) ? newElement.props.children : null;
} else {
return child;
}
});
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SlotClone, { ...slotProps, ref: forwardedRef, children: React.isValidElement(newElement) ? React.cloneElement(newElement, void 0, newChildren) : null });
}
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SlotClone, { ...slotProps, ref: forwardedRef, children });
});
Slot2.displayName = `${ownerName}.Slot`;
return Slot2;
}
var Slot = /* @__PURE__ */ createSlot("Slot");
// @__NO_SIDE_EFFECTS__
function createSlotClone(ownerName) {
const SlotClone = React.forwardRef((props, forwardedRef) => {
const { children, ...slotProps } = props;
if (React.isValidElement(children)) {
const childrenRef = getElementRef(children);
const props2 = mergeProps(slotProps, children.props);
if (children.type !== React.Fragment) {
props2.ref = forwardedRef ? (0, import_react_compose_refs.composeRefs)(forwardedRef, childrenRef) : childrenRef;
}
return React.cloneElement(children, props2);
}
return React.Children.count(children) > 1 ? React.Children.only(null) : null;
});
SlotClone.displayName = `${ownerName}.SlotClone`;
return SlotClone;
}
var SLOTTABLE_IDENTIFIER = Symbol("radix.slottable");
// @__NO_SIDE_EFFECTS__
function createSlottable(ownerName) {
const Slottable2 = ({ children }) => {
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children });
};
Slottable2.displayName = `${ownerName}.Slottable`;
Slottable2.__radixId = SLOTTABLE_IDENTIFIER;
return Slottable2;
}
var Slottable = /* @__PURE__ */ createSlottable("Slottable");
function isSlottable(child) {
return React.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;
}
function mergeProps(slotProps, childProps) {
const overrideProps = { ...childProps };
for (const propName in childProps) {
const slotPropValue = slotProps[propName];
const childPropValue = childProps[propName];
const isHandler = /^on[A-Z]/.test(propName);
if (isHandler) {
if (slotPropValue && childPropValue) {
overrideProps[propName] = (...args) => {
const result = childPropValue(...args);
slotPropValue(...args);
return result;
};
} else if (slotPropValue) {
overrideProps[propName] = slotPropValue;
}
} else if (propName === "style") {
overrideProps[propName] = { ...slotPropValue, ...childPropValue };
} else if (propName === "className") {
overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
}
}
return { ...slotProps, ...overrideProps };
}
function getElementRef(element) {
let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
if (mayWarn) {
return element.ref;
}
getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
if (mayWarn) {
return element.props.ref;
}
return element.props.ref || element.ref;
}
//# sourceMappingURL=index.js.map
@@ -0,0 +1,4 @@
import { getConnInfo } from "./conninfo.js";
import { ALBRequestContext, ApiGatewayRequestContext, ApiGatewayRequestContextV2, LambdaContext } from "./types.js";
import { APIGatewayProxyResult, LambdaEvent, defaultIsContentTypeBinary, handle, streamHandle } from "./handler.js";
export { type ALBRequestContext, type APIGatewayProxyResult, type ApiGatewayRequestContext, type ApiGatewayRequestContextV2, type LambdaContext, type LambdaEvent, defaultIsContentTypeBinary, getConnInfo, handle, streamHandle };
@@ -0,0 +1,4 @@
import { ZodPromiseDef } from "zod/v3";
import { JsonSchema7Type } from "../parseTypes.js";
import { Refs } from "../Refs.js";
export declare function parsePromiseDef(def: ZodPromiseDef, refs: Refs): JsonSchema7Type | undefined;
@@ -0,0 +1,110 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { ZodIssueCode } from "zod/v3";
import { util } from "../helpers/util.js";
const stringMap = z.map(z.string(), z.string());
type stringMap = z.infer<typeof stringMap>;
test("type inference", () => {
util.assertEqual<stringMap, Map<string, string>>(true);
});
test("valid parse", () => {
const result = stringMap.safeParse(
new Map([
["first", "foo"],
["second", "bar"],
])
);
expect(result.success).toEqual(true);
if (result.success) {
expect(result.data.has("first")).toEqual(true);
expect(result.data.has("second")).toEqual(true);
expect(result.data.get("first")).toEqual("foo");
expect(result.data.get("second")).toEqual("bar");
}
});
test("valid parse async", async () => {
const result = await stringMap.spa(
new Map([
["first", "foo"],
["second", "bar"],
])
);
expect(result.success).toEqual(true);
if (result.success) {
expect(result.data.has("first")).toEqual(true);
expect(result.data.has("second")).toEqual(true);
expect(result.data.get("first")).toEqual("foo");
expect(result.data.get("second")).toEqual("bar");
}
});
test("throws when a Set is given", () => {
const result = stringMap.safeParse(new Set([]));
expect(result.success).toEqual(false);
if (result.success === false) {
expect(result.error.issues.length).toEqual(1);
expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type);
}
});
test("throws when the given map has invalid key and invalid input", () => {
const result = stringMap.safeParse(new Map([[42, Symbol()]]));
expect(result.success).toEqual(false);
if (result.success === false) {
expect(result.error.issues.length).toEqual(2);
expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type);
expect(result.error.issues[0].path).toEqual([0, "key"]);
expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type);
expect(result.error.issues[1].path).toEqual([0, "value"]);
}
});
test("throws when the given map has multiple invalid entries", () => {
// const result = stringMap.safeParse(new Map([[42, Symbol()]]));
const result = stringMap.safeParse(
new Map([
[1, "foo"],
["bar", 2],
] as [any, any][]) as Map<any, any>
);
// const result = stringMap.safeParse(new Map([[42, Symbol()]]));
expect(result.success).toEqual(false);
if (result.success === false) {
expect(result.error.issues.length).toEqual(2);
expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type);
expect(result.error.issues[0].path).toEqual([0, "key"]);
expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type);
expect(result.error.issues[1].path).toEqual([1, "value"]);
}
});
test("dirty", async () => {
const map = z.map(
z.string().refine((val) => val === val.toUpperCase(), {
message: "Keys must be uppercase",
}),
z.string()
);
const result = await map.spa(
new Map([
["first", "foo"],
["second", "bar"],
])
);
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues.length).toEqual(2);
expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom);
expect(result.error.issues[0].message).toEqual("Keys must be uppercase");
expect(result.error.issues[1].code).toEqual(z.ZodIssueCode.custom);
expect(result.error.issues[1].message).toEqual("Keys must be uppercase");
}
});
@@ -0,0 +1,24 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Skull = createLucideIcon("Skull", [
["path", { d: "m12.5 17-.5-1-.5 1h1z", key: "3me087" }],
[
"path",
{
d: "M15 22a1 1 0 0 0 1-1v-1a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20v1a1 1 0 0 0 1 1z",
key: "1o5pge"
}
],
["circle", { cx: "15", cy: "12", r: "1", key: "1tmaij" }],
["circle", { cx: "9", cy: "12", r: "1", key: "1vctgf" }]
]);
export { Skull as default };
//# sourceMappingURL=skull.js.map
@@ -0,0 +1 @@
{"version":3,"file":"lazyRouteComponent.cjs","names":[],"sources":["../../src/lazyRouteComponent.tsx"],"sourcesContent":["import * as React from 'react'\nimport { isModuleNotFoundError } from '@tanstack/router-core'\nimport { reactUse } from './utils'\nimport type { AsyncRouteComponent } from './route'\n\n/**\n * Wrap a dynamic import to create a route component that supports\n * `.preload()` and friendly reload-on-module-missing behavior.\n *\n * @param importer Function returning a module promise\n * @param exportName Named export to use (default: `default`)\n * @returns A lazy route component compatible with TanStack Router\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/lazyRouteComponentFunction\n */\nexport function lazyRouteComponent<\n T extends Record<string, any>,\n TKey extends keyof T = 'default',\n>(\n importer: () => Promise<T>,\n exportName?: TKey,\n): T[TKey] extends (props: infer TProps) => any\n ? AsyncRouteComponent<TProps>\n : never {\n let loadPromise: Promise<any> | undefined\n let comp: T[TKey] | T['default']\n let error: any\n let reload: boolean\n\n const load = () => {\n if (!loadPromise) {\n loadPromise = importer()\n .then((res) => {\n loadPromise = undefined\n comp = res[exportName ?? 'default']\n })\n .catch((err) => {\n // We don't want an error thrown from preload in this case, because\n // there's nothing we want to do about module not found during preload.\n // Record the error, the rest is handled during the render path.\n error = err\n // If the load fails due to module not found, it may mean a new version of\n // the build was deployed and the user's browser is still using an old version.\n // If this happens, the old version in the user's browser would have an outdated\n // URL to the lazy module.\n // In that case, we want to attempt one window refresh to get the latest.\n if (isModuleNotFoundError(error)) {\n if (\n error instanceof Error &&\n typeof window !== 'undefined' &&\n typeof sessionStorage !== 'undefined'\n ) {\n // Again, we want to reload one time on module not found error and not enter\n // a reload loop if there is some other issue besides an old deploy.\n // That's why we store our reload attempt in sessionStorage.\n // Use error.message as key because it contains the module path that failed.\n const storageKey = `tanstack_router_reload:${error.message}`\n if (!sessionStorage.getItem(storageKey)) {\n sessionStorage.setItem(storageKey, '1')\n reload = true\n }\n }\n }\n })\n }\n\n return loadPromise\n }\n\n const lazyComp = function Lazy(props: any) {\n // Now that we're out of preload and into actual render path,\n if (reload) {\n // If it was a module loading error,\n // throw eternal suspense while we wait for window to reload\n window.location.reload()\n throw new Promise(() => {})\n }\n if (error) {\n // Otherwise, just throw the error\n throw error\n }\n\n if (!comp) {\n if (reactUse) {\n reactUse(load())\n } else {\n throw load()\n }\n }\n\n return React.createElement(comp, props)\n }\n\n ;(lazyComp as any).preload = load\n\n return lazyComp as any\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAgB,mBAId,UACA,YAGQ;CACR,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,aAAa;AACjB,MAAI,CAAC,YACH,eAAc,UAAU,CACrB,MAAM,QAAQ;AACb,iBAAc,KAAA;AACd,UAAO,IAAI,cAAc;IACzB,CACD,OAAO,QAAQ;AAId,WAAQ;AAMR,QAAA,GAAA,sBAAA,uBAA0B,MAAM;QAE5B,iBAAiB,SACjB,OAAO,WAAW,eAClB,OAAO,mBAAmB,aAC1B;KAKA,MAAM,aAAa,0BAA0B,MAAM;AACnD,SAAI,CAAC,eAAe,QAAQ,WAAW,EAAE;AACvC,qBAAe,QAAQ,YAAY,IAAI;AACvC,eAAS;;;;IAIf;AAGN,SAAO;;CAGT,MAAM,WAAW,SAAS,KAAK,OAAY;AAEzC,MAAI,QAAQ;AAGV,UAAO,SAAS,QAAQ;AACxB,SAAM,IAAI,cAAc,GAAG;;AAE7B,MAAI,MAEF,OAAM;AAGR,MAAI,CAAC,KACH,KAAI,cAAA,SACF,eAAA,SAAS,MAAM,CAAC;MAEhB,OAAM,MAAM;AAIhB,SAAO,MAAM,cAAc,MAAM,MAAM;;AAGvC,UAAiB,UAAU;AAE7B,QAAO"}
@@ -0,0 +1,154 @@
# clsx [![CI](https://github.com/lukeed/clsx/workflows/CI/badge.svg)](https://github.com/lukeed/clsx/actions?query=workflow%3ACI) [![codecov](https://badgen.net/codecov/c/github/lukeed/clsx)](https://codecov.io/gh/lukeed/clsx) [![licenses](https://licenses.dev/b/npm/clsx)](https://licenses.dev/npm/clsx)
> A tiny (239B) utility for constructing `className` strings conditionally.<Br>Also serves as a [faster](bench) & smaller drop-in replacement for the `classnames` module.
This module is available in three formats:
* **ES Module**: `dist/clsx.mjs`
* **CommonJS**: `dist/clsx.js`
* **UMD**: `dist/clsx.min.js`
## Install
```
$ npm install --save clsx
```
## Usage
```js
import clsx from 'clsx';
// or
import { clsx } from 'clsx';
// Strings (variadic)
clsx('foo', true && 'bar', 'baz');
//=> 'foo bar baz'
// Objects
clsx({ foo:true, bar:false, baz:isTrue() });
//=> 'foo baz'
// Objects (variadic)
clsx({ foo:true }, { bar:false }, null, { '--foobar':'hello' });
//=> 'foo --foobar'
// Arrays
clsx(['foo', 0, false, 'bar']);
//=> 'foo bar'
// Arrays (variadic)
clsx(['foo'], ['', 0, false, 'bar'], [['baz', [['hello'], 'there']]]);
//=> 'foo bar baz hello there'
// Kitchen sink (with nesting)
clsx('foo', [1 && 'bar', { baz:false, bat:null }, ['hello', ['world']]], 'cya');
//=> 'foo bar hello world cya'
```
## API
### clsx(...input)
Returns: `String`
#### input
Type: `Mixed`
The `clsx` function can take ***any*** number of arguments, each of which can be an Object, Array, Boolean, or String.
> **Important:** _Any_ falsey values are discarded!<br>Standalone Boolean values are discarded as well.
```js
clsx(true, false, '', null, undefined, 0, NaN);
//=> ''
```
## Modes
There are multiple "versions" of `clsx` available, which allows you to bring only the functionality you need!
#### `clsx`
> **Size (gzip):** 239 bytes<br>
> **Availability:** CommonJS, ES Module, UMD
The default `clsx` module; see [API](#API) for info.
```js
import { clsx } from 'clsx';
// or
import clsx from 'clsx';
```
#### `clsx/lite`
> **Size (gzip):** 140 bytes<br>
> **Availability:** CommonJS, ES Module<br>
> **CAUTION:** Accepts **ONLY** string arguments!
Ideal for applications that ***only*** use the string-builder pattern.
Any non-string arguments are ignored!
```js
import { clsx } from 'clsx/lite';
// or
import clsx from 'clsx/lite';
// string
clsx('hello', true && 'foo', false && 'bar');
// => "hello foo"
// NOTE: Any non-string input(s) ignored
clsx({ foo: true });
//=> ""
```
## Benchmarks
For snapshots of cross-browser results, check out the [`bench`](bench) directory~!
## Support
All versions of Node.js are supported.
All browsers that support [`Array.isArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray#Browser_compatibility) are supported (IE9+).
>**Note:** For IE8 support and older, please install `clsx@1.0.x` and beware of [#17](https://github.com/lukeed/clsx/issues/17).
## Tailwind Support
Here some additional (optional) steps to enable classes autocompletion using `clsx` with Tailwind CSS.
<details>
<summary>
Visual Studio Code
</summary>
1. [Install the "Tailwind CSS IntelliSense" Visual Studio Code extension](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss)
2. Add the following to your [`settings.json`](https://code.visualstudio.com/docs/getstarted/settings):
```json
{
"tailwindCSS.experimental.classRegex": [
["clsx\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"]
]
}
```
</details>
You may find the [`clsx/lite`](#clsxlite) module useful within Tailwind contexts. This is especially true if/when your application **only** composes classes in this pattern:
```js
clsx('text-base', props.active && 'text-primary', props.className);
```
## Related
- [obj-str](https://github.com/lukeed/obj-str) - A smaller (96B) and similiar utility that only works with Objects.
## License
MIT © [Luke Edwards](https://lukeed.com)
@@ -0,0 +1,65 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_helper_ssg_utils = require("./utils.js");
//#region src/helper/ssg/middleware.ts
const SSG_CONTEXT = "HONO_SSG_CONTEXT";
const X_HONO_DISABLE_SSG_HEADER_KEY = "x-hono-disable-ssg";
/**
* @deprecated
* Use `X_HONO_DISABLE_SSG_HEADER_KEY` instead.
* This constant will be removed in the next minor version.
*/
const SSG_DISABLED_RESPONSE = (() => {
try {
return new Response("SSG is disabled", {
status: 404,
headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: "true" }
});
} catch {
return null;
}
})();
/**
* Define SSG Route
*/
const ssgParams = (params) => async (c, next) => {
if (require_helper_ssg_utils.isDynamicRoute(c.req.path)) {
c.req.raw.ssgParams = Array.isArray(params) ? params : await params(c);
return c.notFound();
}
await next();
};
/**
* @experimental
* `isSSGContext` is an experimental feature.
* The API might be changed.
*/
const isSSGContext = (c) => !!c.env?.[SSG_CONTEXT];
/**
* @experimental
* `disableSSG` is an experimental feature.
* The API might be changed.
*/
const disableSSG = () => async function disableSSG(c, next) {
if (isSSGContext(c)) {
c.header(X_HONO_DISABLE_SSG_HEADER_KEY, "true");
return c.notFound();
}
await next();
};
/**
* @experimental
* `onlySSG` is an experimental feature.
* The API might be changed.
*/
const onlySSG = () => async function onlySSG(c, next) {
if (!isSSGContext(c)) return c.notFound();
await next();
};
//#endregion
exports.SSG_CONTEXT = SSG_CONTEXT;
exports.SSG_DISABLED_RESPONSE = SSG_DISABLED_RESPONSE;
exports.X_HONO_DISABLE_SSG_HEADER_KEY = X_HONO_DISABLE_SSG_HEADER_KEY;
exports.disableSSG = disableSSG;
exports.isSSGContext = isSSGContext;
exports.onlySSG = onlySSG;
exports.ssgParams = ssgParams;
@@ -0,0 +1,41 @@
const {
emitForest,
emitForestLines,
parseFunctionRanges,
parseOffsets,
} = require("./ascii");
const {
cloneFunctionCov,
cloneProcessCov,
cloneScriptCov,
cloneRangeCov,
} = require("./clone");
const {
compareScriptCovs,
compareFunctionCovs,
compareRangeCovs,
} = require("./compare");
const {
mergeFunctionCovs,
mergeProcessCovs,
mergeScriptCovs,
} = require("./merge");
const { RangeTree } = require("./range-tree");
module.exports = {
emitForest,
emitForestLines,
parseFunctionRanges,
parseOffsets,
cloneFunctionCov,
cloneProcessCov,
cloneScriptCov,
cloneRangeCov,
compareScriptCovs,
compareFunctionCovs,
compareRangeCovs,
mergeFunctionCovs,
mergeProcessCovs,
mergeScriptCovs,
RangeTree,
};
@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
message: "must match exactly one schema in oneOf",
params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
};
const def = {
keyword: "oneOf",
schemaType: "array",
trackErrors: true,
error,
code(cxt) {
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 = 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() {
schArr.forEach((sch, i) => {
let schCxt;
if ((0, util_1.alwaysValidSchema)(it, sch)) {
gen.var(schValid, true);
}
else {
schCxt = cxt.subschema({
keyword: "oneOf",
schemaProp: i,
compositeRule: true,
}, schValid);
}
if (i > 0) {
gen
.if((0, codegen_1._) `${schValid} && ${valid}`)
.assign(valid, false)
.assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
.else();
}
gen.if(schValid, () => {
gen.assign(valid, true);
gen.assign(passing, i);
if (schCxt)
cxt.mergeEvaluated(schCxt, codegen_1.Name);
});
});
}
},
};
exports.default = def;
//# sourceMappingURL=oneOf.js.map
@@ -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/gopd
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']
@@ -0,0 +1,144 @@
const require_useRouter = require("./useRouter.cjs");
const require_useMatch = require("./useMatch.cjs");
const require_useLoaderData = require("./useLoaderData.cjs");
const require_useLoaderDeps = require("./useLoaderDeps.cjs");
const require_useParams = require("./useParams.cjs");
const require_useSearch = require("./useSearch.cjs");
const require_useNavigate = require("./useNavigate.cjs");
const require_useRouteContext = require("./useRouteContext.cjs");
const require_route = require("./route.cjs");
//#region src/fileRoute.ts
/**
* Creates a file-based Route factory for a given path.
*
* Used by TanStack Router's file-based routing to associate a file with a
* route. The returned function accepts standard route options. In normal usage
* the `path` string is inserted and maintained by the `tsr` generator.
*
* @param path File path literal for the route (usually auto-generated).
* @returns A function that accepts Route options and returns a Route instance.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createFileRouteFunction
*/
function createFileRoute(path) {
return new FileRoute(path, { silent: true }).createRoute;
}
/**
@deprecated It's no longer recommended to use the `FileRoute` class directly.
Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.
*/
var FileRoute = class {
constructor(path, _opts) {
this.path = path;
this.createRoute = (options) => {
if (process.env.NODE_ENV !== "production") {
if (!this.silent) console.warn("Warning: FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead.");
}
const route = require_route.createRoute(options);
route.isRoot = false;
return route;
};
this.silent = _opts?.silent;
}
};
/**
@deprecated It's recommended not to split loaders into separate files.
Instead, place the loader function in the main route file via `createFileRoute`.
*/
function FileRouteLoader(_path) {
if (process.env.NODE_ENV !== "production") console.warn(`Warning: FileRouteLoader is deprecated and will be removed in the next major version. Please place the loader function in the main route file, inside the \`createFileRoute('/path/to/file')(options)\` options`);
return (loaderFn) => loaderFn;
}
var LazyRoute = class {
constructor(opts) {
this.useMatch = (opts) => {
return require_useMatch.useMatch({
select: opts?.select,
from: this.options.id,
structuralSharing: opts?.structuralSharing
});
};
this.useRouteContext = (opts) => {
return require_useRouteContext.useRouteContext({
...opts,
from: this.options.id
});
};
this.useSearch = (opts) => {
return require_useSearch.useSearch({
select: opts?.select,
structuralSharing: opts?.structuralSharing,
from: this.options.id
});
};
this.useParams = (opts) => {
return require_useParams.useParams({
select: opts?.select,
structuralSharing: opts?.structuralSharing,
from: this.options.id
});
};
this.useLoaderDeps = (opts) => {
return require_useLoaderDeps.useLoaderDeps({
...opts,
from: this.options.id
});
};
this.useLoaderData = (opts) => {
return require_useLoaderData.useLoaderData({
...opts,
from: this.options.id
});
};
this.useNavigate = () => {
return require_useNavigate.useNavigate({ from: require_useRouter.useRouter().routesById[this.options.id].fullPath });
};
this.options = opts;
}
};
/**
* Creates a lazily-configurable code-based route stub by ID.
*
* Use this for code-splitting with code-based routes. The returned function
* accepts only non-critical route options like `component`, `pendingComponent`,
* `errorComponent`, and `notFoundComponent` which are applied when the route
* is matched.
*
* @param id Route ID string literal to associate with the lazy route.
* @returns A function that accepts lazy route options and returns a `LazyRoute`.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyRouteFunction
*/
function createLazyRoute(id) {
return (opts) => {
return new LazyRoute({
id,
...opts
});
};
}
/**
* Creates a lazily-configurable file-based route stub by file path.
*
* Use this for code-splitting with file-based routes (eg. `.lazy.tsx` files).
* The returned function accepts only non-critical route options like
* `component`, `pendingComponent`, `errorComponent`, and `notFoundComponent`.
*
* @param id File path literal for the route file.
* @returns A function that accepts lazy route options and returns a `LazyRoute`.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyFileRouteFunction
*/
function createLazyFileRoute(id) {
if (typeof id === "object") return new LazyRoute(id);
return (opts) => new LazyRoute({
id,
...opts
});
}
//#endregion
exports.FileRoute = FileRoute;
exports.FileRouteLoader = FileRouteLoader;
exports.LazyRoute = LazyRoute;
exports.createFileRoute = createFileRoute;
exports.createLazyFileRoute = createLazyFileRoute;
exports.createLazyRoute = createLazyRoute;
//# sourceMappingURL=fileRoute.cjs.map
@@ -0,0 +1,8 @@
/**
* Add the ability for test suites to manually set support flags
* to better test more environments.
*/
const supportsFlags = {};
export { supportsFlags };
//# sourceMappingURL=flags.mjs.map
@@ -0,0 +1,249 @@
/**
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
* Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
* {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
* @module
*/
import { HashMD } from './_md.ts';
import { type CHash, type TRet } from './utils.ts';
/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
declare abstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {
protected abstract A: number;
protected abstract B: number;
protected abstract C: number;
protected abstract D: number;
protected abstract E: number;
protected abstract F: number;
protected abstract G: number;
protected abstract H: number;
constructor(outputLen: number);
protected get(): [number, number, number, number, number, number, number, number];
protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void;
protected process(view: DataView, offset: number): void;
protected roundClean(): void;
destroy(): void;
}
/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
export declare class _SHA256 extends SHA2_32B<_SHA256> {
protected A: number;
protected B: number;
protected C: number;
protected D: number;
protected E: number;
protected F: number;
protected G: number;
protected H: number;
constructor();
}
/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */
export declare class _SHA224 extends SHA2_32B<_SHA224> {
protected A: number;
protected B: number;
protected C: number;
protected D: number;
protected E: number;
protected F: number;
protected G: number;
protected H: number;
constructor();
}
/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */
declare abstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {
protected abstract Ah: number;
protected abstract Al: number;
protected abstract Bh: number;
protected abstract Bl: number;
protected abstract Ch: number;
protected abstract Cl: number;
protected abstract Dh: number;
protected abstract Dl: number;
protected abstract Eh: number;
protected abstract El: number;
protected abstract Fh: number;
protected abstract Fl: number;
protected abstract Gh: number;
protected abstract Gl: number;
protected abstract Hh: number;
protected abstract Hl: number;
constructor(outputLen: number);
protected get(): [
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number
];
protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void;
protected process(view: DataView, offset: number): void;
protected roundClean(): void;
destroy(): void;
}
/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */
export declare class _SHA512 extends SHA2_64B<_SHA512> {
protected Ah: number;
protected Al: number;
protected Bh: number;
protected Bl: number;
protected Ch: number;
protected Cl: number;
protected Dh: number;
protected Dl: number;
protected Eh: number;
protected El: number;
protected Fh: number;
protected Fl: number;
protected Gh: number;
protected Gl: number;
protected Hh: number;
protected Hl: number;
constructor();
}
/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */
export declare class _SHA384 extends SHA2_64B<_SHA384> {
protected Ah: number;
protected Al: number;
protected Bh: number;
protected Bl: number;
protected Ch: number;
protected Cl: number;
protected Dh: number;
protected Dl: number;
protected Eh: number;
protected El: number;
protected Fh: number;
protected Fl: number;
protected Gh: number;
protected Gl: number;
protected Hh: number;
protected Hl: number;
constructor();
}
/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared
* RFC 6234 §6.4 compression engine. */
export declare class _SHA512_224 extends SHA2_64B<_SHA512_224> {
protected Ah: number;
protected Al: number;
protected Bh: number;
protected Bl: number;
protected Ch: number;
protected Cl: number;
protected Dh: number;
protected Dl: number;
protected Eh: number;
protected El: number;
protected Fh: number;
protected Fl: number;
protected Gh: number;
protected Gl: number;
protected Hh: number;
protected Hl: number;
constructor();
}
/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared
* RFC 6234 §6.4 compression engine. */
export declare class _SHA512_256 extends SHA2_64B<_SHA512_256> {
protected Ah: number;
protected Al: number;
protected Bh: number;
protected Bl: number;
protected Ch: number;
protected Cl: number;
protected Dh: number;
protected Dl: number;
protected Eh: number;
protected El: number;
protected Fh: number;
protected Fl: number;
protected Gh: number;
protected Gl: number;
protected Hh: number;
protected Hl: number;
constructor();
}
/**
* SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
*
* - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
* - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
* - Each sha256 hash is executing 2^18 bit operations.
* - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-256.
* ```ts
* sha256(new Uint8Array([97, 98, 99]));
* ```
*/
export declare const sha256: TRet<CHash<_SHA256>>;
/**
* SHA2-224 hash function from RFC 4634.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-224.
* ```ts
* sha224(new Uint8Array([97, 98, 99]));
* ```
*/
export declare const sha224: TRet<CHash<_SHA224>>;
/**
* SHA2-512 hash function from RFC 4634.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-512.
* ```ts
* sha512(new Uint8Array([97, 98, 99]));
* ```
*/
export declare const sha512: TRet<CHash<_SHA512>>;
/**
* SHA2-384 hash function from RFC 4634.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-384.
* ```ts
* sha384(new Uint8Array([97, 98, 99]));
* ```
*/
export declare const sha384: TRet<CHash<_SHA384>>;
/**
* SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
* See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-512/256.
* ```ts
* sha512_256(new Uint8Array([97, 98, 99]));
* ```
*/
export declare const sha512_256: TRet<CHash<_SHA512_256>>;
/**
* SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
* See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-512/224.
* ```ts
* sha512_224(new Uint8Array([97, 98, 99]));
* ```
*/
export declare const sha512_224: TRet<CHash<_SHA512_224>>;
export {};
//# sourceMappingURL=sha2.d.ts.map
@@ -0,0 +1,822 @@
'use strict';
var test = require('tape');
var inspect = require('object-inspect');
var SaferBuffer = require('safer-buffer').Buffer;
var forEach = require('for-each');
var v = require('es-value-fixtures');
var utils = require('../lib/utils');
test('merge()', function (t) {
t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null');
t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array');
t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key');
var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } });
t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array');
var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } });
t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array');
var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' });
t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array');
var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] });
t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] });
var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar');
t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true });
var func = function f() {};
func();
t.deepEqual(
utils.merge(func, { foo: 'bar' }),
[func, { foo: 'bar' }],
'functions can not be merged into'
);
func.bar = 'baz';
t.deepEqual(
utils.merge({ foo: 'bar' }, func),
{ foo: 'bar', bar: 'baz' },
'functions can be merge sources'
);
t.test(
'avoids invoking array setters unnecessarily',
{ skip: typeof Object.defineProperty !== 'function' },
function (st) {
var setCount = 0;
var getCount = 0;
var observed = [];
Object.defineProperty(observed, 0, {
get: function () {
getCount += 1;
return { bar: 'baz' };
},
set: function () { setCount += 1; }
});
utils.merge(observed, [null]);
st.equal(setCount, 0);
st.equal(getCount, 1);
observed[0] = observed[0]; // eslint-disable-line no-self-assign
st.equal(setCount, 1);
st.equal(getCount, 2);
st.end();
}
);
t.test('with overflow objects (from arrayLimit)', function (st) {
// arrayLimit is max index, so with limit 0, max index 0 is allowed (1 element)
// To create overflow, need 2+ elements with limit 0, or 3+ with limit 1, etc.
st.test('merges primitive into overflow object at next index', function (s2t) {
// Create an overflow object via combine: 3 elements (indices 0-2) with limit 0
var overflow = utils.combine(['a', 'b'], 'c', 0, false);
s2t.ok(utils.isOverflow(overflow), 'overflow object is marked');
var merged = utils.merge(overflow, 'd');
s2t.deepEqual(merged, { 0: 'a', 1: 'b', 2: 'c', 3: 'd' }, 'adds primitive at next numeric index');
s2t.end();
});
st.test('merges primitive into regular object with numeric keys normally', function (s2t) {
var obj = { 0: 'a', 1: 'b' };
s2t.notOk(utils.isOverflow(obj), 'plain object is not marked as overflow');
var merged = utils.merge(obj, 'c');
s2t.deepEqual(merged, { 0: 'a', 1: 'b', c: true }, 'adds primitive as key (not at next index)');
s2t.end();
});
st.test('merges primitive into object with non-numeric keys normally', function (s2t) {
var obj = { foo: 'bar' };
var merged = utils.merge(obj, 'baz');
s2t.deepEqual(merged, { foo: 'bar', baz: true }, 'adds primitive as key with value true');
s2t.end();
});
st.test('with strictMerge, wraps object and primitive in array', function (s2t) {
var obj = { foo: 'bar' };
var merged = utils.merge(obj, 'baz', { strictMerge: true });
s2t.deepEqual(merged, [{ foo: 'bar' }, 'baz'], 'wraps in array with strictMerge');
s2t.end();
});
st.test('with strictMerge, repeated conflicts append instead of nesting a new wrapper', function (s2t) {
var opts = { strictMerge: true };
var wrapped = utils.merge({ foo: 'bar' }, 'baz', opts);
s2t.deepEqual(wrapped, [{ foo: 'bar' }, 'baz'], 'first conflict wraps in an array');
var withObject = utils.merge(wrapped, { qux: 'quux' }, opts);
s2t.deepEqual(
withObject,
{ 0: { foo: 'bar' }, 1: 'baz', qux: 'quux' },
'merging an object converts the wrapper to an object'
);
var second = utils.merge(withObject, 'corge', opts);
s2t.deepEqual(
second,
{ 0: { foo: 'bar' }, 1: 'baz', 2: 'corge', qux: 'quux' },
'a second conflict appends at the next index'
);
var third = utils.merge(second, 'grault', opts);
s2t.deepEqual(
third,
{ 0: { foo: 'bar' }, 1: 'baz', 2: 'corge', 3: 'grault', qux: 'quux' },
'a third conflict appends again, so nesting depth stays constant'
);
s2t.end();
});
st.test('with strictMerge, a caller-supplied array is still wrapped, not appended to', function (s2t) {
var merged = utils.merge({ 0: 'a', 1: 'b' }, 'c', { strictMerge: true });
s2t.deepEqual(merged, [{ 0: 'a', 1: 'b' }, 'c'], 'an unmarked object with numeric keys is wrapped');
s2t.end();
});
st.test('with strictMerge, throws instead of appending a conflict past arrayLimit with throwOnLimitExceeded', function (s2t) {
var appendConflict = function (options) {
var wrapped = utils.merge({ foo: 'bar' }, 'baz', { strictMerge: true });
var container = utils.merge(wrapped, { qux: 'quux' }, { strictMerge: true });
return utils.merge(container, 'corge', options);
};
s2t['throws'](
function () { appendConflict({ strictMerge: true, arrayLimit: 1, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
'appending to a two-element container past arrayLimit throws'
);
s2t['throws'](
function () { appendConflict({ strictMerge: true, arrayLimit: 2, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 2 elements allowed in an array.'),
'uses the plural message when arrayLimit is not 1'
);
s2t.deepEqual(
appendConflict({ strictMerge: true, arrayLimit: 3, throwOnLimitExceeded: true }),
{ 0: { foo: 'bar' }, 1: 'baz', 2: 'corge', qux: 'quux' },
'appends while the container stays within arrayLimit'
);
s2t.deepEqual(
appendConflict({ strictMerge: true, arrayLimit: 1 }),
{ 0: { foo: 'bar' }, 1: 'baz', 2: 'corge', qux: 'quux' },
'still appends past arrayLimit without throwOnLimitExceeded, since the container is already an object'
);
s2t.end();
});
st.test('with strictMerge, a conflict appends after numeric keys already in its container', function (s2t) {
var opts = { strictMerge: true };
var container = utils.merge(utils.merge({ foo: 'bar' }, 'baz', opts), { qux: 'quux' }, opts);
var withIndex = utils.merge(container, { 2: 'keep' }, opts);
s2t.deepEqual(
utils.merge(withIndex, 'corge', opts),
{ 0: { foo: 'bar' }, 1: 'baz', 2: 'keep', 3: 'corge', qux: 'quux' },
'a numeric key merged into the container is not overwritten'
);
var sparse = [];
sparse[2] = 'keep';
var extended = utils.merge(utils.merge({ foo: 'bar' }, 'baz', opts), sparse, opts);
s2t.deepEqual(extended, [{ foo: 'bar' }, 'baz', 'keep'], 'an indexed value extends the container while it is an array');
var converted = utils.merge(extended, { qux: 'quux' }, opts);
s2t.deepEqual(
utils.merge(converted, 'corge', opts),
{ 0: { foo: 'bar' }, 1: 'baz', 2: 'keep', 3: 'corge', qux: 'quux' },
'converting the container to an object keeps its last index'
);
s2t.end();
});
st.test('enforces arrayLimit on the two-element array built for colliding values', function (s2t) {
s2t['throws'](
function () { utils.merge({ foo: 'bar' }, 'baz', { strictMerge: true, arrayLimit: 1, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
'a strictMerge conflict throws at arrayLimit 1'
);
s2t['throws'](
function () { utils.merge('a', 'b', { arrayLimit: 0, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 0 elements allowed in an array.'),
'two colliding primitives throw at arrayLimit 0'
);
var conflict = utils.merge({ foo: 'bar' }, 'baz', { strictMerge: true, arrayLimit: 1 });
s2t.ok(utils.isOverflow(conflict), 'without throwOnLimitExceeded, a strictMerge conflict converts to an overflow object');
s2t.deepEqual(conflict, { 0: { foo: 'bar' }, 1: 'baz' }, 'holding both values');
var pair = utils.merge('a', 'b', { arrayLimit: 1 });
s2t.ok(utils.isOverflow(pair), 'without throwOnLimitExceeded, two colliding primitives convert to an overflow object');
s2t.deepEqual(pair, { 0: 'a', 1: 'b' }, 'holding both values');
s2t.deepEqual(
utils.merge({ foo: 'bar' }, 'baz', { strictMerge: true, arrayLimit: 2, throwOnLimitExceeded: true }),
[{ foo: 'bar' }, 'baz'],
'a strictMerge conflict within arrayLimit is still an array'
);
s2t.deepEqual(
utils.merge('a', 'b', { arrayLimit: 2, throwOnLimitExceeded: true }),
['a', 'b'],
'two colliding primitives within arrayLimit are still an array'
);
s2t.end();
});
st.test('seeds an overflow container index from the keys it already holds', function (s2t) {
var overflow = utils.combine(['a'], 'b', 0, false);
s2t.ok(utils.isOverflow(overflow), 'the source is an overflow object');
var merged = utils.merge({ 2: 'keep', z: 'zz' }, overflow);
s2t.ok(utils.isOverflow(merged), 'the result is marked as overflow');
s2t.deepEqual(
utils.merge(merged, 'c'),
{ 0: 'a', 1: 'b', 2: 'keep', 3: 'c', z: 'zz' },
'the next value lands after the highest numeric key the container already held'
);
s2t.end();
});
st.test('merges overflow object into primitive', function (s2t) {
// Create an overflow object via combine: 2 elements (indices 0-1) with limit 0
var overflow = utils.combine(['a'], 'b', 0, false);
s2t.ok(utils.isOverflow(overflow), 'overflow object is marked');
var merged = utils.merge('c', overflow);
s2t.ok(utils.isOverflow(merged), 'result is also marked as overflow');
s2t.deepEqual(merged, { 0: 'c', 1: 'a', 2: 'b' }, 'creates object with primitive at 0, source values shifted');
s2t.end();
});
st.test('merges overflow object into primitive with plainObjects', function (s2t) {
var overflow = utils.combine(['a'], 'b', 0, false);
s2t.ok(utils.isOverflow(overflow), 'overflow object is marked');
var merged = utils.merge('c', overflow, { plainObjects: true });
s2t.ok(utils.isOverflow(merged), 'result is also marked as overflow');
s2t.deepEqual(merged, { __proto__: null, 0: 'c', 1: 'a', 2: 'b' }, 'creates null-proto object with primitive at 0');
s2t.end();
});
st.test('merges overflow object with multiple values into primitive', function (s2t) {
// Create an overflow object via combine: 3 elements (indices 0-2) with limit 0
var overflow = utils.combine(['b', 'c'], 'd', 0, false);
s2t.ok(utils.isOverflow(overflow), 'overflow object is marked');
var merged = utils.merge('a', overflow);
s2t.deepEqual(merged, { 0: 'a', 1: 'b', 2: 'c', 3: 'd' }, 'shifts all source indices by 1');
s2t.end();
});
st.test('merges regular object into primitive as array', function (s2t) {
var obj = { foo: 'bar' };
var merged = utils.merge('a', obj);
s2t.deepEqual(merged, ['a', { foo: 'bar' }], 'creates array with primitive and object');
s2t.end();
});
st.test('merges primitive into array that exceeds arrayLimit', function (s2t) {
var arr = ['a', 'b', 'c'];
var merged = utils.merge(arr, 'd', { arrayLimit: 1 });
s2t.ok(utils.isOverflow(merged), 'result is marked as overflow');
s2t.deepEqual(merged, { 0: 'a', 1: 'b', 2: 'c', 3: 'd' }, 'converts to overflow object with primitive appended');
s2t.end();
});
st.test('merges array into primitive that exceeds arrayLimit', function (s2t) {
var merged = utils.merge('a', ['b', 'c'], { arrayLimit: 1 });
s2t.ok(utils.isOverflow(merged), 'result is marked as overflow');
s2t.deepEqual(merged, { 0: 'a', 1: 'b', 2: 'c' }, 'converts to overflow object');
s2t.end();
});
st.test('merges primitive into array at the arrayLimit boundary, consistently with combine', function (s2t) {
var merged = utils.merge(['a'], 'b', { arrayLimit: 1 });
s2t.ok(utils.isOverflow(merged), 'result is marked as overflow at the boundary');
s2t.deepEqual(merged, { 0: 'a', 1: 'b' }, 'converts to overflow object instead of a length-2 array');
s2t.end();
});
st.test('merges two arrays that exceed arrayLimit into an overflow object', function (s2t) {
var merged = utils.merge(['a'], ['b'], { arrayLimit: 1 });
s2t.ok(utils.isOverflow(merged), 'result is marked as overflow');
s2t.deepEqual(merged, { 0: 'a', 1: 'b' }, 'array-into-array merge enforces arrayLimit like combine');
s2t.end();
});
st.test('throws at the arrayLimit boundary when merging a primitive into an array with throwOnLimitExceeded', function (s2t) {
s2t['throws'](
function () { utils.merge(['a'], 'b', { arrayLimit: 1, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
'throws when the resulting length would exceed arrayLimit'
);
s2t.end();
});
st.test('throws when merging two arrays past arrayLimit with throwOnLimitExceeded', function (s2t) {
s2t['throws'](
function () { utils.merge(['a'], ['b'], { arrayLimit: 1, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
'array-into-array merge throws rather than silently exceeding arrayLimit'
);
s2t['throws'](
function () { utils.merge(['a', 'b', 'c'], ['d', 'e', 'f'], { arrayLimit: 2, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 2 elements allowed in an array.'),
'uses the plural message when arrayLimit is not 1'
);
s2t.end();
});
st.test('throws instead of merging primitive into over-limit array when throwOnLimitExceeded is set', function (s2t) {
s2t['throws'](
function () { utils.merge(['a', 'b', 'c'], 'd', { arrayLimit: 1, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
'throws rather than converting to an overflow object'
);
s2t['throws'](
function () { utils.merge(['a', 'b', 'c'], 'd', { arrayLimit: 2, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 2 elements allowed in an array.'),
'uses the plural message when arrayLimit is not 1'
);
s2t.end();
});
st.test('throws instead of merging array into primitive when throwOnLimitExceeded is set', function (s2t) {
s2t['throws'](
function () { utils.merge('a', ['b', 'c'], { arrayLimit: 1, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
'throws rather than converting to an overflow object'
);
s2t['throws'](
function () { utils.merge('a', ['b', 'c', 'd'], { arrayLimit: 2, throwOnLimitExceeded: true }); },
new RangeError('Array limit exceeded. Only 2 elements allowed in an array.'),
'uses the plural message when arrayLimit is not 1'
);
s2t.end();
});
st.end();
});
t.end();
});
test('assign()', function (t) {
var target = { a: 1, b: 2 };
var source = { b: 3, c: 4 };
var result = utils.assign(target, source);
t.equal(result, target, 'returns the target');
t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged');
t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched');
t.end();
});
test('combine()', function (t) {
t.test('both arrays', function (st) {
var a = [1];
var b = [2];
var combined = utils.combine(a, b);
st.deepEqual(a, [1], 'a is not mutated');
st.deepEqual(b, [2], 'b is not mutated');
st.notEqual(a, combined, 'a !== combined');
st.notEqual(b, combined, 'b !== combined');
st.deepEqual(combined, [1, 2], 'combined is a + b');
st.end();
});
t.test('one array, one non-array', function (st) {
var aN = 1;
var a = [aN];
var bN = 2;
var b = [bN];
var combinedAnB = utils.combine(aN, b);
st.deepEqual(b, [bN], 'b is not mutated');
st.notEqual(aN, combinedAnB, 'aN + b !== aN');
st.notEqual(a, combinedAnB, 'aN + b !== a');
st.notEqual(bN, combinedAnB, 'aN + b !== bN');
st.notEqual(b, combinedAnB, 'aN + b !== b');
st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array');
var combinedABn = utils.combine(a, bN);
st.deepEqual(a, [aN], 'a is not mutated');
st.notEqual(aN, combinedABn, 'a + bN !== aN');
st.notEqual(a, combinedABn, 'a + bN !== a');
st.notEqual(bN, combinedABn, 'a + bN !== bN');
st.notEqual(b, combinedABn, 'a + bN !== b');
st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array');
st.end();
});
t.test('neither is an array', function (st) {
var combined = utils.combine(1, 2);
st.notEqual(1, combined, '1 + 2 !== 1');
st.notEqual(2, combined, '1 + 2 !== 2');
st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array');
st.end();
});
t.test('with arrayLimit', function (st) {
st.test('under the limit', function (s2t) {
var combined = utils.combine(['a', 'b'], 'c', 10, false);
s2t.deepEqual(combined, ['a', 'b', 'c'], 'returns array when under limit');
s2t.ok(Array.isArray(combined), 'result is an array');
s2t.end();
});
st.test('exactly at the limit stays as array', function (s2t) {
var combined = utils.combine(['a', 'b'], 'c', 3, false);
s2t.deepEqual(combined, ['a', 'b', 'c'], 'stays as array when count equals limit');
s2t.ok(Array.isArray(combined), 'result is an array');
s2t.end();
});
st.test('over the limit', function (s2t) {
var combined = utils.combine(['a', 'b', 'c'], 'd', 3, false);
s2t.deepEqual(combined, { 0: 'a', 1: 'b', 2: 'c', 3: 'd' }, 'converts to object when over limit');
s2t.notOk(Array.isArray(combined), 'result is not an array');
s2t.end();
});
st.test('with arrayLimit 1', function (s2t) {
var combined = utils.combine([], 'a', 1, false);
s2t.deepEqual(combined, ['a'], 'stays as array when count equals limit');
s2t.ok(Array.isArray(combined), 'result is an array');
s2t.end();
});
st.test('with arrayLimit 0 converts single element to object', function (s2t) {
var combined = utils.combine([], 'a', 0, false);
s2t.deepEqual(combined, { 0: 'a' }, 'converts to object when count exceeds limit');
s2t.notOk(Array.isArray(combined), 'result is not an array');
s2t.end();
});
st.test('with arrayLimit 0 and two elements converts to object', function (s2t) {
var combined = utils.combine(['a'], 'b', 0, false);
s2t.deepEqual(combined, { 0: 'a', 1: 'b' }, 'converts to object when count exceeds limit');
s2t.notOk(Array.isArray(combined), 'result is not an array');
s2t.end();
});
st.test('with plainObjects option', function (s2t) {
var combined = utils.combine(['a', 'b'], 'c', 1, true);
var expected = { __proto__: null, 0: 'a', 1: 'b', 2: 'c' };
s2t.deepEqual(combined, expected, 'converts to object with null prototype');
s2t.equal(Object.getPrototypeOf(combined), null, 'result has null prototype when plainObjects is true');
s2t.end();
});
st.end();
});
t.test('with throwOnLimitExceeded', function (st) {
st.test('throws when concatenation exceeds the limit', function (s2t) {
s2t['throws'](
function () { utils.combine(['a', 'b', 'c'], 'd', 3, false, true); },
new RangeError('Array limit exceeded. Only 3 elements allowed in an array.'),
'throws instead of converting to an overflow object'
);
s2t['throws'](
function () { utils.combine([], 'a', 0, false, true); },
new RangeError('Array limit exceeded. Only 0 elements allowed in an array.'),
'throws with the correct count at arrayLimit 0'
);
s2t.end();
});
st.test('throws when adding to an existing overflow object', function (s2t) {
var overflow = utils.combine(['a', 'b'], 'c', 0, false);
s2t.ok(utils.isOverflow(overflow), 'initial object is marked as overflow');
s2t['throws'](
function () { utils.combine(overflow, 'd', 0, false, true); },
new RangeError('Array limit exceeded. Only 0 elements allowed in an array.'),
'throws rather than appending to the overflow object'
);
s2t['throws'](
function () { utils.combine(overflow, 'd', 1, false, true); },
new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
'uses the singular message at arrayLimit 1'
);
s2t.end();
});
st.test('does not throw when within the limit', function (s2t) {
var combined = utils.combine(['a'], 'b', 5, false, true);
s2t.deepEqual(combined, ['a', 'b'], 'returns the array unchanged when under the limit');
s2t.end();
});
st.end();
});
t.test('with existing overflow object', function (st) {
st.test('adds to existing overflow object at next index', function (s2t) {
// Create overflow object first via combine: 3 elements (indices 0-2) with limit 0
var overflow = utils.combine(['a', 'b'], 'c', 0, false);
s2t.ok(utils.isOverflow(overflow), 'initial object is marked as overflow');
var combined = utils.combine(overflow, 'd', 10, false);
s2t.equal(combined, overflow, 'returns the same object (mutated)');
s2t.deepEqual(combined, { 0: 'a', 1: 'b', 2: 'c', 3: 'd' }, 'adds value at next numeric index');
s2t.end();
});
st.test('does not treat plain object with numeric keys as overflow', function (s2t) {
var plainObj = { 0: 'a', 1: 'b' };
s2t.notOk(utils.isOverflow(plainObj), 'plain object is not marked as overflow');
// combine treats this as a regular value, not an overflow object to append to
var combined = utils.combine(plainObj, 'c', 10, false);
s2t.deepEqual(combined, [{ 0: 'a', 1: 'b' }, 'c'], 'concatenates as regular values');
s2t.end();
});
st.end();
});
t.end();
});
test('decode', function (t) {
t.equal(
utils.decode('a+b'),
'a b',
'decodes + to space'
);
t.equal(
utils.decode('name%2Eobj'),
'name.obj',
'decodes a string'
);
t.equal(
utils.decode('name%2Eobj%2Efoo', null, 'iso-8859-1'),
'name.obj.foo',
'decodes a string in iso-8859-1'
);
t.test('strings with no percent sign', function (st) {
st.equal(utils.decode(''), '', 'empty string');
st.equal(utils.decode('abc'), 'abc', 'returns a plain string unchanged');
st.equal(utils.decode('abc', null, 'iso-8859-1'), 'abc', 'returns a plain string unchanged in iso-8859-1');
st.equal(utils.decode('a++b+'), 'a b ', 'decodes every + to a space');
st.equal(utils.decode('a++b+', null, 'iso-8859-1'), 'a b ', 'decodes every + to a space in iso-8859-1');
st.equal(utils.decode('\uD800x\uDC00'), '\uD800x\uDC00', 'leaves lone surrogates unchanged');
st.equal(utils.decode('😀+'), '😀 ', 'leaves surrogate pairs unchanged');
st.equal(utils.decode('a=b&c'), 'a=b&c', 'leaves delimiters unchanged');
st.end();
});
t.test('strings with a percent sign', function (st) {
st.equal(utils.decode('a+%20b'), 'a b', 'decodes both + and an escape');
st.equal(utils.decode('%E9+x', null, 'iso-8859-1'), 'é x', 'decodes both + and an escape in iso-8859-1');
st.equal(utils.decode('a+%'), 'a %', 'decodes + even when the escape is malformed');
st.equal(utils.decode('a+%E0%A4%A'), 'a %E0%A4%A', 'decodes + even when the escape is truncated');
st.end();
});
t.test('non-strings', function (st) {
forEach(v.nullPrimitives, function (nullish) {
st['throws'](
function () { utils.decode(nullish); },
TypeError,
inspect(nullish) + ' is not a string'
);
});
st['throws'](
function () { utils.decode(['a']); },
TypeError,
'an array is not a string'
);
/* eslint no-new-wrappers: 0 */
st.equal(utils.decode(new String('ab')), 'ab', 'a boxed string decodes to a primitive');
st.equal(utils.decode(new String('a+b')), 'a b', 'a boxed string with + decodes to a primitive');
st.equal(utils.decode(new String('a%20b')), 'a b', 'a boxed string with an escape decodes to a primitive');
st.end();
});
t.end();
});
test('encode', function (t) {
forEach(v.nullPrimitives, function (nullish) {
t['throws'](
function () { utils.encode(nullish); },
TypeError,
inspect(nullish) + ' is not a string'
);
});
t.equal(utils.encode(''), '', 'empty string returns itself');
t.deepEqual(utils.encode([]), [], 'empty array returns itself');
t.deepEqual(utils.encode({ length: 0 }), { length: 0 }, 'empty arraylike returns itself');
t.test('symbols', { skip: !v.hasSymbols }, function (st) {
st.equal(utils.encode(Symbol('x')), 'Symbol%28x%29', 'symbol is encoded');
st.end();
});
t.equal(
utils.encode('(abc)'),
'%28abc%29',
'encodes parentheses'
);
t.equal(
utils.encode({ toString: function () { return '(abc)'; } }),
'%28abc%29',
'toStrings and encodes parentheses'
);
t.equal(
utils.encode('abc 123 💩', null, 'iso-8859-1'),
'abc%20123%20%26%2355357%3B%26%2356489%3B',
'encodes in iso-8859-1'
);
var longString = '';
var expectedString = '';
for (var i = 0; i < 1500; i++) {
longString += ' ';
expectedString += '%20';
}
t.equal(
utils.encode(longString),
expectedString,
'encodes a long string'
);
var boundary = '';
var expected = '';
for (var j = 0; j < 1023; j++) {
boundary += 'a';
expected += 'a';
}
boundary += '😀';
expected += '%F0%9F%98%80';
t.equal(
utils.encode(boundary),
expected,
'encodes a surrogate pair split across long-string chunks'
);
var laterBoundary = '';
var laterExpected = '';
for (var k = 0; k < 2047; k++) {
laterBoundary += 'a';
laterExpected += 'a';
}
laterBoundary += '😀';
laterExpected += '%F0%9F%98%80';
t.equal(
utils.encode(laterBoundary),
laterExpected,
'encodes a surrogate pair split across a later chunk boundary'
);
var twoPairs = '';
for (k = 0; k < 1023; k++) {
twoPairs += 'a';
}
twoPairs += '😀';
for (k = 0; k < 1022; k++) {
twoPairs += 'b';
}
twoPairs += '😀';
t.equal(
(utils.encode(twoPairs).match(/%F0%9F%98%80/g) || []).length,
2,
'encodes two surrogate pairs each split across a chunk boundary'
);
var roundTrip = '';
for (k = 0; k < 1023; k++) {
roundTrip += 'a';
}
roundTrip += '😀';
t.equal(
decodeURIComponent(utils.encode(roundTrip)),
roundTrip,
'a boundary-split surrogate pair round-trips through decodeURIComponent'
);
var loneBoundary = '';
var loneExpected = '';
for (k = 0; k < 1023; k++) {
loneBoundary += 'a';
loneExpected += 'a';
}
loneBoundary += '\uD83DX';
loneExpected += '%F0%9F%91%98';
t.equal(
utils.encode(loneBoundary),
loneExpected,
'a lone high surrogate at a chunk boundary encodes the same as mid-chunk'
);
t.equal(
utils.encode('\x28\x29'),
'%28%29',
'encodes parens normally'
);
t.equal(
utils.encode('\x28\x29', null, null, null, 'RFC1738'),
'()',
'does not encode parens in RFC1738'
);
// todo RFC1738 format
t.equal(
utils.encode('Āက豈'),
'%C4%80%E1%80%80%EF%A4%80',
'encodes multibyte chars'
);
t.equal(
utils.encode('\uD83D \uDCA9'),
'%F0%9F%90%A0%F0%BA%90%80',
'encodes lone surrogates'
);
t.end();
});
test('isBuffer()', function (t) {
var fn = function () {};
fn();
forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], fn, /a/g], function (x) {
t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer');
});
var fakeBuffer = { constructor: Buffer };
t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer');
forEach(['x', 1, true, {}, [], { isBuffer: true }], function (notCallable) {
var obj = { constructor: { isBuffer: notCallable } };
t.doesNotThrow(function () { utils.isBuffer(obj); }, 'non-callable `constructor.isBuffer` (' + inspect(notCallable) + ') does not throw');
t.equal(utils.isBuffer(obj), false, 'non-callable `constructor.isBuffer` (' + inspect(notCallable) + ') is not a buffer');
});
var nullObject = { __proto__: null, constructor: { __proto__: null, isBuffer: 'y' } };
t.equal(utils.isBuffer(nullObject), false, 'null object with non-callable `constructor.isBuffer` is not a buffer');
var duckBuffer = { constructor: { isBuffer: function () { return true; } } };
t.equal(utils.isBuffer(duckBuffer), true, 'callable `constructor.isBuffer` is still honored');
var saferBuffer = SaferBuffer.from('abc');
t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer');
var buffer = SaferBuffer.from('abc');
t.notEqual(saferBuffer, buffer, 'different buffer instances');
t.equal(utils.isBuffer(buffer), true, 'another Buffer instance is a buffer');
t.end();
});
test('isRegExp()', function (t) {
t.equal(utils.isRegExp(/a/g), true, 'RegExp is a RegExp');
t.equal(utils.isRegExp(new RegExp('a', 'g')), true, 'new RegExp is a RegExp');
t.equal(utils.isRegExp(new Date()), false, 'Date is not a RegExp');
forEach(v.primitives, function (primitive) {
t.equal(utils.isRegExp(primitive), false, inspect(primitive) + ' is not a RegExp');
});
t.end();
});
@@ -0,0 +1,42 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
class AsyncSeriesBailHookCodeFactory extends HookCodeFactory {
content({ onError, onResult, resultReturns, onDone }) {
return this.callTapsSeries({
onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true),
onResult: (i, result, next) =>
`if(${result} !== undefined) {\n${onResult(
result
)}\n} else {\n${next()}}\n`,
resultReturns,
onDone
});
}
}
const factory = new AsyncSeriesBailHookCodeFactory();
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
function AsyncSeriesBailHook(args = [], name = undefined) {
const hook = new Hook(args, name);
hook.constructor = AsyncSeriesBailHook;
hook.compile = COMPILE;
hook._call = undefined;
hook.call = undefined;
return hook;
}
AsyncSeriesBailHook.prototype = null;
module.exports = AsyncSeriesBailHook;
@@ -0,0 +1,15 @@
//#region src/router/reg-exp-router/node.d.ts
export declare const LABEL_REG_EXP_STR = "[^/]+";
export declare const ONLY_WILDCARD_REG_EXP_STR = ".*";
export declare const TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
export declare const PATH_ERROR: unique symbol;
export type ParamAssocArray = [string, number][];
export interface Context {
varIndex: number;
}
export declare class Node {
insert(tokens: readonly string[], index: number, paramMap: ParamAssocArray, context: Context, isStatic: boolean): void;
buildRegExpStr(): string;
}
//#endregion
@@ -0,0 +1,23 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Flashlight = createLucideIcon("Flashlight", [
[
"path",
{
d: "M18 6c0 2-2 2-2 4v10a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2V10c0-2-2-2-2-4V2h12z",
key: "1orkel"
}
],
["line", { x1: "6", x2: "18", y1: "6", y2: "6", key: "1z11jq" }],
["line", { x1: "12", x2: "12", y1: "12", y2: "12", key: "1f4yc1" }]
]);
export { Flashlight as default };
//# sourceMappingURL=flashlight.js.map
@@ -0,0 +1 @@
{"version":3,"file":"github.js","sources":["../../../src/icons/github.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Github\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTUgMjJ2LTRhNC44IDQuOCAwIDAgMC0xLTMuNWMzIDAgNi0yIDYtNS41LjA4LTEuMjUtLjI3LTIuNDgtMS0zLjUuMjgtMS4xNS4yOC0yLjM1IDAtMy41IDAgMC0xIDAtMyAxLjUtMi42NC0uNS01LjM2LS41LTggMEM2IDIgNSAyIDUgMmMtLjMgMS4xNS0uMyAyLjM1IDAgMy41QTUuNDAzIDUuNDAzIDAgMCAwIDQgOWMwIDMuNSAzIDUuNSA2IDUuNS0uMzkuNDktLjY4IDEuMDUtLjg1IDEuNjUtLjE3LjYtLjIyIDEuMjMtLjE1IDEuODV2NCIgLz4KICA8cGF0aCBkPSJNOSAxOGMtNC41MSAyLTUtMi03LTIiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/github\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n * @deprecated Brand icons have been deprecated and are due to be removed, please refer to https://github.com/lucide-icons/lucide/issues/670. We recommend using https://simpleicons.org/?q=github instead. This icon will be removed in v1.0\n */\nconst Github = createLucideIcon('Github', [\n [\n 'path',\n {\n d: 'M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4',\n key: 'tonef',\n },\n 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event.ts"],"sourcesContent":["import { addDomEvent } from \"motion-dom\"\nimport { addPointerInfo, EventListenerWithPointInfo } from \"./event-info\"\n\nexport function addPointerEvent(\n target: EventTarget,\n eventName: string,\n handler: EventListenerWithPointInfo,\n options?: AddEventListenerOptions\n) {\n return addDomEvent(target, eventName, addPointerInfo(handler), options)\n}\n"],"names":[],"mappings":";;;AAGM,SAAU,eAAe,CAC3B,MAAmB,EACnB,SAAiB,EACjB,OAAmC,EACnC,OAAiC,EAAA;AAEjC,IAAA,OAAO,WAAW,CAAC,MAAM,EAAE,SAAS,EAAE,cAAc,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;AAC3E;;;;"}
@@ -0,0 +1,14 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var mini = require('framer-motion/mini');
Object.keys(mini).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return mini[k]; }
});
});
@@ -0,0 +1,115 @@
# env-paths
> Get paths for storing things like data, config, cache, etc
Uses the correct OS-specific paths. Most developers get this wrong.
## Install
```
$ npm install env-paths
```
## Usage
```js
const envPaths = require('env-paths');
const paths = envPaths('MyApp');
paths.data;
//=> '/home/sindresorhus/.local/share/MyApp-nodejs'
paths.config
//=> '/home/sindresorhus/.config/MyApp-nodejs'
```
## API
### paths = envPaths(name, options?)
Note: It only generates the path strings. It doesn't create the directories for you. You could use [`make-dir`](https://github.com/sindresorhus/make-dir) to create the directories.
#### name
Type: `string`
Name of your project. Used to generate the paths.
#### options
Type: `object`
##### suffix
Type: `string`<br>
Default: `'nodejs'`
**Don't use this option unless you really have to!**<br>
Suffix appended to the project name to avoid name conflicts with native
apps. Pass an empty string to disable it.
### paths.data
Directory for data files.
Example locations (with the default `nodejs` [suffix](#suffix)):
- macOS: `~/Library/Application Support/MyApp-nodejs`
- Windows: `%LOCALAPPDATA%\MyApp-nodejs\Data` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Data`)
- Linux: `~/.local/share/MyApp-nodejs` (or `$XDG_DATA_HOME/MyApp-nodejs`)
### paths.config
Directory for config files.
Example locations (with the default `nodejs` [suffix](#suffix)):
- macOS: `~/Library/Preferences/MyApp-nodejs`
- Windows: `%APPDATA%\MyApp-nodejs\Config` (for example, `C:\Users\USERNAME\AppData\Roaming\MyApp-nodejs\Config`)
- Linux: `~/.config/MyApp-nodejs` (or `$XDG_CONFIG_HOME/MyApp-nodejs`)
### paths.cache
Directory for non-essential data files.
Example locations (with the default `nodejs` [suffix](#suffix)):
- macOS: `~/Library/Caches/MyApp-nodejs`
- Windows: `%LOCALAPPDATA%\MyApp-nodejs\Cache` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Cache`)
- Linux: `~/.cache/MyApp-nodejs` (or `$XDG_CACHE_HOME/MyApp-nodejs`)
### paths.log
Directory for log files.
Example locations (with the default `nodejs` [suffix](#suffix)):
- macOS: `~/Library/Logs/MyApp-nodejs`
- Windows: `%LOCALAPPDATA%\MyApp-nodejs\Log` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Log`)
- Linux: `~/.local/state/MyApp-nodejs` (or `$XDG_STATE_HOME/MyApp-nodejs`)
### paths.temp
Directory for temporary files.
Example locations (with the default `nodejs` [suffix](#suffix)):
- macOS: `/var/folders/jf/f2twvvvs5jl_m49tf034ffpw0000gn/T/MyApp-nodejs`
- Windows: `%LOCALAPPDATA%\Temp\MyApp-nodejs` (for example, `C:\Users\USERNAME\AppData\Local\Temp\MyApp-nodejs`)
- Linux: `/tmp/USERNAME/MyApp-nodejs`
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-env-paths?utm_source=npm-env-paths&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
@@ -0,0 +1,128 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "अक्षर", verb: "हुनुपर्छ" },
file: { unit: "बाइट", verb: "हुनुपर्छ" },
array: { unit: "तत्व", verb: "हुनुपर्छ" },
set: { unit: "तत्व", verb: "हुनुपर्छ" },
map: { unit: "प्रविष्टि", verb: "हुनुपर्छ" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "इनपुट",
email: "इमेल ठेगाना",
url: "URL",
emoji: "इमोजी",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO मिति र समय",
date: "ISO मिति",
time: "ISO समय",
duration: "ISO अवधि",
ipv4: "IPv4 ठेगाना",
ipv6: "IPv6 ठेगाना",
mac: "MAC ठेगाना",
cidrv4: "IPv4 दायरा",
cidrv6: "IPv6 दायरा",
base64: "base64-इन्कोड गरिएको स्ट्रिङ",
base64url: "base64url-इन्कोड गरिएको स्ट्रिङ",
json_string: "JSON स्ट्रिङ",
e164: "E.164 नम्बर",
credit_card: "क्रेडिट कार्ड नम्बर",
currency_code: "मुद्रा कोड",
iban: "IBAN",
jwt: "JWT",
template_literal: "इनपुट",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
return `अमान्य इनपुट: अपेक्षित ${expected}, प्राप्त ${received}`;
}
case "invalid_value":
if (issue.values.length === 1) return `अमान्य इनपुट: अपेक्षित ${util.stringifyPrimitive(issue.values[0])}`;
return `अमान्य विकल्प: अपेक्षित मानहरू मध्ये एक ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `धेरै ठूलो: ${issue.origin ?? "मान"} मा ${adj}${issue.maximum.toString()} ${sizing.unit} ${sizing.verb}`;
return `धेरै ठूलो: ${issue.origin ?? "मान"} ${adj}${issue.maximum.toString()} हुनुपर्छ`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing)
return `धेरै सानो: ${issue.origin} मा ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
return `धेरै सानो: ${issue.origin} ${adj}${issue.minimum.toString()} हुनुपर्छ`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") return `अमान्य स्ट्रिङ: "${_issue.prefix}" बाट सुरु हुनुपर्छ`;
if (_issue.format === "ends_with") return `अमान्य स्ट्रिङ: "${_issue.suffix}" मा समाप्त हुनुपर्छ`;
if (_issue.format === "includes") return `अमान्य स्ट्रिङ: "${_issue.includes}" समावेश हुनुपर्छ`;
if (_issue.format === "regex") return `अमान्य स्ट्रिङ: ढाँचा ${_issue.pattern} सँग मेल खानुपर्छ`;
return `अमान्य ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `अमान्य संख्या: ${issue.divisor} को गुणज हुनुपर्छ`;
case "unrecognized_keys":
return `अपरिचित कुञ्जी${issue.keys.length > 1 ? "हरू" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `अमान्य कुञ्जी: ${issue.origin} मा`;
case "invalid_union":
if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {
const opts = issue.options.map((o) => `'${o}'`).join(" | ");
return `अमान्य डिस्क्रिमिनेटर मान: अपेक्षित ${opts}`;
}
return "अमान्य इनपुट";
case "invalid_element":
return `अमान्य मान: ${issue.origin} मा`;
default:
return `अमान्य इनपुट`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}
@@ -0,0 +1,3 @@
"use strict";
const get = require("./set-Bwi5SIy8.js");
module.exports = get.get;
@@ -0,0 +1 @@
module.exports={A:{A:{"1":"_V","16":"FD","260":"_HB"},B:{"1":"_J"},C:{"1":"_6L","132":"_hO","2180":"_eJ"},D:{"1":"_ZD","16":"_Y"},E:{"1":"_YB","16":"_4"},F:{"1":"_a","132":"_T"},G:{"16":"ED","132":"_sC","516":"_t"},H:{"2":"1D"},I:{"1":"_X","16":"_BO 5D","1025":"ED"},J:{"1":"A","16":"D"},K:{"1":"H","16":"_cB","132":"aC"},L:{"1":"I"},M:{"1":"YC"},N:{"1":"B","16":"A"},O:{"1":"bC"},P:{"1":"_F"},Q:{"1":"JE"},R:{"1":"KE"},S:{"1":"ME","2180":"LE"}},B:5,C:"Selection API",D:true};
@@ -0,0 +1 @@
{"version":3,"names":["_file","require","_buildExternalHelpers","resolvers","_environment","_types","data","Object","defineProperty","exports","enumerable","get","_parser","_traverse","_template","_index2","_transform","_transformFile","_transformAst","_parse","version","resolvePlugin","name","dirname","filepath","resolvePreset","DEFAULT_EXTENSIONS","freeze","OptionManager","init","opts","loadOptionsSync","Plugin","alias","Error","types","traverse","tokTypes","template"],"sources":["../src/index.ts"],"sourcesContent":["if (!process.env.IS_PUBLISH && !USE_ESM && process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"BABEL_8_BREAKING is only supported in ESM. Please run `make use-esm`.\",\n );\n}\n\nexport const version = PACKAGE_JSON.version;\n\nexport { default as File } from \"./transformation/file/file.ts\";\nexport type { default as PluginPass } from \"./transformation/plugin-pass.ts\";\nexport { default as buildExternalHelpers } from \"./tools/build-external-helpers.ts\";\n\nimport * as resolvers from \"./config/files/index.ts\";\n// For backwards-compatibility, we expose the resolvers\n// with the old API.\nexport const resolvePlugin = (name: string, dirname: string) =>\n resolvers.resolvePlugin(name, dirname, false).filepath;\nexport const resolvePreset = (name: string, dirname: string) =>\n resolvers.resolvePreset(name, dirname, false).filepath;\n\nexport { getEnv } from \"./config/helpers/environment.ts\";\n\n// NOTE: Lazy re-exports aren't detected by the Node.js CJS-ESM interop.\n// These are handled by pluginInjectNodeReexportsHints in our babel.config.js\n// so that they can work well.\nexport * as types from \"@babel/types\";\nexport { tokTypes } from \"@babel/parser\";\nexport { default as traverse } from \"@babel/traverse\";\nexport { default as template } from \"@babel/template\";\n\n// rollup-plugin-dts assumes that all re-exported types are also valid values\n// Visitor is only a type, so we need to use this workaround to prevent\n// rollup-plugin-dts from breaking it.\n// TODO: Figure out how to fix this upstream.\nexport type { NodePath, Scope } from \"@babel/traverse\";\nexport type Visitor<S = unknown> = import(\"@babel/traverse\").Visitor<S>;\n\nexport {\n createConfigItem,\n createConfigItemAsync,\n createConfigItemSync,\n} from \"./config/index.ts\";\n\nexport {\n loadOptions,\n loadOptionsAsync,\n loadPartialConfig,\n loadPartialConfigAsync,\n loadPartialConfigSync,\n} from \"./config/index.ts\";\nimport { loadOptionsSync } from \"./config/index.ts\";\nimport type {\n ConfigApplicableTest,\n PluginItem,\n} from \"./config/validation/options.ts\";\nexport { loadOptionsSync };\nexport type { PluginItem };\n\nexport type PresetObject = {\n overrides?: PresetObject[];\n test?: ConfigApplicableTest;\n plugins?: PluginItem[];\n};\n\nexport type {\n CallerMetadata,\n ConfigAPI,\n ConfigItem,\n InputOptions,\n NormalizedOptions,\n PartialConfig,\n PluginAPI,\n PluginObject,\n PresetAPI,\n} from \"./config/index.ts\";\n\nexport {\n type FileResult,\n transform,\n transformAsync,\n transformSync,\n} from \"./transform.ts\";\nexport {\n transformFile,\n transformFileAsync,\n transformFileSync,\n} from \"./transform-file.ts\";\nexport {\n transformFromAst,\n transformFromAstAsync,\n transformFromAstSync,\n} from \"./transform-ast.ts\";\nexport { parse, parseAsync, parseSync } from \"./parse.ts\";\n\n/**\n * Recommended set of compilable extensions. Not used in @babel/core directly, but meant as\n * as an easy source for tooling making use of @babel/core.\n */\nexport const DEFAULT_EXTENSIONS = Object.freeze([\n \".js\",\n \".jsx\",\n \".es6\",\n \".es\",\n \".mjs\",\n \".cjs\",\n] as const);\n\nif (!process.env.BABEL_8_BREAKING && !USE_ESM) {\n // For easier backward-compatibility, provide an API like the one we exposed in Babel 6.\n // eslint-disable-next-line no-restricted-globals\n exports.OptionManager = class OptionManager {\n init(opts: any) {\n return loadOptionsSync(opts);\n }\n };\n\n // eslint-disable-next-line no-restricted-globals\n exports.Plugin = function Plugin(alias: string) {\n throw new Error(\n `The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`,\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,IAAAA,KAAA,GAAAC,OAAA;AAEA,IAAAC,qBAAA,GAAAD,OAAA;AAEA,IAAAE,SAAA,GAAAF,OAAA;AAQA,IAAAG,YAAA,GAAAH,OAAA;AAAyD,SAAAI,OAAA;EAAA,MAAAC,IAAA,GAAAL,OAAA;EAAAI,MAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAAAC,MAAA,CAAAC,cAAA,KAAAC,OAAA;EAAAC,UAAA;EAAAC,GAAA,WAAAA,CAAA;IAAA,OAAAN,MAAA;EAAA;AAAA;AAMzD,SAAAO,QAAA;EAAA,MAAAN,IAAA,GAAAL,OAAA;EAAAW,OAAA,YAAAA,CAAA;IAAA,OAAAN,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAO,UAAA;EAAA,MAAAP,IAAA,GAAAL,OAAA;EAAAY,SAAA,YAAAA,CAAA;IAAA,OAAAP,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAQ,UAAA;ELine truncated