docs: 仓库链接指向本镜像仓库
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run

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,362 @@
/**
* @fileoverview Rule to require or disallow yoda comparisons
* @author Nicholas C. Zakas
*/
"use strict";
//--------------------------------------------------------------------------
// Requirements
//--------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Determines whether an operator is a comparison operator.
* @param {string} operator The operator to check.
* @returns {boolean} Whether or not it is a comparison operator.
*/
function isComparisonOperator(operator) {
return /^(?:==|===|!=|!==|<|>|<=|>=)$/u.test(operator);
}
/**
* Determines whether an operator is an equality operator.
* @param {string} operator The operator to check.
* @returns {boolean} Whether or not it is an equality operator.
*/
function isEqualityOperator(operator) {
return /^(?:==|===)$/u.test(operator);
}
/**
* Determines whether an operator is one used in a range test.
* Allowed operators are `<` and `<=`.
* @param {string} operator The operator to check.
* @returns {boolean} Whether the operator is used in range tests.
*/
function isRangeTestOperator(operator) {
return ["<", "<="].includes(operator);
}
/**
* Determines whether a non-Literal node is a negative number that should be
* treated as if it were a single Literal node.
* @param {ASTNode} node Node to test.
* @returns {boolean} True if the node is a negative number that looks like a
* real literal and should be treated as such.
*/
function isNegativeNumericLiteral(node) {
return (
node.type === "UnaryExpression" &&
node.operator === "-" &&
node.prefix &&
astUtils.isNumericLiteral(node.argument)
);
}
/**
* Determines whether a non-Literal node should be treated as a single Literal node.
* @param {ASTNode} node Node to test
* @returns {boolean} True if the node should be treated as a single Literal node.
*/
function looksLikeLiteral(node) {
return (
isNegativeNumericLiteral(node) || astUtils.isStaticTemplateLiteral(node)
);
}
/**
* Attempts to derive a Literal node from nodes that are treated like literals.
* @param {ASTNode} node Node to normalize.
* @returns {ASTNode} One of the following options.
* 1. The original node if the node is already a Literal
* 2. A normalized Literal node with the negative number as the value if the
* node represents a negative number literal.
* 3. A normalized Literal node with the string as the value if the node is
* a Template Literal without expression.
* 4. Otherwise `null`.
*/
function getNormalizedLiteral(node) {
if (node.type === "Literal") {
return node;
}
if (isNegativeNumericLiteral(node)) {
return {
type: "Literal",
value: -node.argument.value,
raw: `-${node.argument.value}`,
};
}
if (astUtils.isStaticTemplateLiteral(node)) {
return {
type: "Literal",
value: node.quasis[0].value.cooked,
raw: node.quasis[0].value.raw,
};
}
return null;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [
"never",
{
exceptRange: false,
onlyEquality: false,
},
],
docs: {
description: 'Require or disallow "Yoda" conditions',
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/yoda",
},
schema: [
{
enum: ["always", "never"],
},
{
type: "object",
properties: {
exceptRange: {
type: "boolean",
},
onlyEquality: {
type: "boolean",
},
},
additionalProperties: false,
},
],
fixable: "code",
messages: {
expected:
"Expected literal to be on the {{expectedSide}} side of {{operator}}.",
},
},
create(context) {
const [when, { exceptRange, onlyEquality }] = context.options;
const always = when === "always";
const sourceCode = context.sourceCode;
/**
* Determines whether node represents a range test.
* A range test is a "between" test like `(0 <= x && x < 1)` or an "outside"
* test like `(x < 0 || 1 <= x)`. It must be wrapped in parentheses, and
* both operators must be `<` or `<=`. Finally, the literal on the left side
* must be less than or equal to the literal on the right side so that the
* test makes any sense.
* @param {ASTNode} node LogicalExpression node to test.
* @returns {boolean} Whether node is a range test.
*/
function isRangeTest(node) {
const left = node.left,
right = node.right;
/**
* Determines whether node is of the form `0 <= x && x < 1`.
* @returns {boolean} Whether node is a "between" range test.
*/
function isBetweenTest() {
if (
node.operator === "&&" &&
astUtils.isSameReference(left.right, right.left)
) {
const leftLiteral = getNormalizedLiteral(left.left);
const rightLiteral = getNormalizedLiteral(right.right);
if (leftLiteral === null && rightLiteral === null) {
return false;
}
if (rightLiteral === null || leftLiteral === null) {
return true;
}
if (leftLiteral.value <= rightLiteral.value) {
return true;
}
}
return false;
}
/**
* Determines whether node is of the form `x < 0 || 1 <= x`.
* @returns {boolean} Whether node is an "outside" range test.
*/
function isOutsideTest() {
if (
node.operator === "||" &&
astUtils.isSameReference(left.left, right.right)
) {
const leftLiteral = getNormalizedLiteral(left.right);
const rightLiteral = getNormalizedLiteral(right.left);
if (leftLiteral === null && rightLiteral === null) {
return false;
}
if (rightLiteral === null || leftLiteral === null) {
return true;
}
if (leftLiteral.value <= rightLiteral.value) {
return true;
}
}
return false;
}
/**
* Determines whether node is wrapped in parentheses.
* @returns {boolean} Whether node is preceded immediately by an open
* paren token and followed immediately by a close
* paren token.
*/
function isParenWrapped() {
return astUtils.isParenthesised(sourceCode, node);
}
return (
node.type === "LogicalExpression" &&
left.type === "BinaryExpression" &&
right.type === "BinaryExpression" &&
isRangeTestOperator(left.operator) &&
isRangeTestOperator(right.operator) &&
(isBetweenTest() || isOutsideTest()) &&
isParenWrapped()
);
}
const OPERATOR_FLIP_MAP = {
"===": "===",
"!==": "!==",
"==": "==",
"!=": "!=",
"<": ">",
">": "<",
"<=": ">=",
">=": "<=",
};
/**
* Returns a string representation of a BinaryExpression node with its sides/operator flipped around.
* @param {ASTNode} node The BinaryExpression node
* @returns {string} A string representation of the node with the sides and operator flipped
*/
function getFlippedString(node) {
const operatorToken = sourceCode.getFirstTokenBetween(
node.left,
node.right,
token => token.value === node.operator,
);
const lastLeftToken = sourceCode.getTokenBefore(operatorToken);
const firstRightToken = sourceCode.getTokenAfter(operatorToken);
const source = sourceCode.getText();
const leftText = source.slice(
node.range[0],
lastLeftToken.range[1],
);
const textBeforeOperator = source.slice(
lastLeftToken.range[1],
operatorToken.range[0],
);
const textAfterOperator = source.slice(
operatorToken.range[1],
firstRightToken.range[0],
);
const rightText = source.slice(
firstRightToken.range[0],
node.range[1],
);
const tokenBefore = sourceCode.getTokenBefore(node);
const tokenAfter = sourceCode.getTokenAfter(node);
let prefix = "";
let suffix = "";
if (
tokenBefore &&
tokenBefore.range[1] === node.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBefore, firstRightToken)
) {
prefix = " ";
}
if (
tokenAfter &&
node.range[1] === tokenAfter.range[0] &&
!astUtils.canTokensBeAdjacent(lastLeftToken, tokenAfter)
) {
suffix = " ";
}
return (
prefix +
rightText +
textBeforeOperator +
OPERATOR_FLIP_MAP[operatorToken.value] +
textAfterOperator +
leftText +
suffix
);
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
BinaryExpression(node) {
const expectedLiteral = always ? node.left : node.right;
const expectedNonLiteral = always ? node.right : node.left;
// If `expectedLiteral` is not a literal, and `expectedNonLiteral` is a literal, raise an error.
if (
(expectedNonLiteral.type === "Literal" ||
looksLikeLiteral(expectedNonLiteral)) &&
!(
expectedLiteral.type === "Literal" ||
looksLikeLiteral(expectedLiteral)
) &&
!(!isEqualityOperator(node.operator) && onlyEquality) &&
isComparisonOperator(node.operator) &&
!(exceptRange && isRangeTest(node.parent))
) {
context.report({
node,
messageId: "expected",
data: {
operator: node.operator,
expectedSide: always ? "left" : "right",
},
fix: fixer =>
fixer.replaceText(node, getFlippedString(node)),
});
}
},
};
},
};
@@ -0,0 +1 @@
{"version":3,"file":"arrow-down-wide-narrow.js","sources":["../../../src/icons/arrow-down-wide-narrow.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ArrowDownWideNarrow\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtMyAxNiA0IDQgNC00IiAvPgogIDxwYXRoIGQ9Ik03IDIwVjQiIC8+CiAgPHBhdGggZD0iTTExIDRoMTAiIC8+CiAgPHBhdGggZD0iTTExIDhoNyIgLz4KICA8cGF0aCBkPSJNMTEgMTJoNCIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/arrow-down-wide-narrow\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 ArrowDownWideNarrow = createLucideIcon('ArrowDownWideNarrow', [\n ['path', { d: 'm3 16 4 4 4-4', key: '1co6wj' }],\n ['path', { d: 'M7 20V4', key: '1yoxec' }],\n ['path', { d: 'M11 4h10', key: '1w87gc' }],\n ['path', { d: 'M11 8h7', key: 'djye34' }],\n ['path', { d: 'M11 12h4', key: 'q8tih4' }],\n]);\n\nexport default ArrowDownWideNarrow;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAsB,iBAAiB,qBAAuB,CAAA,CAAA,CAAA;AAAA,CAAA,CAClE,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAiB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC9C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,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,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,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,106 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _keywords = require('./keywords');
var _types = require('./types');
class Scope {
constructor(startTokenIndex, endTokenIndex, isFunctionScope) {
this.startTokenIndex = startTokenIndex;
this.endTokenIndex = endTokenIndex;
this.isFunctionScope = isFunctionScope;
}
} exports.Scope = Scope;
class StateSnapshot {
constructor(
potentialArrowAt,
noAnonFunctionType,
inDisallowConditionalTypesContext,
tokensLength,
scopesLength,
pos,
type,
contextualKeyword,
start,
end,
isType,
scopeDepth,
error,
) {;this.potentialArrowAt = potentialArrowAt;this.noAnonFunctionType = noAnonFunctionType;this.inDisallowConditionalTypesContext = inDisallowConditionalTypesContext;this.tokensLength = tokensLength;this.scopesLength = scopesLength;this.pos = pos;this.type = type;this.contextualKeyword = contextualKeyword;this.start = start;this.end = end;this.isType = isType;this.scopeDepth = scopeDepth;this.error = error;}
} exports.StateSnapshot = StateSnapshot;
class State {constructor() { State.prototype.__init.call(this);State.prototype.__init2.call(this);State.prototype.__init3.call(this);State.prototype.__init4.call(this);State.prototype.__init5.call(this);State.prototype.__init6.call(this);State.prototype.__init7.call(this);State.prototype.__init8.call(this);State.prototype.__init9.call(this);State.prototype.__init10.call(this);State.prototype.__init11.call(this);State.prototype.__init12.call(this);State.prototype.__init13.call(this); }
// Used to signify the start of a potential arrow function
__init() {this.potentialArrowAt = -1}
// Used by Flow to handle an edge case involving function type parsing.
__init2() {this.noAnonFunctionType = false}
// Used by TypeScript to handle ambiguities when parsing conditional types.
__init3() {this.inDisallowConditionalTypesContext = false}
// Token store.
__init4() {this.tokens = []}
// Array of all observed scopes, ordered by their ending position.
__init5() {this.scopes = []}
// The current position of the tokenizer in the input.
__init6() {this.pos = 0}
// Information about the current token.
__init7() {this.type = _types.TokenType.eof}
__init8() {this.contextualKeyword = _keywords.ContextualKeyword.NONE}
__init9() {this.start = 0}
__init10() {this.end = 0}
__init11() {this.isType = false}
__init12() {this.scopeDepth = 0}
/**
* If the parser is in an error state, then the token is always tt.eof and all functions can
* keep executing but should be written so they don't get into an infinite loop in this situation.
*
* This approach, combined with the ability to snapshot and restore state, allows us to implement
* backtracking without exceptions and without needing to explicitly propagate error states
* everywhere.
*/
__init13() {this.error = null}
snapshot() {
return new StateSnapshot(
this.potentialArrowAt,
this.noAnonFunctionType,
this.inDisallowConditionalTypesContext,
this.tokens.length,
this.scopes.length,
this.pos,
this.type,
this.contextualKeyword,
this.start,
this.end,
this.isType,
this.scopeDepth,
this.error,
);
}
restoreFromSnapshot(snapshot) {
this.potentialArrowAt = snapshot.potentialArrowAt;
this.noAnonFunctionType = snapshot.noAnonFunctionType;
this.inDisallowConditionalTypesContext = snapshot.inDisallowConditionalTypesContext;
this.tokens.length = snapshot.tokensLength;
this.scopes.length = snapshot.scopesLength;
this.pos = snapshot.pos;
this.type = snapshot.type;
this.contextualKeyword = snapshot.contextualKeyword;
this.start = snapshot.start;
this.end = snapshot.end;
this.isType = snapshot.isType;
this.scopeDepth = snapshot.scopeDepth;
this.error = snapshot.error;
}
} exports.default = State;
@@ -0,0 +1,7 @@
/**
* @fileoverview This file exports everything for this package.
* @author Nicholas C. Zakas
*/
export * from "./node-hfs.js";
export { Hfs } from "@humanfs/core";
@@ -0,0 +1,66 @@
{
"name": "eslint-scope",
"description": "ECMAScript scope analyzer for ESLint",
"homepage": "https://github.com/eslint/js/blob/main/packages/eslint-scope/README.md",
"main": "./dist/eslint-scope.cjs",
"types": "./lib/index.d.cts",
"type": "module",
"exports": {
".": {
"import": {
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
},
"require": {
"types": "./lib/index.d.cts",
"default": "./dist/eslint-scope.cjs"
}
},
"./package.json": "./package.json"
},
"version": "9.1.2",
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint/js.git",
"directory": "packages/eslint-scope"
},
"funding": "https://opencollective.com/eslint",
"keywords": [
"eslint"
],
"bugs": {
"url": "https://github.com/eslint/js/issues"
},
"license": "BSD-2-Clause",
"scripts": {
"build": "rollup -c",
"lint:types": "attw --pack",
"pretest": "npm run build",
"test": "node Makefile.js test && npm run test:types",
"test:types": "tsc -p tsconfig.json && tsc -p tests/types/tsconfig.json"
},
"files": [
"LICENSE",
"README.md",
"lib",
"dist/eslint-scope.cjs"
],
"dependencies": {
"@types/esrecurse": "^4.3.1",
"@types/estree": "^1.0.8",
"esrecurse": "^4.3.0",
"estraverse": "^5.2.0"
},
"devDependencies": {
"@typescript-eslint/parser": "^8.7.0",
"chai": "^6.0.0",
"eslint": ">=10.0.0-rc.0 <10.0.0 || ^10.0.0",
"eslint-visitor-keys": "^5.0.1",
"espree": "^11.2.0",
"npm-license": "^0.3.3",
"shelljs": "^0.8.5"
}
}
@@ -0,0 +1,57 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
// flowlint unclear-type:off
export type HermesPosition = {
/** >= 1 */
+line: number,
/** >= 0 */
+column: number,
};
export type HermesSourceLocation = {
start?: HermesPosition,
end?: HermesPosition,
rangeStart?: number,
rangeEnd?: number,
};
export type HermesNode = {
type: string,
[string]: any,
};
export type HermesToken = {
type:
| 'Boolean'
| 'Identifier'
| 'Keyword'
| 'Null'
| 'Numeric'
| 'BigInt'
| 'Punctuator'
| 'String'
| 'RegularExpression'
| 'Template'
| 'JSXText',
loc: HermesSourceLocation,
value: ?string,
};
export type HermesComment = {
type: 'CommentLine' | 'CommentBlock' | 'InterpreterDirective',
loc: HermesSourceLocation,
value: ?string,
};
export type HermesProgram = {
type: 'Program',
loc: HermesSourceLocation,
body: Array<?HermesNode>,
comments: Array<HermesComment>,
tokens?: Array<HermesToken>,
interpreter?: ?HermesComment,
};
@@ -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 ShoppingBag = createLucideIcon("ShoppingBag", [
["path", { d: "M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z", key: "hou9p0" }],
["path", { d: "M3 6h18", key: "d0wm0j" }],
["path", { d: "M16 10a4 4 0 0 1-8 0", key: "1ltviw" }]
]);
export { ShoppingBag as default };
//# sourceMappingURL=shopping-bag.js.map
@@ -0,0 +1 @@
{"version":3,"file":"utils.cjs","sources":["../../src/scoring/utils.ts"],"sourcesContent":[null],"names":["LOG10","Math","log","LOG2","nCk","n","k","count","coEff","i","log10","log2","factorial","num","rval"],"mappings":";;AAAA,MAAMA,KAAK,GAAGC,IAAI,CAACC,GAAG,CAAC,EAAE,CAAC;AAC1B,MAAMC,IAAI,GAAGF,IAAI,CAACC,GAAG,CAAC,CAAC,CAAC;AAExB,YAAe;AACb;AACA;AACAE,EAAAA,GAAGA,CAACC,CAAS,EAAEC,CAAS,EAAA;IACtB,IAAIC,KAAK,GAAGF,CAAC;IACb,IAAIC,CAAC,GAAGC,KAAK,EAAE;AACb,MAAA,OAAO,CAAC;AACV,IAAA;IACA,IAAID,CAAC,KAAK,CAAC,EAAE;AACX,MAAA,OAAO,CAAC;AACV,IAAA;IACA,IAAIE,KAAK,GAAG,CAAC;AACb,IAAA,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,IAAIH,CAAC,EAAEG,CAAC,IAAI,CAAC,EAAE;AAC9BD,MAAAA,KAAK,IAAID,KAAK;AACdC,MAAAA,KAAK,IAAIC,CAAC;AACVF,MAAAA,KAAK,IAAI,CAAC;AACZ,IAAA;AACA,IAAA,OAAOC,KAAK;EACd,CAAC;EACDE,KAAKA,CAACL,CAAS,EAAA;AACb,IAAA,IAAIA,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACrB,OAAOJ,IAAI,CAACC,GAAG,CAACG,CAAC,CAAC,GAAGL,KAAK,CAAA;EAC5B,CAAC;EACDW,IAAIA,CAACN,CAAS,EAAA;AACZ,IAAA,OAAOJ,IAAI,CAACC,GAAG,CAACG,CAAC,CAAC,GAAGF,IAAI;EAC3B,CAAC;EACDS,SAASA,CAACC,GAAW,EAAA;IACnB,IAAIC,IAAI,GAAG,CAAC;AACZ,IAAA,KAAK,IAAIL,CAAC,GAAG,CAAC,EAAEA,CAAC,IAAII,GAAG,EAAEJ,CAAC,IAAI,CAAC,EAAEK,IAAI,IAAIL,CAAC;AAC3C,IAAA,OAAOK,IAAI;AACb,EAAA;CACD;;;;"}
@@ -0,0 +1,313 @@
"use client";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
require("./_virtual/_rolldown/runtime.cjs");
const require_awaited = require("./awaited.cjs");
const require_CatchBoundary = require("./CatchBoundary.cjs");
const require_ClientOnly = require("./ClientOnly.cjs");
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_link = require("./link.cjs");
const require_route = require("./route.cjs");
const require_fileRoute = require("./fileRoute.cjs");
const require_lazyRouteComponent = require("./lazyRouteComponent.cjs");
const require_not_found = require("./not-found.cjs");
const require_ScriptOnce = require("./ScriptOnce.cjs");
const require_Match = require("./Match.cjs");
const require_Matches = require("./Matches.cjs");
const require_router = require("./router.cjs");
const require_RouterProvider = require("./RouterProvider.cjs");
const require_ScrollRestoration = require("./ScrollRestoration.cjs");
const require_useBlocker = require("./useBlocker.cjs");
const require_useRouterState = require("./useRouterState.cjs");
const require_useLocation = require("./useLocation.cjs");
const require_useCanGoBack = require("./useCanGoBack.cjs");
const require_Asset = require("./Asset.cjs");
const require_headContentUtils = require("./headContentUtils.cjs");
const require_HeadContent = require("./HeadContent.cjs");
const require_Scripts = require("./Scripts.cjs");
let _tanstack_router_core = require("@tanstack/router-core");
let _tanstack_history = require("@tanstack/history");
exports.Asset = require_Asset.Asset;
exports.Await = require_awaited.Await;
exports.Block = require_useBlocker.Block;
exports.CatchBoundary = require_CatchBoundary.CatchBoundary;
exports.CatchNotFound = require_not_found.CatchNotFound;
exports.ClientOnly = require_ClientOnly.ClientOnly;
Object.defineProperty(exports, "DEFAULT_PROTOCOL_ALLOWLIST", {
enumerable: true,
get: function() {
return _tanstack_router_core.DEFAULT_PROTOCOL_ALLOWLIST;
}
});
exports.DefaultGlobalNotFound = require_not_found.DefaultGlobalNotFound;
exports.ErrorComponent = require_CatchBoundary.ErrorComponent;
exports.FileRoute = require_fileRoute.FileRoute;
exports.FileRouteLoader = require_fileRoute.FileRouteLoader;
exports.HeadContent = require_HeadContent.HeadContent;
exports.LazyRoute = require_fileRoute.LazyRoute;
exports.Link = require_link.Link;
exports.Match = require_Match.Match;
exports.MatchRoute = require_Matches.MatchRoute;
exports.Matches = require_Matches.Matches;
exports.Navigate = require_useNavigate.Navigate;
exports.NotFoundRoute = require_route.NotFoundRoute;
exports.Outlet = require_Match.Outlet;
exports.RootRoute = require_route.RootRoute;
exports.Route = require_route.Route;
exports.RouteApi = require_route.RouteApi;
exports.Router = require_router.Router;
exports.RouterContextProvider = require_RouterProvider.RouterContextProvider;
exports.RouterProvider = require_RouterProvider.RouterProvider;
exports.ScriptOnce = require_ScriptOnce.ScriptOnce;
exports.Scripts = require_Scripts.Scripts;
exports.ScrollRestoration = require_ScrollRestoration.ScrollRestoration;
Object.defineProperty(exports, "SearchParamError", {
enumerable: true,
get: function() {
return _tanstack_router_core.SearchParamError;
}
});
Object.defineProperty(exports, "cleanPath", {
enumerable: true,
get: function() {
return _tanstack_router_core.cleanPath;
}
});
Object.defineProperty(exports, "composeRewrites", {
enumerable: true,
get: function() {
return _tanstack_router_core.composeRewrites;
}
});
Object.defineProperty(exports, "createBrowserHistory", {
enumerable: true,
get: function() {
return _tanstack_history.createBrowserHistory;
}
});
Object.defineProperty(exports, "createControlledPromise", {
enumerable: true,
get: function() {
return _tanstack_router_core.createControlledPromise;
}
});
exports.createFileRoute = require_fileRoute.createFileRoute;
Object.defineProperty(exports, "createHashHistory", {
enumerable: true,
get: function() {
return _tanstack_history.createHashHistory;
}
});
Object.defineProperty(exports, "createHistory", {
enumerable: true,
get: function() {
return _tanstack_history.createHistory;
}
});
exports.createLazyFileRoute = require_fileRoute.createLazyFileRoute;
exports.createLazyRoute = require_fileRoute.createLazyRoute;
exports.createLink = require_link.createLink;
Object.defineProperty(exports, "createMemoryHistory", {
enumerable: true,
get: function() {
return _tanstack_history.createMemoryHistory;
}
});
exports.createRootRoute = require_route.createRootRoute;
exports.createRootRouteWithContext = require_route.createRootRouteWithContext;
exports.createRoute = require_route.createRoute;
exports.createRouteMask = require_route.createRouteMask;
exports.createRouter = require_router.createRouter;
Object.defineProperty(exports, "createRouterConfig", {
enumerable: true,
get: function() {
return _tanstack_router_core.createRouterConfig;
}
});
Object.defineProperty(exports, "createSerializationAdapter", {
enumerable: true,
get: function() {
return _tanstack_router_core.createSerializationAdapter;
}
});
Object.defineProperty(exports, "deepEqual", {
enumerable: true,
get: function() {
return _tanstack_router_core.deepEqual;
}
});
Object.defineProperty(exports, "defaultParseSearch", {
enumerable: true,
get: function() {
return _tanstack_router_core.defaultParseSearch;
}
});
Object.defineProperty(exports, "defaultStringifySearch", {
enumerable: true,
get: function() {
return _tanstack_router_core.defaultStringifySearch;
}
});
Object.defineProperty(exports, "defer", {
enumerable: true,
get: function() {
return _tanstack_router_core.defer;
}
});
Object.defineProperty(exports, "functionalUpdate", {
enumerable: true,
get: function() {
return _tanstack_router_core.functionalUpdate;
}
});
exports.getRouteApi = require_route.getRouteApi;
Object.defineProperty(exports, "interpolatePath", {
enumerable: true,
get: function() {
return _tanstack_router_core.interpolatePath;
}
});
Object.defineProperty(exports, "isMatch", {
enumerable: true,
get: function() {
return _tanstack_router_core.isMatch;
}
});
Object.defineProperty(exports, "isNotFound", {
enumerable: true,
get: function() {
return _tanstack_router_core.isNotFound;
}
});
Object.defineProperty(exports, "isPlainArray", {
enumerable: true,
get: function() {
return _tanstack_router_core.isPlainArray;
}
});
Object.defineProperty(exports, "isPlainObject", {
enumerable: true,
get: function() {
return _tanstack_router_core.isPlainObject;
}
});
Object.defineProperty(exports, "isRedirect", {
enumerable: true,
get: function() {
return _tanstack_router_core.isRedirect;
}
});
Object.defineProperty(exports, "joinPaths", {
enumerable: true,
get: function() {
return _tanstack_router_core.joinPaths;
}
});
Object.defineProperty(exports, "lazyFn", {
enumerable: true,
get: function() {
return _tanstack_router_core.lazyFn;
}
});
exports.lazyRouteComponent = require_lazyRouteComponent.lazyRouteComponent;
exports.linkOptions = require_link.linkOptions;
Object.defineProperty(exports, "notFound", {
enumerable: true,
get: function() {
return _tanstack_router_core.notFound;
}
});
Object.defineProperty(exports, "parseSearchWith", {
enumerable: true,
get: function() {
return _tanstack_router_core.parseSearchWith;
}
});
Object.defineProperty(exports, "redirect", {
enumerable: true,
get: function() {
return _tanstack_router_core.redirect;
}
});
Object.defineProperty(exports, "replaceEqualDeep", {
enumerable: true,
get: function() {
return _tanstack_router_core.replaceEqualDeep;
}
});
Object.defineProperty(exports, "resolvePath", {
enumerable: true,
get: function() {
return _tanstack_router_core.resolvePath;
}
});
Object.defineProperty(exports, "retainSearchParams", {
enumerable: true,
get: function() {
return _tanstack_router_core.retainSearchParams;
}
});
Object.defineProperty(exports, "rootRouteId", {
enumerable: true,
get: function() {
return _tanstack_router_core.rootRouteId;
}
});
exports.rootRouteWithContext = require_route.rootRouteWithContext;
Object.defineProperty(exports, "stringifySearchWith", {
enumerable: true,
get: function() {
return _tanstack_router_core.stringifySearchWith;
}
});
Object.defineProperty(exports, "stripSearchParams", {
enumerable: true,
get: function() {
return _tanstack_router_core.stripSearchParams;
}
});
Object.defineProperty(exports, "trimPath", {
enumerable: true,
get: function() {
return _tanstack_router_core.trimPath;
}
});
Object.defineProperty(exports, "trimPathLeft", {
enumerable: true,
get: function() {
return _tanstack_router_core.trimPathLeft;
}
});
Object.defineProperty(exports, "trimPathRight", {
enumerable: true,
get: function() {
return _tanstack_router_core.trimPathRight;
}
});
exports.useAwaited = require_awaited.useAwaited;
exports.useBlocker = require_useBlocker.useBlocker;
exports.useCanGoBack = require_useCanGoBack.useCanGoBack;
exports.useChildMatches = require_Matches.useChildMatches;
exports.useElementScrollRestoration = require_ScrollRestoration.useElementScrollRestoration;
exports.useHydrated = require_ClientOnly.useHydrated;
exports.useLinkProps = require_link.useLinkProps;
exports.useLoaderData = require_useLoaderData.useLoaderData;
exports.useLoaderDeps = require_useLoaderDeps.useLoaderDeps;
exports.useLocation = require_useLocation.useLocation;
exports.useMatch = require_useMatch.useMatch;
exports.useMatchRoute = require_Matches.useMatchRoute;
exports.useMatches = require_Matches.useMatches;
exports.useNavigate = require_useNavigate.useNavigate;
exports.useParams = require_useParams.useParams;
exports.useParentMatches = require_Matches.useParentMatches;
exports.useRouteContext = require_useRouteContext.useRouteContext;
exports.useRouter = require_useRouter.useRouter;
exports.useRouterState = require_useRouterState.useRouterState;
exports.useSearch = require_useSearch.useSearch;
exports.useTags = require_headContentUtils.useTags;
@@ -0,0 +1 @@
{"version":3,"file":"matching.cjs","sources":["../../../src/matcher/regex/matching.ts"],"sourcesContent":[null],"names":["MatchRegex","MatcherBaseClass","match","password","matches","Object","keys","REGEXEN","forEach","name","regex","lastIndex","regexMatch","exec","token","push","pattern","i","index","j","length","regexName","sorted"],"mappings":";;;;;;AAOA;;;;AAIG;AACH,MAAMA,UAAW,SAAQC,sBAAgB,CAAA;AACvCC,EAAAA,KAAKA,CAAC;AAAEC,IAAAA;AAAQ,GAAqB,EAAA;IACnC,MAAMC,OAAO,GAAiB,EAAE;IAChCC,MAAM,CAACC,IAAI,CAACC,cAAO,CAAC,CAACC,OAAO,CAAEC,IAAI,IAAI;AACpC,MAAA,MAAMC,KAAK,GAAGH,cAAO,CAACE,IAAmB,CAAC;AAC1CC,MAAAA,KAAK,CAACC,SAAS,GAAG,CAAC,CAAA;AAEnB,MAAA,IAAIC,UAAkC;MAEtC,OAAQA,UAAU,GAAGF,KAAK,CAACG,IAAI,CAACV,QAAQ,CAAC,EAAG;AAC1C,QAAA,IAAIS,UAAU,EAAE;AACd,UAAA,MAAME,KAAK,GAAGF,UAAU,CAAC,CAAC,CAAC;UAC3BR,OAAO,CAACW,IAAI,CAAC;AACXC,YAAAA,OAAO,EAAE,OAAO;YAChBF,KAAK;YACLG,CAAC,EAAEL,UAAU,CAACM,KAAK;AACnBC,YAAAA,CAAC,EAAEP,UAAU,CAACM,KAAK,GAAGN,UAAU,CAAC,CAAC,CAAC,CAACQ,MAAM,GAAG,CAAC;AAC9CC,YAAAA,SAAS,EAAEZ,IAAmB;AAC9BG,YAAAA;AACD,WAAA,CAAC;AACJ,QAAA;AACF,MAAA;AACF,IAAA,CAAC,CAAC;IACF,OAAOU,aAAM,CAAClB,OAAO,CAAC;AACxB,EAAA;AACD;;;;"}
@@ -0,0 +1 @@
{"version":3,"file":"decode-data-xml.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/decode-data-xml.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAE9C,eAAe,IAAI,WAAW;AAC1B,kBAAkB;AAClB,uFAAuF;KAClF,KAAK,CAAC,EAAE,CAAC;KACT,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CACnC,CAAC"}
@@ -0,0 +1,9 @@
/**
* @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.
*/
export { default } from './braces.js';
//# sourceMappingURL=curly-braces.js.map
@@ -0,0 +1,34 @@
{
"name": "shebang-command",
"version": "2.0.0",
"description": "Get the command from a shebang",
"license": "MIT",
"repository": "kevva/shebang-command",
"author": {
"name": "Kevin Mårtensson",
"email": "kevinmartensson@gmail.com",
"url": "github.com/kevva"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"cmd",
"command",
"parse",
"shebang"
],
"dependencies": {
"shebang-regex": "^3.0.0"
},
"devDependencies": {
"ava": "^2.3.0",
"xo": "^0.24.0"
}
}
@@ -0,0 +1,198 @@
import Tokenizer, { type Callbacks, QuoteType } from "./Tokenizer.js";
export interface ParserOptions {
/**
* Indicates whether special tags (`<script>`, `<style>`, and `<title>`) should get special treatment
* and if "empty" tags (eg. `<br>`) can have children. If `false`, the content of special tags
* will be text only. For feeds and other XML content (documents that don't consist of HTML),
* set this to `true`.
*
* @default false
*/
xmlMode?: boolean;
/**
* Decode entities within the document.
*
* @default true
*/
decodeEntities?: boolean;
/**
* If set to true, all tags will be lowercased.
*
* @default !xmlMode
*/
lowerCaseTags?: boolean;
/**
* If set to `true`, all attribute names will be lowercased. This has noticeable impact on speed.
*
* @default !xmlMode
*/
lowerCaseAttributeNames?: boolean;
/**
* If set to true, CDATA sections will be recognized as text even if the xmlMode option is not enabled.
* NOTE: If xmlMode is set to `true` then CDATA sections will always be recognized as text.
*
* @default xmlMode
*/
recognizeCDATA?: boolean;
/**
* If set to `true`, self-closing tags will trigger the onclosetag event even if xmlMode is not set to `true`.
* NOTE: If xmlMode is set to `true` then self-closing tags will always be recognized.
*
* @default xmlMode
*/
recognizeSelfClosing?: boolean;
/**
* Allows the default tokenizer to be overwritten.
*/
Tokenizer?: typeof Tokenizer;
}
export interface Handler {
onparserinit(parser: Parser): void;
/**
* Resets the handler back to starting state
*/
onreset(): void;
/**
* Signals the handler that parsing is done
*/
onend(): void;
onerror(error: Error): void;
onclosetag(name: string, isImplied: boolean): void;
onopentagname(name: string): void;
/**
*
* @param name Name of the attribute
* @param value Value of the attribute.
* @param quote Quotes used around the attribute. `null` if the attribute has no quotes around the value, `undefined` if the attribute has no value.
*/
onattribute(name: string, value: string, quote?: string | undefined | null): void;
onopentag(name: string, attribs: {
[s: string]: string;
}, isImplied: boolean): void;
ontext(data: string): void;
oncomment(data: string): void;
oncdatastart(): void;
oncdataend(): void;
oncommentend(): void;
onprocessinginstruction(name: string, data: string): void;
}
export declare class Parser implements Callbacks {
private readonly options;
/** The start index of the last event. */
startIndex: number;
/** The end index of the last event. */
endIndex: number;
/**
* Store the start index of the current open tag,
* so we can update the start index for attributes.
*/
private openTagStart;
private tagname;
private attribname;
private attribvalue;
private attribs;
private readonly stack;
/** Determines whether self-closing tags are recognized. */
private readonly foreignContext;
private readonly cbs;
private readonly lowerCaseTagNames;
private readonly lowerCaseAttributeNames;
private readonly recognizeSelfClosing;
/** We are parsing HTML. Inverse of the `xmlMode` option. */
private readonly htmlMode;
private readonly tokenizer;
private readonly buffers;
private bufferOffset;
/** The index of the last written buffer. Used when resuming after a `pause()`. */
private writeIndex;
/** Indicates whether the parser has finished running / `.end` has been called. */
private ended;
constructor(cbs?: Partial<Handler> | null, options?: ParserOptions);
/** @internal */
ontext(start: number, endIndex: number): void;
/** @internal */
ontextentity(cp: number, endIndex: number): void;
/**
* Checks if the current tag is a void element. Override this if you want
* to specify your own additional void elements.
*/
protected isVoidElement(name: string): boolean;
/** @internal */
onopentagname(start: number, endIndex: number): void;
private emitOpenTag;
private endOpenTag;
/** @internal */
onopentagend(endIndex: number): void;
/** @internal */
onclosetag(start: number, endIndex: number): void;
/** @internal */
onselfclosingtag(endIndex: number): void;
private closeCurrentTag;
/** @internal */
onattribname(start: number, endIndex: number): void;
/** @internal */
onattribdata(start: number, endIndex: number): void;
/** @internal */
onattribentity(cp: number): void;
/** @internal */
onattribend(quote: QuoteType, endIndex: number): void;
private getInstructionName;
/** @internal */
ondeclaration(start: number, endIndex: number): void;
/** @internal */
onprocessinginstruction(start: number, endIndex: number): void;
/** @internal */
oncomment(start: number, endIndex: number, offset: number): void;
/** @internal */
oncdata(start: number, endIndex: number, offset: number): void;
/** @internal */
onend(): void;
/**
* Resets the parser to a blank state, ready to parse a new HTML document
*/
reset(): void;
/**
* Resets the parser, then parses a complete document and
* pushes it to the handler.
*
* @param data Document to parse.
*/
parseComplete(data: string): void;
private getSlice;
private shiftBuffer;
/**
* Parses a chunk of data and calls the corresponding callbacks.
*
* @param chunk Chunk to parse.
*/
write(chunk: string): void;
/**
* Parses the end of the buffer and clears the stack, calls onend.
*
* @param chunk Optional final chunk to parse.
*/
end(chunk?: string): void;
/**
* Pauses parsing. The parser won't emit events until `resume` is called.
*/
pause(): void;
/**
* Resumes parsing after `pause` was called.
*/
resume(): void;
/**
* Alias of `write`, for backwards compatibility.
*
* @param chunk Chunk to parse.
* @deprecated
*/
parseChunk(chunk: string): void;
/**
* Alias of `end`, for backwards compatibility.
*
* @param chunk Optional final chunk to parse.
* @deprecated
*/
done(chunk?: string): void;
}
//# sourceMappingURL=Parser.d.ts.map
@@ -0,0 +1,467 @@
// @ts-self-types="./index.d.ts"
/**
* @fileoverview Merge Strategy
*/
//-----------------------------------------------------------------------------
// Class
//-----------------------------------------------------------------------------
/**
* Container class for several different merge strategies.
*/
class MergeStrategy {
/**
* Merges two keys by overwriting the first with the second.
* @template TValue1 The type of the value from the first object key.
* @template TValue2 The type of the value from the second object key.
* @param {TValue1} value1 The value from the first object key.
* @param {TValue2} value2 The value from the second object key.
* @returns {TValue2} The second value.
*/
static overwrite(value1, value2) {
return value2;
}
/**
* Merges two keys by replacing the first with the second only if the
* second is defined.
* @template TValue1 The type of the value from the first object key.
* @template TValue2 The type of the value from the second object key.
* @param {TValue1} value1 The value from the first object key.
* @param {TValue2} value2 The value from the second object key.
* @returns {TValue1 | TValue2} The second value if it is defined.
*/
static replace(value1, value2) {
if (typeof value2 !== "undefined") {
return value2;
}
return value1;
}
/**
* Merges two properties by assigning properties from the second to the first.
* @template {Record<string | number | symbol, unknown> | undefined} TValue1 The type of the value from the first object key.
* @template {Record<string | number | symbol, unknown>} TValue2 The type of the value from the second object key.
* @param {TValue1} value1 The value from the first object key.
* @param {TValue2} value2 The value from the second object key.
* @returns {Omit<TValue1, keyof TValue2> & TValue2} A new object containing properties from both value1 and
* value2.
*/
static assign(value1, value2) {
return Object.assign({}, value1, value2);
}
}
/**
* @fileoverview Validation Strategy
*/
//-----------------------------------------------------------------------------
// Class
//-----------------------------------------------------------------------------
/**
* Container class for several different validation strategies.
*/
class ValidationStrategy {
/**
* Validates that a value is an array.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static array(value) {
if (!Array.isArray(value)) {
throw new TypeError("Expected an array.");
}
}
/**
* Validates that a value is a boolean.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static boolean(value) {
if (typeof value !== "boolean") {
throw new TypeError("Expected a boolean.");
}
}
/**
* Validates that a value is a number.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static number(value) {
if (typeof value !== "number") {
throw new TypeError("Expected a number.");
}
}
/**
* Validates that a value is an object.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static object(value) {
if (!value || typeof value !== "object") {
throw new TypeError("Expected an object.");
}
}
/**
* Validates that a value is an object or null.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static "object?"(value) {
if (typeof value !== "object") {
throw new TypeError("Expected an object or null.");
}
}
/**
* Validates that a value is a string.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static string(value) {
if (typeof value !== "string") {
throw new TypeError("Expected a string.");
}
}
/**
* Validates that a value is a non-empty string.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static "string!"(value) {
if (typeof value !== "string" || value.length === 0) {
throw new TypeError("Expected a non-empty string.");
}
}
}
/**
* @fileoverview Object Schema
*/
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/** @import * as $typests from "./types.ts"; */
/** @typedef {$typests.BuiltInMergeStrategy} BuiltInMergeStrategy */
/** @typedef {$typests.BuiltInValidationStrategy} BuiltInValidationStrategy */
/** @typedef {$typests.CustomMergeStrategy} CustomMergeStrategy */
/** @typedef {$typests.CustomValidationStrategy} CustomValidationStrategy */
/** @typedef {$typests.ObjectDefinition} ObjectDefinition */
/** @typedef {$typests.PropertyDefinition} PropertyDefinition */
/** @typedef {$typests.PropertyDefinitionWithSchema} PropertyDefinitionWithSchema */
/** @typedef {$typests.PropertyDefinitionWithStrategies} PropertyDefinitionWithStrategies */
//-----------------------------------------------------------------------------
// Private
//-----------------------------------------------------------------------------
/**
* Validates a schema strategy.
* @param {string} name The name of the key this strategy is for.
* @param {PropertyDefinition} definition The strategy for the object key.
* @returns {void}
* @throws {TypeError} When the strategy is missing a name.
* @throws {TypeError} When the strategy is missing a merge() method.
* @throws {TypeError} When the strategy is missing a validate() method.
*/
function validateDefinition(name, definition) {
let hasSchema = false;
if (definition.schema) {
if (typeof definition.schema === "object") {
hasSchema = true;
} else {
throw new TypeError("Schema must be an object.");
}
}
if (typeof definition.merge === "string") {
if (!(definition.merge in MergeStrategy)) {
throw new TypeError(
`Definition for key "${name}" missing valid merge strategy.`,
);
}
} else if (!hasSchema && typeof definition.merge !== "function") {
throw new TypeError(
`Definition for key "${name}" must have a merge property.`,
);
}
if (typeof definition.validate === "string") {
if (!(definition.validate in ValidationStrategy)) {
throw new TypeError(
`Definition for key "${name}" missing valid validation strategy.`,
);
}
} else if (!hasSchema && typeof definition.validate !== "function") {
throw new TypeError(
`Definition for key "${name}" must have a validate() method.`,
);
}
}
//-----------------------------------------------------------------------------
// Errors
//-----------------------------------------------------------------------------
/**
* Error when an unexpected key is found.
*/
class UnexpectedKeyError extends Error {
/**
* Creates a new instance.
* @param {string} key The key that was unexpected.
*/
constructor(key) {
super(`Unexpected key "${key}" found.`);
}
}
/**
* Error when a required key is missing.
*/
class MissingKeyError extends Error {
/**
* Creates a new instance.
* @param {string} key The key that was missing.
*/
constructor(key) {
super(`Missing required key "${key}".`);
}
}
/**
* Error when a key requires other keys that are missing.
*/
class MissingDependentKeysError extends Error {
/**
* Creates a new instance.
* @param {string} key The key that was unexpected.
* @param {Array<string>} requiredKeys The keys that are required.
*/
constructor(key, requiredKeys) {
super(`Key "${key}" requires keys "${requiredKeys.join('", "')}".`);
}
}
/**
* Wrapper error for errors occuring during a merge or validate operation.
*/
class WrapperError extends Error {
/**
* Creates a new instance.
* @param {string} key The object key causing the error.
* @param {Error} source The source error.
*/
constructor(key, source) {
super(`Key "${key}": ${source.message}`, { cause: source });
// copy over custom properties that aren't represented
for (const sourceKey of Object.keys(source)) {
if (!(sourceKey in this)) {
this[sourceKey] = source[sourceKey];
}
}
}
}
//-----------------------------------------------------------------------------
// Main
//-----------------------------------------------------------------------------
/**
* Represents an object validation/merging schema.
*/
class ObjectSchema {
/**
* Track all definitions in the schema by key.
* @type {Map<string, PropertyDefinition>}
*/
#definitions = new Map();
/**
* Separately track any keys that are required for faster validation.
* @type {Map<string, PropertyDefinition>}
*/
#requiredKeys = new Map();
/**
* Creates a new instance.
* @param {ObjectDefinition} definitions The schema definitions.
* @throws {Error} When the definitions are missing or invalid.
*/
constructor(definitions) {
if (!definitions) {
throw new Error("Schema definitions missing.");
}
// add in all strategies
for (const key of Object.keys(definitions)) {
const definition = definitions[key];
validateDefinition(key, definition);
let normalizedDefinition = definition;
// normalize merge and validate methods if subschema is present
if (typeof normalizedDefinition.schema === "object") {
const schema = new ObjectSchema(normalizedDefinition.schema);
normalizedDefinition = {
...normalizedDefinition,
merge(first = {}, second = {}) {
return schema.merge(first, second);
},
validate(value) {
ValidationStrategy.object(value);
schema.validate(value);
},
};
}
// normalize the merge method in case there's a string
if (typeof normalizedDefinition.merge === "string") {
normalizedDefinition = {
...normalizedDefinition,
merge: MergeStrategy[normalizedDefinition.merge],
};
}
// normalize the validate method in case there's a string
if (typeof normalizedDefinition.validate === "string") {
normalizedDefinition = {
...normalizedDefinition,
validate: ValidationStrategy[normalizedDefinition.validate],
};
}
this.#definitions.set(key, normalizedDefinition);
if (normalizedDefinition.required) {
this.#requiredKeys.set(key, normalizedDefinition);
}
}
}
/**
* Determines if a strategy has been registered for the given object key.
* @param {string} key The object key to find a strategy for.
* @returns {boolean} True if the key has a strategy registered, false if not.
*/
hasKey(key) {
return this.#definitions.has(key);
}
/**
* Merges objects together to create a new object comprised of the keys
* of the all objects. Keys are merged based on the each key's merge
* strategy.
* @param {...Object} objects The objects to merge.
* @returns {Object} A new object with a mix of all objects' keys.
* @throws {TypeError} If any object is invalid.
*/
merge(...objects) {
// double check arguments
if (objects.length < 2) {
throw new TypeError("merge() requires at least two arguments.");
}
if (
objects.some(
object => object === null || typeof object !== "object",
)
) {
throw new TypeError("All arguments must be objects.");
}
return objects.reduce((result, object) => {
this.validate(object);
for (const [key, strategy] of this.#definitions) {
try {
if (key in result || key in object) {
const merge = /** @type {Function} */ (strategy.merge);
const value = merge.call(
this,
result[key],
object[key],
);
if (value !== undefined) {
result[key] = value;
}
}
} catch (ex) {
throw new WrapperError(key, ex);
}
}
return result;
}, {});
}
/**
* Validates an object's keys based on the validate strategy for each key.
* @param {Object} object The object to validate.
* @returns {void}
* @throws {Error} When the object is invalid.
*/
validate(object) {
// check existing keys first
for (const key of Object.keys(object)) {
// check to see if the key is defined
if (!this.hasKey(key)) {
throw new UnexpectedKeyError(key);
}
// validate existing keys
const definition = /** @type {PropertyDefinition} */ (
this.#definitions.get(key)
); // `definition` is guaranteed to exist since we check with `hasKey()` above.
// first check to see if any other keys are required
if (Array.isArray(definition.requires)) {
if (
!definition.requires.every(otherKey => otherKey in object)
) {
throw new MissingDependentKeysError(
key,
definition.requires,
);
}
}
// now apply remaining validation strategy
try {
const validate = /** @type {Function} */ (definition.validate);
validate.call(definition, object[key]);
} catch (ex) {
throw new WrapperError(key, ex);
}
}
// ensure required keys aren't missing
for (const [key] of this.#requiredKeys) {
if (!(key in object)) {
throw new MissingKeyError(key);
}
}
}
}
export { MergeStrategy, ObjectSchema, ValidationStrategy };
@@ -0,0 +1,22 @@
/**
* @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 Banana = createLucideIcon("Banana", [
["path", { d: "M4 13c3.5-2 8-2 10 2a5.5 5.5 0 0 1 8 5", key: "1cscit" }],
[
"path",
{
d: "M5.15 17.89c5.52-1.52 8.65-6.89 7-12C11.55 4 11.5 2 13 2c3.22 0 5 5.5 5 8 0 6.5-4.2 12-10.49 12C5.11 22 2 22 2 20c0-1.5 1.14-1.55 3.15-2.11Z",
key: "1y1nbv"
}
]
]);
export { Banana as default };
//# sourceMappingURL=banana.js.map
@@ -0,0 +1,40 @@
import { MiddlewareHandler } from "../../types.js";
//#region src/middleware/etag/index.d.ts
type ETagOptions = {
retainedHeaders?: string[];
weak?: boolean;
generateDigest?: (body: Uint8Array<ArrayBuffer>) => ArrayBuffer | Promise<ArrayBuffer>;
};
/**
* Default headers to pass through on 304 responses. From the spec:
* > The response must not contain a body and must include the headers that
* > would have been sent in an equivalent 200 OK response: Cache-Control,
* > Content-Location, Date, ETag, Expires, and Vary.
*/
export declare const RETAINED_304_HEADERS: string[];
/**
* ETag Middleware for Hono.
*
* @see {@link https://hono.dev/docs/middleware/builtin/etag}
*
* @param {ETagOptions} [options] - The options for the ETag middleware.
* @param {boolean} [options.weak=false] - Define using or not using a weak validation. If true is set, then `W/` is added to the prefix of the value.
* @param {string[]} [options.retainedHeaders=RETAINED_304_HEADERS] - The headers that you want to retain in the 304 Response.
* @param {function(Uint8Array): ArrayBuffer | Promise<ArrayBuffer>} [options.generateDigest] -
* A custom digest generation function. By default, it uses 'SHA-1'
* This function is called with the response body as a `Uint8Array` and should return a hash as an `ArrayBuffer` or a Promise of one.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use('/etag/*', etag())
* app.get('/etag/abc', (c) => {
* return c.text('Hono is hot')
* })
* ```
*/
export declare const etag: (options?: ETagOptions) => MiddlewareHandler;
//#endregion
export {};
@@ -0,0 +1,52 @@
import type { Options, SucraseContext, Transform } from "../index";
import { type ClassInfo } from "../util/getClassInfo";
export interface RootTransformerResult {
code: string;
mappings: Array<number | undefined>;
}
export default class RootTransformer {
private transformers;
private nameManager;
private tokens;
private generatedVariables;
private isImportsTransformEnabled;
private isReactHotLoaderTransformEnabled;
private disableESTransforms;
private helperManager;
constructor(sucraseContext: SucraseContext, transforms: Array<Transform>, enableLegacyBabel5ModuleInterop: boolean, options: Options);
transform(): RootTransformerResult;
processBalancedCode(): void;
processToken(): void;
/**
* Skip past a class with a name and return that name.
*/
processNamedClass(): string;
processClass(): void;
/**
* We want to just handle class fields in all contexts, since TypeScript supports them. Later,
* when some JS implementations support class fields, this should be made optional.
*/
processClassBody(classInfo: ClassInfo, className: string | null): void;
makeConstructorInitCode(constructorInitializerStatements: Array<string>, instanceInitializerNames: Array<string>, className: string): string;
/**
* Normally it's ok to simply remove type tokens, but we need to be more careful when dealing with
* arrow function return types since they can confuse the parser. In that case, we want to move
* the close-paren to the same line as the arrow.
*
* See https://github.com/alangpierce/sucrase/issues/391 for more details.
*/
processPossibleArrowParamEnd(): boolean;
/**
* An async arrow function might be of the form:
*
* async <
* T
* >() => {}
*
* in which case, removing the type parameters will cause a syntax error. Detect this case and
* move the open-paren earlier.
*/
processPossibleAsyncArrowWithTypeParams(): boolean;
processPossibleTypeRange(): boolean;
shiftMappings(mappings: Array<number | undefined>, prefixLength: number): Array<number | undefined>;
}
@@ -0,0 +1 @@
module.exports={C:{"34":0.0331,"50":0.00552,"63":0.00552,"72":0.00552,"79":0.00552,"89":0.00552,"96":0.00552,"102":0.00552,"103":0.00552,"107":0.00552,"111":0.00552,"112":0.06068,"115":0.09929,"120":0.07722,"121":0.171,"123":0.03861,"124":0.04413,"125":0.00552,"127":0.05516,"130":0.01655,"131":0.00552,"132":0.01655,"140":0.03861,"141":0.01655,"142":0.00552,"143":0.02206,"144":0.00552,"146":0.00552,"148":0.00552,"149":0.01103,"150":0.04413,"151":0.00552,"152":0.02758,"153":0.05516,"154":0.18203,"155":0.65089,"156":0.6564,"157":0.02758,_:"2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 51 52 53 54 55 56 57 58 59 60 61 62 64 65 66 67 68 69 70 71 73 74 75 76 77 78 80 81 82 83 84 85 86 87 88 90 91 92 93 94 95 97 98 99 100 101 104 105 106 108 109 110 113 114 116 117 118 119 122 126 128 129 133 134 135 136 137 138 139 145 147 158 159 160 3.5 3.6"},D:{"54":0.00552,"55":0.00552,"59":0.00552,"64":0.00552,"69":0.01103,"71":0.01655,"72":0.00552,"73":0.00552,"74":0.01655,"75":0.01655,"76":0.00552,"77":0.01103,"79":0.01655,"80":0.01655,"81":0.01655,"83":0.00552,"84":0.00552,"86":0.00552,"87":0.04964,"89":0.00552,"90":0.01103,"93":0.01655,"95":0.03861,"96":0.00552,"97":0.00552,"98":0.00552,"99":0.00552,"101":0.01655,"102":0.01103,"103":0.04413,"104":0.01655,"105":0.02758,"106":0.02758,"107":0.01655,"108":0.02206,"109":0.37509,"110":0.02206,"111":0.05516,"112":0.02758,"113":0.00552,"114":0.01655,"115":0.01103,"116":0.08826,"117":0.01655,"118":0.40267,"119":0.15996,"120":0.18754,"121":0.01103,"122":0.03861,"123":0.05516,"124":0.08274,"125":0.00552,"126":0.03861,"127":0.01103,"128":0.04964,"130":0.02206,"131":0.14342,"132":0.01103,"133":0.14342,"134":0.1379,"135":0.11032,"136":0.22064,"137":0.14893,"138":0.24822,"139":0.20409,"140":0.15996,"141":0.16548,"142":0.67847,"143":0.01655,"144":0.04964,"145":0.02758,"146":0.12135,"147":0.1048,"148":0.15445,"149":0.21512,"150":0.55712,"151":2.11814,"152":12.30068,"153":11.23609,"154":2.23398,"155":0.04964,"156":0.00552,_:"4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 56 57 58 60 61 62 63 65 66 67 68 70 78 85 88 91 92 94 100 129 157"},F:{"73":0.00552,"86":0.00552,"90":0.01103,"94":0.00552,"95":0.00552,"100":0.05516,"101":0.0331,"102":0.01103,"106":0.01655,"107":0.01103,"114":0.00552,"115":0.01103,"116":0.00552,"120":0.02206,"121":0.00552,"122":0.00552,"124":0.00552,"126":0.00552,"131":0.00552,"132":0.00552,"133":0.01655,"134":0.07171,"135":0.98185,_:"9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 60 62 63 64 65 66 67 68 69 70 71 72 74 75 76 77 78 79 80 81 82 83 84 85 87 88 89 91 92 93 96 97 98 99 103 104 105 108 109 110 111 112 113 117 118 119 123 125 127 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"14":0.00552,"15":0.00552,"16":0.01103,"18":0.04964,"84":0.00552,"89":0.00552,"90":0.01655,"92":0.14893,"100":0.03861,"109":0.01103,"111":0.00552,"112":0.01103,"114":0.02758,"115":0.00552,"119":0.06068,"120":0.09377,"121":0.01103,"122":0.04964,"124":0.01103,"126":0.00552,"128":0.01655,"137":0.00552,"139":0.04413,"140":0.03861,"141":0.01655,"142":0.01103,"143":0.00552,"144":0.01655,"145":0.0331,"146":0.02758,"147":0.02206,"148":0.02758,"149":0.04413,"150":0.08274,"151":0.2427,"152":2.15676,"153":2.46565,"154":0.50196,_:"12 13 17 79 80 81 83 85 86 87 88 91 93 94 95 96 97 98 99 101 102 103 104 105 106 107 108 110 113 116 117 118 123 125 127 129 130 131 132 133 134 135 136 138"},E:{"12":0.00552,"27":0.02758,_:"4 5 6 7 8 9 10 11 13 14 15 3.1 3.2 5.1 6.1 7.1 9.1 10.1 15.2-15.3 15.4 15.5 16.0 16.1 16.2 16.3 16.4 16.5 17.2 17.4 17.5 18.2 18.4 26.0 26.1 27.1 27.2 TP","11.1":0.00552,"12.1":0.00552,"13.1":0.00552,"14.1":0.02206,"15.1":0.01655,"15.6":0.04413,"16.6":0.0331,"17.0":0.00552,"17.1":0.26477,"17.3":0.00552,"17.6":0.05516,"18.0":0.00552,"18.1":0.00552,"18.3":0.00552,"18.5-18.7":0.00552,"26.2":0.01103,"26.3":0.01103,"26.4":0.01103,"26.5":0.07722,"26.6":0.19306},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00049,"5.0-5.1":0.00049,"6.0-6.1":0,"7.0-7.1":0.00098,"8.1-8.4":0,"9.0-9.2":0,"9.3":0,"10.0-10.2":0,"10.3":0.00489,"11.0-11.2":0.00049,"11.3-11.4":0.00098,"12.0-12.1":0,"12.2-12.5":0.01272,"13.0-13.1":0,"13.2":0.00245,"13.3":0,"13.4-13.7":0.00049,"14.0-14.4":0.00196,"14.5-14.8":0.00294,"15.0-15.1":0.00294,"15.2-15.3":0.00196,"15.4":0.00245,"15.5":0.00294,"15.6-15.8":0.0636,"16.0":0.00489,"16.1":0.00881,"16.2":0.00489,"16.3":0.01076,"16.4":0.00245,"16.5":0.00391,"16.6-16.7":0.08855,"17.0":0.00342,"17.1":0.00489,"17.2":0.00489,"17.3":0.00734,"17.4":0.01027,"17.5":0.02006,"17.6-17.7":0.05186,"18.0":0.01076,"18.1":0.02152,"18.2":0.02935,"18.3":0.05088,"18.4":0.0318,"18.5-18.7":0.657,"26.0":0.0318,"26.1":0.03229,"26.2":0.08414,"26.3":0.09099,"26.4":0.06653,"26.5":0.44567,"26.6":2.74982,"27.0":0.21085,"27.1":0,"27.2":0.005Line truncated
@@ -0,0 +1 @@
{"version":3,"file":"size-rollup-m.js","sources":["../../motion-utils/dist/es/clamp.mjs","../lib/context/LayoutGroupContext.js","../lib/context/LazyContext.js","../lib/context/MotionConfigContext.js","../lib/context/MotionContext/index.js","../../motion-dom/dist/es/animation/utils/is-css-variable.mjs","../../motion-dom/dist/es/value/types/numbers/index.mjs","../../motion-dom/dist/es/value/types/utils/sanitize.mjs","../../motion-dom/dist/es/value/types/utils/float-regex.mjs","../../motion-dom/dist/es/value/types/utils/single-color-regex.mjs","../../motion-dom/dist/es/value/types/color/utils.mjs","../../motion-dom/dist/es/value/types/utils/is-nullish.mjs","../../motion-dom/dist/es/value/types/color/rgba.mjs","../../motion-dom/dist/es/value/types/color/hex.mjs","../../motion-dom/dist/es/value/types/numbers/units.mjs","../../motion-dom/dist/es/value/types/color/hsla.mjs","../../motion-dom/dist/es/value/types/color/index.mjs","../../motion-dom/dist/es/value/types/utils/color-regex.mjs","../../motion-dom/dist/es/value/types/complex/index.mjs","../../motion-dom/dist/es/render/utils/keys-transform.mjs","../../motion-dom/dist/es/render/utils/resolve-variants.mjs","../../motion-dom/dist/es/value/utils/is-motion-value.mjs","../../motion-dom/dist/es/animation/optimized-appear/data-id.mjs","../../motion-dom/dist/es/render/dom/utils/camel-to-dash.mjs","../../motion-dom/dist/es/value/types/int.mjs","../../motion-dom/dist/es/value/types/maps/number.mjs","../../motion-dom/dist/es/value/types/maps/transform.mjs","../../motion-dom/dist/es/value/types/utils/get-as-type.mjs","../../motion-dom/dist/es/render/utils/is-animation-controls.mjs","../../motion-dom/dist/es/render/utils/is-variant-label.mjs","../../motion-dom/dist/es/render/utils/variant-props.mjs","../../motion-dom/dist/es/render/utils/is-controlling-variants.mjs","../../motion-dom/dist/es/render/VisualElement.mjs","../../motion-dom/dist/es/render/html/utils/build-transform.mjs","../../motion-dom/dist/es/render/html/utils/build-styles.mjs","../../motion-dom/dist/es/projection/styles/scale-border-radius.mjs","../../motion-dom/dist/es/projection/styles/scale-box-shadow.mjs","../../motion-dom/dist/es/utils/mix/number.mjs","../../motion-dom/dist/es/projection/styles/scale-correction.mjs","../../motion-dom/dist/es/render/utils/is-forced-motion-value.mjs","../../motion-dom/dist/es/render/html/utils/scrape-motion-values.mjs","../../motion-dom/dist/es/render/svg/utils/path.mjs","../../motion-dom/dist/es/render/svg/utils/build-attrs.mjs","../../motion-dom/dist/es/value/utils/resolve-motion-value.mjs","../lib/context/MotionContext/create.js","../lib/context/MotionContext/utils.js","../lib/render/html/utils/create-render-state.js","../lib/render/html/use-props.js","../lib/render/svg/utils/create-render-state.js","../lib/render/svg/use-props.js","../../motion-dom/dist/es/render/svg/utils/is-svg-tag.mjs","../lib/motion/utils/valid-prop.js","../lib/render/dom/utils/filter-props.js","../lib/render/svg/lowercase-elements.js","../lib/render/dom/utils/is-svg-component.js","../lib/render/dom/use-render.js","../lib/context/PresenceContext.js","../lib/motion/utils/use-visual-state.js","../lib/utils/use-constant.js","../lib/render/html/use-html-visual-state.js","../lib/render/svg/use-svg-visual-state.js","../../motion-dom/dist/es/render/svg/utils/scrape-motion-values.mjs","../lib/motion/features/definitions.js","../lib/motion/utils/symbol.js","../lib/motion/utils/use-motion-ref.js","../lib/context/SwitchLayoutGroupContext.js","../lib/utils/is-ref-object.js","../lib/utils/is-browser.js","../lib/utils/use-isomorphic-effect.js","../lib/motion/utils/use-visual-element.js","../lib/motion/index.js","../lib/render/components/m/create.js","../lib/render/components/m/elements.js","../lib/render/components/m/size.js"],"sourcesContent":["const clamp = (min, max, v) => {\n if (v > max)\n return max;\n if (v < min)\n return min;\n return v;\n};\n\nexport { clamp };\n//# sourceMappingURL=clamp.mjs.map\n","\"use client\";\nimport { createContext } from \"react\";\nexport const LayoutGroupContext = createContext({});\n//# sourceMappingURL=LayoutGroupContext.js.map","\"use client\";\nimport { createContext } from \"react\";\nexport const LazyContext = createContext({ strict: false });\n//# sourceMappingURL=LazyContext.js.map","\"use client\";\nimport { createContext } from \"react\";\n/**\n * @public\n */\nexport const MotionConfigContext = createContext({\n transformPagePoint: (p) => p,\n isStatic: false,\n reducedMotion: \"never\",\n});\n//# sourceMappingURL=MotionConfigContext.js.map","\"use client\";\nimport { createContext } from \"react\";\nexport const MotionContext = /* @__PURE__ */ createContext({});\n//# sourceMappingURL=index.js.map","const checkStringStartsWith = (token) => (key) => typeof key === \"string\" && key.startsWith(token);\nconst isCSSVariableName = \n/*@__PURE__*/ checkStringStartsWith(\"--\");\nconst startsAsVariableToken = \n/*@__PURE__*/ checkStrinLine truncated
@@ -0,0 +1,123 @@
import { URL } from 'node:url'
import Dispatcher from './dispatcher'
import buildConnector from './connector'
import TClientStats from './client-stats'
type ClientConnectOptions = Omit<Dispatcher.ConnectOptions, 'origin'>
/**
* A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default.
*/
export class Client extends Dispatcher {
constructor (url: string | URL, options?: Client.Options)
/** Property to get and set the pipelining factor. */
pipelining: number
/** `true` after `client.close()` has been called. */
closed: boolean
/** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */
destroyed: boolean
/** Aggregate stats for a Client. */
readonly stats: TClientStats
// Override dispatcher APIs.
override connect (
options: ClientConnectOptions
): Promise<Dispatcher.ConnectData>
override connect (
options: ClientConnectOptions,
callback: (err: Error | null, data: Dispatcher.ConnectData) => void
): void
}
export declare namespace Client {
export interface OptionsInterceptors {
Client: readonly Dispatcher.DispatchInterceptor[];
}
export interface Options {
/** TODO */
interceptors?: OptionsInterceptors;
/** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */
maxHeaderSize?: number;
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */
headersTimeout?: number;
/** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */
socketTimeout?: never;
/** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */
requestTimeout?: never;
/** TODO */
connectTimeout?: number;
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */
bodyTimeout?: number;
/** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */
idleTimeout?: never;
/** @deprecated unsupported keepAlive, use pipelining=0 instead */
keepAlive?: never;
/** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */
keepAliveTimeout?: number;
/** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */
maxKeepAliveTimeout?: never;
/** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */
keepAliveMaxTimeout?: number;
/** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */
keepAliveTimeoutThreshold?: number;
/** TODO */
socketPath?: string;
/** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */
pipelining?: number;
/** @deprecated use the connect option instead */
tls?: never;
/** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */
strictContentLength?: boolean;
/** TODO */
maxCachedSessions?: number;
/** TODO */
connect?: Partial<buildConnector.BuildOptions> | buildConnector.connector;
/** TODO */
maxRequestsPerClient?: number;
/** TODO */
localAddress?: string;
/** Max response body size in bytes, -1 is disabled */
maxResponseSize?: number;
/** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */
autoSelectFamily?: boolean;
/** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */
autoSelectFamilyAttemptTimeout?: number;
/**
* @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation.
* @default false
*/
allowH2?: boolean;
/**
* @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
* @default 100
*/
maxConcurrentStreams?: number;
/**
* @description Sets the HTTP/2 stream-level flow-control window size (SETTINGS_INITIAL_WINDOW_SIZE).
* @default 262144
*/
initialWindowSize?: number;
/**
* @description Sets the HTTP/2 connection-level flow-control window size (ClientHttp2Session.setLocalWindowSize).
* @default 524288
*/
connectionWindowSize?: number;
/**
* @description Time interval between PING frames dispatch
* @default 60000
*/
pingInterval?: number;
}
export interface SocketInfo {
localAddress?: string
localPort?: number
remoteAddress?: string
remotePort?: number
remoteFamily?: string
timeout?: number
bytesWritten?: number
bytesRead?: number
}
}
export default Client
@@ -0,0 +1,19 @@
import { Context, Env, MiddlewareHandler } from "hono";
//#region src/serve-static.d.ts
type ServeStaticOptions<E extends Env = Env> = {
/**
* Root path. Relative path is based on current working directory from which the app was started.
*/
root?: string;
path?: string;
index?: string;
precompressed?: boolean; /** Allow percent signs in the routed request path. Defaults to false. */
allowPercentInPath?: boolean;
rewriteRequestPath?: (path: string, c: Context<E>) => string;
onFound?: (path: string, c: Context<E>) => void | Promise<void>;
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>;
};
declare const serveStatic: <E extends Env = any>(options?: ServeStaticOptions<E>) => MiddlewareHandler<E>;
//#endregion
export { ServeStaticOptions, serveStatic };
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_K","2":"_I"},C:{"1":"_PI","2":"_TS","194":"_YF _KH"},D:{"1":"_vO","2":"_hJ","33":"_rB _ZQ"},E:{"1":"_PD","2":"_ZC","33":"_iC PD"},F:{"1":"_uR","2":"_j G _O","33":"_PO"},G:{"1":"_WJ","2":"_EB","33":"_lC _CP"},H:{"2":"1D"},I:{"1":"_YD","2":"_W","33":"6D"},J:{"2":"D","33":"A"},K:{"1":"H","2":"_D"},L:{"1":"I"},M:{"1":"YC"},N:{"2":"_A"},O:{"1":"bC"},P:{"1":"_F"},Q:{"1":"JE"},R:{"1":"KE"},S:{"1":"_C"}},B:4,C:"CSS3 font-kerning",D:true};
@@ -0,0 +1,13 @@
/**
* @fileoverview JSON reporter
* @author Burak Yigit Kaya aka BYK
*/
"use strict";
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = function (results) {
return JSON.stringify(results);
};
@@ -0,0 +1,7 @@
// Generated using scripts/write-decode-map.ts
export default new Uint16Array(
// prettier-ignore
"\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022"
.split("")
.map((c) => c.charCodeAt(0)));
//# sourceMappingURL=decode-data-xml.js.map
@@ -0,0 +1,36 @@
import { D as BindingViteResolvePluginConfig, E as BindingViteReporterPluginConfig, S as BindingViteJsonPluginConfig, T as BindingViteReactRefreshWrapperPluginConfig, b as BindingViteDynamicImportVarsPluginConfig, l as BindingIsolatedDeclarationPluginConfig, s as BindingEsmExternalRequirePluginConfig, w as BindingViteModulePreloadPolyfillPluginConfig, x as BindingViteImportGlobPluginConfig, y as BindingViteBuildImportAnalysisPluginConfig } from "./binding-D26QphWG.mjs";
import { F as BuiltinPlugin, Wt as StringOrRegExp } from "./define-config-BhJ90aEv.mjs";
//#region src/builtin-plugin/constructors.d.ts
declare function viteModulePreloadPolyfillPlugin(config?: BindingViteModulePreloadPolyfillPluginConfig): BuiltinPlugin;
type DynamicImportVarsPluginConfig = Omit<BindingViteDynamicImportVarsPluginConfig, "include" | "exclude"> & {
include?: StringOrRegExp | StringOrRegExp[];
exclude?: StringOrRegExp | StringOrRegExp[];
};
declare function viteDynamicImportVarsPlugin(config?: DynamicImportVarsPluginConfig): BuiltinPlugin;
declare function viteImportGlobPlugin(config?: BindingViteImportGlobPluginConfig): BuiltinPlugin;
declare function viteReporterPlugin(config: BindingViteReporterPluginConfig): BuiltinPlugin;
declare function viteLoadFallbackPlugin(): BuiltinPlugin;
declare function viteJsonPlugin(config: BindingViteJsonPluginConfig): BuiltinPlugin;
declare function viteBuildImportAnalysisPlugin(config: BindingViteBuildImportAnalysisPluginConfig): BuiltinPlugin;
declare function viteResolvePlugin(config: Omit<BindingViteResolvePluginConfig, "yarnPnp">): BuiltinPlugin;
declare function isolatedDeclarationPlugin(config?: BindingIsolatedDeclarationPluginConfig): BuiltinPlugin;
declare function viteWebWorkerPostPlugin(): BuiltinPlugin;
/**
* A plugin that converts CommonJS require() calls for external dependencies into ESM import statements.
*
* @see https://rolldown.rs/builtin-plugins/esm-external-require
* @category Builtin Plugins
*/
declare function esmExternalRequirePlugin(config?: BindingEsmExternalRequirePluginConfig): BuiltinPlugin;
type ViteReactRefreshWrapperPluginConfig = Omit<BindingViteReactRefreshWrapperPluginConfig, "include" | "exclude"> & {
include?: StringOrRegExp | StringOrRegExp[];
exclude?: StringOrRegExp | StringOrRegExp[];
};
/**
* This plugin should not be used for Rolldown.
*/
declare function oxcRuntimePlugin(): BuiltinPlugin;
declare function viteReactRefreshWrapperPlugin(config: ViteReactRefreshWrapperPluginConfig): BuiltinPlugin;
//#endregion
export { viteDynamicImportVarsPlugin as a, viteLoadFallbackPlugin as c, viteReporterPlugin as d, viteResolvePlugin as f, viteBuildImportAnalysisPlugin as i, viteModulePreloadPolyfillPlugin as l, isolatedDeclarationPlugin as n, viteImportGlobPlugin as o, viteWebWorkerPostPlugin as p, oxcRuntimePlugin as r, viteJsonPlugin as s, esmExternalRequirePlugin as t, viteReactRefreshWrapperPlugin as u };
@@ -0,0 +1,670 @@
'use strict'
/**
* @see https://www.rfc-editor.org/rfc/rfc9110.html#name-date-time-formats
*
* @param {string} date
* @returns {Date | undefined}
*/
function parseHttpDate (date) {
// Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
// Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format
switch (date[3]) {
case ',': return parseImfDate(date)
case ' ': return parseAscTimeDate(date)
default: return parseRfc850Date(date)
}
}
function makeDate (year, monthIdx, day, hour, minute, second, weekday) {
const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second))
// Date.UTC treats years 0-99 as 1900-1999. Reset the full year so component
// checks below validate the HTTP date as written.
if (year >= 0 && year <= 99) {
result.setUTCFullYear(year)
}
return result.getUTCFullYear() === year &&
result.getUTCMonth() === monthIdx &&
result.getUTCDate() === day &&
result.getUTCHours() === hour &&
result.getUTCMinutes() === minute &&
result.getUTCSeconds() === second &&
result.getUTCDay() === weekday
? result
: undefined
}
/**
* @see https://httpwg.org/specs/rfc9110.html#preferred.date.format
*
* @param {string} date
* @returns {Date | undefined}
*/
function parseImfDate (date) {
if (
date.length !== 29 ||
date[4] !== ' ' ||
date[7] !== ' ' ||
date[11] !== ' ' ||
date[16] !== ' ' ||
date[19] !== ':' ||
date[22] !== ':' ||
date[25] !== ' ' ||
date[26] !== 'G' ||
date[27] !== 'M' ||
date[28] !== 'T'
) {
return undefined
}
let weekday = -1
if (date[0] === 'S' && date[1] === 'u' && date[2] === 'n') { // Sunday
weekday = 0
} else if (date[0] === 'M' && date[1] === 'o' && date[2] === 'n') { // Monday
weekday = 1
} else if (date[0] === 'T' && date[1] === 'u' && date[2] === 'e') { // Tuesday
weekday = 2
} else if (date[0] === 'W' && date[1] === 'e' && date[2] === 'd') { // Wednesday
weekday = 3
} else if (date[0] === 'T' && date[1] === 'h' && date[2] === 'u') { // Thursday
weekday = 4
} else if (date[0] === 'F' && date[1] === 'r' && date[2] === 'i') { // Friday
weekday = 5
} else if (date[0] === 'S' && date[1] === 'a' && date[2] === 't') { // Saturday
weekday = 6
} else {
return undefined // Not a valid day of the week
}
let day = 0
if (date[5] === '0') {
// Single digit day, e.g. "Sun Nov 6 08:49:37 1994"
const code = date.charCodeAt(6)
if (code < 49 || code > 57) {
return undefined // Not a digit
}
day = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(5)
if (code1 < 49 || code1 > 51) {
return undefined // Not a digit between 1 and 3
}
const code2 = date.charCodeAt(6)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
day = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
let monthIdx = -1
if (
(date[8] === 'J' && date[9] === 'a' && date[10] === 'n')
) {
monthIdx = 0 // Jan
} else if (
(date[8] === 'F' && date[9] === 'e' && date[10] === 'b')
) {
monthIdx = 1 // Feb
} else if (
(date[8] === 'M' && date[9] === 'a')
) {
if (date[10] === 'r') {
monthIdx = 2 // Mar
} else if (date[10] === 'y') {
monthIdx = 4 // May
} else {
return undefined // Invalid month
}
} else if (
(date[8] === 'J')
) {
if (date[9] === 'a' && date[10] === 'n') {
monthIdx = 0 // Jan
} else if (date[9] === 'u') {
if (date[10] === 'n') {
monthIdx = 5 // Jun
} else if (date[10] === 'l') {
monthIdx = 6 // Jul
} else {
return undefined // Invalid month
}
} else {
return undefined // Invalid month
}
} else if (
(date[8] === 'A')
) {
if (date[9] === 'p' && date[10] === 'r') {
monthIdx = 3 // Apr
} else if (date[9] === 'u' && date[10] === 'g') {
monthIdx = 7 // Aug
} else {
return undefined // Invalid month
}
} else if (
(date[8] === 'S' && date[9] === 'e' && date[10] === 'p')
) {
monthIdx = 8 // Sep
} else if (
(date[8] === 'O' && date[9] === 'c' && date[10] === 't')
) {
monthIdx = 9 // Oct
} else if (
(date[8] === 'N' && date[9] === 'o' && date[10] === 'v')
) {
monthIdx = 10 // Nov
} else if (
(date[8] === 'D' && date[9] === 'e' && date[10] === 'c')
) {
monthIdx = 11 // Dec
} else {
// Not a valid month
return undefined
}
const yearDigit1 = date.charCodeAt(12)
if (yearDigit1 < 48 || yearDigit1 > 57) {
return undefined // Not a digit
}
const yearDigit2 = date.charCodeAt(13)
if (yearDigit2 < 48 || yearDigit2 > 57) {
return undefined // Not a digit
}
const yearDigit3 = date.charCodeAt(14)
if (yearDigit3 < 48 || yearDigit3 > 57) {
return undefined // Not a digit
}
const yearDigit4 = date.charCodeAt(15)
if (yearDigit4 < 48 || yearDigit4 > 57) {
return undefined // Not a digit
}
const year = (yearDigit1 - 48) * 1000 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48)
let hour = 0
if (date[17] === '0') {
const code = date.charCodeAt(18)
if (code < 48 || code > 57) {
return undefined // Not a digit
}
hour = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(17)
if (code1 < 48 || code1 > 50) {
return undefined // Not a digit between 0 and 2
}
const code2 = date.charCodeAt(18)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
if (code1 === 50 && code2 > 51) {
return undefined // Hour cannot be greater than 23
}
hour = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
let minute = 0
if (date[20] === '0') {
const code = date.charCodeAt(21)
if (code < 48 || code > 57) {
return undefined // Not a digit
}
minute = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(20)
if (code1 < 48 || code1 > 53) {
return undefined // Not a digit between 0 and 5
}
const code2 = date.charCodeAt(21)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
minute = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
let second = 0
if (date[23] === '0') {
const code = date.charCodeAt(24)
if (code < 48 || code > 57) {
return undefined // Not a digit
}
second = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(23)
if (code1 < 48 || code1 > 53) {
return undefined // Not a digit between 0 and 5
}
const code2 = date.charCodeAt(24)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
second = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
return makeDate(year, monthIdx, day, hour, minute, second, weekday)
}
/**
* @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats
*
* @param {string} date
* @returns {Date | undefined}
*/
function parseAscTimeDate (date) {
// This is assumed to be in UTC
if (
date.length !== 24 ||
date[7] !== ' ' ||
date[10] !== ' ' ||
date[19] !== ' '
) {
return undefined
}
let weekday = -1
if (date[0] === 'S' && date[1] === 'u' && date[2] === 'n') { // Sunday
weekday = 0
} else if (date[0] === 'M' && date[1] === 'o' && date[2] === 'n') { // Monday
weekday = 1
} else if (date[0] === 'T' && date[1] === 'u' && date[2] === 'e') { // Tuesday
weekday = 2
} else if (date[0] === 'W' && date[1] === 'e' && date[2] === 'd') { // Wednesday
weekday = 3
} else if (date[0] === 'T' && date[1] === 'h' && date[2] === 'u') { // Thursday
weekday = 4
} else if (date[0] === 'F' && date[1] === 'r' && date[2] === 'i') { // Friday
weekday = 5
} else if (date[0] === 'S' && date[1] === 'a' && date[2] === 't') { // Saturday
weekday = 6
} else {
return undefined // Not a valid day of the week
}
let monthIdx = -1
if (
(date[4] === 'J' && date[5] === 'a' && date[6] === 'n')
) {
monthIdx = 0 // Jan
} else if (
(date[4] === 'F' && date[5] === 'e' && date[6] === 'b')
) {
monthIdx = 1 // Feb
} else if (
(date[4] === 'M' && date[5] === 'a')
) {
if (date[6] === 'r') {
monthIdx = 2 // Mar
} else if (date[6] === 'y') {
monthIdx = 4 // May
} else {
return undefined // Invalid month
}
} else if (
(date[4] === 'J')
) {
if (date[5] === 'a' && date[6] === 'n') {
monthIdx = 0 // Jan
} else if (date[5] === 'u') {
if (date[6] === 'n') {
monthIdx = 5 // Jun
} else if (date[6] === 'l') {
monthIdx = 6 // Jul
} else {
return undefined // Invalid month
}
} else {
return undefined // Invalid month
}
} else if (
(date[4] === 'A')
) {
if (date[5] === 'p' && date[6] === 'r') {
monthIdx = 3 // Apr
} else if (date[5] === 'u' && date[6] === 'g') {
monthIdx = 7 // Aug
} else {
return undefined // Invalid month
}
} else if (
(date[4] === 'S' && date[5] === 'e' && date[6] === 'p')
) {
monthIdx = 8 // Sep
} else if (
(date[4] === 'O' && date[5] === 'c' && date[6] === 't')
) {
monthIdx = 9 // Oct
} else if (
(date[4] === 'N' && date[5] === 'o' && date[6] === 'v')
) {
monthIdx = 10 // Nov
} else if (
(date[4] === 'D' && date[5] === 'e' && date[6] === 'c')
) {
monthIdx = 11 // Dec
} else {
// Not a valid month
return undefined
}
let day = 0
if (date[8] === ' ') {
// Single digit day, e.g. "Sun Nov 6 08:49:37 1994"
const code = date.charCodeAt(9)
if (code < 49 || code > 57) {
return undefined // Not a digit
}
day = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(8)
if (code1 < 49 || code1 > 51) {
return undefined // Not a digit between 1 and 3
}
const code2 = date.charCodeAt(9)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
day = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
let hour = 0
if (date[11] === '0') {
const code = date.charCodeAt(12)
if (code < 48 || code > 57) {
return undefined // Not a digit
}
hour = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(11)
if (code1 < 48 || code1 > 50) {
return undefined // Not a digit between 0 and 2
}
const code2 = date.charCodeAt(12)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
if (code1 === 50 && code2 > 51) {
return undefined // Hour cannot be greater than 23
}
hour = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
let minute = 0
if (date[14] === '0') {
const code = date.charCodeAt(15)
if (code < 48 || code > 57) {
return undefined // Not a digit
}
minute = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(14)
if (code1 < 48 || code1 > 53) {
return undefined // Not a digit between 0 and 5
}
const code2 = date.charCodeAt(15)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
minute = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
let second = 0
if (date[17] === '0') {
const code = date.charCodeAt(18)
if (code < 48 || code > 57) {
return undefined // Not a digit
}
second = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(17)
if (code1 < 48 || code1 > 53) {
return undefined // Not a digit between 0 and 5
}
const code2 = date.charCodeAt(18)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
second = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
const yearDigit1 = date.charCodeAt(20)
if (yearDigit1 < 48 || yearDigit1 > 57) {
return undefined // Not a digit
}
const yearDigit2 = date.charCodeAt(21)
if (yearDigit2 < 48 || yearDigit2 > 57) {
return undefined // Not a digit
}
const yearDigit3 = date.charCodeAt(22)
if (yearDigit3 < 48 || yearDigit3 > 57) {
return undefined // Not a digit
}
const yearDigit4 = date.charCodeAt(23)
if (yearDigit4 < 48 || yearDigit4 > 57) {
return undefined // Not a digit
}
const year = (yearDigit1 - 48) * 1000 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48)
return makeDate(year, monthIdx, day, hour, minute, second, weekday)
}
/**
* @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats
*
* @param {string} date
* @returns {Date | undefined}
*/
function parseRfc850Date (date) {
let commaIndex = -1
let weekday = -1
if (date[0] === 'S') {
if (date[1] === 'u' && date[2] === 'n' && date[3] === 'd' && date[4] === 'a' && date[5] === 'y') {
weekday = 0 // Sunday
commaIndex = 6
} else if (date[1] === 'a' && date[2] === 't' && date[3] === 'u' && date[4] === 'r' && date[5] === 'd' && date[6] === 'a' && date[7] === 'y') {
weekday = 6 // Saturday
commaIndex = 8
}
} else if (date[0] === 'M' && date[1] === 'o' && date[2] === 'n' && date[3] === 'd' && date[4] === 'a' && date[5] === 'y') {
weekday = 1 // Monday
commaIndex = 6
} else if (date[0] === 'T') {
if (date[1] === 'u' && date[2] === 'e' && date[3] === 's' && date[4] === 'd' && date[5] === 'a' && date[6] === 'y') {
weekday = 2 // Tuesday
commaIndex = 7
} else if (date[1] === 'h' && date[2] === 'u' && date[3] === 'r' && date[4] === 's' && date[5] === 'd' && date[6] === 'a' && date[7] === 'y') {
weekday = 4 // Thursday
commaIndex = 8
}
} else if (date[0] === 'W' && date[1] === 'e' && date[2] === 'd' && date[3] === 'n' && date[4] === 'e' && date[5] === 's' && date[6] === 'd' && date[7] === 'a' && date[8] === 'y') {
weekday = 3 // Wednesday
commaIndex = 9
} else if (date[0] === 'F' && date[1] === 'r' && date[2] === 'i' && date[3] === 'd' && date[4] === 'a' && date[5] === 'y') {
weekday = 5 // Friday
commaIndex = 6
} else {
// Not a valid day name
return undefined
}
if (
date[commaIndex] !== ',' ||
(date.length - commaIndex - 1) !== 23 ||
date[commaIndex + 1] !== ' ' ||
date[commaIndex + 4] !== '-' ||
date[commaIndex + 8] !== '-' ||
date[commaIndex + 11] !== ' ' ||
date[commaIndex + 14] !== ':' ||
date[commaIndex + 17] !== ':' ||
date[commaIndex + 20] !== ' ' ||
date[commaIndex + 21] !== 'G' ||
date[commaIndex + 22] !== 'M' ||
date[commaIndex + 23] !== 'T'
) {
return undefined
}
let day = 0
if (date[commaIndex + 2] === '0') {
// Single digit day, e.g. "Sun Nov 6 08:49:37 1994"
const code = date.charCodeAt(commaIndex + 3)
if (code < 49 || code > 57) {
return undefined // Not a digit
}
day = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(commaIndex + 2)
if (code1 < 49 || code1 > 51) {
return undefined // Not a digit between 1 and 3
}
const code2 = date.charCodeAt(commaIndex + 3)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
day = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
let monthIdx = -1
if (
(date[commaIndex + 5] === 'J' && date[commaIndex + 6] === 'a' && date[commaIndex + 7] === 'n')
) {
monthIdx = 0 // Jan
} else if (
(date[commaIndex + 5] === 'F' && date[commaIndex + 6] === 'e' && date[commaIndex + 7] === 'b')
) {
monthIdx = 1 // Feb
} else if (
(date[commaIndex + 5] === 'M' && date[commaIndex + 6] === 'a' && date[commaIndex + 7] === 'r')
) {
monthIdx = 2 // Mar
} else if (
(date[commaIndex + 5] === 'A' && date[commaIndex + 6] === 'p' && date[commaIndex + 7] === 'r')
) {
monthIdx = 3 // Apr
} else if (
(date[commaIndex + 5] === 'M' && date[commaIndex + 6] === 'a' && date[commaIndex + 7] === 'y')
) {
monthIdx = 4 // May
} else if (
(date[commaIndex + 5] === 'J' && date[commaIndex + 6] === 'u' && date[commaIndex + 7] === 'n')
) {
monthIdx = 5 // Jun
} else if (
(date[commaIndex + 5] === 'J' && date[commaIndex + 6] === 'u' && date[commaIndex + 7] === 'l')
) {
monthIdx = 6 // Jul
} else if (
(date[commaIndex + 5] === 'A' && date[commaIndex + 6] === 'u' && date[commaIndex + 7] === 'g')
) {
monthIdx = 7 // Aug
} else if (
(date[commaIndex + 5] === 'S' && date[commaIndex + 6] === 'e' && date[commaIndex + 7] === 'p')
) {
monthIdx = 8 // Sep
} else if (
(date[commaIndex + 5] === 'O' && date[commaIndex + 6] === 'c' && date[commaIndex + 7] === 't')
) {
monthIdx = 9 // Oct
} else if (
(date[commaIndex + 5] === 'N' && date[commaIndex + 6] === 'o' && date[commaIndex + 7] === 'v')
) {
monthIdx = 10 // Nov
} else if (
(date[commaIndex + 5] === 'D' && date[commaIndex + 6] === 'e' && date[commaIndex + 7] === 'c')
) {
monthIdx = 11 // Dec
} else {
// Not a valid month
return undefined
}
const yearDigit1 = date.charCodeAt(commaIndex + 9)
if (yearDigit1 < 48 || yearDigit1 > 57) {
return undefined // Not a digit
}
const yearDigit2 = date.charCodeAt(commaIndex + 10)
if (yearDigit2 < 48 || yearDigit2 > 57) {
return undefined // Not a digit
}
let year = (yearDigit1 - 48) * 10 + (yearDigit2 - 48) // Convert ASCII codes to number
// RFC 6265 states that the year is in the range 1970-2069.
// @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.1
//
// 3. If the year-value is greater than or equal to 70 and less than or
// equal to 99, increment the year-value by 1900.
// 4. If the year-value is greater than or equal to 0 and less than or
// equal to 69, increment the year-value by 2000.
year += year < 70 ? 2000 : 1900
let hour = 0
if (date[commaIndex + 12] === '0') {
const code = date.charCodeAt(commaIndex + 13)
if (code < 48 || code > 57) {
return undefined // Not a digit
}
hour = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(commaIndex + 12)
if (code1 < 48 || code1 > 50) {
return undefined // Not a digit between 0 and 2
}
const code2 = date.charCodeAt(commaIndex + 13)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
if (code1 === 50 && code2 > 51) {
return undefined // Hour cannot be greater than 23
}
hour = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
let minute = 0
if (date[commaIndex + 15] === '0') {
const code = date.charCodeAt(commaIndex + 16)
if (code < 48 || code > 57) {
return undefined // Not a digit
}
minute = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(commaIndex + 15)
if (code1 < 48 || code1 > 53) {
return undefined // Not a digit between 0 and 5
}
const code2 = date.charCodeAt(commaIndex + 16)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
minute = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
let second = 0
if (date[commaIndex + 18] === '0') {
const code = date.charCodeAt(commaIndex + 19)
if (code < 48 || code > 57) {
return undefined // Not a digit
}
second = code - 48 // Convert ASCII code to number
} else {
const code1 = date.charCodeAt(commaIndex + 18)
if (code1 < 48 || code1 > 53) {
return undefined // Not a digit between 0 and 5
}
const code2 = date.charCodeAt(commaIndex + 19)
if (code2 < 48 || code2 > 57) {
return undefined // Not a digit
}
second = (code1 - 48) * 10 + (code2 - 48) // Convert ASCII codes to number
}
return makeDate(year, monthIdx, day, hour, minute, second, weekday)
}
module.exports = {
parseHttpDate
}
@@ -0,0 +1,43 @@
{
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)",
"name": "which",
"description": "Like which(1) unix command. Find the first instance of an executable in the PATH.",
"version": "2.0.2",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/node-which.git"
},
"main": "which.js",
"bin": {
"node-which": "./bin/node-which"
},
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
},
"devDependencies": {
"mkdirp": "^0.5.0",
"rimraf": "^2.6.2",
"tap": "^14.6.9"
},
"scripts": {
"test": "tap",
"preversion": "npm test",
"postversion": "npm publish",
"prepublish": "npm run changelog",
"prechangelog": "bash gen-changelog.sh",
"changelog": "git add CHANGELOG.md",
"postchangelog": "git commit -m 'update changelog - '${npm_package_version}",
"postpublish": "git push origin --follow-tags"
},
"files": [
"which.js",
"bin/node-which"
],
"tap": {
"check-coverage": true
},
"engines": {
"node": ">= 8"
}
}
@@ -0,0 +1,718 @@
export default `flf2a$ 7 6 20 15 2
Rounded by Nick Miners N.M.Miners@durham.ac.uk
May 1994
$$#
$$#
$$#
$$#
$$#
$$#
$$##
_ #
| |#
| |#
|_|#
_ #
|_|#
##
_ _ #
( )( )#
|/ \\|#
#
#
#
##
_ _ #
_| U |_ #
(_ _)#
_| O |_ #
(_ _)#
|_n_| #
##
_ #
_| |_ #
| ___)#
|___ |#
(_ _|#
|_| #
##
_ _ #
(_) | |#
/ / #
/ / #
/ / _ #
|_| (_)#
##
___ #
/ _ \\ #
( (_) ) #
) _ ( #
( (/ \\ #
\\__/\\_)#
##
_ #
( )#
|/ #
#
#
#
##
_ #
/ )#
| | #
| | #
| | #
\\_)#
##
_ #
( \\ #
| |#
| |#
| |#
(_/ #
##
_ #
_ | | _ #
( \\| |/ )#
) ( #
(_/| |\\_)#
|_| #
##
#
_ #
_| |_ #
(_ _)#
|_| #
#
##
#
#
#
#
_ #
( )#
|/ ##
#
#
_____ #
(_____)#
#
#
##
#
#
#
#
_ #
(_)#
##
_ #
| |#
/ / #
/ / #
/ / #
|_| #
##
_____ #
(_____) #
_ __ _ #
| |/ /| |#
| /_| |#
\\_____/ #
##
___ #
(___) #
_ #
| | #
_| |_ #
(_____)#
##
______ #
(_____ \\ #
____) )#
/ ____/ #
| (_____ #
|_______)#
##
______ #
(_____ \\ #
_____) )#
(_____ ( #
_____) )#
(______/ #
##
_ _ #
| | (_)#
| |_____ #
|_____ |#
| |#
|_|#
##
_______ #
(_______)#
______ #
(_____ \\ #
_____) )#
(______/ #
##
_______ #
(_______)#
______ #
| ___ \\ #
| |___) )#
|______/ #
##
_______ #
(_______)#
_ #
/ ) #
/ / #
(_/ #
##
_____ #
(_____) #
_____ #
/ ___ \\ #
( (___) )#
\\_____/ #
##
_______ #
(_______)#
_______ #
(_____ |#
| |#
|_|#
##
#
#
_ #
(_)#
_ #
(_)#
##
#
#
_ #
(_)#
_ #
( )#
|/ ##
#
_ #
/ )#
( ( #
\\_)#
#
##
#
_____ #
(_____)#
_____ #
(_____)#
#
##
#
_ #
( \\ #
) )#
(_/ #
#
##
___ #
/ _ \\ #
(_( ) )#
(_/ #
_ #
(_) #
##
_____ #
/ __ \\ #
| | / )#
| | \\__/ #
| |____ #
\\_____) #
##
_______ #
(_______)#
_______ #
| ___ |#
| | | |#
|_| |_|#
##
______ #
(____ \\ #
____) )#
| __ ( #
| |__) )#
|______/ #
##
_______ #
(_______)#
_ #
| | #
| |_____ #
\\______)#
##
______ #
(______) #
_ _ #
| | | |#
| |__/ / #
|_____/ #
##
_______ #
(_______)#
_____ #
| ___) #
| |_____ #
|_______)#
##
_______ #
(_______)#
_____ #
| ___) #
| | #
|_| #
##
_______ #
(_______)#
_ ___ #
| | (_ |#
| |___) |#
\\_____/ #
##
_ _ #
(_) (_)#
_______ #
| ___ |#
| | | |#
|_| |_|#
##
_ #
| |#
| |#
| |#
| |#
|_|#
##
_______ #
(_______)#
_ #
_ | | #
| |_| | #
\\___/ #
##
_ _ #
(_) | |#
_____| |#
| _ _)#
| | \\ \\ #
|_| \\_)#
##
_ #
(_) #
_ #
| | #
| |_____ #
|_______)#
##
_______ #
(_______)#
_ _ _ #
| ||_|| |#
| | | |#
|_| |_|#
##
_______ #
(_______)#
_ _ #
| | | |#
| | | |#
|_| |_|#
##
_______ #
(_______)#
_ _ #
| | | |#
| |___| |#
\\_____/ #
##
______ #
(_____ \\ #
_____) )#
| ____/ #
| | #
|_| #
##
_______ #
(_______)#
_ _ #
| | | | #
| |__| | #
\\______)#
##
______ #
(_____ \\ #
_____) )#
| __ / #
| | \\ \\ #
|_| |_|#
##
______ #
/ _____)#
( (____ #
\\____ \\ #
_____) )#
(______/ #
##
_______ #
(_______)#
_ #
| | #
| | #
|_| #
##
_ _ #
(_) (_)#
_ _ #
| | | |#
| |___| |#
\\_____/ #
##
_ _ #
(_) (_)#
_ _ #
| | | |#
\\ \\ / / #
\\___/ #
##
_ _ _ #
(_)(_)(_)#
_ _ _ #
| || || |#
| || || |#
\\_____/ #
##
_ _ #
(_) (_)#
___ #
| | #
/ / \\ \\ #
|_| |_|#
##
_ _ #
| | | |#
| |___| |#
|_____ |#
_____| |#
(_______|#
##
_______ #
(_______)#
__ #
/ / #
/ /____ #
(_______)#
##
___ #
| _)#
| | #
| | #
| |_ #
|___)#
##
_ #
| | #
\\ \\ #
\\ \\ #
\\ \\ #
|_|#
##
___ #
(_ |#
| |#
| |#
_| |#
(___|#
##
__ #
/ \\ #
(_/\\_)#
#
#
#
##
#
#
#
#
_______ #
(_______)#
##
_ #
( )#
\\|#
#
#
#
##
#
#
_____ #
(____ |#
/ ___ |#
\\_____|#
##
_ #
| | #
| |__ #
| _ \\ #
| |_) )#
|____/ #
##
#
#
____ #
/ ___)#
( (___ #
\\____)#
##
_ #
| |#
__| |#
/ _ |#
( (_| |#
\\____|#
##
#
#
_____ #
| ___ |#
| ____|#
|_____)#
##
___ #
/ __)#
_| |__ #
(_ __)#
| | #
|_| #
##
#
#
____ #
/ _ |#
( (_| |#
\\___ |#
(_____|##
_ #
| | #
| |__ #
| _ \\ #
| | | |#
|_| |_|#
##
_ #
(_)#
_ #
| |#
| |#
|_|#
##
_ #
(_)#
_ #
| |#
| |#
_| |#
(__/ ##
_ #
| | #
| | _ #
| |_/ )#
| _ ( #
|_| \\_)#
##
_ #
| | #
| | #
| | #
| | #
\\_)#
##
#
#
____ #
| \\ #
| | | |#
|_|_|_|#
##
#
#
____ #
| _ \\ #
| | | |#
|_| |_|#
##
#
#
___ #
/ _ \\ #
| |_| |#
\\___/ #
##
#
#
____ #
| _ \\ #
| |_| |#
| __/ #
|_| ##
#
#
____ #
/ _ |#
| |_| |#
\\__ |#
|_|##
#
#
____ #
/ ___)#
| | #
|_| #
##
#
#
___ #
/___)#
|___ |#
(___/ #
##
#
_ #
_| |_ #
(_ _)#
| |_ #
\\__)#
##
#
#
_ _ #
| | | |#
| |_| |#
|____/ #
##
#
#
_ _ #
| | | |#
\\ V / #
\\_/ #
##
#
#
_ _ _ #
| | | |#
| | | |#
\\___/ #
##
#
#
_ _ #
( \\ / )#
) X ( #
(_/ \\_)#
##
#
#
_ _ #
| | | |#
| |_| |#
\\__ |#
(____/ ##
#
#
_____ #
(___ )#
/ __/ #
(_____)#
##
__ #
/ _)#
| | #
( ( #
| |_ #
\\__)#
##
_ #
| |#
|_|#
_ #
| |#
|_|#
##
__ #
(_ \\ #
| | #
) )#
_| | #
(__/ #
##
__ _ #
/ \\/ )#
(_/\\__/ #
#
#
#
##
_______ #
(_)___(_)#
_______ #
| ___ |#
| | | |#
|_| |_|#
##
_______ #
(_)___(_)#
_ _ #
| | | |#
| |___| |#
\\_____/ #
##
_ _ #
(_) (_)#
_ _ #
| | | |#
| |___| |#
\\_____/ #
##
_ _ #
(_) (_)#
_____ #
(____ |#
/ ___ |#
\\_____|#
##
_ _ #
(_) (_)#
___ #
/ _ \\ #
| |_| |#
\\___/ #
##
_ _ #
(_) (_)#
_ _ #
| | | |#
| |_| |#
|____/ #
##
___ #
/ _ \\ #
| ( ) )#
| |( ( #
| | ) )#
|_|(_/ #
##
`
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_yO","2":"_0 T"},C:{"1":"_1R","2":"_o _oC _L"},D:{"1":"_zO","2":"_v T"},E:{"1":"_PD","2":"_CI"},F:{"1":"_bJ","2":"_XS"},G:{"1":"_kG","2":"_AI"},H:{"2":"1D"},I:{"1":"I","2":"_G"},J:{"2":"_B"},K:{"1":"H","2":"_D"},L:{"1":"I"},M:{"1":"YC"},N:{"2":"_A"},O:{"1":"bC"},P:{"1":"_yD","2":"_WE"},Q:{"2":"JE"},R:{"1":"KE"},S:{"1":"ME","2":"LE"}},B:4,C:"CSS revert value",D:true};
@@ -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/hasown
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 a single custom sponsorship URL
@@ -0,0 +1,120 @@
function coerce(value) {
if (value instanceof Error) return value.stack || value.message;
return value;
}
function selectColor(colors, namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0;
}
return colors[Math.abs(hash) % colors.length];
}
function matchesTemplate(search, template) {
let searchIndex = 0;
let templateIndex = 0;
let starIndex = -1;
let matchIndex = 0;
while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") {
starIndex = templateIndex;
matchIndex = searchIndex;
templateIndex++;
} else {
searchIndex++;
templateIndex++;
}
else if (starIndex !== -1) {
templateIndex = starIndex + 1;
matchIndex++;
searchIndex = matchIndex;
} else return false;
while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++;
return templateIndex === template.length;
}
function humanize(value) {
if (value >= 1e3) return `${(value / 1e3).toFixed(1)}s`;
return `${value}ms`;
}
let globalNamespaces = "";
function namespaces() {
return globalNamespaces;
}
function createDebug(namespace, options) {
let prevTime;
let enableOverride;
let namespacesCache;
let enabledCache;
const debug = (...args) => {
if (!debug.enabled) return;
const curr = Date.now();
const diff = curr - (prevTime || curr);
prevTime = curr;
args[0] = coerce(args[0]);
if (typeof args[0] !== "string") args.unshift("%O");
let index = 0;
args[0] = args[0].replace(/%([a-z%])/gi, (match, format) => {
if (match === "%%") return "%";
index++;
const formatter = options.formatters[format];
if (typeof formatter === "function") {
const value = args[index];
match = formatter.call(debug, value);
args.splice(index, 1);
index--;
}
return match;
});
options.formatArgs.call(debug, diff, args);
debug.log(...args);
};
debug.extend = function(namespace$1, delimiter = ":") {
return createDebug(this.namespace + delimiter + namespace$1, {
useColors: this.useColors,
color: this.color,
formatArgs: this.formatArgs,
formatters: this.formatters,
inspectOpts: this.inspectOpts,
log: this.log,
humanize: this.humanize
});
};
Object.assign(debug, options);
debug.namespace = namespace;
Object.defineProperty(debug, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride != null) return enableOverride;
if (namespacesCache !== globalNamespaces) {
namespacesCache = globalNamespaces;
enabledCache = enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
return debug;
}
let names = [];
let skips = [];
function enable(namespaces$1) {
globalNamespaces = namespaces$1;
names = [];
skips = [];
const split = globalNamespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean);
for (const ns of split) if (ns[0] === "-") skips.push(ns.slice(1));
else names.push(ns);
}
function disable() {
const namespaces$1 = [...names, ...skips.map((namespace) => `-${namespace}`)].join(",");
enable("");
return namespaces$1;
}
function enabled(name) {
for (const skip of skips) if (matchesTemplate(name, skip)) return false;
for (const ns of names) if (matchesTemplate(name, ns)) return true;
return false;
}
export { namespaces as a, enabled as i, disable as n, humanize as o, enable as r, selectColor as s, createDebug as t };
@@ -0,0 +1,6 @@
"use strict";
const addObject = require("./addObject-BB40bW2H.js");
function add(date, num, unit) {
return typeof num === "object" && num !== null ? addObject.addObject(date, num, 1) : addObject.addNumber(date, num, unit);
}
module.exports = add;
@@ -0,0 +1,645 @@
import { expect, expectTypeOf, test } from "vitest";
import * as zm from "zod/mini";
import * as z from "zod/v4";
test("validate answers like safeParse.success", () => {
expect(z.validate(z.string(), "asdf")).toBe(true);
expect(z.validate(z.string(), 12)).toBe(false);
expect(z.validate(z.number().int().min(0), 5)).toBe(true);
expect(z.validate(z.number().int().min(0), -5)).toBe(false);
const schema = z.object({ a: z.string(), b: z.array(z.number()) });
expect(z.validate(schema, { a: "x", b: [1, 2] })).toBe(true);
expect(z.validate(schema, { a: "x", b: [1, "2"] })).toBe(false);
expect(z.validate(schema, null)).toBe(false);
});
test("validate runs transforms and refinements for the verdict only", () => {
const schema = z
.string()
.transform((s) => s.length)
.pipe(z.number().max(3));
expect(z.validate(schema, "ab")).toBe(true);
expect(z.validate(schema, "abcd")).toBe(false);
expect(z.validate(z.coerce.number(), "5")).toBe(true);
});
test("validate narrows to the input type", () => {
const value: unknown = "hi";
if (z.validate(z.string(), value)) {
expectTypeOf(value).toEqualTypeOf<string>();
}
const transforming = z.string().transform((s) => s.length);
if (z.validate(transforming, value)) {
expectTypeOf(value).toEqualTypeOf<string>();
}
});
test("validate throws on async schemas; validateAsync handles them", async () => {
const schema = z.string().refine(async (s) => s.length > 2);
expect(() => z.validate(schema, "asdf")).toThrow();
await expect(z.validateAsync(schema, "asdf")).resolves.toBe(true);
await expect(z.validateAsync(schema, "a")).resolves.toBe(false);
await expect(z.validateAsync(z.string(), "a")).resolves.toBe(true);
// a promise-returning callback that is not declared async compiles, so the compiled schema must stay off the fast path
const compiled = z.compile(z.string().refine((s) => Promise.resolve(s.length > 1)));
await expect(z.validateAsync(compiled, "abc")).resolves.toBe(true);
await expect(z.validateAsync(compiled, "a")).resolves.toBe(false);
});
test("validate agrees with the compiled fast path and keeps the callback bound", () => {
let calls = 0;
const schema = z.object({
name: z.string().refine((s) => {
calls++;
return s.length > 1;
}),
});
const compiled = z.compile(schema);
calls = 0;
expect(z.validate(compiled, { name: "ok" })).toBe(true);
expect(calls).toBe(1);
calls = 0;
expect(z.validate(compiled, { name: "x" })).toBe(false);
// a user callback can throw, so its rejection is not decidable and the fallback still runs
expect(calls).toBeLessThanOrEqual(2);
expect(z.validate(compiled, { name: 42 })).toBe(false);
expect(z.validate(compiled, { name: "x" }, {})).toBe(false);
expect(z.validate(schema, { name: "ok" })).toBe(true);
});
test("the validate shortcut is taken for callback-free schemas only", () => {
const definite = (s: z.ZodType) => (z.compile(s, { strict: true }) as any)._zod.bag.validator?.definite;
// nothing here can throw, so a compiled rejection is proof the runtime would reject
expect(definite(z.object({ a: z.string().min(1), b: z.number().max(3), c: z.email() }))).toBe(true);
expect(definite(z.array(z.enum(["a", "b"])))).toBe(true);
// each of these can answer INVALID for something the interpreter throws on
expect(definite(z.object({ a: z.string().refine(() => true) }))).toBe(false);
expect(definite(z.string().transform((v) => v))).toBe(false);
expect(definite(z.custom(() => true))).toBe(false);
expect(definite(z.number().catch(0))).toBe(false);
expect(definite(z.lazy(() => z.string()))).toBe(false);
expect(
definite(
z.intersection(
z.number(),
z.number().transform((x) => x + 1)
)
)
).toBe(false);
expect(
definite(
z.record(
z.string().transform((k) => k),
z.number()
)
)
).toBe(false);
});
test("compiled validate keeps the fallback where INVALID is not a decidable rejection", () => {
// an intersection answers INVALID for an unmergeable merge, which the interpreter answers with a throw — a fast false would misreport a schema bug
const unmergeable = z.compile(
z.intersection(
z.number(),
z.number().transform((x) => x + 1)
),
{ strict: true }
);
expect(() => z.validate(unmergeable, 1234)).toThrow("Unmergable intersection");
// a when-gated check islands at codegen, and an island answers INVALID for an async run too
const gated = z.number().refine(() => Promise.resolve(true));
(gated._zod.def.checks![0]!._zod.def as { when?: unknown }).when = () => true;
const compiled = z.compile(z.object({ n: gated }), { strict: true });
expect(() => z.validate(compiled, { n: 3 })).toThrow(z.core.$ZodAsyncError);
expect(() => z.validate(z.object({ n: gated }), { n: 3 })).toThrow(z.core.$ZodAsyncError);
// a plain function handing back a promise answers INVALID for union parity, so a transform is never a decidable rejection
const piped = z.string().transform(() => Promise.resolve(1));
expect(() => z.validate(z.compile(piped, { strict: true }), "x")).toThrow(z.core.$ZodAsyncError);
expect(() => z.validate(piped, "x")).toThrow(z.core.$ZodAsyncError);
// a continuable child issue short-circuits the compiled intersection before its merge, but the interpreter reaches the merge and throws
const continuable = z.intersection(
z.number().min(10),
z.number().transform((x) => x + 1)
);
expect(() => z.validate(z.compile(continuable, { strict: true }), 1)).toThrow("Unmergable intersection");
expect(() => z.validate(continuable, 1)).toThrow("Unmergable intersection");
});
test("compiled validate agrees with the interpreter, verdict and throw alike", () => {
// guards the `definite` flag: a new generator that answers INVALID for something the interpreter throws on must clear it, or this fails
const thenable = () => Promise.resolve(1) as never;
const schemas: z.ZodType[] = [
z.object({ a: z.string(), b: z.number().min(1) }),
z.strictObject({ a: z.string() }),
z.array(z.string().min(1)),
z.tuple([z.string()], z.number()),
z.record(z.string(), z.number()),
// a record key compiles in its own context, so its definiteness has to be carried out
z.record(z.string().transform(thenable), z.number()),
z.record(z.email(), z.number()),
z.union([z.string(), z.number()]),
z.intersection(
z.number(),
z.number().transform((x) => x + 1)
),
z.intersection(
z.number().min(10),
z.number().transform((x) => x + 1)
),
// unmergeable with no user callback in it, so only the intersection itself can clear the flag
z.intersection(z.string().default("a"), z.string().default("b")),
z.lazy(() => z.object({ a: z.string() })),
z.number().catch(0),
z.nonoptional(z.string().optional()),
z.map(z.string(), z.number()),
z.set(z.string().min(2)),
z.templateLiteral(["a", z.number()]),
z.coerce.number(),
z.stringbool(),
z.string().transform(thenable),
z.union([z.string().transform(thenable), z.number()]),
z.array(z.string().transform(thenable)),
z.custom(thenable),
z.string().refine(thenable),
z.string().pipe(z.string().min(3)),
// a codec's decode is the pipe branch's transform, and a plain function can still hand back a promise
z.codec(z.string(), z.number(), { decode: thenable, encode: String }),
z.object({ first: z.string(), second: z.codec(z.string(), z.number(), { decode: thenable, encode: String }) }),
// a continuable check does not settle the interpreter's walk, so it reaches a throwing callback the compiled path short-circuits past — the first-failure exit does not cover the check chain
z
.string()
.min(5)
.refine(() => {
throw new RangeError("u");
}),
z
.string()
.min(5)
.superRefine(() => {
throw new RangeError("u");
}),
// a user callback can throw, and compiled code can reject an earlier sibling before ever reaching it
z.object({
first: z.string(),
second: z.string().refine(() => {
throw new RangeError("u");
}),
}),
z.object({
first: z.string(),
second: z.custom(() => {
throw new TypeError("u");
}),
}),
// superRefine and check take the other branch of the refine generator than refine does
z.object({
first: z.string(),
second: z.string().superRefine(() => {
throw new RangeError("u");
}),
}),
z.string().superRefine(thenable as never),
z.object({
first: z.string(),
second: z.string().transform(() => {
throw new RangeError("u");
}),
}),
z.object({ first: z.string(), second: z.custom(thenable) }),
z.tuple([
z.string(),
z.number().catch(() => {
throw new RangeError("u");
}),
]),
];
const inputs = [
"x",
"ab",
"",
0,
1,
Number.NaN,
true,
null,
undefined,
{},
{ a: "x" },
{ a: 1 },
[],
["x"],
new Map(),
new Set(["a"]),
"true",
// the exposing shape: an earlier field the compiled path rejects before it reaches the throwing one
{ first: 1, second: "s" },
{ first: "s", second: "s" },
{ first: 1 },
[1, "x"],
["s", "x"],
];
const outcome = (fn: () => unknown) => {
try {
return `ok:${fn()}`;
} catch (err) {
return `throw:${(err as Error)?.constructor?.name}`;
}
};
for (const schema of schemas) {
let compiled: z.ZodType;
try {
compiled = z.compile(schema, { strict: true });
} catch {
continue; // refused at codegen, so there is no fast path to disagree
}
for (const input of inputs) {
expect(
outcome(() => z.validate(compiled, input)),
`${JSON.stringify(input)} on ${schema._zod.def.type}`
).toBe(outcome(() => z.validate(schema, input)));
}
}
});
test("validate is exported from zod/mini", () => {
expect(zm.validate(zm.string(), "a")).toBe(true);
expect(zm.validate(zm.string(), 1)).toBe(false);
expect(zm.validate(zm.object({ a: zm.number() }), { a: 1 })).toBe(true);
});
test("the validate method matches the top-level function", () => {
expect(z.string().validate("asdf")).toBe(true);
expect(z.string().validate(12)).toBe(false);
expect(z.object({ a: z.string() }).validate({ a: "x" })).toBe(true);
expect(z.object({ a: z.string() }).validate({ a: 1 })).toBe(false);
expect(z.compile(z.object({ a: z.string() })).validate({ a: "x" })).toBe(true);
});
test("the validate method narrows to the input type", () => {
const value: unknown = "hi";
if (z.string().validate(value)) {
expectTypeOf(value).toEqualTypeOf<string>();
}
const transforming = z.string().transform((s) => s.length);
if (transforming.validate(value)) {
expectTypeOf(value).toEqualTypeOf<string>();
expectTypeOf(value).not.toEqualTypeOf<number>();
}
});
test("the validate method takes a params argument", () => {
let calls = 0;
const error = () => {
calls++;
return "bad";
};
expect(z.string().validate(12, { error })).toBe(false);
expect(z.string().validate("ok", { error })).toBe(true);
// a ctx defeats the compiled definite shortcut, so this is the fallback answering
expect(z.compile(z.string()).validate(12, { error })).toBe(false);
expect(z.string().validate("ok", { jitless: true })).toBe(true);
// no issue is ever finalized, so an error map never runs
expect(calls).toBe(0);
});
test("the validateAsync method handles async schemas the method form throws on", async () => {
const schema = z.string().refine(async (s) => s.length > 2);
expect(() => schema.validate("asdf")).toThrow(z.core.$ZodAsyncError);
await expect(schema.validateAsync("asdf")).resolves.toBe(true);
await expect(schema.validateAsync("a")).resolves.toBe(false);
await expect(z.string().validateAsync(12)).resolves.toBe(false);
});
test("zod/mini has no validate method", () => {
const schema = zm.string();
expect("parse" in schema).toBe(true);
expect("validate" in schema).toBe(false);
expect("validateAsync" in schema).toBe(false);
});
// counts reads of each child slot, so a stopped walk is observable without putting a callback in the schema — a refinement spy would work too, but reading the input says nothing about what ran
function counted(
slots: Record<string, unknown>,
bad: Record<string, unknown> = {}
): [Record<string, unknown>, () => number] {
let reads = 0;
const obj: Record<string, unknown> = { ...bad };
for (const [k, v] of Object.entries(slots)) {
Object.defineProperty(obj, k, {
enumerable: true,
get() {
reads++;
return v;
},
});
}
return [obj, () => reads];
}
test("validate stops a container at its first aborting issue", () => {
const shape = { a: z.number(), b: z.string(), c: z.string() };
for (const jitless of [false, true]) {
const label = jitless ? "interpreted" : "compiled";
const [input, reads] = counted({ b: "x", c: "x" }, { a: "no" });
expect(z.validate(z.object(shape), input, { jitless }), label).toBe(false);
expect(reads(), `${label}: keys read after the first abort`).toBe(0);
const [ok, okReads] = counted({ b: "x", c: "x" }, { a: 1 });
expect(z.validate(z.object(shape), ok, { jitless }), label).toBe(true);
expect(okReads(), `${label}: a valid parse still reads every key`).toBe(2);
}
// an array stops at the first bad element
const arr: unknown[] = [1];
let elementReads = 0;
for (const i of [1, 2]) {
Object.defineProperty(arr, i, {
enumerable: true,
get() {
elementReads++;
return "x";
},
});
}
expect(z.validate(z.array(z.string()), arr)).toBe(false);
expect(elementReads, "elements read after the first abort").toBe(0);
// the shape phase's abort carries across into the catchall
const [co, coReads] = counted({ b: "x" }, { a: "no" });
expect(z.validate(z.object({ a: z.number() }).catchall(z.string()), co)).toBe(false);
expect(coReads(), "catchall keys read after the shape aborted").toBe(0);
// and a tuple's fixed items carry into its rest
const tup: unknown[] = ["no"];
let restReads = 0;
for (const i of [1, 2]) {
Object.defineProperty(tup, i, {
enumerable: true,
get() {
restReads++;
return "x";
},
});
}
expect(z.validate(z.tuple([z.number()], z.string()), tup)).toBe(false);
expect(restReads, "rest elements read after a fixed item aborted").toBe(0);
});
test("a default provider runs only when the key is absent", () => {
const boom = (): never => {
throw new RangeError("boom");
};
// the provider sits behind an accessor, so reading the def would call it
for (const [name, schema] of [
["default", z.object({ a: z.number(), b: z.string().default(boom as any) })],
["prefault", z.object({ a: z.number(), b: z.string().prefault(boom as any) })],
] as const) {
expect(z.validate(schema, { a: "bad", b: "ok" }), name).toBe(false);
expect(z.validate(schema, { a: 1, b: "ok" }), name).toBe(true);
}
// absent, the provider does run, and its throw is the parse's own
expect(() => z.validate(z.object({ b: z.string().default(boom as any) }), {})).toThrow(RangeError);
});
test("the first failure stops the walk whatever follows it", () => {
// a sibling after the failure is never parsed, so its refinement never runs
let calls = 0;
const spy = z.string().refine(() => {
calls++;
return true;
});
expect(z.validate(z.object({ a: z.number(), b: spy, c: spy }), { a: "no", b: "x", c: "x" })).toBe(false);
expect(calls).toBe(0);
// reads of the trailing key say whether the walk stopped, without putting a callback in the schema
const skips = (b: z.ZodType, value: unknown = "x") => {
let reads = 0;
const input: Record<string, unknown> = { a: "no" };
Object.defineProperty(input, "b", {
enumerable: true,
get() {
reads++;
return value;
},
});
z.validate(z.object({ a: z.number(), b }), input);
return reads === 0;
};
// the trailing key is skipped no matter what it holds -- user code included, since it is never reached
for (const [name, b, value] of [
["plain", z.string(), "x"],
["min", z.string().min(2), "x"],
["email", z.email(), "x"],
["array", z.array(z.string().min(2)), ["ab"]],
["error map", z.string({ error: () => "nope" }), "x"],
["transform", z.string().transform((v) => v), "x"],
["refine", z.string().refine(() => true), "x"],
["custom", z.custom(() => true), "x"],
["catch", z.string().catch("x"), "x"],
["lazy", z.lazy(() => z.string()), "x"],
["coerce", z.coerce.number(), 1],
] as [string, z.ZodType, unknown][]) {
expect(skips(b, value), name).toBe(true);
}
});
test("a continuable issue never stops the walk", () => {
// .min() is continuable, so a surrounding schema can still reconcile it and the guard must not stop
let calls = 0;
const el = z
.string()
.min(5)
.refine(() => {
calls++;
return true;
});
expect(z.validate(z.array(el), ["a", "b", "c"])).toBe(false);
expect(calls).toBe(3);
});
test("z.record keeps walking under validate", () => {
// deliberate asymmetry: a record's invalid_key aborts, but an enclosing intersection reconciles it against the sibling operand, so a stopped loop hides keys the sibling does not own
let reads = 0;
const input: Record<string, unknown> = { a: 1 };
for (const k of ["b", "c"]) {
Object.defineProperty(input, k, {
enumerable: true,
get() {
reads++;
return "x";
},
});
}
expect(z.validate(z.record(z.string(), z.string()), input)).toBe(false);
expect(reads).toBe(2);
});
test("validate matches safeParse where an issue can still be reconciled away", async () => {
const recA = z.record(z.string().regex(/^a/), z.any());
const recB = z.record(z.string().regex(/^b/), z.any());
const schemas: z.ZodType[] = [
z.intersection(recA, recB),
z.intersection(recA.pipe(z.any()), recB.pipe(z.any())),
z.intersection(z.strictObject({ a: z.string() }), z.strictObject({ b: z.number() })),
z.intersection(z.array(z.string()), z.array(z.string().min(2))),
z.strictObject({ a: z.string() }).pipe(z.any()),
z.union([z.strictObject({ a: z.string() }), z.strictObject({ a: z.string(), b: z.number() })]),
z.array(z.string()).catch([]),
z.object({ a: z.string() }).optional(),
];
const inputs: unknown[] = [
{ a1: 1, b1: 2 },
{ a1: 1, b1: 2, zz: 3 },
{ a1: 1, zz: 2, b1: 3, yy: 4 },
{ b1: 1, a1: 2, zz: 3, yy: 4 },
{ a: "x", b: 1 },
{ a: "x", b: 1, c: 9 },
{ a: "x" },
["ab", "cd"],
["a", "b"],
undefined,
];
const outcome = (fn: () => unknown) => {
try {
return `ok:${fn()}`;
} catch (err) {
return `throw:${(err as Error)?.constructor?.name}`;
}
};
const outcomeAsync = async (fn: () => Promise<unknown>) => {
try {
return `ok:${await fn()}`;
} catch (err) {
return `throw:${(err as Error)?.constructor?.name}`;
}
};
for (const schema of schemas) {
for (const input of inputs) {
const label = `${schema._zod.def.type} on ${JSON.stringify(input)}`;
expect(
outcome(() => z.validate(schema, input)),
label
).toBe(outcome(() => schema.safeParse(input).success));
expect(await outcomeAsync(() => z.validateAsync(schema, input)), label).toBe(
await outcomeAsync(async () => (await schema.safeParseAsync(input)).success)
);
}
}
});
test("abortEarly does not leak into safeParse", () => {
const schema = z.object({ a: z.string(), b: z.string(), c: z.string() });
expect(schema.safeParse({ a: 1, b: 2, c: 3 }).error!.issues).toHaveLength(3);
expect(z.validate(schema, { a: 1, b: 2, c: 3 })).toBe(false);
expect(schema.safeParse({ a: 1, b: 2, c: 3 }).error!.issues).toHaveLength(3);
});
test("a callback after the first failure never runs, so validate answers where safeParse throws", () => {
const boom = (): never => {
throw new RangeError("boom");
};
// the deliberate divergence, in every shape that can carry a callback: an earlier sibling settles the boolean, so the later throw is never reached
const lateSym = Symbol("late");
const cases: [string, z.ZodType, unknown][] = [
["object transform", z.object({ a: z.number(), b: z.string().transform(boom) }), { a: "bad", b: "ok" }],
["object refine", z.object({ a: z.number(), b: z.string().refine(boom) }), { a: "bad", b: "ok" }],
["object custom", z.object({ a: z.number(), b: z.custom(boom) }), { a: "bad", b: "ok" }],
// these three hang the callback off `_zod.check` rather than the def
["object check", z.object({ a: z.number(), b: z.string().check(boom) }), { a: "bad", b: "ok" }],
["object superRefine", z.object({ a: z.number(), b: z.string().superRefine(boom) }), { a: "bad", b: "ok" }],
["object overwrite", z.object({ a: z.number(), b: z.string().overwrite(boom as any) }), { a: "bad", b: "ok" }],
// the input must carry the same symbol with a value the field accepts, or the transform never runs and the row asserts nothing
[
"symbol key",
z.object({ a: z.number(), [lateSym]: z.string().transform(boom) } as any),
{ a: "bad", [lateSym]: "ok" },
],
["object catch", z.object({ a: z.number(), b: z.string().catch(boom) }), { a: "bad", b: 1 }],
["object lazy", z.object({ a: z.number(), b: z.lazy(() => z.string().transform(boom)) }), { a: "bad", b: "ok" }],
["array", z.array(z.union([z.number(), z.string().transform(boom)])), [true, "throws"]],
["tuple rest", z.tuple([z.number()], z.string().transform(boom)), ["bad", "throws"]],
["catchall", z.object({ a: z.number() }).catchall(z.string().transform(boom)), { a: "bad", b: "ok" }],
["set", z.set(z.union([z.number(), z.string().transform(boom)])), new Set([true, "throws"])],
[
"map",
z.map(z.string(), z.union([z.number(), z.string().transform(boom)])),
new Map<any, any>([
[1, 0],
["k", "throws"],
]),
],
];
const outcome = (fn: () => unknown) => {
try {
return `ok:${fn()}`;
} catch (err) {
return `throw:${(err as Error)?.constructor?.name}`;
}
};
for (const [name, schema, input] of cases) {
// safeParse walks the whole tree and reaches the throw; validate settled the answer at the earlier sibling and never runs it
expect(
outcome(() => schema.safeParse(input).success),
`${name}: safeParse`
).toBe("throw:RangeError");
expect(
outcome(() => z.validate(schema, input)),
`${name}: validate`
).toBe("ok:false");
}
});
test("the stop lands between children, not inside one", () => {
const boom = (): never => {
throw new RangeError("boom");
};
// both parse as a unit, so an abort in one half cannot skip the other; stopping inside either risks a discarded issue turning a false into a true
const pairs: [string, z.ZodType, unknown][] = [
["map entry", z.map(z.number(), z.string().transform(boom)), new Map([["bad", "ok"]])],
["tuple fixed item", z.tuple([z.number(), z.string().transform(boom)]), ["bad", "ok"]],
];
for (const [name, schema, input] of pairs) {
expect(() => z.validate(schema, input), name).toThrow(RangeError);
expect(() => schema.safeParse(input), `${name}: safeParse agrees`).toThrow(RangeError);
}
// between children, the stop does happen
expect(z.validate(z.object({ a: z.number(), b: z.string().transform(boom) }), { a: "bad", b: "ok" })).toBe(false);
expect(z.validate(z.array(z.union([z.number(), z.string().transform(boom)])), [true, "ok"])).toBe(false);
});
test("validate rethrows a callback it actually reaches", () => {
const boom = (): never => {
throw new RangeError("boom");
};
// nothing rejects before the callback, so validate reaches it and the throw is the caller's
const cases: [string, z.ZodType, unknown][] = [
["transform", z.object({ a: z.string().transform(boom), b: z.number() }), { a: "ok", b: "bad" }],
["refine", z.object({ a: z.string().refine(boom), b: z.number() }), { a: "ok", b: "bad" }],
["check", z.object({ a: z.string().check(boom), b: z.number() }), { a: "ok", b: "bad" }],
["array element", z.array(z.string().transform(boom)), ["ok", "ok"]],
["catchall", z.object({}).catchall(z.string().transform(boom)), { a: "ok" }],
["set", z.set(z.string().transform(boom)), new Set(["ok"])],
["map", z.map(z.string(), z.string().transform(boom)), new Map([["k", "ok"]])],
["tuple rest", z.tuple([z.string()], z.string().transform(boom)), ["ok", "ok"]],
];
for (const [name, schema, input] of cases) {
expect(() => z.validate(schema, input), name).toThrow(RangeError);
}
});
@@ -0,0 +1,16 @@
import { color } from '../color/index.mjs';
import { complex } from '../complex/index.mjs';
import { dimensionValueTypes } from '../dimensions.mjs';
import { testValueType } from '../test.mjs';
/**
* A list of all ValueTypes
*/
const valueTypes = [...dimensionValueTypes, color, complex];
/**
* Tests a value against the list of ValueTypes
*/
const findValueType = (v) => valueTypes.find(testValueType(v));
export { findValueType };
//# sourceMappingURL=find.mjs.map
@@ -0,0 +1,711 @@
'use strict'
const { normalizeIPv6, removeDotSegments, removeDotSegmentsRelative, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require('./lib/utils')
const { SCHEMES, getSchemeHandler } = require('./lib/schemes')
const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u
const MALFORMED_SCHEME_ERROR = 'URI scheme is malformed.'
const MALFORMED_HOST_ERROR = 'URI host is malformed.'
// ASCII characters outside the RFC 3986 reg-name set (unreserved, sub-delims
// and "%" for pct-encoded): C0 controls, space, DEL, and "#/:<>?@[\]^`{|}.
const FORBIDDEN_DOMAIN_HOST_CHARACTER = /[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u
/**
* RFC 3986 section 3.1 does not allow percent-encoding in a scheme, so the
* scheme is validated as-is and never decoded. Decoding would let inert input
* such as `%6Aavascript:` become a live `javascript:` scheme.
*
* @param {string} scheme
* @returns {string}
*/
function validateScheme (scheme) {
const stringScheme = String(scheme)
if (!VALID_SCHEME.test(stringScheme)) {
throw new TypeError(MALFORMED_SCHEME_ERROR)
}
return stringScheme
}
/**
* @template {import('./types/index').URIComponent|string} T
* @param {T} uri
* @param {import('./types/index').Options} [options]
* @returns {T}
*/
function normalize (uri, options) {
if (typeof uri === 'string') {
uri = /** @type {T} */ (normalizeString(uri, options))
} else if (typeof uri === 'object') {
uri = /** @type {T} */ (parse(serialize(uri, options), options))
}
return uri
}
/**
* @param {string} baseURI
* @param {string} relativeURI
* @param {import('./types/index').Options} [options]
* @returns {string}
*/
function resolve (baseURI, relativeURI, options) {
const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }
const {
parsed: baseParsed,
malformedAuthorityOrPort: baseMalformed,
malformedPercentEncoding: baseMalformedPercentEncoding,
malformedSchemeSpecific: baseMalformedSchemeSpecific,
malformedHost: baseMalformedHost,
malformedScheme: baseMalformedScheme
} = parseWithStatus(baseURI, schemelessOptions)
const {
parsed: relativeParsed,
malformedAuthorityOrPort: relativeMalformed,
malformedPercentEncoding: relativeMalformedPercentEncoding,
malformedSchemeSpecific: relativeMalformedSchemeSpecific,
malformedHost: relativeMalformedHost,
malformedScheme: relativeMalformedScheme
} = parseWithStatus(relativeURI, schemelessOptions)
if (
baseMalformed ||
relativeMalformed ||
baseMalformedPercentEncoding ||
relativeMalformedPercentEncoding ||
baseMalformedSchemeSpecific ||
relativeMalformedSchemeSpecific ||
baseMalformedHost ||
relativeMalformedHost ||
baseMalformedScheme ||
relativeMalformedScheme
) {
throw new Error(baseParsed.error || relativeParsed.error || 'URI is malformed.')
}
const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true)
const resolvedSchemeHandler = getSchemeHandler((options && options.scheme) || resolved.scheme)
const resolvedHost = resolved.host
const resolvedHostIsIP = resolvedHost !== undefined && resolvedHost !== '' &&
(isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6)
// Inputs are parsed scheme-neutrally, so delimiters and controls in a domain
// host are only detected here, once the final scheme is known. They always
// fail closed, including in percent-encoded hosts.
if (hasForbiddenDomainHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP)) {
throw new Error(MALFORMED_HOST_ERROR)
}
canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP)
// Percent escapes in an ASCII reg-name are encoded data. The WHATWG hostname
// parser can reject them even though fast-uri preserves them safely as RFC
// 3986 data. A raw non-ASCII host must still fail closed if conversion fails.
const encodedASCIIHost = resolvedHost && resolvedHost.indexOf('%') !== -1 &&
!/\P{ASCII}/u.test(resolvedHost)
if (resolved.error && !encodedASCIIHost) {
throw new Error(resolved.error)
}
schemelessOptions.skipEscape = true
return serialize(resolved, schemelessOptions)
}
/**
* @param {import ('./types/index').URIComponent} base
* @param {import ('./types/index').URIComponent} relative
* @param {import('./types/index').Options} [options]
* @param {boolean} [skipNormalization=false]
* @returns {import ('./types/index').URIComponent}
*/
function resolveComponent (base, relative, options, skipNormalization) {
/** @type {import('./types/index').URIComponent} */
const target = {}
if (!skipNormalization) {
base = parse(serialize(base, options), options) // normalize base component
relative = parse(serialize(relative, options), options) // normalize relative component
}
options = options || {}
if (!options.tolerant && relative.scheme) {
target.scheme = relative.scheme
// target.authority = relative.authority;
target.userinfo = relative.userinfo
target.host = relative.host
target.port = relative.port
target.path = removeDotSegments(relative.path || '')
target.query = relative.query
} else {
if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
// target.authority = relative.authority;
target.userinfo = relative.userinfo
target.host = relative.host
target.port = relative.port
target.path = removeDotSegments(relative.path || '')
target.query = relative.query
} else {
if (!relative.path) {
target.path = base.path
if (relative.query !== undefined) {
target.query = relative.query
} else {
target.query = base.query
}
} else {
if (relative.path[0] === '/') {
target.path = removeDotSegments(relative.path)
} else {
const baseHasAuthority = base.userinfo !== undefined || base.host !== undefined || base.port !== undefined
if (baseHasAuthority && !base.path) {
target.path = '/' + relative.path
} else if (!base.path) {
target.path = relative.path
} else {
target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path
}
target.path = base.scheme === undefined && !baseHasAuthority && target.path[0] !== '/'
? removeDotSegmentsRelative(target.path)
: removeDotSegments(target.path)
}
target.query = relative.query
}
// target.authority = base.authority;
target.userinfo = base.userinfo
target.host = base.host
target.port = base.port
}
target.scheme = base.scheme
}
target.fragment = relative.fragment
return target
}
/**
* @param {import ('./types/index').URIComponent|string} uriA
* @param {import ('./types/index').URIComponent|string} uriB
* @param {import ('./types/index').Options} options
* @returns {boolean}
*/
function equal (uriA, uriB, options) {
const normalizedA = normalizeComparableURI(uriA, options)
const normalizedB = normalizeComparableURI(uriB, options)
return normalizedA !== undefined && normalizedB !== undefined && normalizedA === normalizedB
}
/**
* @param {Readonly<import('./types/index').URIComponent>} cmpts
* @param {import('./types/index').Options} [opts]
* @returns {string}
*/
function serialize (cmpts, opts) {
const component = {
host: cmpts.host,
scheme: cmpts.scheme,
userinfo: cmpts.userinfo,
port: cmpts.port,
path: cmpts.path,
query: cmpts.query,
nid: cmpts.nid,
nss: cmpts.nss,
uuid: cmpts.uuid,
fragment: cmpts.fragment,
reference: cmpts.reference,
resourceName: cmpts.resourceName,
secure: cmpts.secure,
error: ''
}
const options = Object.assign({}, opts)
const uriTokens = []
if (component.scheme) {
component.scheme = validateScheme(component.scheme)
}
// find scheme handler
const schemeHandler = getSchemeHandler(options.scheme || component.scheme)
// perform scheme specific serialization
if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options)
const hasAuthority = component.userinfo !== undefined || component.host !== undefined || component.port !== undefined
// A reference with no emitted scheme is path-noscheme: a bare ':' in its
// first path segment would reparse as a scheme (RFC 3986 3.3/4.2). Enforced
// under skipEscape too (resolve()), so the reapply below gates on this flag.
const schemelessReference = (component.scheme === undefined || options.reference === 'suffix') && !hasAuthority
const pathNoScheme = !options.skipEscape && schemelessReference
if (component.path !== undefined) {
if (!options.skipEscape) {
component.path = serializePathEncoding(component.path, pathNoScheme)
} else {
component.path = normalizePercentEncoding(component.path)
}
}
if (options.reference !== 'suffix' && component.scheme) {
// Scheme handlers may replace the scheme during serialization.
component.scheme = validateScheme(component.scheme)
uriTokens.push(component.scheme, ':')
}
const authority = recomposeAuthority(component)
if (authority !== undefined) {
if (options.reference !== 'suffix') {
uriTokens.push('//')
}
uriTokens.push(authority)
if (component.path && component.path[0] !== '/') {
uriTokens.push('/')
}
}
if (component.path !== undefined) {
let s = component.path
if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
// A relative-path reference keeps its unresolvable leading ".." segments
// and must never become root-relative (RFC 3986 section 5.2.4 applies to
// merged target paths, not to the reference itself).
s = schemelessReference && s[0] !== '/'
? removeDotSegmentsRelative(s)
: removeDotSegments(s)
}
// Dot-segment removal can expose a colon that was not originally in the
// first segment (for example, "./a:b"). Reapply path-noscheme encoding so
// the serialized relative reference cannot be reparsed as a URI scheme.
if (schemelessReference) {
s = serializePathEncoding(s, true)
}
if (
authority === undefined &&
s[0] === '/' &&
s[1] === '/'
) {
// don't allow the path to start with "//"
s = '/%2F' + s.slice(2)
}
uriTokens.push(s)
}
if (component.query !== undefined) {
uriTokens.push('?', encodeQuery(component.query))
}
if (component.fragment !== undefined) {
uriTokens.push('#', encodeFragment(component.fragment))
}
return uriTokens.join('')
}
const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u
// Captures the authority component (between "//" and the next "/", "?" or "#"),
// with or without a scheme prefix, for the literal-backslash rejection below.
const AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/
// Captures the leading authority-introducer region after an optional scheme: a
// run of forward slashes, backslashes, and the characters the WHATWG URL parser
// removes before parsing (TAB U+0009, LF U+000A, CR U+000D). A valid introducer
// is exactly "//". Node treats "\" as "/" on special schemes and strips those
// characters first, so forms like "\\", "/\", "\/", "/<TAB>/", or a leading
// "<TAB>//" reach an authority in Node while fast-uri's URI_PARSE folds them into
// the path group (host confusion / SSRF / redirect bypass).
const AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/
/**
* @param {import('./types/index').URIComponent} parsed
* @param {RegExpMatchArray} matches
* @returns {string|undefined}
*/
function getParseError (parsed, matches) {
if (matches[2] !== undefined && parsed.path && parsed.path[0] !== '/') {
return 'URI path must start with "/" when authority is present.'
}
if (typeof parsed.port === 'number' && (parsed.port < 0 || parsed.port > 65535)) {
return 'URI port is malformed.'
}
return undefined
}
/**
* Checks percent syntax without decoding the represented octets. RFC 3986
* percent-encoding is byte-oriented, so sequences such as `%FF` are valid even
* though they are not independently valid UTF-8.
*
* @param {string|undefined} component
* @returns {boolean}
*/
function hasMalformedPercentEncoding (component) {
if (component === undefined) return false
let percent = component.indexOf('%')
while (percent !== -1) {
if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {
return true
}
percent = component.indexOf('%', percent + 3)
}
return false
}
/**
* Whether the host is a bracketed IP literal (RFC 3986 `IP-literal`).
* An unterminated `[` is not a literal, so it must still be validated as a
* reg-name instead of being waved through as an IP.
*
* @param {string} host
* @returns {boolean}
*/
function isIPLiteral (host) {
return host[0] === '[' && host[host.length - 1] === ']'
}
/**
* @param {RegExpMatchArray} matches
* @returns {boolean}
*/
function hasMalformedComponentPercentEncoding (matches) {
// Bracketed IP literals use a raw "%" as the zone separator for historical
// compatibility. Their parsing is intentionally left to normalizeIPv6.
const host = matches[4]
return hasMalformedPercentEncoding(matches[3]) ||
(host !== undefined && !isIPLiteral(host) && hasMalformedPercentEncoding(host)) ||
hasMalformedPercentEncoding(matches[6]) ||
hasMalformedPercentEncoding(matches[7]) ||
hasMalformedPercentEncoding(matches[8])
}
/**
* @param {import('./types/index').URIComponent} parsed
* @param {import('./types/index').Options} options
* @param {{ domainHost?: boolean, unicodeSupport?: boolean }|undefined} schemeHandler
* @param {boolean} isIP
* @returns {boolean} whether host conversion failed
*/
function canonicalizeHost (parsed, options, schemeHandler, isIP) {
if (hasForbiddenDomainHost(parsed, options, schemeHandler, isIP)) {
parsed.error = parsed.error || MALFORMED_HOST_ERROR
return true
}
if (
!options.unicodeSupport &&
(!schemeHandler || !schemeHandler.unicodeSupport) &&
parsed.host &&
!isIPLiteral(parsed.host) &&
(options.domainHost || (schemeHandler && schemeHandler.domainHost)) &&
isIP === false &&
nonSimpleDomain(parsed.host)
) {
let url
try {
url = new URL('http://' + parsed.host)
} catch (e) {
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e
return true
}
// The WHATWG parser must have read the whole input as a host. Anything
// else means it found a delimiter fast-uri did not, so its hostname would
// describe a different authority.
if (!isHostOnlyURL(url)) {
parsed.error = parsed.error || MALFORMED_HOST_ERROR
return true
}
parsed.host = url.hostname
}
return false
}
/**
* Whether a domain host contains an ASCII character that RFC 3986 does not
* allow in a reg-name (unreserved, sub-delims, or pct-encoded). Such a host is
* rejected instead of being handed to the WHATWG URL parser, which would treat
* "@" as a userinfo delimiter (silently dropping the data before it) and strip
* TAB, LF, and CR. Non-ASCII characters remain allowed for IDNs.
*
* @param {import('./types/index').URIComponent} parsed
* @param {import('./types/index').Options} options
* @param {{ domainHost?: boolean }|undefined} schemeHandler
* @param {boolean} isIP
* @returns {boolean}
*/
function hasForbiddenDomainHost (parsed, options, schemeHandler, isIP) {
return Boolean(
parsed.host &&
isIP === false &&
!isIPLiteral(parsed.host) &&
(options.domainHost || (schemeHandler && schemeHandler.domainHost)) &&
FORBIDDEN_DOMAIN_HOST_CHARACTER.test(parsed.host)
)
}
/**
* @param {URL} url
* @returns {boolean}
*/
function isHostOnlyURL (url) {
return url.username === '' &&
url.password === '' &&
url.port === '' &&
url.pathname === '/' &&
url.search === '' &&
url.hash === '' &&
url.hostname !== ''
}
/**
* @param {string} uri
* @param {import('./types/index').Options} [opts]
* @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
*/
function parseWithStatus (uri, opts) {
const options = Object.assign({}, opts)
/** @type {import('./types/index').URIComponent} */
const parsed = {
scheme: undefined,
userinfo: undefined,
host: '',
port: undefined,
path: '',
query: undefined,
fragment: undefined
}
let malformedAuthorityOrPort = false
let malformedPercentEncoding = false
let malformedSchemeSpecific = false
let malformedHost = false
let malformedIPLiteral = false
let malformedScheme = false
let isIP = false
if (options.reference === 'suffix') {
if (options.scheme) {
uri = options.scheme + ':' + uri
} else {
uri = '//' + uri
}
}
// A literal backslash (U+005C) is not a valid RFC 3986 URI character and is
// not an authority delimiter. Reject it in the authority rather than
// rewriting it: normalizing "\" -> "/" (WHATWG error recovery) could silently
// change the resource identified by an otherwise-invalid input, and lets "\"
// act as a host delimiter here while Node's native URL parses a different
// host (SSRF / redirect / origin-allowlist bypass). Percent-encoded %5C is
// untouched and remains valid encoded data.
const authorityMatch = uri.match(AUTHORITY_PREFIX)
if (authorityMatch !== null && authorityMatch[1].indexOf('\\') !== -1) {
parsed.error = 'URI authority must not contain a literal backslash.'
malformedAuthorityOrPort = true
}
// Reject a malformed or whitespace-smuggled authority introducer. fast-uri
// only recognizes a literal "//"; anything else in the leading separator run
// (a backslash, or a "//" that appears only after removing the TAB/LF/CR that
// Node strips) means the authority fast-uri parses differs from the one Node's
// URL resolves. Reject rather than rewrite, mirroring the literal-backslash
// guard above. Percent-encoded forms (%5C, %09) are untouched, valid data.
const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION)
if (introducerMatch !== null) {
const region = introducerMatch[1]
const normalizedRegion = region.replace(/[\t\n\r]/g, '')
// Two or more leading separators introduce an authority.
if (normalizedRegion.length >= 2) {
if (normalizedRegion.slice(0, 2) !== '//') {
parsed.error = parsed.error || 'URI authority must not contain a literal backslash.'
malformedAuthorityOrPort = true
} else if (region.length !== normalizedRegion.length) {
parsed.error = parsed.error || 'URI authority introducer must not contain whitespace.'
malformedAuthorityOrPort = true
}
}
}
const matches = uri.match(URI_PARSE)
if (matches) {
// store each component
parsed.scheme = matches[1]
parsed.userinfo = matches[3]
parsed.host = matches[4]
parsed.port = parseInt(matches[5], 10)
parsed.path = matches[6] || ''
parsed.query = matches[7]
parsed.fragment = matches[8]
if (parsed.scheme !== undefined) {
if (VALID_SCHEME.test(parsed.scheme)) {
parsed.scheme = parsed.scheme.toLowerCase()
} else {
parsed.error = parsed.error || MALFORMED_SCHEME_ERROR
malformedScheme = true
}
}
malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches)
if (malformedPercentEncoding) {
parsed.error = parsed.error || 'URI contains malformed percent-encoding.'
}
// fix port number
if (isNaN(parsed.port)) {
parsed.port = matches[5]
}
const parseError = getParseError(parsed, matches)
if (parseError !== undefined) {
parsed.error = parsed.error || parseError
malformedAuthorityOrPort = true
}
if (parsed.host) {
const ipv4result = isIPv4(parsed.host)
if (ipv4result === false) {
const bracketedIPLiteral = isIPLiteral(parsed.host)
const hasIPLiteralBracket = parsed.host.indexOf('[') !== -1 || parsed.host.indexOf(']') !== -1
const ipv6result = normalizeIPv6(parsed.host)
isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true
malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true)
parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase()
if (malformedIPLiteral) {
parsed.error = parsed.error || MALFORMED_HOST_ERROR
malformedAuthorityOrPort = true
}
} else {
isIP = true
}
}
if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {
parsed.reference = 'same-document'
} else if (parsed.scheme === undefined) {
parsed.reference = 'relative'
} else if (parsed.fragment === undefined) {
parsed.reference = 'absolute'
} else {
parsed.reference = 'uri'
}
// check for reference errors
if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {
parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'
}
// find scheme handler
const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme)
// convert Unicode IDN -> ASCII IDN when the effective scheme uses domain hosts
if (!malformedIPLiteral) {
malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP)
}
if (uri.indexOf('%') !== -1 && parsed.host !== undefined && !malformedIPLiteral) {
let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true)
if (!isIP) {
// Fold reg-name case after decoding unreserved octets. The second
// pass only restores uppercase hex in escapes that remain encoded.
host = normalizePercentEncoding(host.toLowerCase())
}
// Resolution parses both inputs with the internal `null` scheme before
// the effective scheme is known. Keep raw host delimiters for that step
// so resolve() can reject them for domain-host schemes; the resolved
// authority is encoded when it is serialized.
parsed.host = isIP || options.scheme !== 'null' ? reescapeHostDelimiters(host, isIP) : host
}
if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
if (parsed.path) {
parsed.path = normalizePathEncoding(parsed.path)
}
if (parsed.query) {
parsed.query = normalizeQueryFragmentEncoding(parsed.query)
}
if (parsed.fragment) {
parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment)
}
}
// perform scheme specific parsing
if (schemeHandler && schemeHandler.parse) {
schemeHandler.parse(parsed, options)
if (schemeHandler === SCHEMES.urn && parsed.nid === undefined) {
malformedSchemeSpecific = true
}
}
} else {
parsed.error = parsed.error || 'URI can not be parsed.'
}
return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }
}
/**
* @param {string} uri
* @param {import('./types/index').Options} [opts]
* @returns
*/
function parse (uri, opts) {
return parseWithStatus(uri, opts).parsed
}
/**
* @param {string} uri
* @param {import('./types/index').Options} [opts]
* @returns {string}
*/
function normalizeString (uri, opts) {
return normalizeStringWithStatus(uri, opts).normalized
}
/**
* @param {string} uri
* @param {import('./types/index').Options} [opts]
* @returns {{ normalized: string, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
*/
function normalizeStringWithStatus (uri, opts) {
const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts)
return {
normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
malformedAuthorityOrPort,
malformedPercentEncoding,
malformedSchemeSpecific,
malformedHost,
malformedScheme
}
}
/**
* @param {import ('./types/index').URIComponent|string} uri
* @param {import('./types/index').Options} [opts]
* @returns {string|undefined}
*/
function normalizeComparableURI (uri, opts) {
if (typeof uri !== 'string' && typeof uri !== 'object') {
return undefined
}
let value
try {
value = typeof uri === 'string' ? uri : serialize(uri, opts)
} catch {
return undefined
}
const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts)
return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? undefined : normalized
}
const fastUri = {
SCHEMES,
normalize,
resolve,
resolveComponent,
equal,
serialize,
parse
}
module.exports = fastUri
module.exports.default = fastUri
module.exports.fastUri = fastUri
@@ -0,0 +1,516 @@
import { LazyRoute } from './fileRoute.cjs';
import { NotFoundError } from './not-found.cjs';
import { RedirectFnRoute } from './redirect.cjs';
import { NavigateOptions, ParsePathParams } from './link.cjs';
import { ParsedLocation } from './location.cjs';
import { AnyRouteMatch, MakePreValidationErrorHandlingRouteMatchUnion, MakeRouteMatchFromRoute, MakeRouteMatchUnion, RouteMatch } from './Matches.cjs';
import { RootRouteId } from './root.cjs';
import { ParseRoute, RouteById, RouteIds, RoutePaths } from './routeInfo.cjs';
import { AnyRouter, Register, RegisteredRouter, SSROption } from './router.cjs';
import { BuildLocationFn, NavigateFn } from './RouterProvider.cjs';
import { Assign, Awaitable, Constrain, Expand, IntersectAssign, LooseAsyncReturnType, LooseReturnType, NoInfer } from './utils.cjs';
import { AnySchema, AnyStandardSchemaValidator, AnyValidator, AnyValidatorAdapter, AnyValidatorObj, DefaultValidator, ResolveSearchValidatorInput, ResolveValidatorOutput, StandardSchemaValidator, ValidatorAdapter, ValidatorFn, ValidatorObj } from './validators.cjs';
import { ValidateSerializableLifecycleResult } from './ssr/serializer/transformer.cjs';
export type AnyPathParams = {};
export type SearchSchemaInput = {
__TSearchSchemaInput__: 'TSearchSchemaInput';
};
export type AnyContext = {};
export interface RouteContext {
}
export type PreloadableObj = {
preload?: () => Promise<void>;
};
export type RoutePathOptions<TCustomId, TPath> = {
path: TPath;
} | {
id: TCustomId;
};
export interface StaticDataRouteOption {
}
export type RoutePathOptionsIntersection<TCustomId, TPath> = {
path: TPath;
id: TCustomId;
};
export type SearchFilter<TInput, TResult = TInput> = (prev: TInput) => TResult;
export type SearchMiddlewareContext<TSearchSchema> = {
search: TSearchSchema;
next: (newSearch: TSearchSchema) => TSearchSchema;
};
export type SearchMiddleware<TSearchSchema> = (ctx: SearchMiddlewareContext<TSearchSchema>) => TSearchSchema;
export type ResolveId<TParentRoute, TCustomId extends string, TPath extends string> = TParentRoute extends {
id: infer TParentId extends string;
} ? RoutePrefix<TParentId, string extends TCustomId ? TPath : TCustomId> : RootRouteId;
export type InferFullSearchSchema<TRoute> = TRoute extends {
types: {
fullSearchSchema: infer TFullSearchSchema;
};
} ? TFullSearchSchema : {};
export type InferFullSearchSchemaInput<TRoute> = TRoute extends {
types: {
fullSearchSchemaInput: infer TFullSearchSchemaInput;
};
} ? TFullSearchSchemaInput : {};
export type InferAllParams<TRoute> = TRoute extends {
types: {
allParams: infer TAllParams;
};
} ? TAllParams : {};
export type InferAllContext<TRoute> = unknown extends TRoute ? TRoute : TRoute extends {
types: {
allContext: infer TAllContext;
};
} ? TAllContext : {};
export type ResolveSearchSchemaFnInput<TSearchValidator> = TSearchValidator extends (input: infer TSearchSchemaInput) => any ? TSearchSchemaInput extends SearchSchemaInput ? Omit<TSearchSchemaInput, keyof SearchSchemaInput> : ResolveSearchSchemaFn<TSearchValidator> : AnySchema;
export type ResolveSearchSchemaInput<TSearchValidator> = TSearchValidator extends AnyStandardSchemaValidator ? NonNullable<TSearchValidator['~standard']['types']>['input'] : TSearchValidator extends AnyValidatorAdapter ? TSearchValidator['types']['input'] : TSearchValidator extends AnyValidatorObj ? ResolveSearchSchemaFnInput<TSearchValidator['parse']> : ResolveSearchSchemaFnInput<TSearchValidator>;
export type ResolveSearchSchemaFn<TSearchValidator> = TSearchValidator extends (...args: any) => infer TSearchSchema ? TSearchSchema : AnySchema;
export type ResolveSearchSchema<TSearchValidator> = unknown extends TSearchValidator ? TSearchValidator : TSearchValidator extends AnyStandardSchemaValidator ? NonNullable<TSearchValidator['~standard']['types']>['output'] : TSearchValidator extends AnyValidatorAdapter ? TSearchValidator['types']['output'] : TSearchValidator extends AnyValidatorObj ? ResolveSearchSchemaFn<TSearchValidator['parse']> : ResolveSearchSchemaFn<TSearchValidator>;
export type ResolveRequiredParams<TPath extends string, T> = {
[K in ParsePathParams<TPath>['required']]: T;
};
export type ResolveOptionalParams<TPath extends string, T> = {
[K in ParsePathParams<TPath>['optional']]?: T | undefined;
};
export type ResolveParams<TPath extends string, T = string> = ResolveRequiredParams<TPath, T> & ResolveOptionalParams<TPath, T>;
export type ParseParamsFn<in out TPath extends string, in out TParams> = (rawParams: Expand<ResolveParams<TPath>>) => TParams | false;
type ValidateParsedParams<TPath extends string, TParams> = [TParams] extends [
ResolveParams<TPath, any>
] ? unknown : never;
export type StringifyParamsFn<in out TPath extends string, in out TParams> = (params: TParams) => ResolveParams<TPath>;
export type ParamsOptions<in out TPath extends string, in out TParams> = {
params?: {
parse?: ParseParamsFn<TPath, TParams> & ValidateParsedParams<TPath, TParams>;
stringify?: StringifyParamsFn<TPath, TParams>;
};
/**
@deprecated Use params.parse instead
*/
parseParams?: ParseParamsFn<TPath, TParams> & ValidateParsedParams<TPath, TParams>;
/**
@deprecated Use params.stringify instead
*/
stringifyParams?: StringifyParamsFn<TPath, TParams>;
};
interface RequiredStaticDataRouteOption {
staticData: StaticDataRouteOption;
}
interface OptionalStaticDataRouteOption {
staticData?: StaticDataRouteOption;
}
export type UpdatableStaticRouteOption = {} extends StaticDataRouteOption ? OptionalStaticDataRouteOption : RequiredStaticDataRouteOption;
export type MetaDescriptor = {
charSet: 'utf-8';
} | {
title: string;
} | {
name: string;
content: string;
} | {
property: string;
content: string;
} | {
httpEquiv: string;
content: string;
} | {
'script:ld+json': LdJsonObject;
} | {
tagName: 'meta' | 'link';
[name: string]: string;
} | Record<string, unknown>;
type LdJsonObject = {
[Key in string]: LdJsonValue;
} & {
[Key in string]?: LdJsonValue | undefined;
};
type LdJsonArray = Array<LdJsonValue> | ReadonlyArray<LdJsonValue>;
type LdJsonPrimitive = string | number | boolean | null;
type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
export type RouteLinkEntry = {};
export type SearchValidator<TInput, TOutput> = ValidatorObj<TInput, TOutput> | ValidatorFn<TInput, TOutput> | ValidatorAdapter<TInput, TOutput> | StandardSchemaValidator<TInput, TOutput> | undefined;
export type AnySearchValidator = SearchValidator<any, any>;
export type DefaultSearchValidator = SearchValidator<Record<string, unknown>, AnySchema>;
export type RoutePrefix<TPrefix extends string, TPath extends string> = string extends TPath ? RootRouteId : TPath extends string ? TPrefix extends RootRouteId ? TPath extends '/' ? '/' : `/${TrimPath<TPath>}` : `${TPrefix}/${TPath}` extends '/' ? '/' : `/${TrimPathLeft<`${TrimPathRight<TPrefix>}/${TrimPath<TPath>}`>}` : never;
export type TrimPath<T extends string> = '' extends T ? '' : TrimPathRight<TrimPathLeft<T>>;
export type TrimPathLeft<T extends string> = T extends `${RootRouteId}/${infer U}` ? TrimPathLeft<U> : T extends `/${infer U}` ? TrimPathLeft<U> : T;
export type TrimPathRight<T extends string> = T extends '/' ? '/' : T extends `${infer U}/` ? TrimPathRight<U> : T;
export type ContextReturnType<TContextFn> = unknown extends TContextFn ? TContextFn : LooseReturnType<TContextFn> extends never ? AnyContext : LooseReturnType<TContextFn>;
export type ContextAsyncReturnType<TContextFn> = unknown extends TContextFn ? TContextFn : LooseAsyncReturnType<TContextFn> extends never ? AnyContext : LooseAsyncReturnType<TContextFn>;
export type ResolveRouteContext<TRouteContextFn, TBeforeLoadFn> = Assign<ContextReturnType<TRouteContextFn>, ContextAsyncReturnType<TBeforeLoadFn>>;
export type ResolveRouteLoaderFn<TLoaderFn> = TLoaderFn extends {
handler: infer THandler;
} ? THandler : TLoaderFn;
export type RouteLoaderObject<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TParams = {}, TLoaderDeps = {}, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TServerMiddlewares = unknown, THandlers = undefined> = {
handler: RouteLoaderFn<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>;
staleReloadMode?: LoaderStaleReloadMode;
};
export type ResolveLoaderData<TLoaderFn> = unknown extends TLoaderFn ? TLoaderFn : LooseAsyncReturnType<ResolveRouteLoaderFn<TLoaderFn>> extends never ? undefined : LooseAsyncReturnType<ResolveRouteLoaderFn<TLoaderFn>>;
export type ResolveFullSearchSchema<TParentRoute extends AnyRoute, TSearchValidator> = unknown extends TParentRoute ? ResolveValidatorOutput<TSearchValidator> : IntersectAssign<InferFullSearchSchema<TParentRoute>, ResolveValidatorOutput<TSearchValidator>>;
export type ResolveFullSearchSchemaInput<TParentRoute extends AnyRoute, TSearchValidator> = IntersectAssign<InferFullSearchSchemaInput<TParentRoute>, ResolveSearchValidatorInput<TSearchValidator>>;
export type ResolveAllParamsFromParent<TParentRoute extends AnyRoute, TParams> = Assign<InferAllParams<TParentRoute>, TParams>;
export type RouteContextParameter<TParentRoute extends AnyRoute, TRouterContext> = unknown extends TParentRoute ? TRouterContext : Assign<TRouterContext, InferAllContext<TParentRoute>>;
export type BeforeLoadContextParameter<TParentRoute extends AnyRoute, TRouterContext, TRouteContextFn> = Assign<RouteContextParameter<TParentRoute, TRouterContext>, ContextReturnType<TRouteContextFn>>;
export type ResolveAllContext<TParentRoute extends AnyRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn> = Assign<BeforeLoadContextParameter<TParentRoute, TRouterContext, TRouteContextFn>, ContextAsyncReturnType<TBeforeLoadFn>>;
export interface FullSearchSchemaOption<in out TParentRoute extends AnyRoute, in out TSearchValidator> {
search: Expand<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>;
}
export interface RemountDepsOptions<in out TRouteId, in out TFullSearchSchema, in out TAllParams, in out TLoaderDeps> {
routeId: TRouteId;
search: TFullSearchSchema;
params: TAllParams;
loaderDeps: TLoaderDeps;
}
export type MakeRemountDepsOptionsUnion<TRouteTree extends AnyRoute = RegisteredRouter['routeTree']> = ParseRoute<TRouteTree> extends infer TRoute extends AnyRoute ? TRoute extends any ? RemountDepsOptions<TRoute['id'], TRoute['types']['fullSearchSchema'], TRoute['types']['allParams'], TRoute['types']['loaderDeps']> : never : never;
export interface RouteTypes<in out TRegister, in out TParentRoute extends AnyRoute, in out TPath extends string, in out TFullPath extends string, in out TCustomId extends string, in out TId extends string, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps, in out TLoaderFn, in out TChildren, in out TFileRouteTypes, in out TSSR, in out TServerMiddlewares, in out THandlers> {
parentRoute: TParentRoute;
path: TPath;
to: TrimPathRight<TFullPath>;
fullPath: TFullPath;
customId: TCustomId;
id: TId;
searchSchema: ResolveValidatorOutput<TSearchValidator>;
searchSchemaInput: ResolveSearchValidatorInput<TSearchValidator>;
searchValidator: TSearchValidator;
fullSearchSchema: ResolveFullSearchSchema<TParentRoute, TSearchValidator>;
fullSearchSchemaInput: ResolveFullSearchSchemaInput<TParentRoute, TSearchValidator>;
params: TParams;
allParams: ResolveAllParamsFromParent<TParentRoute, TParams>;
routerContext: TRouterContext;
routeContext: ResolveRouteContext<TRouteContextFn, TBeforeLoadFn>;
routeContextFn: TRouteContextFn;
beforeLoadFn: TBeforeLoadFn;
allContext: ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>;
children: TChildren;
loaderData: ResolveLoaderData<TLoaderFn>;
loaderDeps: TLoaderDeps;
fileRouteTypes: TFileRouteTypes;
ssr: ResolveSSR<TSSR>;
allSsr: ResolveAllSSR<TParentRoute, TSSR>;
}
export type ResolveSSR<TSSR> = TSSR extends (...args: ReadonlyArray<any>) => any ? LooseReturnType<TSSR> : TSSR;
export type ResolveAllSSR<TParentRoute extends AnyRoute, TSSR> = unknown extends TParentRoute ? ResolveSSR<TSSR> : unknown extends TSSR ? TParentRoute['types']['allSsr'] : ResolveSSR<TSSR>;
export type ResolveFullPath<TParentRoute extends AnyRoute, TPath extends string, TPrefixed = RoutePrefix<TParentRoute['fullPath'], TPath>> = TPrefixed extends RootRouteId ? '/' : TPrefixed;
export interface RouteExtensions<in out TId, in out TFullPath> {
id: TId;
fullPath: TFullPath;
}
export type RouteLazyFn<TRoute extends AnyRoute> = (lazyFn: () => Promise<LazyRoute<TRoute>>) => TRoute;
export type RouteAddChildrenFn<in out TRegister, in out TParentRoute extends AnyRoute, in out TPath extends string, in out TFullPath extends string, in out TCustomId extends string, in out TId extends string, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps extends Record<string, any>, in out TLoaderFn, in out TFileRouteTypes, in out TSSR, in out TServerMiddlewares, in out THandlers> = <const TNewChildren>(children: Constrain<TNewChildren, ReadonlyArray<AnyRoute> | Record<string, AnyRoute>>) => Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TNewChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
export type RouteAddFileChildrenFn<in out TRegister, in out TParentRoute extends AnyRoute, in out TPath extends string, in out TFullPath extends string, in out TCustomId extends string, in out TId extends string, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps extends Record<string, any>, in out TLoaderFn, in out TFileRouteTypes, in out TSSR, in out TServerMiddlewares, in out THandlers> = <const TNewChildren>(children: TNewChildren) => Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TNewChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
export type RouteAddFileTypesFn<TRegister, TParentRoute extends AnyRoute, TPath extends string, TFullPath extends string, TCustomId extends string, TId extends string, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps extends Record<string, any>, TLoaderFn, TChildren, TSSR, TServerMiddlewares, THandlers> = <TNewFileRouteTypes>() => Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TNewFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
export interface Route<in out TRegister, in out TParentRoute extends AnyRoute, in out TPath extends string, in out TFullPath extends string, in out TCustomId extends string, in out TId extends string, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps extends Record<string, any>, in out TLoaderFn, in out TChildren, in out TFileRouteTypes, in out TSSR, in out TServerMiddlewares, in out THandlers> extends RouteExtensions<TId, TFullPath> {
path: TPath;
parentRoute: TParentRoute;
children?: TChildren;
types: RouteTypes<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
options: RouteOptions<TRegister, TParentRoute, TId, TCustomId, TFullPath, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers>;
isRoot: TParentRoute extends AnyRoute ? true : false;
lazyFn?: () => Promise<LazyRoute<Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>>>;
rank: number;
to: TrimPathRight<TFullPath>;
init: (opts: {
originalIndex: number;
}) => void;
update: (options: UpdatableRouteOptions<TParentRoute, TCustomId, TFullPath, TParams, TSearchValidator, TLoaderFn, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn>) => this;
lazy: RouteLazyFn<Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>>;
addChildren: RouteAddChildrenFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
_addFileChildren: RouteAddFileChildrenFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
_addFileTypes: RouteAddFileTypesFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TSSR, TServerMiddlewares, THandlers>;
/**
* Create a redirect with `from` automatically set to this route's path.
* Enables relative redirects like `Route.redirect({ to: './overview' })`.
* @param opts Redirect options (same as `redirect()` but without `from`)
* @returns A redirect Response that can be thrown from loaders/beforeLoad
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction
*/
redirect: RedirectFnRoute<TFullPath>;
}
export type AnyRoute = Route<any, any, any, any, any, any, any, any, any, any, any, any, any, any, any, any, any, any>;
export type AnyRouteWithContext<TContext> = AnyRoute & {
types: {
allContext: TContext;
};
};
export type RouteOptions<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TCustomId extends string = string, TFullPath extends string = string, TPath extends string = string, TSearchValidator = undefined, TParams = AnyPathParams, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> = BaseRouteOptions<TRegister, TParentRoute, TId, TCustomId, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers> & UpdatableRouteOptions<NoInfer<TParentRoute>, NoInfer<TCustomId>, NoInfer<TFullPath>, NoInfer<TParams>, NoInfer<TSearchValidator>, NoInfer<TLoaderFn>, NoInfer<TLoaderDeps>, NoInfer<TRouterContext>, NoInfer<TRouteContextFn>, NoInfer<TBeforeLoadFn>>;
export type RouteContextFn<in out TParentRoute extends AnyRoute, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteId> = (ctx: RouteContextOptions<TParentRoute, TSearchValidator, TParams, TRouterContext, TRouteId>) => any;
export type FileBaseRouteOptions<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TPath extends string = string, TSearchValidator = undefined, TParams = {}, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TRemountDepsFn = AnyContext, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> = ParamsOptions<TPath, TParams> & FilebaseRouteOptionsInterface<TRegister, TParentRoute, TId, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TRemountDepsFn, TSSR, TServerMiddlewares, THandlers>;
export interface FilebaseRouteOptionsInterface<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TPath extends string = string, TSearchValidator = undefined, TParams = {}, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TRemountDepsFn = AnyContext, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> {
validateSearch?: Constrain<TSearchValidator, AnyValidator, DefaultValidator>;
shouldReload?: boolean | ((match: LoaderFnContext<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>) => any);
context?: Constrain<TRouteContextFn, (ctx: RouteContextOptions<TParentRoute, TParams, TRouterContext, TLoaderDeps, TId>) => any>;
ssr?: Constrain<TSSR, undefined | SSROption | ((ctx: SsrContextOptions<TParentRoute, TSearchValidator, TParams>) => Awaitable<undefined | SSROption>)>;
beforeLoad?: Constrain<TBeforeLoadFn, (ctx: BeforeLoadContextOptions<TRegister, TParentRoute, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TId, TServerMiddlewares, THandlers>) => ValidateSerializableLifecycleResult<TRegister, TParentRoute, TSSR, TBeforeLoadFn>>;
loaderDeps?: (opts: FullSearchSchemaOption<TParentRoute, TSearchValidator>) => TLoaderDeps;
remountDeps?: Constrain<TRemountDepsFn, (opt: RemountDepsOptions<TId, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>, TLoaderDeps>) => any>;
loader?: Constrain<TLoaderFn, RouteLoaderFn<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers> | RouteLoaderObject<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>>;
}
export type BaseRouteOptions<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TCustomId extends string = string, TPath extends string = string, TSearchValidator = undefined, TParams = {}, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> = RoutePathOptions<TCustomId, TPath> & FileBaseRouteOptions<TRegister, TParentRoute, TId, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, AnyContext, TSSR, TServerMiddlewares, THandlers> & {
getParentRoute: () => TParentRoute;
};
export interface ContextOptions<in out TParentRoute extends AnyRoute, in out TParams, in out TRouteId> {
abortController: AbortController;
preload: boolean;
params: Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>;
location: ParsedLocation;
/**
* @deprecated Use `throw redirect({ to: '/somewhere' })` instead
**/
navigate: NavigateFn;
buildLocation: BuildLocationFn;
cause: 'preload' | 'enter' | 'stay';
matches: Array<MakeRouteMatchUnion>;
routeId: TRouteId;
}
export interface RouteContextOptions<in out TParentRoute extends AnyRoute, in out TParams, in out TRouterContext, in out TLoaderDeps, in out TRouteId> extends ContextOptions<TParentRoute, TParams, TRouteId> {
deps: TLoaderDeps;
context: Expand<RouteContextParameter<TParentRoute, TRouterContext>>;
}
export interface SsrContextOptions<in out TParentRoute extends AnyRoute, in out TSearchValidator, in out TParams> {
params: {
status: 'success';
value: Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>;
} | {
status: 'error';
error: unknown;
};
search: {
status: 'success';
value: Expand<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>;
} | {
status: 'error';
error: unknown;
};
location: ParsedLocation;
matches: Array<MakePreValidationErrorHandlingRouteMatchUnion>;
}
export interface BeforeLoadContextOptions<in out TRegister, in out TParentRoute extends AnyRoute, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TRouteId, in out TServerMiddlewares, in out THandlers> extends ContextOptions<TParentRoute, TParams, TRouteId>, FullSearchSchemaOption<TParentRoute, TSearchValidator> {
context: Expand<BeforeLoadContextParameter<TParentRoute, TRouterContext, TRouteContextFn>>;
}
type AssetFnContextOptions<in out TRouteId, in out TFullPath, in out TParentRoute extends AnyRoute, in out TParams, in out TSearchValidator, in out TLoaderFn, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps> = {
ssr?: {
nonce?: string;
};
matches: Array<RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>>;
match: RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>;
params: ResolveAllParamsFromParent<TParentRoute, TParams>;
loaderData?: ResolveLoaderData<TLoaderFn>;
};
export interface DefaultUpdatableRouteOptionsExtensions {
component?: unknown;
errorComponent?: unknown;
notFoundComponent?: unknown;
pendingComponent?: unknown;
}
export interface UpdatableRouteOptionsExtensions extends DefaultUpdatableRouteOptionsExtensions {
}
export interface UpdatableRouteOptions<in out TParentRoute extends AnyRoute, in out TRouteId, in out TFullPath, in out TParams, in out TSearchValidator, in out TLoaderFn, in out TLoaderDeps, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn> extends UpdatableStaticRouteOption, UpdatableRouteOptionsExtensions {
/**
* If true, this route will be matched as case-sensitive
*
* @default false
*/
caseSensitive?: boolean;
/**
* If true, this route will be forcefully wrapped in a suspense boundary
*/
wrapInSuspense?: boolean;
pendingMs?: number;
pendingMinMs?: number;
staleTime?: number;
gcTime?: number;
preload?: boolean;
preloadStaleTime?: number;
preloadGcTime?: number;
search?: {
middlewares?: Array<SearchMiddleware<ResolveFullSearchSchemaInput<TParentRoute, TSearchValidator>>>;
};
/**
@deprecated Use search.middlewares instead
*/
preSearchFilters?: Array<SearchFilter<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>>;
/**
@deprecated Use search.middlewares instead
*/
postSearchFilters?: Array<SearchFilter<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>>;
onCatch?: (error: Error) => void;
onError?: (err: any) => void;
onEnter?: (match: RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>) => void;
onStay?: (match: RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>) => void;
onLeave?: (match: RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>) => void;
headers?: (ctx: AssetFnContextOptions<TRouteId, TFullPath, TParentRoute, TParams, TSearchValidator, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps>) => Awaitable<Record<string, string> | undefined>;
head?: (ctx: AssetFnContextOptions<TRouteId, TFullPath, TParentRoute, TParams, TSearchValidator, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps>) => Awaitable<{
links?: AnyRouteMatch['links'];
scripts?: AnyRouteMatch['headScripts'];
meta?: AnyRouteMatch['meta'];
styles?: AnyRouteMatch['styles'];
}>;
scripts?: (ctx: AssetFnContextOptions<TRouteId, TFullPath, TParentRoute, TParams, TSearchValidator, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps>) => Awaitable<AnyRouteMatch['scripts']>;
codeSplitGroupings?: Array<Array<'loader' | 'component' | 'pendingComponent' | 'notFoundComponent' | 'errorComponent'>>;
}
export type RouteLoaderFn<in out TRegister, in out TParentRoute extends AnyRoute = AnyRoute, in out TId extends string = string, in out TParams = {}, in out TLoaderDeps = {}, in out TRouterContext = {}, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TServerMiddlewares = unknown, in out THandlers = undefined> = (match: LoaderFnContext<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>) => any;
export type LoaderStaleReloadMode = 'background' | 'blocking';
export type RouteLoaderEntry<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TParams = {}, TLoaderDeps = {}, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TServerMiddlewares = unknown, THandlers = undefined> = RouteLoaderFn<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers> | RouteLoaderObject<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>;
export interface LoaderFnContext<in out TRegister = unknown, in out TParentRoute extends AnyRoute = AnyRoute, in out TId extends string = string, in out TParams = {}, in out TLoaderDeps = {}, in out TRouterContext = {}, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TServerMiddlewares = unknown, in out THandlers = undefined> {
abortController: AbortController;
preload: boolean;
params: Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>;
deps: TLoaderDeps;
context: Expand<ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>>;
location: ParsedLocation;
/**
* @deprecated Use `throw redirect({ to: '/somewhere' })` instead
**/
navigate: (opts: NavigateOptions<AnyRouter>) => Promise<void> | void;
parentMatchPromise: TId extends RootRouteId ? never : Promise<MakeRouteMatchFromRoute<TParentRoute>>;
cause: 'preload' | 'enter' | 'stay';
route: AnyRoute;
}
export interface DefaultRootRouteOptionsExtensions {
shellComponent?: unknown;
}
export interface RootRouteOptionsExtensions extends DefaultRootRouteOptionsExtensions {
}
export interface RootRouteOptions<TRegister = unknown, TSearchValidator = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> extends Omit<RouteOptions<TRegister, any, // TParentRoute
RootRouteId, // TId
RootRouteId, // TCustomId
'', // TFullPath
'', // TPath
TSearchValidator, {}, // TParams
TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers>, 'path' | 'id' | 'getParentRoute' | 'caseSensitive' | 'parseParams' | 'stringifyParams' | 'params'>, RootRouteOptionsExtensions {
}
export type RouteConstraints = {
TParentRoute: AnyRoute;
TPath: string;
TFullPath: string;
TCustomId: string;
TId: string;
TSearchSchema: AnySchema;
TFullSearchSchema: AnySchema;
TParams: Record<string, any>;
TAllParams: Record<string, any>;
TParentContext: AnyContext;
TRouteContext: RouteContext;
TAllContext: AnyContext;
TRouterContext: AnyContext;
TChildren: unknown;
TRouteTree: AnyRoute;
};
export type RouteTypesById<TRouter extends AnyRouter, TId> = RouteById<TRouter['routeTree'], TId>['types'];
export type RouteMask<TRouteTree extends AnyRoute> = {
routeTree: TRouteTree;
from: RoutePaths<TRouteTree>;
to?: any;
params?: any;
search?: any;
hash?: any;
state?: any;
unmaskOnReload?: boolean;
};
/**
* @deprecated Use `ErrorComponentProps` instead.
*/
export type ErrorRouteProps = {
error: unknown;
info?: {
componentStack: string;
};
reset: () => void;
};
export type ErrorComponentProps<TError = Error> = {
error: TError;
info?: {
componentStack: string;
};
reset: () => void;
};
export type NotFoundRouteProps = {
data?: unknown;
isNotFound: boolean;
routeId: RouteIds<RegisteredRouter['routeTree']>;
};
export declare class BaseRoute<in out TRegister = Register, in out TParentRoute extends AnyRoute = AnyRoute, in out TPath extends string = '/', in out TFullPath extends string = ResolveFullPath<TParentRoute, TPath>, in out TCustomId extends string = string, in out TId extends string = ResolveId<TParentRoute, TCustomId, TPath>, in out TSearchValidator = undefined, in out TParams = ResolveParams<TPath>, in out TRouterContext = AnyContext, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TLoaderDeps extends Record<string, any> = {}, in out TLoaderFn = undefined, in out TChildren = unknown, in out TFileRouteTypes = unknown, in out TSSR = unknown, in out TServerMiddlewares = unknown, in out THandlers = undefined> {
isRoot: TParentRoute extends AnyRoute ? true : false;
options: RouteOptions<TRegister, TParentRoute, TId, TCustomId, TFullPath, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers>;
parentRoute: TParentRoute;
private _id;
private _path;
private _fullPath;
private _to;
get to(): TrimPathRight<TFullPath>;
get id(): TId;
get path(): TPath;
get fullPath(): TFullPath;
children?: TChildren;
originalIndex?: number;
rank: number;
lazyFn?: () => Promise<LazyRoute<Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>>>;
constructor(options?: RouteOptions<TRegister, TParentRoute, TId, TCustomId, TFullPath, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers>);
types: RouteTypes<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
init: (opts: {
originalIndex: number;
}) => void;
addChildren: RouteAddChildrenFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
_addFileChildren: RouteAddFileChildrenFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
_addFileTypes: RouteAddFileTypesFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TSSR, TServerMiddlewares, THandlers>;
updateLoader: <TNewLoaderFn>(options: {
loader: Constrain<TNewLoaderFn, RouteLoaderFn<TRegister, TParentRoute, TCustomId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn>>;
}) => BaseRoute<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TNewLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
update: (options: UpdatableRouteOptions<TParentRoute, TCustomId, TFullPath, TParams, TSearchValidator, TLoaderFn, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn>) => this;
lazy: RouteLazyFn<Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>>;
/**
* Create a redirect with `from` automatically set to this route's fullPath.
* Enables relative redirects like `Route.redirect({ to: './overview' })`.
* @param opts Redirect options (same as `redirect()` but without `from`)
* @returns A redirect Response that can be thrown from loaders/beforeLoad
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction
*/
redirect: RedirectFnRoute<TFullPath>;
}
export declare class BaseRouteApi<TId, TRouter extends AnyRouter = RegisteredRouter> {
id: TId;
constructor({ id }: {
id: TId;
});
notFound: (opts?: NotFoundError) => NotFoundError;
/**
* Create a redirect with `from` automatically set to this route's path.
* Enables relative redirects like `routeApi.redirect({ to: './overview' })`.
* @param opts Redirect options (same as `redirect()` but without `from`)
* @returns A redirect Response that can be thrown from loaders/beforeLoad
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction
*/
redirect: RedirectFnRoute<RouteTypesById<TRouter, TId>['fullPath']>;
}
export interface RootRoute<in out TRegister, in out TSearchValidator = undefined, in out TRouterContext = {}, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TLoaderDeps extends Record<string, any> = {}, in out TLoaderFn = undefined, in out TChildren = unknown, in out TFileRouteTypes = unknown, in out TSSR = unknown, in out TServerMiddlewares = unknown, in out THandlers = undefined> extends Route<TRegister, any, // TParentRoute
'/', // TPath
'/', // TFullPath
string, // TCustomId
RootRouteId, // TId
TSearchValidator, // TSearchValidator
{}, // TParams
TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, // TChildren
TFileRouteTypes, TSSR, TServerMiddlewares, THandlers> {
}
export declare class BaseRootRoute<in out TRegister = Register, in out TSearchValidator = undefined, in out TRouterContext = {}, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TLoaderDeps extends Record<string, any> = {}, in out TLoaderFn = undefined, in out TChildren = unknown, in out TFileRouteTypes = unknown, in out TSSR = unknown, in out TServerMiddlewares = unknown, in out THandlers = undefined> extends BaseRoute<TRegister, any, // TParentRoute
'/', // TPath
'/', // TFullPath
string, // TCustomId
RootRouteId, // TId
TSearchValidator, // TSearchValidator
{}, // TParams
TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, // TChildren
TFileRouteTypes, TSSR, TServerMiddlewares, THandlers> {
constructor(options?: RootRouteOptions<TRegister, TSearchValidator, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TSSR, TServerMiddlewares, THandlers>);
}
export interface RouteLike {
id: string;
isRoot?: boolean;
path?: string;
fullPath: string;
rank?: number;
parentRoute?: RouteLike;
children?: Array<RouteLike>;
options?: {
caseSensitive?: boolean;
};
}
export {};
@@ -0,0 +1,16 @@
/**
* @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 Tally2 = createLucideIcon("Tally2", [
["path", { d: "M4 4v16", key: "6qkkli" }],
["path", { d: "M9 4v16", key: "81ygyz" }]
]);
export { Tally2 as default };
//# sourceMappingURL=tally-2.js.map
@@ -0,0 +1,9 @@
/**
* @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.
*/
export { default } from './octagon-x.js';
//# sourceMappingURL=x-octagon.js.map
@@ -0,0 +1 @@
{"version":3,"file":"locate-off.js","sources":["../../../src/icons/locate-off.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name LocateOff\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8bGluZSB4MT0iMiIgeDI9IjUiIHkxPSIxMiIgeTI9IjEyIiAvPgogIDxsaW5lIHgxPSIxOSIgeDI9IjIyIiB5MT0iMTIiIHkyPSIxMiIgLz4KICA8bGluZSB4MT0iMTIiIHgyPSIxMiIgeTE9IjIiIHkyPSI1IiAvPgogIDxsaW5lIHgxPSIxMiIgeDI9IjEyIiB5MT0iMTkiIHkyPSIyMiIgLz4KICA8cGF0aCBkPSJNNy4xMSA3LjExQzUuODMgOC4zOSA1IDEwLjEgNSAxMmMwIDMuODcgMy4xMyA3IDcgNyAxLjkgMCAzLjYxLS44MyA0Ljg5LTIuMTEiIC8+CiAgPHBhdGggZD0iTTE4LjcxIDEzLjk2Yy4xOS0uNjMuMjktMS4yOS4yOS0xLjk2IDAtMy44Ny0zLjEzLTctNy03LS42NyAwLTEuMzMuMS0xLjk2LjI5IiAvPgogIDxsaW5lIHgxPSIyIiB4Mj0iMjIiIHkxPSIyIiB5Mj0iMjIiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/locate-off\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 LocateOff = createLucideIcon('LocateOff', [\n ['line', { x1: '2', x2: '5', y1: '12', y2: '12', key: 'bvdh0s' }],\n ['line', { x1: '19', x2: '22', y1: '12', y2: '12', key: '1tbv5k' }],\n ['line', { x1: '12', x2: '12', y1: '2', y2: '5', key: '11lu5j' }],\n ['line', { x1: '12', x2: '12', y1: '19', y2: '22', key: 'x3vr5v' }],\n [\n 'path',\n {\n d: 'M7.11 7.11C5.83 8.39 5 10.1 5 12c0 3.87 3.13 7 7 7 1.9 0 3.61-.83 4.89-2.11',\n key: '1oh7ia',\n },\n ],\n [\n 'path',\n {\n d: 'M18.71 13.96c.19-.63.29-1.29.29-1.96 0-3.87-3.13-7-7-7-.67 0-1.33.1-1.96.29',\n key: '3qdecy',\n },\n ],\n ['line', { x1: '2', x2: '22', y1: '2', y2: '22', key: 'a6p6uj' }],\n]);\n\nexport default LocateOff;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAY,iBAAiB,WAAa,CAAA,CAAA,CAAA;AAAA,CAC9C,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAK,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAChE,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAClE,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAK,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAChE,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAClE,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA;AAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACP,CAAA,CAAA,CAAA,CAAA;AAAA,CACF,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA;AAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACP,CAAA,CAAA,CAAA,CAAA;AAAA,CACF,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CLine truncated
@@ -0,0 +1 @@
{"version":3,"file":"WithPromise.mjs","sources":["../../../../src/animation/utils/WithPromise.ts"],"sourcesContent":["export class WithPromise {\n protected _finished: Promise<void>\n\n resolve: VoidFunction\n\n constructor() {\n this.updateFinished()\n }\n\n get finished() {\n return this._finished\n }\n\n protected updateFinished() {\n this._finished = new Promise<void>((resolve) => {\n this.resolve = resolve\n })\n }\n\n protected notifyFinished() {\n this.resolve()\n }\n\n /**\n * Allows the animation to be awaited.\n *\n * @deprecated Use `finished` instead.\n */\n then(onResolve: VoidFunction, onReject?: VoidFunction) {\n return this.finished.then(onResolve, onReject)\n }\n}\n"],"names":[],"mappings":"MAAa,WAAW,CAAA;AAKpB,IAAA,WAAA,GAAA;QACI,IAAI,CAAC,cAAc,EAAE;IACzB;AAEA,IAAA,IAAI,QAAQ,GAAA;QACR,OAAO,IAAI,CAAC,SAAS;IACzB;IAEU,cAAc,GAAA;QACpB,IAAI,CAAC,SAAS,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,KAAI;AAC3C,YAAA,IAAI,CAAC,OAAO,GAAG,OAAO;AAC1B,QAAA,CAAC,CAAC;IACN;IAEU,cAAc,GAAA;QACpB,IAAI,CAAC,OAAO,EAAE;IAClB;AAEA;;;;AAIG;IACH,IAAI,CAAC,SAAuB,EAAE,QAAuB,EAAA;QACjD,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC;IAClD;AACH;;;;"}
@@ -0,0 +1 @@
{"version":3,"file":"route.cjs","names":[],"sources":["../../src/route.ts"],"sourcesContent":["import { invariant } from './invariant'\nimport { joinPaths, trimPathLeft, trimPathRight } from './path'\nimport { notFound } from './not-found'\nimport { redirect } from './redirect'\nimport { rootRouteId } from './root'\nimport type { LazyRoute } from './fileRoute'\nimport type { NotFoundError } from './not-found'\nimport type { RedirectFnRoute } from './redirect'\nimport type { NavigateOptions, ParsePathParams } from './link'\nimport type { ParsedLocation } from './location'\nimport type {\n AnyRouteMatch,\n MakePreValidationErrorHandlingRouteMatchUnion,\n MakeRouteMatchFromRoute,\n MakeRouteMatchUnion,\n RouteMatch,\n} from './Matches'\nimport type { RootRouteId } from './root'\nimport type { ParseRoute, RouteById, RouteIds, RoutePaths } from './routeInfo'\nimport type { AnyRouter, Register, RegisteredRouter, SSROption } from './router'\nimport type { BuildLocationFn, NavigateFn } from './RouterProvider'\nimport type {\n Assign,\n Awaitable,\n Constrain,\n Expand,\n IntersectAssign,\n LooseAsyncReturnType,\n LooseReturnType,\n NoInfer,\n} from './utils'\nimport type {\n AnySchema,\n AnyStandardSchemaValidator,\n AnyValidator,\n AnyValidatorAdapter,\n AnyValidatorObj,\n DefaultValidator,\n ResolveSearchValidatorInput,\n ResolveValidatorOutput,\n StandardSchemaValidator,\n ValidatorAdapter,\n ValidatorFn,\n ValidatorObj,\n} from './validators'\nimport type { ValidateSerializableLifecycleResult } from './ssr/serializer/transformer'\n\nexport type AnyPathParams = {}\n\nexport type SearchSchemaInput = {\n __TSearchSchemaInput__: 'TSearchSchemaInput'\n}\n\nexport type AnyContext = {}\n\nexport interface RouteContext {}\n\nexport type PreloadableObj = { preload?: () => Promise<void> }\n\nexport type RoutePathOptions<TCustomId, TPath> =\n | {\n path: TPath\n }\n | {\n id: TCustomId\n }\n\nexport interface StaticDataRouteOption {}\n\nexport type RoutePathOptionsIntersection<TCustomId, TPath> = {\n path: TPath\n id: TCustomId\n}\n\nexport type SearchFilter<TInput, TResult = TInput> = (prev: TInput) => TResult\n\nexport type SearchMiddlewareContext<TSearchSchema> = {\n search: TSearchSchema\n next: (newSearch: TSearchSchema) => TSearchSchema\n}\n\nexport type SearchMiddleware<TSearchSchema> = (\n ctx: SearchMiddlewareContext<TSearchSchema>,\n) => TSearchSchema\n\nexport type ResolveId<\n TParentRoute,\n TCustomId extends string,\n TPath extends string,\n> = TParentRoute extends { id: infer TParentId extends string }\n ? RoutePrefix<TParentId, string extends TCustomId ? TPath : TCustomId>\n : RootRouteId\n\nexport type InferFullSearchSchema<TRoute> = TRoute extends {\n types: {\n fullSearchSchema: infer TFullSearchSchema\n }\n}\n ? TFullSearchSchema\n : {}\n\nexport type InferFullSearchSchemaInput<TRoute> = TRoute extends {\n types: {\n fullSearchSchemaInput: infer TFullSearchSchemaInput\n }\n}\n ? TFullSearchSchemaInput\n : {}\n\nexport type InferAllParams<TRoute> = TRoute extends {\n types: {\n allParams: infer TAllParams\n }\n}\n ? TAllParams\n : {}\n\nexport type InferAllContext<TRoute> = unknown extends TRoute\n ? TRoute\n : TRoute extends {\n types: {\n allContext: infer TAllContext\n }\n }\n ? TAllContext\n : {}\n\nexport type ResolveSearchSchemaFnInput<TSearchValidator> =\n TSearchValidator extends (input: infer TSearchSchemaInput) => any\n ? TSearchSchemaInput extends SearchSchemaInput\n ? Omit<TSearchSchemaInput, keyof SearchSchemaInput>\n : ResolveSearchSchemaFn<TSearchValidator>\n : AnySchema\n\nexport type ResolveSearchSchemaInput<TSearchValidator> =\n TSearchValidator extends AnyStandardSchemaValidator\n ? NonNullable<TSearchValidator['~standard']['types']>['input']\n : TSearchValidator extends AnyValidatorAdapter\n ? TSearchValidator['types']['input']\n : TSearchValidator extends AnyValidatorObj\n ? ResolveSearchSchemaFnInput<TSearchValidator['parse']>\n : ResolveSearchSchemaFnInput<TSearchValidator>\n\nexport type ResolveSearchSchemaFn<TSearchValidator> = TSearchValidator extends (\n ...args: any\n) => infer TSearchSchema\n ? TSearchSchema\n : AnySchema\n\nexport type ResolveSearchSchema<TSearchValidator> =\n unknown extends TSearchValidator\n ? TSearchValidator\n : TSearchValidator extends AnyStandardSchemaValidator\n ? NonNullable<TSearchValidator['~standard']['types']>['output']\n : TSearchValidator extends AnyValidatorAdapter\n ? TSearchValidator['types']['output']\n : TSearchValidator extends AnyValidatorObj\n ? ResolveSearchSchemaFn<TSearchValidator['parse']>\n : ResolveSearchSchemaFn<TSearchValidator>\n\nexport type ResolveRequiredParams<TPath extends string, T> = {\n [K in ParsePathParams<TPath>['required']]: T\n}\n\nexport type ResolveOptionalParams<TPath extends string, T> = {\n [K in PLine truncated
@@ -0,0 +1 @@
{"version":3,"file":"cigarette.js","sources":["../../../src/icons/cigarette.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Cigarette\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTcgMTJIM2ExIDEgMCAwIDAtMSAxdjJhMSAxIDAgMCAwIDEgMWgxNCIgLz4KICA8cGF0aCBkPSJNMTggOGMwLTIuNS0yLTIuNS0yLTUiIC8+CiAgPHBhdGggZD0iTTIxIDE2YTEgMSAwIDAgMCAxLTF2LTJhMSAxIDAgMCAwLTEtMSIgLz4KICA8cGF0aCBkPSJNMjIgOGMwLTIuNS0yLTIuNS0yLTUiIC8+CiAgPHBhdGggZD0iTTcgMTJ2NCIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/cigarette\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 Cigarette = createLucideIcon('Cigarette', [\n ['path', { d: 'M17 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h14', key: '1mb5g1' }],\n ['path', { d: 'M18 8c0-2.5-2-2.5-2-5', key: '1il607' }],\n ['path', { d: 'M21 16a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1', key: '1yl5r7' }],\n ['path', { d: 'M22 8c0-2.5-2-2.5-2-5', key: '1gah44' }],\n ['path', { d: 'M7 12v4', key: 'jqww69' }],\n]);\n\nexport default Cigarette;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAY,iBAAiB,WAAa,CAAA,CAAA,CAAA;AAAA,CAAA,CAC9C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA6C,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC1E,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAyB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACtD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAyC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACtE,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAyB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACtD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC1C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"file":"globe-2.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
@@ -0,0 +1,67 @@
const { closest, distance } = require("./mod.js");
const levenshtein = (a, b) => {
if (a.length === 0) {
return b.length;
}
if (b.length === 0) {
return a.length;
}
if (a.length > b.length) {
const tmp = a;
a = b;
b = tmp;
}
const row = [];
for (let i = 0; i <= a.length; i++) {
row[i] = i;
}
for (let i = 1; i <= b.length; i++) {
let prev = i;
for (let j = 1; j <= a.length; j++) {
let val = 0;
if (b.charAt(i - 1) === a.charAt(j - 1)) {
val = row[j - 1];
} else {
val = Math.min(row[j - 1] + 1, prev + 1, row[j] + 1);
}
row[j - 1] = prev;
prev = val;
}
row[a.length] = prev;
}
return row[a.length];
};
const makeid = (length) => {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
test("test compare", () => {
for (let i = 0; i < 1000; i++) {
const rnd_num1 = (Math.random() * 1000) | 0;
const rnd_num2 = (Math.random() * 1000) | 0;
const rnd_string1 = makeid(rnd_num1);
const rnd_string2 = makeid(rnd_num2);
const actual = distance(rnd_string1, rnd_string2);
const expected = levenshtein(rnd_string1, rnd_string2);
expect(actual).toBe(expected);
}
});
test("test find", () => {
const actual = closest("fast", ["slow", "faster", "fastest"]);
const expected = "faster";
expect(actual).toBe(expected);
});
@@ -0,0 +1,23 @@
'use strict';
const fs = require('fs');
const shebangCommand = require('shebang-command');
function readShebang(command) {
// Read the first 150 bytes from the file
const size = 150;
const buffer = Buffer.alloc(size);
let fd;
try {
fd = fs.openSync(command, 'r');
fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);
} catch (e) { /* Empty */ }
// Attempt to extract shebang (null is returned if not a shebang)
return shebangCommand(buffer.toString());
}
module.exports = readShebang;
@@ -0,0 +1,139 @@
# statuses
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][ci-image]][ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
HTTP status utility for node.
This module provides a list of status codes and messages sourced from
a few different projects:
* The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml)
* The [Node.js project](https://nodejs.org/)
* The [NGINX project](https://www.nginx.com/)
* The [Apache HTTP Server project](https://httpd.apache.org/)
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install statuses
```
## API
<!-- eslint-disable no-unused-vars -->
```js
var status = require('statuses')
```
### status(code)
Returns the status message string for a known HTTP status code. The code
may be a number or a string. An error is thrown for an unknown status code.
<!-- eslint-disable no-undef -->
```js
status(403) // => 'Forbidden'
status('403') // => 'Forbidden'
status(306) // throws
```
### status(msg)
Returns the numeric status code for a known HTTP status message. The message
is case-insensitive. An error is thrown for an unknown status message.
<!-- eslint-disable no-undef -->
```js
status('forbidden') // => 403
status('Forbidden') // => 403
status('foo') // throws
```
### status.codes
Returns an array of all the status codes as `Integer`s.
### status.code[msg]
Returns the numeric status code for a known status message (in lower-case),
otherwise `undefined`.
<!-- eslint-disable no-undef, no-unused-expressions -->
```js
status['not found'] // => 404
```
### status.empty[code]
Returns `true` if a status code expects an empty body.
<!-- eslint-disable no-undef, no-unused-expressions -->
```js
status.empty[200] // => undefined
status.empty[204] // => true
status.empty[304] // => true
```
### status.message[code]
Returns the string message for a known numeric status code, otherwise
`undefined`. This object is the same format as the
[Node.js http module `http.STATUS_CODES`](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes).
<!-- eslint-disable no-undef, no-unused-expressions -->
```js
status.message[404] // => 'Not Found'
```
### status.redirect[code]
Returns `true` if a status code is a valid redirect status.
<!-- eslint-disable no-undef, no-unused-expressions -->
```js
status.redirect[200] // => undefined
status.redirect[301] // => true
```
### status.retry[code]
Returns `true` if you should retry the rest.
<!-- eslint-disable no-undef, no-unused-expressions -->
```js
status.retry[501] // => undefined
status.retry[503] // => true
```
## License
[MIT](LICENSE)
[ci-image]: https://badgen.net/github/checks/jshttp/statuses/master?label=ci
[ci-url]: https://github.com/jshttp/statuses/actions?query=workflow%3Aci
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/statuses/master
[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master
[node-version-image]: https://badgen.net/npm/node/statuses
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/statuses
[npm-url]: https://npmjs.org/package/statuses
[npm-version-image]: https://badgen.net/npm/v/statuses
[ossf-scorecard-badge]: https://api.securityscorecards.dev/projects/github.com/jshttp/statuses/badge
[ossf-scorecard-visualizer]: https://kooltheba.github.io/openssf-scorecard-api-visualizer/#/projects/github.com/jshttp/statuses
@@ -0,0 +1,9 @@
"use client";
import { useEffect } from 'react';
function useUnmountEffect(callback) {
return useEffect(() => () => callback(), []);
}
export { useUnmountEffect };
//# sourceMappingURL=use-unmount-effect.mjs.map
@@ -0,0 +1,114 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
enum testEnum {
A = 0,
B = 1,
}
const schemas = [
z.string().readonly(),
z.number().readonly(),
z.nan().readonly(),
z.bigint().readonly(),
z.boolean().readonly(),
z.date().readonly(),
z.undefined().readonly(),
z.null().readonly(),
z.any().readonly(),
z.unknown().readonly(),
z.void().readonly(),
z.function().args(z.string(), z.number()).readonly(),
z.array(z.string()).readonly(),
z.tuple([z.string(), z.number()]).readonly(),
z.map(z.string(), z.date()).readonly(),
z.set(z.promise(z.string())).readonly(),
z.record(z.string()).readonly(),
z.record(z.string(), z.number()).readonly(),
z.object({ a: z.string(), 1: z.number() }).readonly(),
z.nativeEnum(testEnum).readonly(),
z.promise(z.string()).readonly(),
] as const;
test("flat inference", () => {
util.assertEqual<z.infer<(typeof schemas)[0]>, string>(true);
util.assertEqual<z.infer<(typeof schemas)[1]>, number>(true);
util.assertEqual<z.infer<(typeof schemas)[2]>, number>(true);
util.assertEqual<z.infer<(typeof schemas)[3]>, bigint>(true);
util.assertEqual<z.infer<(typeof schemas)[4]>, boolean>(true);
util.assertEqual<z.infer<(typeof schemas)[5]>, Date>(true);
util.assertEqual<z.infer<(typeof schemas)[6]>, undefined>(true);
util.assertEqual<z.infer<(typeof schemas)[7]>, null>(true);
util.assertEqual<z.infer<(typeof schemas)[8]>, any>(true);
util.assertEqual<z.infer<(typeof schemas)[9]>, Readonly<unknown>>(true);
util.assertEqual<z.infer<(typeof schemas)[10]>, void>(true);
util.assertEqual<z.infer<(typeof schemas)[11]>, (args_0: string, args_1: number, ...args_2: unknown[]) => unknown>(
true
);
util.assertEqual<z.infer<(typeof schemas)[12]>, readonly string[]>(true);
util.assertEqual<z.infer<(typeof schemas)[13]>, readonly [string, number]>(true);
util.assertEqual<z.infer<(typeof schemas)[14]>, ReadonlyMap<string, Date>>(true);
util.assertEqual<z.infer<(typeof schemas)[15]>, ReadonlySet<Promise<string>>>(true);
util.assertEqual<z.infer<(typeof schemas)[16]>, Readonly<Record<string, string>>>(true);
util.assertEqual<z.infer<(typeof schemas)[17]>, Readonly<Record<string, number>>>(true);
util.assertEqual<z.infer<(typeof schemas)[18]>, { readonly a: string; readonly 1: number }>(true);
util.assertEqual<z.infer<(typeof schemas)[19]>, Readonly<testEnum>>(true);
util.assertEqual<z.infer<(typeof schemas)[20]>, Promise<string>>(true);
});
test("object freezing", () => {
expect(Object.isFrozen(z.array(z.string()).readonly().parse(["a"]))).toBe(true);
expect(Object.isFrozen(z.tuple([z.string(), z.number()]).readonly().parse(["a", 1]))).toBe(true);
expect(
Object.isFrozen(
z
.map(z.string(), z.date())
.readonly()
.parse(new Map([["a", new Date()]]))
)
).toBe(true);
expect(
Object.isFrozen(
z
.set(z.promise(z.string()))
.readonly()
.parse(new Set([Promise.resolve("a")]))
)
).toBe(true);
expect(Object.isFrozen(z.record(z.string()).readonly().parse({ a: "b" }))).toBe(true);
expect(Object.isFrozen(z.record(z.string(), z.number()).readonly().parse({ a: 1 }))).toBe(true);
expect(Object.isFrozen(z.object({ a: z.string(), 1: z.number() }).readonly().parse({ a: "b", 1: 2 }))).toBe(true);
expect(Object.isFrozen(z.promise(z.string()).readonly().parse(Promise.resolve("a")))).toBe(true);
});
test("async object freezing", async () => {
expect(Object.isFrozen(await z.array(z.string()).readonly().parseAsync(["a"]))).toBe(true);
expect(Object.isFrozen(await z.tuple([z.string(), z.number()]).readonly().parseAsync(["a", 1]))).toBe(true);
expect(
Object.isFrozen(
await z
.map(z.string(), z.date())
.readonly()
.parseAsync(new Map([["a", new Date()]]))
)
).toBe(true);
expect(
Object.isFrozen(
await z
.set(z.promise(z.string()))
.readonly()
.parseAsync(new Set([Promise.resolve("a")]))
)
).toBe(true);
expect(Object.isFrozen(await z.record(z.string()).readonly().parseAsync({ a: "b" }))).toBe(true);
expect(Object.isFrozen(await z.record(z.string(), z.number()).readonly().parseAsync({ a: 1 }))).toBe(true);
expect(
Object.isFrozen(await z.object({ a: z.string(), 1: z.number() }).readonly().parseAsync({ a: "b", 1: 2 }))
).toBe(true);
expect(Object.isFrozen(await z.promise(z.string()).readonly().parseAsync(Promise.resolve("a")))).toBe(true);
});
@@ -0,0 +1,22 @@
import type { TSESLint } from '@typescript-eslint/utils';
export type Options = [
{
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;
ignoreBooleanCoercion?: boolean;
ignoreConditionalTests?: boolean;
ignoreIfStatements?: boolean;
ignoreMixedLogicalExpressions?: boolean;
ignorePrimitives?: true | {
bigint?: boolean;
boolean?: boolean;
number?: boolean;
string?: boolean;
};
ignoreTernaryTests?: boolean;
}
];
export type MessageIds = 'noStrictNullCheck' | 'preferNullishOverAssignment' | 'preferNullishOverOr' | 'preferNullishOverTernary' | 'suggestNullish';
declare const _default: TSESLint.RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
name: string;
};
export default _default;
@@ -0,0 +1,298 @@
/* Base */
body,
html {
margin: 0;
padding: 0;
height: 100%;
}
body {
color: #333;
background-color: #fcfcfc;
font: 14px/14px -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI',
Roboto, 'Helvetica Neue', Arial, sans-serif;
}
button {
margin: 0;
border: none;
font: inherit;
color: inherit;
}
button:focus {
outline: none;
}
*,
*:after,
*:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
/* Typography */
h1 {
font-size: 20px;
line-height: 20px;
margin: 0;
}
a {
color: #0074d9;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.small {
font-size: 12px;
}
.strong {
font-weight: bold;
}
.center {
text-align: center;
}
.quiet {
opacity: 0.7;
}
/* Colors */
.low {
background: #fce1e5;
}
.low--dark {
background: #c21f39;
}
.medium {
background: #fff4c2;
}
.medium--dark {
background: #f9cd0b;
}
.high {
background: rgb(230, 245, 208);
}
.high--dark {
background: rgb(77, 146, 33);
}
/* App */
.app {
height: 100%;
}
/* Layout */
.layout {
display: flex;
flex-direction: column;
min-height: 100%;
padding: 20px;
}
.layout__section {
flex-grow: 0;
}
.layout__section--fill {
flex-grow: 1;
}
.layout__section + .layout__section {
margin-top: 20px;
}
@media only screen and (max-width: 640px) {
.col3 {
width: 100%;
max-width: 100%;
}
.hide-mobile {
display: none !important;
}
}
/* Toolbar */
.toolbar {
display: flex;
flex-wrap: wrap;
}
.toolbar__item {
margin-right: 40px;
margin-bottom: 10px;
}
/* Toggle */
.toggle {
display: inline-flex;
align-items: center;
}
.toggle__label {
margin-right: 0.5em;
}
.toggle__options {
display: inline-block;
border: 1px solid #0074d9;
border-radius: 4px;
color: #0074d9;
overflow: hidden;
white-space: nowrap;
}
.toggle__option {
padding: 4px 8px;
background: #fcfcfc;
}
.toggle__option + .toggle__option {
border-left: 1px solid #0074d9;
}
.toggle__option.is-toggled {
color: #fff;
background: #0074d9;
border-left-color: #fcfcfc;
}
/* Expand */
.expandbutton {
display: inline-block;
width: 1em;
margin-right: 0.25em;
padding: 0;
background-color: transparent;
font-weight: bold;
}
/* Fraction */
.fraction {
font-size: 12px;
color: #666;
padding: 2px 4px;
border-radius: 4px;
}
/* Coverage */
.coverage-summary {
border-collapse: collapse;
}
.coverage-summary tbody tr {
border-bottom: 1px solid #fff;
}
.coverage-summary td,
.coverage-summary th {
padding: 5px;
}
.coverage-summary th {
text-align: left;
font-weight: normal;
white-space: nowrap;
}
.coverage-summary th.abs,
.coverage-summary td.pct,
.coverage-summary td.abs {
text-align: right;
}
.coverage-summary th.file {
min-width: 300px;
text-align: left;
}
.coverage-summary td.file {
white-space: nowrap;
}
.coverage-summary td.pct {
font-weight: 400;
}
.coverage-summary td.abs {
color: #666;
font-size: 12px;
}
.coverage-summary td.empty {
opacity: 0.5;
}
.coverage-summary .headercell {
border-top: 1px solid #eee;
text-align: right;
font-size: 12px;
color: #666;
}
.coverage-summary .headercell:nth-child(5n - 3),
.coverage-summary td:nth-child(5n - 3) {
border-left: 2px solid #fcfcfc;
padding-left: 2em;
}
.filetab {
display: inline-block;
width: 1em;
}
/* Sorter */
.sorter {
display: inline-block;
width: 7px;
height: 10px;
margin-left: 0.5em;
background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent;
}
.sorted .sorter {
background-position: 0 -20px;
}
.sorted-desc .sorter {
background-position: 0 -10px;
}
.sortable {
cursor: pointer;
}
/* Bar */
.bar {
width: 50px;
height: 5px;
background: #fff;
}
.bar__data {
height: 100%;
}
@@ -0,0 +1 @@
import"./chunk-F4544Y4M.mjs";import"./chunk-TDNFF6A4.mjs";import"./chunk-X4GG3EDV.mjs";function i(r){let n={};for(let[e,t]of Object.entries(r??{}))if(e!=="__CSS_VALUES__")if(typeof t=="object"&&t!==null)for(let[o,f]of Object.entries(i(t)))n[`${e}${o==="DEFAULT"?"":`-${o}`}`]=f;else n[e]=t;if("__CSS_VALUES__"in r)for(let[e,t]of Object.entries(r.__CSS_VALUES__))(Number(t)&4)===0&&(n[e]=r[e]);return n}export{i as default};
@@ -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 AlignStartVertical = createLucideIcon("AlignStartVertical", [
["rect", { width: "9", height: "6", x: "6", y: "14", rx: "2", key: "lpm2y7" }],
["rect", { width: "16", height: "6", x: "6", y: "4", rx: "2", key: "rdj6ps" }],
["path", { d: "M2 2v20", key: "1ivd8o" }]
]);
export { AlignStartVertical as default };
//# sourceMappingURL=align-start-vertical.js.map
@@ -0,0 +1,14 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_adapter_bun_server = require("./server.js");
const require_adapter_bun_conninfo = require("./conninfo.js");
const require_adapter_bun_serve_static = require("./serve-static.js");
const require_adapter_bun_ssg = require("./ssg.js");
const require_adapter_bun_websocket = require("./websocket.js");
exports.bunFileSystemModule = require_adapter_bun_ssg.bunFileSystemModule;
exports.createBunWebSocket = require_adapter_bun_websocket.createBunWebSocket;
exports.getBunServer = require_adapter_bun_server.getBunServer;
exports.getConnInfo = require_adapter_bun_conninfo.getConnInfo;
exports.serveStatic = require_adapter_bun_serve_static.serveStatic;
exports.toSSG = require_adapter_bun_ssg.toSSG;
exports.upgradeWebSocket = require_adapter_bun_websocket.upgradeWebSocket;
exports.websocket = require_adapter_bun_websocket.websocket;
@@ -0,0 +1,16 @@
/**
* @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 ToggleLeft = createLucideIcon("ToggleLeft", [
["rect", { width: "20", height: "12", x: "2", y: "6", rx: "6", ry: "6", key: "f2vt7d" }],
["circle", { cx: "8", cy: "12", r: "2", key: "1nvbw3" }]
]);
export { ToggleLeft as default };
//# sourceMappingURL=toggle-left.js.map
@@ -0,0 +1,97 @@
{
"name": "@vitest/mocker",
"type": "module",
"version": "4.1.12",
"description": "Vitest module mocker implementation",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
"directory": "packages/mocker"
},
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"mock"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./node": {
"types": "./dist/node.d.ts",
"default": "./dist/node.js"
},
"./browser": {
"types": "./dist/browser.d.ts",
"default": "./dist/browser.js"
},
"./redirect": {
"types": "./dist/redirect.d.ts",
"default": "./dist/redirect.js"
},
"./automock": {
"types": "./dist/automock.d.ts",
"default": "./dist/automock.js"
},
"./register": {
"types": "./dist/register.d.ts",
"default": "./dist/register.js"
},
"./auto-register": {
"types": "./dist/register.d.ts",
"default": "./dist/register.js"
},
"./transforms": {
"types": "./dist/transforms.d.ts",
"default": "./dist/transforms.js"
},
"./package.json": "./package.json"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"*.d.ts",
"dist"
],
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"msw": {
"optional": true
},
"vite": {
"optional": true
}
},
"dependencies": {
"estree-walker": "^3.0.3",
"magic-string": "^0.30.21",
"@vitest/spy": "4.1.12"
},
"devDependencies": {
"@types/estree": "^1.0.8",
"acorn-walk": "^8.3.5",
"cjs-module-lexer": "^2.2.0",
"es-module-lexer": "^2.0.0",
"msw": "^2.12.10",
"pathe": "^2.0.3",
"vite": "^6.3.5",
"@vitest/spy": "4.1.12",
"@vitest/utils": "4.1.12"
},
"scripts": {
"build": "premove dist && rollup -c",
"dev": "rollup -c --watch"
}
}
@@ -0,0 +1 @@
{"version":3,"file":"history.js","sources":["../../../src/icons/history.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name History\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMyAxMmE5IDkgMCAxIDAgOS05IDkuNzUgOS43NSAwIDAgMC02Ljc0IDIuNzRMMyA4IiAvPgogIDxwYXRoIGQ9Ik0zIDN2NWg1IiAvPgogIDxwYXRoIGQ9Ik0xMiA3djVsNCAyIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/history\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 History = createLucideIcon('History', [\n ['path', { d: 'M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8', key: '1357e3' }],\n ['path', { d: 'M3 3v5h5', key: '1xhq8a' }],\n ['path', { d: 'M12 7v5l4 2', key: '1fdv2h' }],\n]);\n\nexport default History;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAU,iBAAiB,SAAW,CAAA,CAAA,CAAA;AAAA,CAAA,CAC1C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAqD,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAClF,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,CAAe,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC9C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"file":"development.cjs","names":[],"sources":["../../../src/isServer/development.ts"],"sourcesContent":["// Development/test mode - returns undefined so fallback to router.isServer is used\nexport const isServer: boolean | undefined = undefined\n"],"mappings":";;AACA,MAAa,WAAgC,KAAA"}
@@ -0,0 +1,285 @@
/**
* The `timer` module exposes a global API for scheduling functions to
* be called at some future period of time. Because the timer functions are
* globals, there is no need to import `node:timers` to use the API.
*
* The timer functions within Node.js implement a similar API as the timers API
* provided by Web Browsers but use a different internal implementation that is
* built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout).
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers.js)
*/
declare module "timers" {
import { Abortable } from "node:events";
import * as promises from "node:timers/promises";
export interface TimerOptions extends Abortable {
/**
* Set to `false` to indicate that the scheduled `Timeout`
* should not require the Node.js event loop to remain active.
* @default true
*/
ref?: boolean | undefined;
}
global {
namespace NodeJS {
/**
* This object is created internally and is returned from `setImmediate()`. It
* can be passed to `clearImmediate()` in order to cancel the scheduled
* actions.
*
* By default, when an immediate is scheduled, the Node.js event loop will continue
* running as long as the immediate is active. The `Immediate` object returned by
* `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`
* functions that can be used to control this default behavior.
*/
interface Immediate extends RefCounted, Disposable {
/**
* If true, the `Immediate` object will keep the Node.js event loop active.
* @since v11.0.0
*/
hasRef(): boolean;
/**
* When called, requests that the Node.js event loop _not_ exit so long as the
* `Immediate` is active. Calling `immediate.ref()` multiple times will have no
* effect.
*
* By default, all `Immediate` objects are "ref'ed", making it normally unnecessary
* to call `immediate.ref()` unless `immediate.unref()` had been called previously.
* @since v9.7.0
* @returns a reference to `immediate`
*/
ref(): this;
/**
* When called, the active `Immediate` object will not require the Node.js event
* loop to remain active. If there is no other activity keeping the event loop
* running, the process may exit before the `Immediate` object's callback is
* invoked. Calling `immediate.unref()` multiple times will have no effect.
* @since v9.7.0
* @returns a reference to `immediate`
*/
unref(): this;
/**
* Cancels the immediate. This is similar to calling `clearImmediate()`.
* @since v20.5.0, v18.18.0
*/
[Symbol.dispose](): void;
_onImmediate(...args: any[]): void;
}
// Legacy interface used in Node.js v9 and prior
// TODO: remove in a future major version bump
/** @deprecated Use `NodeJS.Timeout` instead. */
interface Timer extends RefCounted {
hasRef(): boolean;
refresh(): this;
[Symbol.toPrimitive](): number;
}
/**
* This object is created internally and is returned from `setTimeout()` and
* `setInterval()`. It can be passed to either `clearTimeout()` or
* `clearInterval()` in order to cancel the scheduled actions.
*
* By default, when a timer is scheduled using either `setTimeout()` or
* `setInterval()`, the Node.js event loop will continue running as long as the
* timer is active. Each of the `Timeout` objects returned by these functions
* export both `timeout.ref()` and `timeout.unref()` functions that can be used to
* control this default behavior.
*/
interface Timeout extends RefCounted, Disposable, Timer {
/**
* Cancels the timeout.
* @since v0.9.1
* @legacy Use `clearTimeout()` instead.
* @returns a reference to `timeout`
*/
close(): this;
/**
* If true, the `Timeout` object will keep the Node.js event loop active.
* @since v11.0.0
*/
hasRef(): boolean;
/**
* When called, requests that the Node.js event loop _not_ exit so long as the
* `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect.
*
* By default, all `Timeout` objects are "ref'ed", making it normally unnecessary
* to call `timeout.ref()` unless `timeout.unref()` had been called previously.
* @since v0.9.1
* @returns a reference to `timeout`
*/
ref(): this;
/**
* Sets the timer's start time to the current time, and reschedules the timer to
* call its callback at the previously specified duration adjusted to the current
* time. This is useful for refreshing a timer without allocating a new
* JavaScript object.
*
* Using this on a timer that has already called its callback will reactivate the
* timer.
* @since v10.2.0
* @returns a reference to `timeout`
*/
refresh(): this;
/**
* When called, the active `Timeout` object will not require the Node.js event loop
* to remain active. If there is no other activity keeping the event loop running,
* the process may exit before the `Timeout` object's callback is invoked. Calling
* `timeout.unref()` multiple times will have no effect.
* @since v0.9.1
* @returns a reference to `timeout`
*/
unref(): this;
/**
* Coerce a `Timeout` to a primitive. The primitive can be used to
* clear the `Timeout`. The primitive can only be used in the
* same thread where the timeout was created. Therefore, to use it
* across `worker_threads` it must first be passed to the correct
* thread. This allows enhanced compatibility with browser
* `setTimeout()` and `setInterval()` implementations.
* @since v14.9.0, v12.19.0
*/
[Symbol.toPrimitive](): number;
/**
* Cancels the timeout.
* @since v20.5.0, v18.18.0
*/
[Symbol.dispose](): void;
_onTimeout(...args: any[]): void;
}
}
/**
* Schedules the "immediate" execution of the `callback` after I/O events'
* callbacks.
*
* When multiple calls to `setImmediate()` are made, the `callback` functions are
* queued for execution in the order in which they are created. The entire callback
* queue is processed every event loop iteration. If an immediate timer is queued
* from inside an executing callback, that timer will not be triggered until the
* next event loop iteration.
*
* If `callback` is not a function, a `TypeError` will be thrown.
*
* This method has a custom variant for promises that is available using
* `timersPromises.setImmediate()`.
* @since v0.9.1
* @param callback The function to call at the end of this turn of
* the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout)
* @param args Optional arguments to pass when the `callback` is called.
* @returns for use with `clearImmediate()`
*/
function setImmediate<TArgs extends any[]>(
callback: (...args: TArgs) => void,
...args: TArgs
): NodeJS.Immediate;
// Allow a single void-accepting argument to be optional in arguments lists.
// Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258)
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
function setImmediate(callback: (_: void) => void): NodeJS.Immediate;
namespace setImmediate {
import __promisify__ = promises.setImmediate;
export { __promisify__ };
}
/**
* Schedules repeated execution of `callback` every `delay` milliseconds.
*
* When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay`
* will be set to `1`. Non-integer delays are truncated to an integer.
*
* If `callback` is not a function, a `TypeError` will be thrown.
*
* This method has a custom variant for promises that is available using
* `timersPromises.setInterval()`.
* @since v0.0.1
* @param callback The function to call when the timer elapses.
* @param delay The number of milliseconds to wait before calling the
* `callback`. **Default:** `1`.
* @param args Optional arguments to pass when the `callback` is called.
* @returns for use with `clearInterval()`
*/
function setInterval<TArgs extends any[]>(
callback: (...args: TArgs) => void,
delay?: number,
...args: TArgs
): NodeJS.Timeout;
// Allow a single void-accepting argument to be optional in arguments lists.
// Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258)
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
function setInterval(callback: (_: void) => void, delay?: number): NodeJS.Timeout;
/**
* Schedules execution of a one-time `callback` after `delay` milliseconds.
*
* The `callback` will likely not be invoked in precisely `delay` milliseconds.
* Node.js makes no guarantees about the exact timing of when callbacks will fire,
* nor of their ordering. The callback will be called as close as possible to the
* time specified.
*
* When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay`
* will be set to `1`. Non-integer delays are truncated to an integer.
*
* If `callback` is not a function, a `TypeError` will be thrown.
*
* This method has a custom variant for promises that is available using
* `timersPromises.setTimeout()`.
* @since v0.0.1
* @param callback The function to call when the timer elapses.
* @param delay The number of milliseconds to wait before calling the
* `callback`. **Default:** `1`.
* @param args Optional arguments to pass when the `callback` is called.
* @returns for use with `clearTimeout()`
*/
function setTimeout<TArgs extends any[]>(
callback: (...args: TArgs) => void,
delay?: number,
...args: TArgs
): NodeJS.Timeout;
// Allow a single void-accepting argument to be optional in arguments lists.
// Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258)
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout;
namespace setTimeout {
import __promisify__ = promises.setTimeout;
export { __promisify__ };
}
/**
* Cancels an `Immediate` object created by `setImmediate()`.
* @since v0.9.1
* @param immediate An `Immediate` object as returned by `setImmediate()`.
*/
function clearImmediate(immediate: NodeJS.Immediate | undefined): void;
/**
* Cancels a `Timeout` object created by `setInterval()`.
* @since v0.0.1
* @param timeout A `Timeout` object as returned by `setInterval()`
* or the primitive of the `Timeout` object as a string or a number.
*/
function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void;
/**
* Cancels a `Timeout` object created by `setTimeout()`.
* @since v0.0.1
* @param timeout A `Timeout` object as returned by `setTimeout()`
* or the primitive of the `Timeout` object as a string or a number.
*/
function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void;
/**
* The `queueMicrotask()` method queues a microtask to invoke `callback`. If
* `callback` throws an exception, the `process` object `'uncaughtException'`
* event will be emitted.
*
* The microtask queue is managed by V8 and may be used in a similar manner to
* the `process.nextTick()` queue, which is managed by Node.js. The
* `process.nextTick()` queue is always processed before the microtask queue
* within each turn of the Node.js event loop.
* @since v11.0.0
* @param callback Function to be queued.
*/
function queueMicrotask(callback: () => void): void;
}
import clearImmediate = globalThis.clearImmediate;
import clearInterval = globalThis.clearInterval;
import clearTimeout = globalThis.clearTimeout;
import setImmediate = globalThis.setImmediate;
import setInterval = globalThis.setInterval;
import setTimeout = globalThis.setTimeout;
export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout };
}
declare module "node:timers" {
export * from "timers";
}
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=elicitationFormExample.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"circle-parking-off.js","sources":["../../../src/icons/circle-parking-off.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name CircleParkingOff\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIgLz4KICA8cGF0aCBkPSJtNSA1IDE0IDE0IiAvPgogIDxwYXRoIGQ9Ik0xMyAxM2EzIDMgMCAxIDAgMC02SDl2MiIgLz4KICA8cGF0aCBkPSJNOSAxN3YtMi4zNCIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/circle-parking-off\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 CircleParkingOff = createLucideIcon('CircleParkingOff', [\n ['circle', { cx: '12', cy: '12', r: '10', key: '1mglay' }],\n ['path', { d: 'm5 5 14 14', key: '11anup' }],\n ['path', { d: 'M13 13a3 3 0 1 0 0-6H9v2', key: 'uoagbd' }],\n ['path', { d: 'M9 17v-2.34', key: 'a9qo08' }],\n]);\n\nexport default CircleParkingOff;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAmB,iBAAiB,kBAAoB,CAAA,CAAA,CAAA;AAAA,CAC5D,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAM,CAAI,CAAA,CAAA,CAAA,IAAA,CAAM,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CAAA,CACzD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA4B,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAe,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC9C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"file":"transformStreamWithRouter.cjs","names":[],"sources":["../../../src/ssr/transformStreamWithRouter.ts"],"sourcesContent":["import { ReadableStream } from 'node:stream/web'\nimport { Readable } from 'node:stream'\nimport { TSR_SCRIPT_BARRIER_ID } from './constants'\nimport type { AnyRouter } from '../router'\n\nexport function transformReadableStreamWithRouter(\n router: AnyRouter,\n routerStream: ReadableStream,\n) {\n return transformStreamWithRouter(router, routerStream)\n}\n\nexport function transformPipeableStreamWithRouter(\n router: AnyRouter,\n routerStream: Readable,\n) {\n return Readable.fromWeb(\n transformStreamWithRouter(router, Readable.toWeb(routerStream)),\n )\n}\n\n// Use string constants for simple indexOf matching\nconst BODY_END_TAG = '</body>'\nconst HTML_END_TAG = '</html>'\n\n// Minimum length of a valid closing tag: </a> = 4 characters\nconst MIN_CLOSING_TAG_LENGTH = 4\n\n// Default timeout values (in milliseconds)\nconst DEFAULT_SERIALIZATION_TIMEOUT_MS = 60000\nconst DEFAULT_LIFETIME_TIMEOUT_MS = 60000\n\n// Module-level encoder (stateless, safe to reuse)\nconst textEncoder = new TextEncoder()\n\n/**\n * Finds the position just after the last valid HTML closing tag in the string.\n *\n * Valid closing tags match the pattern: </[a-zA-Z][\\w:.-]*>\n * Examples: </div>, </my-component>, </slot:name.nested>\n *\n * @returns Position after the last closing tag, or -1 if none found\n */\nfunction findLastClosingTagEnd(str: string): number {\n const len = str.length\n if (len < MIN_CLOSING_TAG_LENGTH) return -1\n\n let i = len - 1\n\n while (i >= MIN_CLOSING_TAG_LENGTH - 1) {\n // Look for > (charCode 62)\n if (str.charCodeAt(i) === 62) {\n // Look backwards for valid tag name characters\n let j = i - 1\n\n // Skip through valid tag name characters\n while (j >= 1) {\n const code = str.charCodeAt(j)\n // Check if it's a valid tag name char: [a-zA-Z0-9_:.-]\n if (\n (code >= 97 && code <= 122) || // a-z\n (code >= 65 && code <= 90) || // A-Z\n (code >= 48 && code <= 57) || // 0-9\n code === 95 || // _\n code === 58 || // :\n code === 46 || // .\n code === 45 // -\n ) {\n j--\n } else {\n break\n }\n }\n\n // Check if the first char after </ is a valid start char (letter only)\n const tagNameStart = j + 1\n if (tagNameStart < i) {\n const startCode = str.charCodeAt(tagNameStart)\n // Tag name must start with a letter (a-z or A-Z)\n if (\n (startCode >= 97 && startCode <= 122) ||\n (startCode >= 65 && startCode <= 90)\n ) {\n // Check for </ (charCodes: < = 60, / = 47)\n if (\n j >= 1 &&\n str.charCodeAt(j) === 47 &&\n str.charCodeAt(j - 1) === 60\n ) {\n return i + 1 // Return position after the closing >\n }\n }\n }\n }\n i--\n }\n return -1\n}\n\nexport function transformStreamWithRouter(\n router: AnyRouter,\n appStream: ReadableStream,\n opts?: {\n /** Timeout for serialization to complete after app render finishes (default: 60000ms) */\n timeoutMs?: number\n /** Maximum lifetime of the stream transform (default: 60000ms). Safety net for cleanup. */\n lifetimeMs?: number\n },\n) {\n // Check upfront if serialization already finished synchronously\n // This is the fast path for routes with no deferred data\n const serializationAlreadyFinished =\n router.serverSsr?.isSerializationFinished() ?? false\n\n // Take any HTML that was buffered before we started listening\n const initialBufferedHtml = router.serverSsr?.takeBufferedHtml()\n\n // True passthrough: if serialization already finished and nothing buffered,\n // we can avoid any decoding/scanning while still honoring cleanup + setRenderFinished.\n if (serializationAlreadyFinished && !initialBufferedHtml) {\n let cleanedUp = false\n let controller: ReadableStreamDefaultController<Uint8Array> | undefined\n let isStreamClosed = false\n let lifetimeTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n const cleanup = () => {\n if (cleanedUp) return\n cleanedUp = true\n\n if (lifetimeTimeoutHandle !== undefined) {\n clearTimeout(lifetimeTimeoutHandle)\n lifetimeTimeoutHandle = undefined\n }\n\n router.serverSsr?.cleanup()\n }\n\n const safeClose = () => {\n if (isStreamClosed) return\n isStreamClosed = true\n try {\n controller?.close()\n } catch {\n // ignore\n }\n }\n\n const safeError = (error: unknown) => {\n if (isStreamClosed) return\n isStreamClosed = true\n try {\n controller?.error(error)\n } catch {\n // ignore\n }\n }\n\n const lifetimeMs = opts?.lifetimeMs ?? DEFAULT_LIFETIME_TIMEOUT_MS\n lifetimeTimeouLine truncated
@@ -0,0 +1,152 @@
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const pkg = require('../package.json')
const JSON5 = require('./')
const argv = parseArgs()
if (argv.version) {
version()
} else if (argv.help) {
usage()
} else {
const inFilename = argv.defaults[0]
let readStream
if (inFilename) {
readStream = fs.createReadStream(inFilename)
} else {
readStream = process.stdin
}
let json5 = ''
readStream.on('data', data => {
json5 += data
})
readStream.on('end', () => {
let space
if (argv.space === 't' || argv.space === 'tab') {
space = '\t'
} else {
space = Number(argv.space)
}
let value
try {
value = JSON5.parse(json5)
if (!argv.validate) {
const json = JSON.stringify(value, null, space)
let writeStream
// --convert is for backward compatibility with v0.5.1. If
// specified with <file> and not --out-file, then a file with
// the same name but with a .json extension will be written.
if (argv.convert && inFilename && !argv.outFile) {
const parsedFilename = path.parse(inFilename)
const outFilename = path.format(
Object.assign(
parsedFilename,
{base: path.basename(parsedFilename.base, parsedFilename.ext) + '.json'}
)
)
writeStream = fs.createWriteStream(outFilename)
} else if (argv.outFile) {
writeStream = fs.createWriteStream(argv.outFile)
} else {
writeStream = process.stdout
}
writeStream.write(json)
}
} catch (err) {
console.error(err.message)
process.exit(1)
}
})
}
function parseArgs () {
let convert
let space
let validate
let outFile
let version
let help
const defaults = []
const args = process.argv.slice(2)
for (let i = 0; i < args.length; i++) {
const arg = args[i]
switch (arg) {
case '--convert':
case '-c':
convert = true
break
case '--space':
case '-s':
space = args[++i]
break
case '--validate':
case '-v':
validate = true
break
case '--out-file':
case '-o':
outFile = args[++i]
break
case '--version':
case '-V':
version = true
break
case '--help':
case '-h':
help = true
break
default:
defaults.push(arg)
break
}
}
return {
convert,
space,
validate,
outFile,
version,
help,
defaults,
}
}
function version () {
console.log(pkg.version)
}
function usage () {
console.log(
`
Usage: json5 [options] <file>
If <file> is not provided, then STDIN is used.
Options:
-s, --space The number of spaces to indent or 't' for tabs
-o, --out-file [file] Output to the specified file, otherwise STDOUT
-v, --validate Validate JSON5 but do not output JSON
-V, --version Output the version number
-h, --help Output usage information`
)
}
@@ -0,0 +1,14 @@
import type { TSESLint } from '@typescript-eslint/utils';
export type Options = [
{
caseSensitive?: boolean;
checkIntersections?: boolean;
checkUnions?: boolean;
groupOrder?: string[];
}
];
export type MessageIds = 'notSorted' | 'notSortedNamed' | 'suggestFix';
declare const _default: TSESLint.RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
name: string;
};
export default _default;
@@ -0,0 +1,300 @@
/**
* @fileoverview Checks for unreachable code due to return, throws, break, and continue.
* @author Joel Feenstra
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* @typedef {Object} ConstructorInfo
* @property {ConstructorInfo | null} upper Info about the constructor that encloses this constructor.
* @property {boolean} hasSuperCall The flag about having `super()` expressions.
*/
/**
* Checks whether or not a given variable declarator has the initializer.
* @param {ASTNode} node A VariableDeclarator node to check.
* @returns {boolean} `true` if the node has the initializer.
*/
function isInitialized(node) {
return Boolean(node.init);
}
/**
* Checks all segments in a set and returns true if all are unreachable.
* @param {Set<CodePathSegment>} segments The segments to check.
* @returns {boolean} True if all segments are unreachable; false otherwise.
*/
function areAllSegmentsUnreachable(segments) {
for (const segment of segments) {
if (segment.reachable) {
return false;
}
}
return true;
}
/**
* The class to distinguish consecutive unreachable statements.
*/
class ConsecutiveRange {
constructor(sourceCode) {
this.sourceCode = sourceCode;
this.startNode = null;
this.endNode = null;
}
/**
* The location object of this range.
* @type {Object}
*/
get location() {
return {
start: this.startNode.loc.start,
end: this.endNode.loc.end,
};
}
/**
* `true` if this range is empty.
* @type {boolean}
*/
get isEmpty() {
return !(this.startNode && this.endNode);
}
/**
* Checks whether the given node is inside of this range.
* @param {ASTNode|Token} node The node to check.
* @returns {boolean} `true` if the node is inside of this range.
*/
contains(node) {
return (
node.range[0] >= this.startNode.range[0] &&
node.range[1] <= this.endNode.range[1]
);
}
/**
* Checks whether the given node is consecutive to this range.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is consecutive to this range.
*/
isConsecutive(node) {
return this.contains(this.sourceCode.getTokenBefore(node));
}
/**
* Merges the given node to this range.
* @param {ASTNode} node The node to merge.
* @returns {void}
*/
merge(node) {
this.endNode = node;
}
/**
* Resets this range by the given node or null.
* @param {ASTNode|null} node The node to reset, or null.
* @returns {void}
*/
reset(node) {
this.startNode = this.endNode = node;
}
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description:
"Disallow unreachable code after `return`, `throw`, `continue`, and `break` statements",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-unreachable",
},
schema: [],
messages: {
unreachableCode: "Unreachable code.",
},
},
create(context) {
/** @type {ConstructorInfo | null} */
let constructorInfo = null;
/** @type {ConsecutiveRange} */
const range = new ConsecutiveRange(context.sourceCode);
/** @type {Array<Set<CodePathSegment>>} */
const codePathSegments = [];
/** @type {Set<CodePathSegment>} */
let currentCodePathSegments = new Set();
/**
* Reports a given node if it's unreachable.
* @param {ASTNode} node A statement node to report.
* @returns {void}
*/
function reportIfUnreachable(node) {
let nextNode = null;
if (
node &&
(node.type === "PropertyDefinition" ||
areAllSegmentsUnreachable(currentCodePathSegments))
) {
// Store this statement to distinguish consecutive statements.
if (range.isEmpty) {
range.reset(node);
return;
}
// Skip if this statement is inside of the current range.
if (range.contains(node)) {
return;
}
// Merge if this statement is consecutive to the current range.
if (range.isConsecutive(node)) {
range.merge(node);
return;
}
nextNode = node;
}
/*
* Report the current range since this statement is reachable or is
* not consecutive to the current range.
*/
if (!range.isEmpty) {
context.report({
messageId: "unreachableCode",
loc: range.location,
node: range.startNode,
});
}
// Update the current range.
range.reset(nextNode);
}
return {
// Manages the current code path.
onCodePathStart() {
codePathSegments.push(currentCodePathSegments);
currentCodePathSegments = new Set();
},
onCodePathEnd() {
currentCodePathSegments = codePathSegments.pop();
},
onUnreachableCodePathSegmentStart(segment) {
currentCodePathSegments.add(segment);
},
onUnreachableCodePathSegmentEnd(segment) {
currentCodePathSegments.delete(segment);
},
onCodePathSegmentEnd(segment) {
currentCodePathSegments.delete(segment);
},
onCodePathSegmentStart(segment) {
currentCodePathSegments.add(segment);
},
// Registers for all statement nodes (excludes FunctionDeclaration).
BlockStatement: reportIfUnreachable,
BreakStatement: reportIfUnreachable,
ClassDeclaration: reportIfUnreachable,
ContinueStatement: reportIfUnreachable,
DebuggerStatement: reportIfUnreachable,
DoWhileStatement: reportIfUnreachable,
ExpressionStatement: reportIfUnreachable,
ForInStatement: reportIfUnreachable,
ForOfStatement: reportIfUnreachable,
ForStatement: reportIfUnreachable,
IfStatement: reportIfUnreachable,
ImportDeclaration: reportIfUnreachable,
LabeledStatement: reportIfUnreachable,
ReturnStatement: reportIfUnreachable,
SwitchStatement: reportIfUnreachable,
ThrowStatement: reportIfUnreachable,
TryStatement: reportIfUnreachable,
VariableDeclaration(node) {
if (
node.kind !== "var" ||
node.declarations.some(isInitialized)
) {
reportIfUnreachable(node);
}
},
WhileStatement: reportIfUnreachable,
WithStatement: reportIfUnreachable,
ExportNamedDeclaration: reportIfUnreachable,
ExportDefaultDeclaration: reportIfUnreachable,
ExportAllDeclaration: reportIfUnreachable,
"Program:exit"() {
reportIfUnreachable();
},
/*
* Instance fields defined in a subclass are never created if the constructor of the subclass
* doesn't call `super()`, so their definitions are unreachable code.
*/
"MethodDefinition[kind='constructor']"() {
constructorInfo = {
upper: constructorInfo,
hasSuperCall: false,
};
},
"MethodDefinition[kind='constructor']:exit"(node) {
const { hasSuperCall } = constructorInfo;
constructorInfo = constructorInfo.upper;
// skip typescript constructors without the body
if (!node.value.body) {
return;
}
const classDefinition = node.parent.parent;
if (classDefinition.superClass && !hasSuperCall) {
for (const element of classDefinition.body.body) {
if (
element.type === "PropertyDefinition" &&
!element.static
) {
reportIfUnreachable(element);
}
}
}
},
"CallExpression > Super.callee"() {
if (constructorInfo) {
constructorInfo.hasSuperCall = true;
}
},
};
},
};
@@ -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 Dock = createLucideIcon("Dock", [
["path", { d: "M2 8h20", key: "d11cs7" }],
["rect", { width: "20", height: "16", x: "2", y: "4", rx: "2", key: "18n3k1" }],
["path", { d: "M6 16h12", key: "u522kt" }]
]);
export { Dock as default };
//# sourceMappingURL=dock.js.map
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Tinylibs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,3 @@
declare const MAX_SAFE_INTEGER: 9007199254740991;
export = MAX_SAFE_INTEGER;
@@ -0,0 +1,140 @@
# uqr
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![bundle][bundle-src]][bundle-href]
[![License][license-src]][license-href]
[![JSDocs][jsdocs-src]][jsdocs-href]
<!-- [![Codecov][codecov-src]][codecov-href] -->
Generate QR Code universally, in any runtime, to ANSI, Unicode or SVG. ES module , zero dependency, tree-shakable.
## Install
```bash
# Using npm
npm install uqr
# Using yarn
yarn add uqr
# Using pnpm
pnpm add uqr
```
## Usage
```ts
import {
encode,
renderANSI,
renderSVG,
renderUnicode,
renderUnicodeCompact,
} from 'uqr'
const svg = renderSVG('Hello, World!')
const ansi = renderANSI('https://192.168.1.100:3000', {
// Error correction level
ecc: 'L',
// Border width
border: 2,
})
// display QR Code in terminal
console.log(ansi)
```
## API
### `encode`
Encode plain text or binary data into QR Code represented by a 2D array.
```ts
import { encode } from 'uqr'
const {
data, // 2D array of boolean, representing the QR Code
version, // QR Code version
size, // size of the QR Code
} = encode(text, options)
```
### `renderANSI`
Render QR Code to [ANSI colored](https://ss64.com/nt/syntax-ansi.html) string.
```ts
import { renderANSI } from 'uqr'
const string = renderANSI(text, options)
console.log(string)
```
### `renderUnicode`
Render QR Code to Unicode string for each pixel. By default it uses `█` and `░` to represent black and white pixels, and it can be customizable.
```ts
import { renderUnicode } from 'uqr'
const string = renderUnicode(text, {
blackChar: '█',
whiteChar: '░',
// ...other options
})
```
### `renderUnicodeCompact`
Render QR Code with two rows into one line with unicode `▀`, `▄`, `█`, ` `. It is useful when you want to display QR Code in terminal with limited height.
```ts
import { renderUnicodeCompact } from 'uqr'
const string = renderUnicodeCompact(text, options)
console.log(string)
```
### `renderSVG`
Render QR Code to SVG string.
```ts
import { renderSVG } from 'uqr'
const string = renderSVG(text, options)
```
## Alternatives
- [etiket](https://github.com/productdevbook/etiket) — Zero-dependency barcode & QR code SVG generator. 20+ formats (1D barcodes, QR, Data Matrix, PDF417, Aztec), styled QR codes with dot types/gradients/logos, tree-shakeable, CLI tool.
## Credits
QR Code generation algorithm is modified from [nayuki/QR-Code-generator](https://github.com/nayuki/QR-Code-generator/blob/master/typescript-javascript/qrcodegen.ts) by Project Nayuki.
CLI renders are inspired by [qrcode-terminal](https://github.com/gtanner/qrcode-terminal).
## License
[MIT](./LICENSE) License
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/uqr?style=flat&colorA=18181B&colorB=F0DB4F
[npm-version-href]: https://npmjs.com/package/uqr
[npm-downloads-src]: https://img.shields.io/npm/dm/uqr?style=flat&colorA=18181B&colorB=F0DB4F
[npm-downloads-href]: https://npmjs.com/package/uqr
[bundle-src]: https://img.shields.io/bundlephobia/minzip/uqr?style=flat&colorA=18181B&colorB=F0DB4F
[bundle-href]: https://bundlephobia.com/result?p=uqr
[license-src]: https://img.shields.io/github/license/unjs/uqr.svg?style=flat&colorA=18181B&colorB=F0DB4F
[license-href]: https://github.com/unjs/uqr/blob/main/LICENSE
[jsdocs-src]: https://img.shields.io/badge/jsDocs.io-reference-18181B?style=flat&colorA=18181B&colorB=F0DB4F
[jsdocs-href]: https://www.jsdocs.io/package/uqr
@@ -0,0 +1 @@
{"version":3,"file":"leafy-green.js","sources":["../../../src/icons/leafy-green.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name LeafyGreen\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMiAyMmMxLjI1LS45ODcgMi4yNy0xLjk3NSAzLjktMi4yYTUuNTYgNS41NiAwIDAgMSAzLjggMS41IDQgNCAwIDAgMCA2LjE4Ny0yLjM1MyAzLjUgMy41IDAgMCAwIDMuNjktNS4xMTZBMy41IDMuNSAwIDAgMCAyMC45NSA4IDMuNSAzLjUgMCAxIDAgMTYgMy4wNWEzLjUgMy41IDAgMCAwLTUuODMxIDEuMzczIDMuNSAzLjUgMCAwIDAtNS4xMTYgMy42OSA0IDQgMCAwIDAtMi4zNDggNi4xNTVDMy40OTkgMTUuNDIgNC40MDkgMTYuNzEyIDQuMiAxOC4xIDMuOTI2IDE5Ljc0MyAzLjAxNCAyMC43MzIgMiAyMiIgLz4KICA8cGF0aCBkPSJNMiAyMiAxNyA3IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/leafy-green\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 LeafyGreen = createLucideIcon('LeafyGreen', [\n [\n 'path',\n {\n d: 'M2 22c1.25-.987 2.27-1.975 3.9-2.2a5.56 5.56 0 0 1 3.8 1.5 4 4 0 0 0 6.187-2.353 3.5 3.5 0 0 0 3.69-5.116A3.5 3.5 0 0 0 20.95 8 3.5 3.5 0 1 0 16 3.05a3.5 3.5 0 0 0-5.831 1.373 3.5 3.5 0 0 0-5.116 3.69 4 4 0 0 0-2.348 6.155C3.499 15.42 4.409 16.712 4.2 18.1 3.926 19.743 3.014 20.732 2 22',\n key: '1134nt',\n },\n ],\n ['path', { d: 'M2 22 17 7', key: '1q7jp2' }],\n]);\n\nexport default LeafyGreen;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAa,iBAAiB,YAAc,CAAA,CAAA,CAAA;AAAA,CAChD,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA;AAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACP,CAAA,CAAA,CAAA,CAAA;AAAA,CACF,CAAA,CAAA,CAAA;AAAA,CAAA,CACA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC7C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,5 @@
import type { RollupLog } from './rollup';
export type GetLogFilter = typeof getLogFilter;
export function getLogFilter(filters: string[]): (log: RollupLog) => boolean;
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
keyword: "anyOf",
schemaType: "array",
trackErrors: true,
code: code_1.validateUnion,
error: { message: "must match a schema in anyOf" },
};
exports.default = def;
//# sourceMappingURL=anyOf.js.map
@@ -0,0 +1,208 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_utils_accept = require("../../utils/accept.js");
const require_helper_cookie_index = require("../../helper/cookie/index.js");
//#region src/middleware/language/language.ts
const DEFAULT_OPTIONS = {
order: [
"querystring",
"cookie",
"header"
],
lookupQueryString: "lang",
lookupCookie: "language",
lookupFromHeaderKey: "accept-language",
lookupFromPathIndex: 0,
caches: ["cookie"],
ignoreCase: true,
fallbackLanguage: "en",
supportedLanguages: ["en"],
cookieOptions: {
sameSite: "Strict",
secure: true,
maxAge: 31536e3,
httpOnly: true
},
debug: false
};
/**
* Parse Accept-Language header values with quality scores
* @param header Accept-Language header string
* @returns Array of parsed languages with quality scores
*/
function parseAcceptLanguage(header) {
return require_utils_accept.parseAccept(header).map(({ type, q }) => ({
lang: type,
q
}));
}
/**
* Validate and normalize language codes
* @param lang Language code to normalize
* @param options Detector options
* @returns Normalized language code or undefined
*/
const normalizeLanguage = (lang, options) => {
if (!lang) return;
try {
let normalizedLang = lang.trim();
if (options.convertDetectedLanguage) normalizedLang = options.convertDetectedLanguage(normalizedLang);
const compLang = options.ignoreCase ? normalizedLang.toLowerCase() : normalizedLang;
const compSupported = options.supportedLanguages.map((l) => options.ignoreCase ? l.toLowerCase() : l);
const exactIndex = compSupported.indexOf(compLang);
if (exactIndex !== -1) return options.supportedLanguages[exactIndex];
let longestMatchIndex = -1;
let longestMatchLength = -1;
for (let i = 0; i < compSupported.length; i++) {
const candidate = compSupported[i];
if (candidate.length < compLang.length && candidate.length > longestMatchLength && compLang.startsWith(candidate) && compLang[candidate.length] === "-") {
longestMatchIndex = i;
longestMatchLength = candidate.length;
}
}
if (longestMatchIndex !== -1) return options.supportedLanguages[longestMatchIndex];
return;
} catch {
return;
}
};
/**
* Detects language from query parameter
*/
const detectFromQuery = (c, options) => {
const query = c.req.query(options.lookupQueryString);
return normalizeLanguage(query, options);
};
/**
* Detects language from cookie
*/
const detectFromCookie = (c, options) => {
const cookie = require_helper_cookie_index.getCookie(c, options.lookupCookie);
return normalizeLanguage(cookie, options);
};
/**
* Detects language from Accept-Language header
*/
function detectFromHeader(c, options) {
try {
const acceptLanguage = c.req.header(options.lookupFromHeaderKey);
if (!acceptLanguage) return;
const languages = parseAcceptLanguage(acceptLanguage);
for (const { lang, q } of languages) {
if (q === 0) continue;
const normalizedLang = normalizeLanguage(lang, options);
if (normalizedLang) return normalizedLang;
}
return;
} catch {
return;
}
}
/**
* Detects language from URL path
*/
function detectFromPath(c, options) {
const langSegment = new URL(c.req.url).pathname.split("/").filter(Boolean)[options.lookupFromPathIndex];
return normalizeLanguage(langSegment, options);
}
/**
* Collection of all language detection strategies
*/
const detectors = {
querystring: detectFromQuery,
cookie: detectFromCookie,
header: detectFromHeader,
path: detectFromPath
};
/**
* Validate detector options
* @param options Detector options to validate
* @throws Error if options are invalid
*/
function validateOptions(options) {
if (!options.supportedLanguages.includes(options.fallbackLanguage)) throw new Error("Fallback language must be included in supported languages");
if (options.lookupFromPathIndex < 0) throw new Error("Path index must be non-negative");
if (!options.order.every((detector) => Object.keys(detectors).includes(detector))) throw new Error("Invalid detector type in order array");
}
/**
* Cache detected language
*/
function cacheLanguage(c, language, options) {
if (!Array.isArray(options.caches) || !options.caches.includes("cookie")) return;
try {
require_helper_cookie_index.setCookie(c, options.lookupCookie, language, options.cookieOptions);
} catch (error) {
if (options.debug) console.error("Failed to cache language:", error);
}
}
/**
* Detect language from request
*/
const detectLanguage = (c, options) => {
let detectedLang;
for (const detectorName of options.order) {
const detector = detectors[detectorName];
try {
detectedLang = detector(c, options);
if (detectedLang) {
if (options.debug) console.log(`Language detected from ${detectorName}: ${detectedLang}`);
break;
}
} catch (error) {
if (options.debug) console.error(`Error in ${detectorName} detector:`, error);
continue;
}
}
const finalLang = detectedLang || options.fallbackLanguage;
if (detectedLang && options.caches) cacheLanguage(c, finalLang, options);
return finalLang;
};
/**
* Language detector middleware factory
* @param userOptions Configuration options for the language detector
* @returns Hono middleware function
*
* @example
* ```ts
* type Variables = LanguageVariables
* const app = new Hono<{ Variables: Variables }>()
*
* app.use(
* languageDetector({
* supportedLanguages: ['en', 'ja'], // Must include fallback
* fallbackLanguage: 'en', // Required
* })
* )
*
* app.get('/', (c) => {
* const lang = c.get('language')
* return c.text(`Current language: ${lang}`)
* })
* ```
*/
const languageDetector = (userOptions) => {
const options = {
...DEFAULT_OPTIONS,
...userOptions,
cookieOptions: {
...DEFAULT_OPTIONS.cookieOptions,
...userOptions.cookieOptions
}
};
validateOptions(options);
return async function languageDetector(ctx, next) {
const lang = detectLanguage(ctx, options);
ctx.set("language", lang);
await next();
};
};
//#endregion
exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
exports.detectFromCookie = detectFromCookie;
exports.detectFromHeader = detectFromHeader;
exports.detectFromPath = detectFromPath;
exports.detectFromQuery = detectFromQuery;
exports.detectors = detectors;
exports.languageDetector = languageDetector;
exports.normalizeLanguage = normalizeLanguage;
exports.parseAcceptLanguage = parseAcceptLanguage;
exports.validateOptions = validateOptions;
@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.d.ts.map
@@ -0,0 +1,158 @@
import * as util from "../core/util.js";
function getArmenianPlural(count, one, many) {
return Math.abs(count) === 1 ? one : many;
}
function withDefiniteArticle(word) {
if (!word)
return "";
const vowels = ["ա", "ե", "ը", "ի", "ո", "ու", "օ"];
const lastChar = word[word.length - 1];
return word + (vowels.includes(lastChar) ? "ն" : "ը");
}
const error = () => {
const Sizable = {
string: {
unit: {
one: "նշան",
many: "նշաններ",
},
verb: "ունենալ",
},
file: {
unit: {
one: "բայթ",
many: "բայթեր",
},
verb: "ունենալ",
},
array: {
unit: {
one: "տարր",
many: "տարրեր",
},
verb: "ունենալ",
},
set: {
unit: {
one: "տարր",
many: "տարրեր",
},
verb: "ունենալ",
},
map: {
unit: {
one: "տարր",
many: "տարրեր",
},
verb: "ունենալ",
},
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
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 = {
nan: "NaN",
number: "թիվ",
array: "զանգված",
};
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;
if (/^[A-Z]/.test(issue.expected)) {
return `Սխալ մուտքագրում․ սպասվում էր instanceof ${issue.expected}, ստացվել է ${received}`;
}
return `Սխալ մուտքագրում․ սպասվում էր ${expected}, ստացվել է ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Սխալ մուտքագրում․ սպասվում էր ${util.stringifyPrimitive(issue.values[1])}`;
return `Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing) {
const maxValue = Number(issue.maximum);
const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many);
return `Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin ?? "արժեք")} կունենա ${adj}${issue.maximum.toString()} ${unit}`;
}
return `Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin ?? "արժեք")} լինի ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
const minValue = Number(issue.minimum);
const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many);
return `Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin)} կունենա ${adj}${issue.minimum.toString()} ${unit}`;
}
return `Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin)} լինի ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
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 `Սխալ բանալի ${withDefiniteArticle(issue.origin)}-ում`;
case "invalid_union":
return "Սխալ մուտքագրում";
case "invalid_element":
return `Սխալ արժեք ${withDefiniteArticle(issue.origin)}-ում`;
default:
return `Սխալ մուտքագրում`;
}
};
};
export default function () {
return {
localeError: error(),
};
}
@@ -0,0 +1,2 @@
export { ModuleImporter };
import { ModuleImporter } from "./module-importer.cjs";
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = shallowEqual;
function shallowEqual(actual, expected) {
const keys = Object.keys(expected);
for (const key of keys) {
if (actual[key] !== expected[key]) {
return false;
}
}
return true;
}
//# sourceMappingURL=shallowEqual.js.map
@@ -0,0 +1,10 @@
{
"rules": {
"multiline-comment-style": 0,
"capitalized-comments": 0,
"unicorn/escape-case": 0,
"unicorn/no-hex-escape": 0,
"unicorn/numeric-separators-style": 0,
"unicorn/prefer-spread": 0
}
}
@@ -0,0 +1,83 @@
import { RouterCore, AnyRoute, CreateRouterFn, RouterConstructorOptions, TrailingSlashOption } from '@tanstack/router-core';
import { RouterHistory } from '@tanstack/history';
import { ErrorRouteComponent, NotFoundRouteComponent, RouteComponent } from './route.js';
declare module '@tanstack/router-core' {
interface RouterOptionsExtensions {
/**
* The default `component` a route should use if no component is provided.
*
* @default Outlet
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultcomponent-property)
*/
defaultComponent?: RouteComponent;
/**
* The default `errorComponent` a route should use if no error component is provided.
*
* @default ErrorComponent
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaulterrorcomponent-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionserrorcomponent)
*/
defaultErrorComponent?: ErrorRouteComponent;
/**
* The default `pendingComponent` a route should use if no pending component is provided.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingcomponent-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#showing-a-pending-component)
*/
defaultPendingComponent?: RouteComponent;
/**
* The default `notFoundComponent` a route should use if no notFound component is provided.
*
* @default NotFound
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultnotfoundcomponent-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/not-found-errors#default-router-wide-not-found-handling)
*/
defaultNotFoundComponent?: NotFoundRouteComponent;
/**
* A component that will be used to wrap the entire router.
*
* This is useful for providing a context to the entire router.
*
* Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#wrap-property)
*/
Wrap?: (props: {
children: any;
}) => React.JSX.Element;
/**
* A component that will be used to wrap the inner contents of the router.
*
* This is useful for providing a context to the inner contents of the router where you also need access to the router context and hooks.
*
* Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#innerwrap-property)
*/
InnerWrap?: (props: {
children: any;
}) => React.JSX.Element;
/**
* The default `onCatch` handler for errors caught by the Router ErrorBoundary
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultoncatch-property)
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionsoncatch)
*/
defaultOnCatch?: (error: Error, errorInfo: React.ErrorInfo) => void;
}
}
/**
* Creates a new Router instance for React.
*
* Pass the returned router to `RouterProvider` to enable routing.
* Notable options: `routeTree` (your route definitions) and `context`
* (required if the root route was created with `createRootRouteWithContext`).
*
* @param options Router options used to configure the router.
* @returns A Router instance to be provided to `RouterProvider`.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction
*/
export declare const createRouter: CreateRouterFn;
export declare class Router<in out TRouteTree extends AnyRoute, in out TTrailingSlashOption extends TrailingSlashOption = 'never', in out TDefaultStructuralSharingOption extends boolean = false, in out TRouterHistory extends RouterHistory = RouterHistory, in out TDehydrated extends Record<string, any> = Record<string, any>> extends RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated> {
constructor(options: RouterConstructorOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>);
}
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _inheritsLoose;
var _setPrototypeOf = require("./setPrototypeOf.js");
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
(0, _setPrototypeOf.default)(subClass, superClass);
}
//# sourceMappingURL=inheritsLoose.js.map