This commit is contained in:
2025-05-09 05:30:08 +02:00
parent 7bb10e7df4
commit 73367bad9e
5322 changed files with 1266973 additions and 313 deletions

View File

@@ -0,0 +1,242 @@
/**
* @fileoverview Enforces that a return statement is present in property getters.
* @author Aladdin-ADD(hh_2013@foxmail.com)
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
/**
* Checks all segments in a set and returns true if any are reachable.
* @param {Set<CodePathSegment>} segments The segments to check.
* @returns {boolean} True if any segment is reachable; false otherwise.
*/
function isAnySegmentReachable(segments) {
for (const segment of segments) {
if (segment.reachable) {
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "problem",
defaultOptions: [
{
allowImplicit: false,
},
],
docs: {
description: "Enforce `return` statements in getters",
recommended: true,
url: "https://eslint.org/docs/latest/rules/getter-return",
},
fixable: null,
schema: [
{
type: "object",
properties: {
allowImplicit: {
type: "boolean",
},
},
additionalProperties: false,
},
],
messages: {
expected: "Expected to return a value in {{name}}.",
expectedAlways: "Expected {{name}} to always return a value.",
},
},
create(context) {
const [{ allowImplicit }] = context.options;
const sourceCode = context.sourceCode;
let funcInfo = {
upper: null,
codePath: null,
hasReturn: false,
shouldCheck: false,
node: null,
currentSegments: [],
};
/**
* Checks whether or not the last code path segment is reachable.
* Then reports this function if the segment is reachable.
*
* If the last code path segment is reachable, there are paths which are not
* returned or thrown.
* @param {ASTNode} node A node to check.
* @returns {void}
*/
function checkLastSegment(node) {
if (
funcInfo.shouldCheck &&
isAnySegmentReachable(funcInfo.currentSegments)
) {
context.report({
node,
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
messageId: funcInfo.hasReturn
? "expectedAlways"
: "expected",
data: {
name: astUtils.getFunctionNameWithKind(funcInfo.node),
},
});
}
}
/**
* Checks whether a node means a getter function.
* @param {ASTNode} node a node to check.
* @returns {boolean} if node means a getter, return true; else return false.
*/
function isGetter(node) {
const parent = node.parent;
if (
TARGET_NODE_TYPE.test(node.type) &&
node.body.type === "BlockStatement"
) {
if (parent.kind === "get") {
return true;
}
if (
parent.type === "Property" &&
astUtils.getStaticPropertyName(parent) === "get" &&
parent.parent.type === "ObjectExpression"
) {
// Object.defineProperty() or Reflect.defineProperty()
if (parent.parent.parent.type === "CallExpression") {
const callNode = parent.parent.parent.callee;
if (
astUtils.isSpecificMemberAccess(
callNode,
"Object",
"defineProperty",
) ||
astUtils.isSpecificMemberAccess(
callNode,
"Reflect",
"defineProperty",
)
) {
return true;
}
}
// Object.defineProperties() or Object.create()
if (
parent.parent.parent.type === "Property" &&
parent.parent.parent.parent.type ===
"ObjectExpression" &&
parent.parent.parent.parent.parent.type ===
"CallExpression"
) {
const callNode =
parent.parent.parent.parent.parent.callee;
return (
astUtils.isSpecificMemberAccess(
callNode,
"Object",
"defineProperties",
) ||
astUtils.isSpecificMemberAccess(
callNode,
"Object",
"create",
)
);
}
}
}
return false;
}
return {
// Stacks this function's information.
onCodePathStart(codePath, node) {
funcInfo = {
upper: funcInfo,
codePath,
hasReturn: false,
shouldCheck: isGetter(node),
node,
currentSegments: new Set(),
};
},
// Pops this function's information.
onCodePathEnd() {
funcInfo = funcInfo.upper;
},
onUnreachableCodePathSegmentStart(segment) {
funcInfo.currentSegments.add(segment);
},
onUnreachableCodePathSegmentEnd(segment) {
funcInfo.currentSegments.delete(segment);
},
onCodePathSegmentStart(segment) {
funcInfo.currentSegments.add(segment);
},
onCodePathSegmentEnd(segment) {
funcInfo.currentSegments.delete(segment);
},
// Checks the return statement is valid.
ReturnStatement(node) {
if (funcInfo.shouldCheck) {
funcInfo.hasReturn = true;
// if allowImplicit: false, should also check node.argument
if (!allowImplicit && !node.argument) {
context.report({
node,
messageId: "expected",
data: {
name: astUtils.getFunctionNameWithKind(
funcInfo.node,
),
},
});
}
}
},
// Reports a given function if the last path is reachable.
"FunctionExpression:exit": checkLastSegment,
"ArrowFunctionExpression:exit": checkLastSegment,
};
},
};

View File

@@ -0,0 +1,581 @@
/**
* @fileoverview Enforces empty lines around comments.
* @author Jamund Ferguson
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Return an array with any line numbers that are empty.
* @param {Array} lines An array of each line of the file.
* @returns {Array} An array of line numbers.
*/
function getEmptyLineNums(lines) {
const emptyLines = lines
.map((line, i) => ({
code: line.trim(),
num: i + 1,
}))
.filter(line => !line.code)
.map(line => line.num);
return emptyLines;
}
/**
* Return an array with any line numbers that contain comments.
* @param {Array} comments An array of comment tokens.
* @returns {Array} An array of line numbers.
*/
function getCommentLineNums(comments) {
const lines = [];
comments.forEach(token => {
const start = token.loc.start.line;
const end = token.loc.end.line;
lines.push(start, end);
});
return lines;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "10.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin-js",
url: "https://eslint.style/packages/js",
},
rule: {
name: "lines-around-comment",
url: "https://eslint.style/rules/js/lines-around-comment",
},
},
],
},
type: "layout",
docs: {
description: "Require empty lines around comments",
recommended: false,
url: "https://eslint.org/docs/latest/rules/lines-around-comment",
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
beforeBlockComment: {
type: "boolean",
default: true,
},
afterBlockComment: {
type: "boolean",
default: false,
},
beforeLineComment: {
type: "boolean",
default: false,
},
afterLineComment: {
type: "boolean",
default: false,
},
allowBlockStart: {
type: "boolean",
default: false,
},
allowBlockEnd: {
type: "boolean",
default: false,
},
allowClassStart: {
type: "boolean",
},
allowClassEnd: {
type: "boolean",
},
allowObjectStart: {
type: "boolean",
},
allowObjectEnd: {
type: "boolean",
},
allowArrayStart: {
type: "boolean",
},
allowArrayEnd: {
type: "boolean",
},
ignorePattern: {
type: "string",
},
applyDefaultIgnorePatterns: {
type: "boolean",
},
afterHashbangComment: {
type: "boolean",
default: false,
},
},
additionalProperties: false,
},
],
messages: {
after: "Expected line after comment.",
before: "Expected line before comment.",
},
},
create(context) {
const options = Object.assign({}, context.options[0]);
const ignorePattern = options.ignorePattern;
const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN;
const customIgnoreRegExp = new RegExp(ignorePattern, "u");
const applyDefaultIgnorePatterns =
options.applyDefaultIgnorePatterns !== false;
options.beforeBlockComment =
typeof options.beforeBlockComment !== "undefined"
? options.beforeBlockComment
: true;
const sourceCode = context.sourceCode;
const lines = sourceCode.lines,
numLines = lines.length + 1,
comments = sourceCode.getAllComments(),
commentLines = getCommentLineNums(comments),
emptyLines = getEmptyLineNums(lines),
commentAndEmptyLines = new Set(commentLines.concat(emptyLines));
/**
* Returns whether or not comments are on lines starting with or ending with code
* @param {token} token The comment token to check.
* @returns {boolean} True if the comment is not alone.
*/
function codeAroundComment(token) {
let currentToken = token;
do {
currentToken = sourceCode.getTokenBefore(currentToken, {
includeComments: true,
});
} while (currentToken && astUtils.isCommentToken(currentToken));
if (
currentToken &&
astUtils.isTokenOnSameLine(currentToken, token)
) {
return true;
}
currentToken = token;
do {
currentToken = sourceCode.getTokenAfter(currentToken, {
includeComments: true,
});
} while (currentToken && astUtils.isCommentToken(currentToken));
if (
currentToken &&
astUtils.isTokenOnSameLine(token, currentToken)
) {
return true;
}
return false;
}
/**
* Returns whether or not comments are inside a node type or not.
* @param {ASTNode} parent The Comment parent node.
* @param {string} nodeType The parent type to check against.
* @returns {boolean} True if the comment is inside nodeType.
*/
function isParentNodeType(parent, nodeType) {
return (
parent.type === nodeType ||
(parent.body && parent.body.type === nodeType) ||
(parent.consequent && parent.consequent.type === nodeType)
);
}
/**
* Returns the parent node that contains the given token.
* @param {token} token The token to check.
* @returns {ASTNode|null} The parent node that contains the given token.
*/
function getParentNodeOfToken(token) {
const node = sourceCode.getNodeByRangeIndex(token.range[0]);
/*
* For the purpose of this rule, the comment token is in a `StaticBlock` node only
* if it's inside the braces of that `StaticBlock` node.
*
* Example where this function returns `null`:
*
* static
* // comment
* {
* }
*
* Example where this function returns `StaticBlock` node:
*
* static
* {
* // comment
* }
*
*/
if (node && node.type === "StaticBlock") {
const openingBrace = sourceCode.getFirstToken(node, {
skip: 1,
}); // skip the `static` token
return token.range[0] >= openingBrace.range[0] ? node : null;
}
return node;
}
/**
* Returns whether or not comments are at the parent start or not.
* @param {token} token The Comment token.
* @param {string} nodeType The parent type to check against.
* @returns {boolean} True if the comment is at parent start.
*/
function isCommentAtParentStart(token, nodeType) {
const parent = getParentNodeOfToken(token);
if (parent && isParentNodeType(parent, nodeType)) {
let parentStartNodeOrToken = parent;
if (parent.type === "StaticBlock") {
parentStartNodeOrToken = sourceCode.getFirstToken(parent, {
skip: 1,
}); // opening brace of the static block
} else if (parent.type === "SwitchStatement") {
parentStartNodeOrToken = sourceCode.getTokenAfter(
parent.discriminant,
{
filter: astUtils.isOpeningBraceToken,
},
); // opening brace of the switch statement
}
return (
token.loc.start.line -
parentStartNodeOrToken.loc.start.line ===
1
);
}
return false;
}
/**
* Returns whether or not comments are at the parent end or not.
* @param {token} token The Comment token.
* @param {string} nodeType The parent type to check against.
* @returns {boolean} True if the comment is at parent end.
*/
function isCommentAtParentEnd(token, nodeType) {
const parent = getParentNodeOfToken(token);
return (
!!parent &&
isParentNodeType(parent, nodeType) &&
parent.loc.end.line - token.loc.end.line === 1
);
}
/**
* Returns whether or not comments are at the block start or not.
* @param {token} token The Comment token.
* @returns {boolean} True if the comment is at block start.
*/
function isCommentAtBlockStart(token) {
return (
isCommentAtParentStart(token, "ClassBody") ||
isCommentAtParentStart(token, "BlockStatement") ||
isCommentAtParentStart(token, "StaticBlock") ||
isCommentAtParentStart(token, "SwitchCase") ||
isCommentAtParentStart(token, "SwitchStatement")
);
}
/**
* Returns whether or not comments are at the block end or not.
* @param {token} token The Comment token.
* @returns {boolean} True if the comment is at block end.
*/
function isCommentAtBlockEnd(token) {
return (
isCommentAtParentEnd(token, "ClassBody") ||
isCommentAtParentEnd(token, "BlockStatement") ||
isCommentAtParentEnd(token, "StaticBlock") ||
isCommentAtParentEnd(token, "SwitchCase") ||
isCommentAtParentEnd(token, "SwitchStatement")
);
}
/**
* Returns whether or not comments are at the class start or not.
* @param {token} token The Comment token.
* @returns {boolean} True if the comment is at class start.
*/
function isCommentAtClassStart(token) {
return isCommentAtParentStart(token, "ClassBody");
}
/**
* Returns whether or not comments are at the class end or not.
* @param {token} token The Comment token.
* @returns {boolean} True if the comment is at class end.
*/
function isCommentAtClassEnd(token) {
return isCommentAtParentEnd(token, "ClassBody");
}
/**
* Returns whether or not comments are at the object start or not.
* @param {token} token The Comment token.
* @returns {boolean} True if the comment is at object start.
*/
function isCommentAtObjectStart(token) {
return (
isCommentAtParentStart(token, "ObjectExpression") ||
isCommentAtParentStart(token, "ObjectPattern")
);
}
/**
* Returns whether or not comments are at the object end or not.
* @param {token} token The Comment token.
* @returns {boolean} True if the comment is at object end.
*/
function isCommentAtObjectEnd(token) {
return (
isCommentAtParentEnd(token, "ObjectExpression") ||
isCommentAtParentEnd(token, "ObjectPattern")
);
}
/**
* Returns whether or not comments are at the array start or not.
* @param {token} token The Comment token.
* @returns {boolean} True if the comment is at array start.
*/
function isCommentAtArrayStart(token) {
return (
isCommentAtParentStart(token, "ArrayExpression") ||
isCommentAtParentStart(token, "ArrayPattern")
);
}
/**
* Returns whether or not comments are at the array end or not.
* @param {token} token The Comment token.
* @returns {boolean} True if the comment is at array end.
*/
function isCommentAtArrayEnd(token) {
return (
isCommentAtParentEnd(token, "ArrayExpression") ||
isCommentAtParentEnd(token, "ArrayPattern")
);
}
/**
* Checks if a comment token has lines around it (ignores inline comments)
* @param {token} token The Comment token.
* @param {Object} opts Options to determine the newline.
* @param {boolean} opts.after Should have a newline after this line.
* @param {boolean} opts.before Should have a newline before this line.
* @returns {void}
*/
function checkForEmptyLine(token, opts) {
if (
applyDefaultIgnorePatterns &&
defaultIgnoreRegExp.test(token.value)
) {
return;
}
if (ignorePattern && customIgnoreRegExp.test(token.value)) {
return;
}
let after = opts.after,
before = opts.before;
const prevLineNum = token.loc.start.line - 1,
nextLineNum = token.loc.end.line + 1,
commentIsNotAlone = codeAroundComment(token);
const blockStartAllowed =
options.allowBlockStart &&
isCommentAtBlockStart(token) &&
!(
options.allowClassStart === false &&
isCommentAtClassStart(token)
),
blockEndAllowed =
options.allowBlockEnd &&
isCommentAtBlockEnd(token) &&
!(
options.allowClassEnd === false &&
isCommentAtClassEnd(token)
),
classStartAllowed =
options.allowClassStart && isCommentAtClassStart(token),
classEndAllowed =
options.allowClassEnd && isCommentAtClassEnd(token),
objectStartAllowed =
options.allowObjectStart && isCommentAtObjectStart(token),
objectEndAllowed =
options.allowObjectEnd && isCommentAtObjectEnd(token),
arrayStartAllowed =
options.allowArrayStart && isCommentAtArrayStart(token),
arrayEndAllowed =
options.allowArrayEnd && isCommentAtArrayEnd(token);
const exceptionStartAllowed =
blockStartAllowed ||
classStartAllowed ||
objectStartAllowed ||
arrayStartAllowed;
const exceptionEndAllowed =
blockEndAllowed ||
classEndAllowed ||
objectEndAllowed ||
arrayEndAllowed;
// ignore top of the file and bottom of the file
if (prevLineNum < 1) {
before = false;
}
if (nextLineNum >= numLines) {
after = false;
}
// we ignore all inline comments
if (commentIsNotAlone) {
return;
}
const previousTokenOrComment = sourceCode.getTokenBefore(token, {
includeComments: true,
});
const nextTokenOrComment = sourceCode.getTokenAfter(token, {
includeComments: true,
});
// check for newline before
if (
!exceptionStartAllowed &&
before &&
!commentAndEmptyLines.has(prevLineNum) &&
!(
astUtils.isCommentToken(previousTokenOrComment) &&
astUtils.isTokenOnSameLine(previousTokenOrComment, token)
)
) {
const lineStart = token.range[0] - token.loc.start.column;
const range = [lineStart, lineStart];
context.report({
node: token,
messageId: "before",
fix(fixer) {
return fixer.insertTextBeforeRange(range, "\n");
},
});
}
// check for newline after
if (
!exceptionEndAllowed &&
after &&
!commentAndEmptyLines.has(nextLineNum) &&
!(
astUtils.isCommentToken(nextTokenOrComment) &&
astUtils.isTokenOnSameLine(token, nextTokenOrComment)
)
) {
context.report({
node: token,
messageId: "after",
fix(fixer) {
return fixer.insertTextAfter(token, "\n");
},
});
}
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
Program() {
comments.forEach(token => {
if (token.type === "Line") {
if (
options.beforeLineComment ||
options.afterLineComment
) {
checkForEmptyLine(token, {
after: options.afterLineComment,
before: options.beforeLineComment,
});
}
} else if (token.type === "Block") {
if (
options.beforeBlockComment ||
options.afterBlockComment
) {
checkForEmptyLine(token, {
after: options.afterBlockComment,
before: options.beforeBlockComment,
});
}
} else if (token.type === "Shebang") {
if (options.afterHashbangComment) {
checkForEmptyLine(token, {
after: options.afterHashbangComment,
before: false,
});
}
}
});
},
};
},
};

View File

@@ -0,0 +1,58 @@
import { useMatch } from './useMatch'
import type {
StructuralSharingOption,
ValidateSelected,
} from './structuralSharing'
import type {
AnyRouter,
RegisteredRouter,
ResolveUseLoaderDeps,
StrictOrFrom,
UseLoaderDepsResult,
} from '@tanstack/router-core'
export interface UseLoaderDepsBaseOptions<
TRouter extends AnyRouter,
TFrom,
TSelected,
TStructuralSharing,
> {
select?: (
deps: ResolveUseLoaderDeps<TRouter, TFrom>,
) => ValidateSelected<TRouter, TSelected, TStructuralSharing>
}
export type UseLoaderDepsOptions<
TRouter extends AnyRouter,
TFrom extends string | undefined,
TSelected,
TStructuralSharing,
> = StrictOrFrom<TRouter, TFrom> &
UseLoaderDepsBaseOptions<TRouter, TFrom, TSelected, TStructuralSharing> &
StructuralSharingOption<TRouter, TSelected, TStructuralSharing>
export type UseLoaderDepsRoute<out TId> = <
TRouter extends AnyRouter = RegisteredRouter,
TSelected = unknown,
TStructuralSharing extends boolean = boolean,
>(
opts?: UseLoaderDepsBaseOptions<TRouter, TId, TSelected, TStructuralSharing> &
StructuralSharingOption<TRouter, TSelected, false>,
) => UseLoaderDepsResult<TRouter, TId, TSelected>
export function useLoaderDeps<
TRouter extends AnyRouter = RegisteredRouter,
const TFrom extends string | undefined = undefined,
TSelected = unknown,
TStructuralSharing extends boolean = boolean,
>(
opts: UseLoaderDepsOptions<TRouter, TFrom, TSelected, TStructuralSharing>,
): UseLoaderDepsResult<TRouter, TFrom, TSelected> {
const { select, ...rest } = opts
return useMatch({
...rest,
select: (s) => {
return select ? select(s.loaderDeps) : s.loaderDeps
},
}) as UseLoaderDepsResult<TRouter, TFrom, TSelected>
}

View File

@@ -0,0 +1,22 @@
/**
Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line.
@example
```
import shebangRegex = require('shebang-regex');
const string = '#!/usr/bin/env node\nconsole.log("unicorns");';
shebangRegex.test(string);
//=> true
shebangRegex.exec(string)[0];
//=> '#!/usr/bin/env node'
shebangRegex.exec(string)[1];
//=> '/usr/bin/env node'
```
*/
declare const shebangRegex: RegExp;
export = shebangRegex;

View File

@@ -0,0 +1 @@
module.exports={C:{"109":0.00479,"115":0.22532,"118":0.00959,"128":0.05273,"132":0.00479,"134":0.00479,"135":1.86007,"136":7.85257,_:"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 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 110 111 112 113 114 116 117 119 120 121 122 123 124 125 126 127 129 130 131 133 137 138 139 140 3.5 3.6"},D:{"39":0.00479,"40":0.00479,"41":0.00479,"42":0.00959,"43":0.00479,"44":0.00479,"45":0.03835,"46":0.00479,"47":0.00479,"48":0.00479,"49":0.00479,"51":0.00479,"52":0.00479,"53":0.00479,"54":0.00479,"55":0.00479,"56":0.00479,"57":0.00479,"58":0.00479,"59":0.00479,"60":0.00479,"79":0.00479,"88":0.00479,"94":0.00479,"99":0.01438,"101":0.00959,"102":0.00479,"103":0.08629,"104":0.00959,"105":0.16779,"108":0.02397,"109":0.16779,"111":0.00479,"112":0.01438,"116":0.12464,"117":0.01438,"119":0.01918,"120":0.02397,"122":0.00479,"123":0.00479,"124":0.02876,"125":0.02876,"126":0.60404,"127":0.08629,"128":0.06712,"129":0.01918,"130":0.06232,"131":0.28764,"132":0.69034,"133":6.90815,"134":8.8689,"135":0.00959,_:"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 50 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 80 81 83 84 85 86 87 89 90 91 92 93 95 96 97 98 100 106 107 110 113 114 115 118 121 136 137 138"},F:{"95":0.02876,"116":0.12944,"117":0.27805,_:"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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"92":0.02397,"100":0.01438,"104":0.14382,"107":0.03356,"109":0.09588,"110":0.00959,"114":0.00479,"115":0.03835,"116":0.00959,"120":0.00479,"121":0.00479,"122":0.01438,"123":0.00479,"126":0.02397,"127":0.00959,"128":0.01918,"129":0.01918,"130":0.02876,"131":0.05273,"132":0.12464,"133":2.84764,"134":6.34726,_:"12 13 14 15 16 17 18 79 80 81 83 84 85 86 87 88 89 90 91 93 94 95 96 97 98 99 101 102 103 105 106 108 111 112 113 117 118 119 124 125"},E:{"13":0.0815,_:"0 4 5 6 7 8 9 10 11 12 14 15 3.1 3.2 5.1 6.1 7.1 9.1 10.1 11.1 12.1 15.2-15.3","13.1":0.02876,"14.1":0.10067,"15.1":0.00479,"15.4":0.00959,"15.5":0.00479,"15.6":0.62322,"16.0":0.18697,"16.1":0.04315,"16.2":0.00479,"16.3":0.02397,"16.4":0.07191,"16.5":0.11026,"16.6":0.73828,"17.0":0.00479,"17.1":0.64719,"17.2":0.04315,"17.3":0.25888,"17.4":0.10067,"17.5":0.12944,"17.6":0.51296,"18.0":0.06712,"18.1":0.52255,"18.2":0.10547,"18.3":3.55715,"18.4":0.00959},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00587,"5.0-5.1":0,"6.0-6.1":0.0176,"7.0-7.1":0.01174,"8.1-8.4":0,"9.0-9.2":0.0088,"9.3":0.04108,"10.0-10.2":0.00293,"10.3":0.06749,"11.0-11.2":0.31102,"11.3-11.4":0.02054,"12.0-12.1":0.01174,"12.2-12.5":0.29048,"13.0-13.1":0.00587,"13.2":0.0088,"13.3":0.01174,"13.4-13.7":0.04108,"14.0-14.4":0.1027,"14.5-14.8":0.12323,"15.0-15.1":0.06749,"15.2-15.3":0.06749,"15.4":0.08216,"15.5":0.09389,"15.6-15.8":1.15605,"16.0":0.16431,"16.1":0.33743,"16.2":0.17605,"16.3":0.30515,"16.4":0.06749,"16.5":0.12617,"16.6-16.7":1.37025,"17.0":0.08216,"17.1":0.14671,"17.2":0.1115,"17.3":0.15551,"17.4":0.31102,"17.5":0.69246,"17.6-17.7":2.00989,"18.0":0.56336,"18.1":1.84264,"18.2":0.82449,"18.3":17.23223,"18.4":0.25527},P:{"4":0.02168,"22":0.02168,"27":1.76697,_:"20 21 23 24 25 26 5.0-5.4 6.2-6.4 8.2 9.2 10.1 11.1-11.2 12.0 13.0 14.0 15.0 16.0 17.0 18.0","7.2-7.4":0.01084,"19.0":0.03252},I:{"0":0.03118,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0,"4.2-4.3":0.00001,"4.4":0,"4.4.3-4.4.4":0.00003},K:{"0":0.05728,_:"10 11 12 11.1 11.5 12.1"},A:{"11":0.05753,_:"6 7 8 9 10 5.5"},S:{_:"2.5 3.0-3.1"},J:{_:"7 10"},N:{_:"10 11"},R:{_:"0"},M:{"0":0.61443},Q:{_:"14.9"},O:{"0":0.00521},H:{"0":0},L:{"0":20.54603}};

View File

@@ -0,0 +1,201 @@
var concatMap = require('concat-map');
var balanced = require('balanced-match');
module.exports = expandTop;
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
function numeric(str) {
return parseInt(str, 10) == str
? parseInt(str, 10)
: str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.');
}
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
if (!str)
return [''];
var parts = [];
var m = balanced('{', '}', str);
if (!m)
return str.split(',');
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(',');
p[p.length-1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length-1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
// I don't know why Bash 4.3 does this, but it does.
// Anything starting with {} will have the first two bytes preserved
// but *only* at the top level, so {},a}b will not expand to anything,
// but a{},b}c will be expanded to [a}c,abc].
// One could argue that this is a bug in Bash, but since the goal of
// this module is to match Bash's rules, we escape a leading {}
if (str.substr(0, 2) === '{}') {
str = '\\{\\}' + str.substr(2);
}
return expand(escapeBraces(str), true).map(unescapeBraces);
}
function identity(e) {
return e;
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand(str, isTop) {
var expansions = [];
var m = balanced('{', '}', str);
if (!m || /\$$/.test(m.pre)) return [str];
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(',') >= 0;
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,.*\}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
return expand(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand(n[0], false).map(embrace);
if (n.length === 1) {
var post = m.post.length
? expand(m.post, false)
: [''];
return post.map(function(p) {
return m.pre + n[0] + p;
});
}
}
}
// at this point, n is the parts, and we know it's not a comma set
// with a single entry.
// no need to expand pre, since it is guaranteed to be free of brace-sets
var pre = m.pre;
var post = m.post.length
? expand(m.post, false)
: [''];
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length)
var incr = n.length == 3
? Math.abs(numeric(n[2]))
: 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\')
c = '';
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join('0');
if (i < 0)
c = '-' + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = concatMap(n, function(el) { return expand(el, false) });
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
return expansions;
}

View File

@@ -0,0 +1,2 @@
import { type ThisEncode } from "./utils.js";
export declare function flatten(this: ThisEncode, input: unknown): number | [number];

View File

@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _classPrivateFieldGet2;
var _assertClassBrand = require("./assertClassBrand.js");
function _classPrivateFieldGet2(privateMap, receiver) {
return privateMap.get((0, _assertClassBrand.default)(privateMap, receiver));
}
//# sourceMappingURL=classPrivateFieldGet2.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_index","require","_index2","toBlock","node","parent","isBlockStatement","blockNodes","isEmptyStatement","isStatement","isFunction","returnStatement","expressionStatement","blockStatement"],"sources":["../../src/converters/toBlock.ts"],"sourcesContent":["import {\n isBlockStatement,\n isFunction,\n isEmptyStatement,\n isStatement,\n} from \"../validators/generated/index.ts\";\nimport {\n returnStatement,\n expressionStatement,\n blockStatement,\n} from \"../builders/generated/index.ts\";\nimport type * as t from \"../index.ts\";\n\nexport default function toBlock(\n node: t.Statement | t.Expression,\n parent?: t.Node,\n): t.BlockStatement {\n if (isBlockStatement(node)) {\n return node;\n }\n\n let blockNodes: t.Statement[] = [];\n\n if (isEmptyStatement(node)) {\n blockNodes = [];\n } else {\n if (!isStatement(node)) {\n if (isFunction(parent)) {\n node = returnStatement(node);\n } else {\n node = expressionStatement(node);\n }\n }\n\n blockNodes = [node];\n }\n\n return blockStatement(blockNodes);\n}\n"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAMA,IAAAC,OAAA,GAAAD,OAAA;AAOe,SAASE,OAAOA,CAC7BC,IAAgC,EAChCC,MAAe,EACG;EAClB,IAAI,IAAAC,uBAAgB,EAACF,IAAI,CAAC,EAAE;IAC1B,OAAOA,IAAI;EACb;EAEA,IAAIG,UAAyB,GAAG,EAAE;EAElC,IAAI,IAAAC,uBAAgB,EAACJ,IAAI,CAAC,EAAE;IAC1BG,UAAU,GAAG,EAAE;EACjB,CAAC,MAAM;IACL,IAAI,CAAC,IAAAE,kBAAW,EAACL,IAAI,CAAC,EAAE;MACtB,IAAI,IAAAM,iBAAU,EAACL,MAAM,CAAC,EAAE;QACtBD,IAAI,GAAG,IAAAO,uBAAe,EAACP,IAAI,CAAC;MAC9B,CAAC,MAAM;QACLA,IAAI,GAAG,IAAAQ,2BAAmB,EAACR,IAAI,CAAC;MAClC;IACF;IAEAG,UAAU,GAAG,CAACH,IAAI,CAAC;EACrB;EAEA,OAAO,IAAAS,sBAAc,EAACN,UAAU,CAAC;AACnC","ignoreList":[]}

View File

@@ -0,0 +1,163 @@
/**
* @fileoverview Disallows unnecessary `return await`
* @author Jordan Harband
* @deprecated in ESLint v8.46.0
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
hasSuggestions: true,
type: "suggestion",
docs: {
description: "Disallow unnecessary `return await`",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-return-await",
},
fixable: null,
deprecated: {
message:
"The original assumption of the rule no longer holds true because of engine optimization.",
url: "https://eslint.org/docs/latest/rules/no-return-await",
deprecatedSince: "8.46.0",
availableUntil: null,
replacedBy: [],
},
schema: [],
messages: {
removeAwait: "Remove redundant `await`.",
redundantUseOfAwait: "Redundant use of `await` on a return value.",
},
},
create(context) {
/**
* Reports a found unnecessary `await` expression.
* @param {ASTNode} node The node representing the `await` expression to report
* @returns {void}
*/
function reportUnnecessaryAwait(node) {
context.report({
node: context.sourceCode.getFirstToken(node),
loc: node.loc,
messageId: "redundantUseOfAwait",
suggest: [
{
messageId: "removeAwait",
fix(fixer) {
const sourceCode = context.sourceCode;
const [awaitToken, tokenAfterAwait] =
sourceCode.getFirstTokens(node, 2);
const areAwaitAndAwaitedExpressionOnTheSameLine =
awaitToken.loc.start.line ===
tokenAfterAwait.loc.start.line;
if (!areAwaitAndAwaitedExpressionOnTheSameLine) {
return null;
}
const [startOfAwait, endOfAwait] = awaitToken.range;
const characterAfterAwait =
sourceCode.text[endOfAwait];
const trimLength =
characterAfterAwait === " " ? 1 : 0;
const range = [
startOfAwait,
endOfAwait + trimLength,
];
return fixer.removeRange(range);
},
},
],
});
}
/**
* Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting
* this function. For example, a statement in a `try` block will always have an error handler. A statement in
* a `catch` block will only have an error handler if there is also a `finally` block.
* @param {ASTNode} node A node representing a location where an could be thrown
* @returns {boolean} `true` if a thrown error will be caught/handled in this function
*/
function hasErrorHandler(node) {
let ancestor = node;
while (
!astUtils.isFunction(ancestor) &&
ancestor.type !== "Program"
) {
if (
ancestor.parent.type === "TryStatement" &&
(ancestor === ancestor.parent.block ||
(ancestor === ancestor.parent.handler &&
ancestor.parent.finalizer))
) {
return true;
}
ancestor = ancestor.parent;
}
return false;
}
/**
* Checks if a node is placed in tail call position. Once `return` arguments (or arrow function expressions) can be a complex expression,
* an `await` expression could or could not be unnecessary by the definition of this rule. So we're looking for `await` expressions that are in tail position.
* @param {ASTNode} node A node representing the `await` expression to check
* @returns {boolean} The checking result
*/
function isInTailCallPosition(node) {
if (node.parent.type === "ArrowFunctionExpression") {
return true;
}
if (node.parent.type === "ReturnStatement") {
return !hasErrorHandler(node.parent);
}
if (
node.parent.type === "ConditionalExpression" &&
(node === node.parent.consequent ||
node === node.parent.alternate)
) {
return isInTailCallPosition(node.parent);
}
if (
node.parent.type === "LogicalExpression" &&
node === node.parent.right
) {
return isInTailCallPosition(node.parent);
}
if (
node.parent.type === "SequenceExpression" &&
node === node.parent.expressions.at(-1)
) {
return isInTailCallPosition(node.parent);
}
return false;
}
return {
AwaitExpression(node) {
if (isInTailCallPosition(node) && !hasErrorHandler(node)) {
reportUnnecessaryAwait(node);
}
},
};
},
};

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _newArrowCheck;
function _newArrowCheck(innerThis, boundThis) {
if (innerThis !== boundThis) {
throw new TypeError("Cannot instantiate an arrow function");
}
}
//# sourceMappingURL=newArrowCheck.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ScriptOnce.js","sources":["../../src/ScriptOnce.tsx"],"sourcesContent":["import jsesc from 'jsesc'\n\nexport function ScriptOnce({\n children,\n log,\n}: {\n children: string\n log?: boolean\n sync?: boolean\n}) {\n if (typeof document !== 'undefined') {\n return null\n }\n\n return (\n <script\n className=\"tsr-once\"\n dangerouslySetInnerHTML={{\n __html: [\n children,\n (log ?? true) && process.env.NODE_ENV === 'development'\n ? `console.info(\\`Injected From Server:\n${jsesc(children.toString(), { quotes: 'backtick' })}\\`)`\n : '',\n 'if (typeof __TSR_SSR__ !== \"undefined\") __TSR_SSR__.cleanScripts()',\n ]\n .filter(Boolean)\n .join('\\n'),\n }}\n />\n )\n}\n"],"names":[],"mappings":";;AAEO,SAAS,WAAW;AAAA,EACzB;AAAA,EACA;AACF,GAIG;AACG,MAAA,OAAO,aAAa,aAAa;AAC5B,WAAA;AAAA,EAAA;AAIP,SAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAU;AAAA,MACV,yBAAyB;AAAA,QACvB,QAAQ;AAAA,UACN;AAAA,WACC,OAAO,SAAS,QAAQ,IAAI,aAAa,gBACtC;AAAA,EACZ,MAAM,SAAS,YAAY,EAAE,QAAQ,WAAY,CAAA,CAAC,QACtC;AAAA,UACJ;AAAA,QAEC,EAAA,OAAO,OAAO,EACd,KAAK,IAAI;AAAA,MAAA;AAAA,IACd;AAAA,EACF;AAEJ;"}

View File

@@ -0,0 +1,422 @@
# jsesc
Given some data, _jsesc_ returns a stringified representation of that data. jsesc is similar to `JSON.stringify()` except:
1. it outputs JavaScript instead of JSON [by default](#json), enabling support for data structures like ES6 maps and sets;
2. it offers [many options](#api) to customize the output;
3. its output is ASCII-safe [by default](#minimal), thanks to its use of [escape sequences](https://mathiasbynens.be/notes/javascript-escapes) where needed.
For any input, jsesc generates the shortest possible valid printable-ASCII-only output. [Heres an online demo.](https://mothereff.in/js-escapes)
jsescs output can be used instead of `JSON.stringify`s to avoid [mojibake](https://en.wikipedia.org/wiki/Mojibake) and other encoding issues, or even to [avoid errors](https://twitter.com/annevk/status/380000829643571200) when passing JSON-formatted data (which may contain U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR, or [lone surrogates](https://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)) to a JavaScript parser or an UTF-8 encoder.
## Installation
Via [npm](https://www.npmjs.com/):
```bash
npm install jsesc
```
In [Node.js](https://nodejs.org/):
```js
const jsesc = require('jsesc');
```
## API
### `jsesc(value, options)`
This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in JavaScript strings](https://mathiasbynens.be/notes/javascript-escapes). The first supported value type is strings:
```js
jsesc('Ich ♥ Bücher');
// → 'Ich \\u2665 B\\xFCcher'
jsesc('foo 𝌆 bar');
// → 'foo \\uD834\\uDF06 bar'
```
Instead of a string, the `value` can also be an array, an object, a map, a set, or a buffer. In such cases, `jsesc` returns a stringified version of the value where any characters that are not printable ASCII symbols are escaped in the same way.
```js
// Escaping an array
jsesc([
'Ich ♥ Bücher', 'foo 𝌆 bar'
]);
// → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']'
// Escaping an object
jsesc({
'Ich ♥ Bücher': 'foo 𝌆 bar'
});
// → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}'
```
The optional `options` argument accepts an object with the following options:
#### `quotes`
The default value for the `quotes` option is `'single'`. This means that any occurrences of `'` in the input string are escaped as `\'`, so that the output can be used in a string literal wrapped in single quotes.
```js
jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.');
// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'single'
});
// → '`Lorem` ipsum "dolor" sit \\\'amet\\\' etc.'
// → "`Lorem` ipsum \"dolor\" sit \\'amet\\' etc."
```
If you want to use the output as part of a string literal wrapped in double quotes, set the `quotes` option to `'double'`.
```js
jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'double'
});
// → '`Lorem` ipsum \\"dolor\\" sit \'amet\' etc.'
// → "`Lorem` ipsum \\\"dolor\\\" sit 'amet' etc."
```
If you want to use the output as part of a template literal (i.e. wrapped in backticks), set the `quotes` option to `'backtick'`.
```js
jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'backtick'
});
// → '\\`Lorem\\` ipsum "dolor" sit \'amet\' etc.'
// → "\\`Lorem\\` ipsum \"dolor\" sit 'amet' etc."
// → `\\\`Lorem\\\` ipsum "dolor" sit 'amet' etc.`
```
This setting also affects the output for arrays and objects:
```js
jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
'quotes': 'double'
});
// → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}'
jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
'quotes': 'double'
});
// → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]'
```
#### `numbers`
The default value for the `numbers` option is `'decimal'`. This means that any numeric values are represented using decimal integer literals. Other valid options are `binary`, `octal`, and `hexadecimal`, which result in binary integer literals, octal integer literals, and hexadecimal integer literals, respectively.
```js
jsesc(42, {
'numbers': 'binary'
});
// → '0b101010'
jsesc(42, {
'numbers': 'octal'
});
// → '0o52'
jsesc(42, {
'numbers': 'decimal'
});
// → '42'
jsesc(42, {
'numbers': 'hexadecimal'
});
// → '0x2A'
```
#### `wrap`
The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting.
```js
jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'single',
'wrap': true
});
// → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\''
// → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'"
jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
'quotes': 'double',
'wrap': true
});
// → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."'
// → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\""
```
#### `es6`
The `es6` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any astral Unicode symbols in the input are escaped using [ECMAScript 6 Unicode code point escape sequences](https://mathiasbynens.be/notes/javascript-escapes#unicode-code-point) instead of using separate escape sequences for each surrogate half. If backwards compatibility with ES5 environments is a concern, dont enable this setting. If the `json` setting is enabled, the value for the `es6` setting is ignored (as if it was `false`).
```js
// By default, the `es6` option is disabled:
jsesc('foo 𝌆 bar 💩 baz');
// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
// To explicitly disable it:
jsesc('foo 𝌆 bar 💩 baz', {
'es6': false
});
// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz'
// To enable it:
jsesc('foo 𝌆 bar 💩 baz', {
'es6': true
});
// → 'foo \\u{1D306} bar \\u{1F4A9} baz'
```
#### `escapeEverything`
The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output are escaped — even printable ASCII symbols.
```js
jsesc('lolwat"foo\'bar', {
'escapeEverything': true
});
// → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72'
// → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72"
```
This setting also affects the output for string literals within arrays and objects.
#### `minimal`
The `minimal` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, only a limited set of symbols in the output are escaped:
* U+0000 `\0`
* U+0008 `\b`
* U+0009 `\t`
* U+000A `\n`
* U+000C `\f`
* U+000D `\r`
* U+005C `\\`
* U+2028 `\u2028`
* U+2029 `\u2029`
* whatever symbol is being used for wrapping string literals (based on [the `quotes` option](#quotes))
* [lone surrogates](https://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)
Note: with this option enabled, jsesc output is no longer guaranteed to be ASCII-safe.
```js
jsesc('foo\u2029bar\nbaz©qux𝌆flops', {
'minimal': false
});
// → 'foo\\u2029bar\\nbaz©qux𝌆flops'
```
#### `isScriptContext`
The `isScriptContext` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, occurrences of [`</script` and `</style`](https://mathiasbynens.be/notes/etago) in the output are escaped as `<\/script` and `<\/style`, and [`<!--`](https://mathiasbynens.be/notes/etago#comment-8) is escaped as `\x3C!--` (or `\u003C!--` when the `json` option is enabled). This setting is useful when jsescs output ends up as part of a `<script>` or `<style>` element in an HTML document.
```js
jsesc('foo</script>bar', {
'isScriptContext': true
});
// → 'foo<\\/script>bar'
```
#### `compact`
The `compact` option takes a boolean value (`true` or `false`), and defaults to `true` (enabled). When enabled, the output for arrays and objects is as compact as possible; its not formatted nicely.
```js
jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
'compact': true // this is the default
});
// → '{\'Ich \u2665 B\xFCcher\':\'foo \uD834\uDF06 bar\'}'
jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
'compact': false
});
// → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
'compact': false
});
// → '[\n\t\'Ich \u2665 B\xFCcher\',\n\t\'foo \uD834\uDF06 bar\'\n]'
```
This setting has no effect on the output for strings.
#### `indent`
The `indent` option takes a string value, and defaults to `'\t'`. When the `compact` setting is disabled (`false`), the value of the `indent` option is used to format the output for arrays and objects.
```js
jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
'compact': false,
'indent': '\t' // this is the default
});
// → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, {
'compact': false,
'indent': ' '
});
// → '{\n \'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}'
jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], {
'compact': false,
'indent': ' '
});
// → '[\n \'Ich \u2665 B\xFCcher\',\n\ t\'foo \uD834\uDF06 bar\'\n]'
```
This setting has no effect on the output for strings.
#### `indentLevel`
The `indentLevel` option takes a numeric value, and defaults to `0`. It represents the current indentation level, i.e. the number of times the value of [the `indent` option](#indent) is repeated.
```js
jsesc(['a', 'b', 'c'], {
'compact': false,
'indentLevel': 1
});
// → '[\n\t\t\'a\',\n\t\t\'b\',\n\t\t\'c\'\n\t]'
jsesc(['a', 'b', 'c'], {
'compact': false,
'indentLevel': 2
});
// → '[\n\t\t\t\'a\',\n\t\t\t\'b\',\n\t\t\t\'c\'\n\t\t]'
```
#### `json`
The `json` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is valid JSON. [Hexadecimal character escape sequences](https://mathiasbynens.be/notes/javascript-escapes#hexadecimal) and [the `\v` or `\0` escape sequences](https://mathiasbynens.be/notes/javascript-escapes#single) are not used. Setting `json: true` implies `quotes: 'double', wrap: true, es6: false`, although these values can still be overridden if needed — but in such cases, the output wont be valid JSON anymore.
```js
jsesc('foo\x00bar\xFF\uFFFDbaz', {
'json': true
});
// → '"foo\\u0000bar\\u00FF\\uFFFDbaz"'
jsesc({ 'foo\x00bar\xFF\uFFFDbaz': 'foo\x00bar\xFF\uFFFDbaz' }, {
'json': true
});
// → '{"foo\\u0000bar\\u00FF\\uFFFDbaz":"foo\\u0000bar\\u00FF\\uFFFDbaz"}'
jsesc([ 'foo\x00bar\xFF\uFFFDbaz', 'foo\x00bar\xFF\uFFFDbaz' ], {
'json': true
});
// → '["foo\\u0000bar\\u00FF\\uFFFDbaz","foo\\u0000bar\\u00FF\\uFFFDbaz"]'
// Values that are acceptable in JSON but arent strings, arrays, or object
// literals cant be escaped, so theyll just be preserved:
jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], {
'json': true
});
// → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]'
// Values that arent allowed in JSON are run through `JSON.stringify()`:
jsesc([ undefined, -Infinity ], {
'json': true
});
// → '[null,null]'
```
**Note:** Using this option on objects or arrays that contain non-string values relies on `JSON.stringify()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](http://bestiejs.github.io/json3/).
#### `lowercaseHex`
The `lowercaseHex` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any alphabetical hexadecimal digits in escape sequences as well as any hexadecimal integer literals (see [the `numbers` option](#numbers)) in the output are in lowercase.
```js
jsesc('Ich ♥ Bücher', {
'lowercaseHex': true
});
// → 'Ich \\u2665 B\\xfccher'
// ^^
jsesc(42, {
'numbers': 'hexadecimal',
'lowercaseHex': true
});
// → '0x2a'
// ^^
```
### `jsesc.version`
A string representing the semantic version number.
### Using the `jsesc` binary
To use the `jsesc` binary in your shell, simply install jsesc globally using npm:
```bash
npm install -g jsesc
```
After that youre able to escape strings from the command line:
```bash
$ jsesc 'föo ♥ bår 𝌆 baz'
f\xF6o \u2665 b\xE5r \uD834\uDF06 baz
```
To escape arrays or objects containing string values, use the `-o`/`--object` option:
```bash
$ jsesc --object '{ "föo": "♥", "bår": "𝌆 baz" }'
{'f\xF6o':'\u2665','b\xE5r':'\uD834\uDF06 baz'}
```
To prettify the output in such cases, use the `-p`/`--pretty` option:
```bash
$ jsesc --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
{
'f\xF6o': '\u2665',
'b\xE5r': '\uD834\uDF06 baz'
}
```
For valid JSON output, use the `-j`/`--json` option:
```bash
$ jsesc --json --pretty '{ "föo": "♥", "bår": "𝌆 baz" }'
{
"f\u00F6o": "\u2665",
"b\u00E5r": "\uD834\uDF06 baz"
}
```
Read a local JSON file, escape any non-ASCII symbols, and save the result to a new file:
```bash
$ jsesc --json --object < data-raw.json > data-escaped.json
```
Or do the same with an online JSON file:
```bash
$ curl -sL "http://git.io/aorKgQ" | jsesc --json --object > data-escaped.json
```
See `jsesc --help` for the full list of options.
## Support
As of v3.0.0, jsesc supports Node.js v6+ only.
Older versions (up to jsesc v1.3.0) support Chrome 27, Firefox 3, Safari 4, Opera 10, IE 6, Node.js v6.0.0, Narwhal 0.3.2, RingoJS 0.8-0.11, PhantomJS 1.9.0, and Rhino 1.7RC4. **Note:** Using the `json` option on objects or arrays that contain non-string values relies on `JSON.parse()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](https://bestiejs.github.io/json3/).
## Author
| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |
## License
This library is available under the [MIT](https://mths.be/mit) license.

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _checkInRHS;
function _checkInRHS(value) {
if (Object(value) !== value) {
throw TypeError("right-hand side of 'in' should be an object, got " + (value !== null ? typeof value : "null"));
}
return value;
}
//# sourceMappingURL=checkInRHS.js.map

View File

@@ -0,0 +1,85 @@
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}

View File

@@ -0,0 +1,327 @@
/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
*/
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */
/**
* @type {VisitorKeys}
*/
const KEYS = {
ArrayExpression: [
"elements"
],
ArrayPattern: [
"elements"
],
ArrowFunctionExpression: [
"params",
"body"
],
AssignmentExpression: [
"left",
"right"
],
AssignmentPattern: [
"left",
"right"
],
AwaitExpression: [
"argument"
],
BinaryExpression: [
"left",
"right"
],
BlockStatement: [
"body"
],
BreakStatement: [
"label"
],
CallExpression: [
"callee",
"arguments"
],
CatchClause: [
"param",
"body"
],
ChainExpression: [
"expression"
],
ClassBody: [
"body"
],
ClassDeclaration: [
"id",
"superClass",
"body"
],
ClassExpression: [
"id",
"superClass",
"body"
],
ConditionalExpression: [
"test",
"consequent",
"alternate"
],
ContinueStatement: [
"label"
],
DebuggerStatement: [],
DoWhileStatement: [
"body",
"test"
],
EmptyStatement: [],
ExperimentalRestProperty: [
"argument"
],
ExperimentalSpreadProperty: [
"argument"
],
ExportAllDeclaration: [
"exported",
"source",
"attributes"
],
ExportDefaultDeclaration: [
"declaration"
],
ExportNamedDeclaration: [
"declaration",
"specifiers",
"source",
"attributes"
],
ExportSpecifier: [
"exported",
"local"
],
ExpressionStatement: [
"expression"
],
ForInStatement: [
"left",
"right",
"body"
],
ForOfStatement: [
"left",
"right",
"body"
],
ForStatement: [
"init",
"test",
"update",
"body"
],
FunctionDeclaration: [
"id",
"params",
"body"
],
FunctionExpression: [
"id",
"params",
"body"
],
Identifier: [],
IfStatement: [
"test",
"consequent",
"alternate"
],
ImportAttribute: [
"key",
"value"
],
ImportDeclaration: [
"specifiers",
"source",
"attributes"
],
ImportDefaultSpecifier: [
"local"
],
ImportExpression: [
"source",
"options"
],
ImportNamespaceSpecifier: [
"local"
],
ImportSpecifier: [
"imported",
"local"
],
JSXAttribute: [
"name",
"value"
],
JSXClosingElement: [
"name"
],
JSXClosingFragment: [],
JSXElement: [
"openingElement",
"children",
"closingElement"
],
JSXEmptyExpression: [],
JSXExpressionContainer: [
"expression"
],
JSXFragment: [
"openingFragment",
"children",
"closingFragment"
],
JSXIdentifier: [],
JSXMemberExpression: [
"object",
"property"
],
JSXNamespacedName: [
"namespace",
"name"
],
JSXOpeningElement: [
"name",
"attributes"
],
JSXOpeningFragment: [],
JSXSpreadAttribute: [
"argument"
],
JSXSpreadChild: [
"expression"
],
JSXText: [],
LabeledStatement: [
"label",
"body"
],
Literal: [],
LogicalExpression: [
"left",
"right"
],
MemberExpression: [
"object",
"property"
],
MetaProperty: [
"meta",
"property"
],
MethodDefinition: [
"key",
"value"
],
NewExpression: [
"callee",
"arguments"
],
ObjectExpression: [
"properties"
],
ObjectPattern: [
"properties"
],
PrivateIdentifier: [],
Program: [
"body"
],
Property: [
"key",
"value"
],
PropertyDefinition: [
"key",
"value"
],
RestElement: [
"argument"
],
ReturnStatement: [
"argument"
],
SequenceExpression: [
"expressions"
],
SpreadElement: [
"argument"
],
StaticBlock: [
"body"
],
Super: [],
SwitchCase: [
"test",
"consequent"
],
SwitchStatement: [
"discriminant",
"cases"
],
TaggedTemplateExpression: [
"tag",
"quasi"
],
TemplateElement: [],
TemplateLiteral: [
"quasis",
"expressions"
],
ThisExpression: [],
ThrowStatement: [
"argument"
],
TryStatement: [
"block",
"handler",
"finalizer"
],
UnaryExpression: [
"argument"
],
UpdateExpression: [
"argument"
],
VariableDeclaration: [
"declarations"
],
VariableDeclarator: [
"id",
"init"
],
WhileStatement: [
"test",
"body"
],
WithStatement: [
"object",
"body"
],
YieldExpression: [
"argument"
]
};
// Types.
const NODE_TYPES = Object.keys(KEYS);
// Freeze the keys.
for (const type of NODE_TYPES) {
Object.freeze(KEYS[type]);
}
Object.freeze(KEYS);
export default KEYS;

View File

@@ -0,0 +1 @@
{"version":3,"file":"searchParams.cjs","sources":["../../src/searchParams.ts"],"sourcesContent":["import { decode, encode } from './qss'\nimport type { AnySchema } from './validators'\n\nexport const defaultParseSearch = parseSearchWith(JSON.parse)\nexport const defaultStringifySearch = stringifySearchWith(\n JSON.stringify,\n JSON.parse,\n)\n\nexport function parseSearchWith(parser: (str: string) => any) {\n return (searchStr: string): AnySchema => {\n if (searchStr.substring(0, 1) === '?') {\n searchStr = searchStr.substring(1)\n }\n\n const query: Record<string, unknown> = decode(searchStr)\n\n // Try to parse any query params that might be json\n for (const key in query) {\n const value = query[key]\n if (typeof value === 'string') {\n try {\n query[key] = parser(value)\n } catch (err) {\n //\n }\n }\n }\n\n return query\n }\n}\n\nexport function stringifySearchWith(\n stringify: (search: any) => string,\n parser?: (str: string) => any,\n) {\n function stringifyValue(val: any) {\n if (typeof val === 'object' && val !== null) {\n try {\n return stringify(val)\n } catch (err) {\n // silent\n }\n } else if (typeof val === 'string' && typeof parser === 'function') {\n try {\n // Check if it's a valid parseable string.\n // If it is, then stringify it again.\n parser(val)\n return stringify(val)\n } catch (err) {\n // silent\n }\n }\n return val\n }\n\n return (search: Record<string, any>) => {\n search = { ...search }\n\n Object.keys(search).forEach((key) => {\n const val = search[key]\n if (typeof val === 'undefined' || val === undefined) {\n delete search[key]\n } else {\n search[key] = stringifyValue(val)\n }\n })\n\n const searchStr = encode(search as Record<string, string>).toString()\n\n return searchStr ? `?${searchStr}` : ''\n }\n}\n\nexport type SearchSerializer = (searchObj: Record<string, any>) => string\nexport type SearchParser = (searchStr: string) => Record<string, any>\n"],"names":["decode","encode"],"mappings":";;;AAGa,MAAA,qBAAqB,gBAAgB,KAAK,KAAK;AACrD,MAAM,yBAAyB;AAAA,EACpC,KAAK;AAAA,EACL,KAAK;AACP;AAEO,SAAS,gBAAgB,QAA8B;AAC5D,SAAO,CAAC,cAAiC;AACvC,QAAI,UAAU,UAAU,GAAG,CAAC,MAAM,KAAK;AACzB,kBAAA,UAAU,UAAU,CAAC;AAAA,IAAA;AAG7B,UAAA,QAAiCA,WAAO,SAAS;AAGvD,eAAW,OAAO,OAAO;AACjB,YAAA,QAAQ,MAAM,GAAG;AACnB,UAAA,OAAO,UAAU,UAAU;AACzB,YAAA;AACI,gBAAA,GAAG,IAAI,OAAO,KAAK;AAAA,iBAClB,KAAK;AAAA,QAAA;AAAA,MAEd;AAAA,IACF;AAGK,WAAA;AAAA,EACT;AACF;AAEgB,SAAA,oBACd,WACA,QACA;AACA,WAAS,eAAe,KAAU;AAChC,QAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AACvC,UAAA;AACF,eAAO,UAAU,GAAG;AAAA,eACb,KAAK;AAAA,MAAA;AAAA,eAGL,OAAO,QAAQ,YAAY,OAAO,WAAW,YAAY;AAC9D,UAAA;AAGF,eAAO,GAAG;AACV,eAAO,UAAU,GAAG;AAAA,eACb,KAAK;AAAA,MAAA;AAAA,IAEd;AAEK,WAAA;AAAA,EAAA;AAGT,SAAO,CAAC,WAAgC;AAC7B,aAAA,EAAE,GAAG,OAAO;AAErB,WAAO,KAAK,MAAM,EAAE,QAAQ,CAAC,QAAQ;AAC7B,YAAA,MAAM,OAAO,GAAG;AACtB,UAAI,OAAO,QAAQ,eAAe,QAAQ,QAAW;AACnD,eAAO,OAAO,GAAG;AAAA,MAAA,OACZ;AACE,eAAA,GAAG,IAAI,eAAe,GAAG;AAAA,MAAA;AAAA,IAClC,CACD;AAED,UAAM,YAAYC,IAAAA,OAAO,MAAgC,EAAE,SAAS;AAE7D,WAAA,YAAY,IAAI,SAAS,KAAK;AAAA,EACvC;AACF;;;;;"}