Website Structure

This commit is contained in:
supalerk-ar66 2026-01-13 10:46:40 +07:00
parent 62812f2090
commit 71f0676a62
22365 changed files with 4265753 additions and 791 deletions

21
Frontend-Learner/node_modules/magic-regexp/LICENCE generated vendored Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Daniel Roe
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.

54
Frontend-Learner/node_modules/magic-regexp/README.md generated vendored Normal file
View file

@ -0,0 +1,54 @@
# 🦄 magic-regexp
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![Github Actions][github-actions-src]][github-actions-href]
[![Codecov][codecov-src]][codecov-href]
[![Bundlephobia][bundlephobia-src]][bundlephobia-href]
> A compiled-away, type-safe, readable RegExp alternative
- [✨  Changelog](https://github.com/danielroe/magic-regexp/blob/main/CHANGELOG.md)
- [📖  Documentation](https://regexp.dev)
- [▶️  Online playground](https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgYwBYEMoBoVQKbox4BKeA5gKIAeYOAJsGcDDnlesjADYCeOI6HgCM8OCADs8AeSgBZaKLgB3aHQDCGKHAC+cAGZQIIOAHIBTZAFp8ZNmBMAoBwHoAVK4dxXKDONtwYCE9vUEhYRAA6KN0DI1NzYCsbO2c9AFdYVDwoSwTkRy8AiACoHgCeMDw4LjwANzwuOFJKGjgBGDQ4fABnNK4YbrgACjts0DxxGHQuAEpg5ydnZzgAFQq8OhR0MBgMqrJDNLBuh2QJbvgASQARAH1iCjgAXlwCImbqMBH2Tl4hk2AdEsJhmEXQ4joQwYTBgERg426QwArKCDhAjhsAIKIgF0EEzOZncQXOBoo6DF4mbpGKqAywAJgAzAAWACcAAY4Fl8Mp9hATBF2mghjd7hQZgB+CJk44uZZwBVwAB6EsWywAimlEgBrSzgoEMWBlbp4ED1KCnc7wADKFFkADUKMQxc9XoQSORPkNPHAJNI5AooYxmKjDpU6Nj-gIAFbQEFYH0CkwJhV+mTyfBBmGh9HhyNmYDiOMzFNtQQif4RZO+yTpwNoTA5jERnFgQhofEJuYOW0Op1iuXK1WW4nwHp9eAvZD4d0fGjfDjcHj-PQQCDOIgXCLR7ogsF6IhQf5CTDOfFwvAXY+n1frzewncgtVNPB6bITZCXopwMD4WrAdFul4LYdj2TYZUGNJukLMgAiyUkwzgcR0BAPARxJFYKAAOQoFYXSnGd3k9ecfTYRc-hUKB1E0aUwyxHE9GAKALg0TB42UVRWKgWjc3o-4TSJai2JLGt-QzPAhgbKACR9BUwQhCJ8DffBxE-FYIH4vBBK4p9FTgeS6EU1931UvB1JXJiWM0eMHG7IkSXHfp6VdTCcLwh4LyvExXIAHieJ4pH8gA+NyQSAA)
## Features
- Runtime is zero-dependency and ultra-minimal
- Ships with transform to compile to pure RegExp
- Automatically typed capture groups
- Natural language syntax
- Generated RegExp displays on hover
[📖  Read more](https://regexp.dev)
## 💻 Development
- Clone this repository
- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` (use `npm i -g corepack` for Node.js < 16.10)
- Install dependencies using `pnpm install`
- Run interactive tests using `pnpm dev`
## Similar packages
- [verbal-expressions](http://verbalexpressions.github.io/)
- [typed-regex](https://github.com/phenax/typed-regex/)
## License
Made with ❤️
Published under [MIT License](./LICENCE).
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/magic-regexp?style=flat-square
[npm-version-href]: https://npmjs.com/package/magic-regexp
[npm-downloads-src]: https://img.shields.io/npm/dm/magic-regexp?style=flat-square
[npm-downloads-href]: https://npmjs.com/package/magic-regexp
[github-actions-src]: https://img.shields.io/github/actions/workflow/status/danielroe/magic-regexp/ci.yml?branch=main&style=flat-square
[github-actions-href]: https://github.com/danielroe/magic-regexp/actions?query=workflow%3Aci
[codecov-src]: https://img.shields.io/codecov/c/gh/danielroe/magic-regexp/main?style=flat-square
[codecov-href]: https://codecov.io/gh/danielroe/magic-regexp
[bundlephobia-src]: https://img.shields.io/bundlephobia/minzip/magic-regexp?style=flat-square
[bundlephobia-href]: https://bundlephobia.com/package/magic-regexp

View file

@ -0,0 +1,265 @@
'use strict';
const regexpTree = require('regexp-tree');
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
const regexpTree__default = /*#__PURE__*/_interopDefaultCompat(regexpTree);
function build(node) {
if (node === null)
return "";
switch (node.type) {
case "CharacterClass": {
const exprs = combineContinuousSimpleChars(node.expressions);
if (exprs.length === 1) {
const first = exprs[0];
if (typeof first === "string") {
return node.negative ? `charNotIn(${first})` : `charIn(${first})`;
} else if (first.type === "Char" && first.kind === "meta" && node.negative) {
if (first.value === "\\t")
return `not.tab`;
if (first.value === "\\n")
return `not.linefeed`;
if (first.value === "\\r")
return `not.carriageReturn`;
} else {
const range = normalizeClassRange(first);
if (range === "A-Z")
return node.negative ? `not.letter.uppercase` : `letter.uppercase`;
else if (range === "a-z")
return node.negative ? `not.letter.lowercase` : `letter.lowercase`;
}
} else if (exprs.length === 2) {
if (typeof exprs[0] !== "string" && typeof exprs[1] !== "string") {
const range1 = normalizeClassRange(exprs[0]);
const range2 = normalizeClassRange(exprs[1]);
if (range1 === "A-Z" && range2 === "a-z" || range1 === "a-z" && range2 === "A-Z")
return node.negative ? `not.letter` : `letter`;
}
}
throw new Error("Unsupported for Complex charactor class");
}
case "Disjunction":
return chain(build(node.left), `or(${build(node.right)})`);
case "Assertion":
switch (node.kind) {
case "\\b":
return "wordBoundary";
case "\\B":
return "not.wordBoundary";
case "^":
return chain("", "at.lineStart()");
case "$":
return chain("", "at.lineEnd()");
case "Lookbehind":
return chain("", `${node.negative ? "notAfter" : "after"}(${build(node.assertion)})`);
case "Lookahead":
return chain("", `${node.negative ? "notBefore" : "before"}(${build(node.assertion)})`);
/* v8 ignore next 2 */
default:
throw new TypeError(`Unknown Assertion kind: ${node.kind}`);
}
case "Char":
if (node.kind === "meta") {
switch (node.value) {
case ".":
return "char";
case "\\w":
return "wordChar";
case "\\d":
return "digit";
case "\\s":
return "whitespace";
case "\\t":
return "tab";
case "\\n":
return "linefeed";
case "\\r":
return "carriageReturn";
case "\\W":
return "not.wordChar";
case "\\D":
return "not.digit";
case "\\S":
return "not.whitespace";
case "\f":
case "\v":
default:
throw new Error(`Unsupported Meta Char: ${node.value}`);
}
} else {
const char = getChar(node);
if (char === null)
throw new Error(`Unknown Char: ${node.value}`);
return `'${char}'`;
}
case "Repetition": {
const quantifier = node.quantifier;
const expr = build(node.expression);
const lazy = !quantifier.greedy;
if (lazy)
throw new Error("Unsupported for lazy quantifier");
switch (quantifier.kind) {
case "+":
return `oneOrMore(${expr})`;
case "?":
return `maybe(${expr})`;
case "*":
return chain(expr, "times.any()");
case "Range":
if (quantifier.from === quantifier.to)
return chain(expr, `times(${quantifier.from})`);
else if (!quantifier.to)
return chain(expr, `times.atLeast(${quantifier.from})`);
else if (quantifier.from === 0)
return chain(expr, `times.atMost(${quantifier.to})`);
return chain(expr, `times.between(${quantifier.from}, ${quantifier.to})`);
/* v8 ignore next 2 */
default:
return "";
}
}
case "Alternative": {
const alts = combineContinuousSimpleChars(node.expressions);
const exprs = [];
for (let i = 0; i < alts.length; i++) {
const alt = alts[i];
if (typeof alt === "string") {
exprs.push(alt);
continue;
}
if (alt.type === "Assertion") {
switch (alt.kind) {
case "^": {
const next = alts[++i];
if (next === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
exprs.push(chain(next, "at.lineStart()"));
continue;
}
case "$": {
const prev = exprs.pop();
if (prev === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
exprs.push(chain(prev, "at.lineEnd()"));
continue;
}
case "Lookbehind": {
const next = alts[++i];
if (next === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
const helper = alt.negative ? "notAfter" : "after";
exprs.push(chain(next, `${helper}(${build(alt.assertion)})`));
continue;
}
case "Lookahead": {
const prev = exprs.pop();
if (prev === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
const helper = alt.negative ? "notBefore" : "before";
exprs.push(chain(prev, `${helper}(${build(alt.assertion)})`));
continue;
}
}
}
if (alt.type === "Backreference") {
if (alt.kind !== "name")
throw new Error(`Unsupport for number reference`);
const ref = chain(`exactly(${exprs.join(", ")})`, `and.referenceTo('${alt.reference}')`);
exprs.length = 0;
exprs.push(ref);
continue;
}
exprs.push(build(alt));
}
return exprs.join(", ");
}
case "Group":
if (node.capturing)
return chain(build(node.expression), node.name ? `as('${node.name}')` : "grouped()");
else return chain(build(node.expression));
/* v8 ignore next 2 */
case "Backreference":
return chain("", `and.referenceTo('${node.reference}')`);
}
}
function normalizeClassRange(node) {
if (node.type === "ClassRange")
return `${node.from.value}-${node.to.value}`;
}
function combineContinuousSimpleChars(expressions) {
let simpleChars = "";
const exprs = expressions.reduce(
(acc, expr) => {
const char = expr.type === "Char" ? getChar(expr) : null;
if (char !== null) {
simpleChars += char;
} else {
if (simpleChars) {
acc.push(`'${simpleChars}'`);
simpleChars = "";
}
acc.push(expr);
}
return acc;
},
[]
);
if (simpleChars)
exprs.push(`'${simpleChars}'`);
return exprs;
}
function getChar(char) {
function escapeSimpleChar(char2) {
return char2 === "'" ? "\\'" : char2;
}
switch (char.kind) {
case "simple":
return escapeSimpleChar(char.value);
case "oct":
case "decimal":
case "hex":
case "unicode":
if ("symbol" in char)
return escapeSimpleChar(char.symbol);
}
return null;
}
function chain(expr, helper) {
let _expr = "";
if (typeof expr === "string") {
if (expr === "")
_expr = "exactly('')";
else _expr = expr.startsWith("'") && expr.endsWith("'") ? `exactly(${expr})` : expr;
} else {
_expr = build(expr);
}
return helper ? `${_expr}.${helper}` : _expr;
}
function buildFlags(flags) {
if (!flags)
return "";
const readableFlags = flags.split("").map((flag) => {
return {
d: "withIndices",
i: "caseInsensitive",
g: "global",
m: "multiline",
s: "dotAll",
u: "unicode",
y: "sticky"
}[flag] || `'${flag}'`;
});
return `[${readableFlags.join(", ")}]`;
}
function convert(regex, { argsOnly = false } = {}) {
const ast = regexpTree__default.parse(regex);
if (ast.type !== "RegExp")
throw new TypeError(`Unexpected RegExp AST: ${ast.type}`);
const flags = buildFlags(ast.flags);
const args = build(ast.body) + (flags ? `, ${flags}` : "");
return argsOnly ? args : `createRegExp(${args})`;
}
exports.convert = convert;

View file

@ -0,0 +1,5 @@
declare function convert(regex: RegExp, { argsOnly }?: {
argsOnly?: boolean | undefined;
}): string;
export { convert };

View file

@ -0,0 +1,5 @@
declare function convert(regex: RegExp, { argsOnly }?: {
argsOnly?: boolean | undefined;
}): string;
export { convert };

View file

@ -0,0 +1,5 @@
declare function convert(regex: RegExp, { argsOnly }?: {
argsOnly?: boolean | undefined;
}): string;
export { convert };

View file

@ -0,0 +1,259 @@
import regexpTree from 'regexp-tree';
function build(node) {
if (node === null)
return "";
switch (node.type) {
case "CharacterClass": {
const exprs = combineContinuousSimpleChars(node.expressions);
if (exprs.length === 1) {
const first = exprs[0];
if (typeof first === "string") {
return node.negative ? `charNotIn(${first})` : `charIn(${first})`;
} else if (first.type === "Char" && first.kind === "meta" && node.negative) {
if (first.value === "\\t")
return `not.tab`;
if (first.value === "\\n")
return `not.linefeed`;
if (first.value === "\\r")
return `not.carriageReturn`;
} else {
const range = normalizeClassRange(first);
if (range === "A-Z")
return node.negative ? `not.letter.uppercase` : `letter.uppercase`;
else if (range === "a-z")
return node.negative ? `not.letter.lowercase` : `letter.lowercase`;
}
} else if (exprs.length === 2) {
if (typeof exprs[0] !== "string" && typeof exprs[1] !== "string") {
const range1 = normalizeClassRange(exprs[0]);
const range2 = normalizeClassRange(exprs[1]);
if (range1 === "A-Z" && range2 === "a-z" || range1 === "a-z" && range2 === "A-Z")
return node.negative ? `not.letter` : `letter`;
}
}
throw new Error("Unsupported for Complex charactor class");
}
case "Disjunction":
return chain(build(node.left), `or(${build(node.right)})`);
case "Assertion":
switch (node.kind) {
case "\\b":
return "wordBoundary";
case "\\B":
return "not.wordBoundary";
case "^":
return chain("", "at.lineStart()");
case "$":
return chain("", "at.lineEnd()");
case "Lookbehind":
return chain("", `${node.negative ? "notAfter" : "after"}(${build(node.assertion)})`);
case "Lookahead":
return chain("", `${node.negative ? "notBefore" : "before"}(${build(node.assertion)})`);
/* v8 ignore next 2 */
default:
throw new TypeError(`Unknown Assertion kind: ${node.kind}`);
}
case "Char":
if (node.kind === "meta") {
switch (node.value) {
case ".":
return "char";
case "\\w":
return "wordChar";
case "\\d":
return "digit";
case "\\s":
return "whitespace";
case "\\t":
return "tab";
case "\\n":
return "linefeed";
case "\\r":
return "carriageReturn";
case "\\W":
return "not.wordChar";
case "\\D":
return "not.digit";
case "\\S":
return "not.whitespace";
case "\f":
case "\v":
default:
throw new Error(`Unsupported Meta Char: ${node.value}`);
}
} else {
const char = getChar(node);
if (char === null)
throw new Error(`Unknown Char: ${node.value}`);
return `'${char}'`;
}
case "Repetition": {
const quantifier = node.quantifier;
const expr = build(node.expression);
const lazy = !quantifier.greedy;
if (lazy)
throw new Error("Unsupported for lazy quantifier");
switch (quantifier.kind) {
case "+":
return `oneOrMore(${expr})`;
case "?":
return `maybe(${expr})`;
case "*":
return chain(expr, "times.any()");
case "Range":
if (quantifier.from === quantifier.to)
return chain(expr, `times(${quantifier.from})`);
else if (!quantifier.to)
return chain(expr, `times.atLeast(${quantifier.from})`);
else if (quantifier.from === 0)
return chain(expr, `times.atMost(${quantifier.to})`);
return chain(expr, `times.between(${quantifier.from}, ${quantifier.to})`);
/* v8 ignore next 2 */
default:
return "";
}
}
case "Alternative": {
const alts = combineContinuousSimpleChars(node.expressions);
const exprs = [];
for (let i = 0; i < alts.length; i++) {
const alt = alts[i];
if (typeof alt === "string") {
exprs.push(alt);
continue;
}
if (alt.type === "Assertion") {
switch (alt.kind) {
case "^": {
const next = alts[++i];
if (next === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
exprs.push(chain(next, "at.lineStart()"));
continue;
}
case "$": {
const prev = exprs.pop();
if (prev === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
exprs.push(chain(prev, "at.lineEnd()"));
continue;
}
case "Lookbehind": {
const next = alts[++i];
if (next === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
const helper = alt.negative ? "notAfter" : "after";
exprs.push(chain(next, `${helper}(${build(alt.assertion)})`));
continue;
}
case "Lookahead": {
const prev = exprs.pop();
if (prev === void 0)
throw new Error(`Unexpected assertion: ${JSON.stringify(alt)}`);
const helper = alt.negative ? "notBefore" : "before";
exprs.push(chain(prev, `${helper}(${build(alt.assertion)})`));
continue;
}
}
}
if (alt.type === "Backreference") {
if (alt.kind !== "name")
throw new Error(`Unsupport for number reference`);
const ref = chain(`exactly(${exprs.join(", ")})`, `and.referenceTo('${alt.reference}')`);
exprs.length = 0;
exprs.push(ref);
continue;
}
exprs.push(build(alt));
}
return exprs.join(", ");
}
case "Group":
if (node.capturing)
return chain(build(node.expression), node.name ? `as('${node.name}')` : "grouped()");
else return chain(build(node.expression));
/* v8 ignore next 2 */
case "Backreference":
return chain("", `and.referenceTo('${node.reference}')`);
}
}
function normalizeClassRange(node) {
if (node.type === "ClassRange")
return `${node.from.value}-${node.to.value}`;
}
function combineContinuousSimpleChars(expressions) {
let simpleChars = "";
const exprs = expressions.reduce(
(acc, expr) => {
const char = expr.type === "Char" ? getChar(expr) : null;
if (char !== null) {
simpleChars += char;
} else {
if (simpleChars) {
acc.push(`'${simpleChars}'`);
simpleChars = "";
}
acc.push(expr);
}
return acc;
},
[]
);
if (simpleChars)
exprs.push(`'${simpleChars}'`);
return exprs;
}
function getChar(char) {
function escapeSimpleChar(char2) {
return char2 === "'" ? "\\'" : char2;
}
switch (char.kind) {
case "simple":
return escapeSimpleChar(char.value);
case "oct":
case "decimal":
case "hex":
case "unicode":
if ("symbol" in char)
return escapeSimpleChar(char.symbol);
}
return null;
}
function chain(expr, helper) {
let _expr = "";
if (typeof expr === "string") {
if (expr === "")
_expr = "exactly('')";
else _expr = expr.startsWith("'") && expr.endsWith("'") ? `exactly(${expr})` : expr;
} else {
_expr = build(expr);
}
return helper ? `${_expr}.${helper}` : _expr;
}
function buildFlags(flags) {
if (!flags)
return "";
const readableFlags = flags.split("").map((flag) => {
return {
d: "withIndices",
i: "caseInsensitive",
g: "global",
m: "multiline",
s: "dotAll",
u: "unicode",
y: "sticky"
}[flag] || `'${flag}'`;
});
return `[${readableFlags.join(", ")}]`;
}
function convert(regex, { argsOnly = false } = {}) {
const ast = regexpTree.parse(regex);
if (ast.type !== "RegExp")
throw new TypeError(`Unexpected RegExp AST: ${ast.type}`);
const flags = buildFlags(ast.flags);
const args = build(ast.body) + (flags ? `, ${flags}` : "");
return argsOnly ? args : `createRegExp(${args})`;
}
export { convert };

View file

@ -0,0 +1,37 @@
'use strict';
const flags = require('./shared/magic-regexp.DNdg2jII.cjs');
const regexp = require('type-level-regexp/regexp');
const createRegExp = (...inputs) => {
const flags$1 = inputs.length > 1 && (Array.isArray(inputs[inputs.length - 1]) || inputs[inputs.length - 1] instanceof Set) ? inputs.pop() : void 0;
return new RegExp(flags.exactly(...inputs).toString(), [...flags$1 || ""].join(""));
};
exports.anyOf = flags.anyOf;
exports.carriageReturn = flags.carriageReturn;
exports.caseInsensitive = flags.caseInsensitive;
exports.char = flags.char;
exports.charIn = flags.charIn;
exports.charNotIn = flags.charNotIn;
exports.digit = flags.digit;
exports.dotAll = flags.dotAll;
exports.exactly = flags.exactly;
exports.global = flags.global;
exports.letter = flags.letter;
exports.linefeed = flags.linefeed;
exports.maybe = flags.maybe;
exports.multiline = flags.multiline;
exports.not = flags.not;
exports.oneOrMore = flags.oneOrMore;
exports.sticky = flags.sticky;
exports.tab = flags.tab;
exports.unicode = flags.unicode;
exports.whitespace = flags.whitespace;
exports.withIndices = flags.withIndices;
exports.word = flags.word;
exports.wordBoundary = flags.wordBoundary;
exports.wordChar = flags.wordChar;
exports.spreadRegExpIterator = regexp.spreadRegExpIterator;
exports.spreadRegExpMatchArray = regexp.spreadRegExpMatchArray;
exports.createRegExp = createRegExp;

View file

@ -0,0 +1,46 @@
import { MatchRegExp, ParseRegExp, MatchAllRegExp, RegExpMatchResult, ReplaceWithRegExp } from 'type-level-regexp/regexp';
export { spreadRegExpIterator, spreadRegExpMatchArray } from 'type-level-regexp/regexp';
import { F as Flag, J as Join, I as InputSource, b as MapToValues, c as MapToGroups, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.cjs';
export { h as Input, a as MagicRegExpMatchArray, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.cjs';
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, Flags extends Flag[] | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[ValueS]: Value;
[FlagsS]: Flags;
};
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, []>;
<Inputs extends InputSource[], FlagUnion extends Flag | undefined = undefined, CloneFlagUnion extends Flag | undefined = FlagUnion, Flags extends Flag[] = CloneFlagUnion extends undefined ? [] : UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, [...Flags] | string | Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, Flags>;
};
declare global {
interface String {
match<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(regexp: R): never;
matchAll<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchAllRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, never>>(regexp: R): never;
replace<InputString extends string, RegExpPattern extends string, Flags extends Flag[], ReplaceValue extends string, RegExpParsedAST extends any[] = string extends RegExpPattern ? never : ParseRegExp<RegExpPattern>, MatchResult = MatchRegExp<InputString, RegExpParsedAST, Flags[number]>, Match extends any[] = MatchResult extends RegExpMatchResult<{
matched: infer MatchArray extends any[];
namedCaptures: [string, any];
input: infer Input extends string;
restInput: string | undefined;
}, {
index: infer Index extends number;
groups: infer Groups;
input: string;
keys: (...arg: any) => any;
}> ? [...MatchArray, Index, Input, Groups] : never>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>, replaceValue: ReplaceValue | ((...match: Match) => ReplaceValue)): any[] extends RegExpParsedAST ? never : ReplaceWithRegExp<InputString, RegExpParsedAST, ReplaceValue, Flags[number]>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, type MagicRegExp, createRegExp };

View file

@ -0,0 +1,46 @@
import { MatchRegExp, ParseRegExp, MatchAllRegExp, RegExpMatchResult, ReplaceWithRegExp } from 'type-level-regexp/regexp';
export { spreadRegExpIterator, spreadRegExpMatchArray } from 'type-level-regexp/regexp';
import { F as Flag, J as Join, I as InputSource, b as MapToValues, c as MapToGroups, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.mjs';
export { h as Input, a as MagicRegExpMatchArray, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.mjs';
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, Flags extends Flag[] | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[ValueS]: Value;
[FlagsS]: Flags;
};
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, []>;
<Inputs extends InputSource[], FlagUnion extends Flag | undefined = undefined, CloneFlagUnion extends Flag | undefined = FlagUnion, Flags extends Flag[] = CloneFlagUnion extends undefined ? [] : UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, [...Flags] | string | Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, Flags>;
};
declare global {
interface String {
match<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(regexp: R): never;
matchAll<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchAllRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, never>>(regexp: R): never;
replace<InputString extends string, RegExpPattern extends string, Flags extends Flag[], ReplaceValue extends string, RegExpParsedAST extends any[] = string extends RegExpPattern ? never : ParseRegExp<RegExpPattern>, MatchResult = MatchRegExp<InputString, RegExpParsedAST, Flags[number]>, Match extends any[] = MatchResult extends RegExpMatchResult<{
matched: infer MatchArray extends any[];
namedCaptures: [string, any];
input: infer Input extends string;
restInput: string | undefined;
}, {
index: infer Index extends number;
groups: infer Groups;
input: string;
keys: (...arg: any) => any;
}> ? [...MatchArray, Index, Input, Groups] : never>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>, replaceValue: ReplaceValue | ((...match: Match) => ReplaceValue)): any[] extends RegExpParsedAST ? never : ReplaceWithRegExp<InputString, RegExpParsedAST, ReplaceValue, Flags[number]>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, type MagicRegExp, createRegExp };

View file

@ -0,0 +1,46 @@
import { MatchRegExp, ParseRegExp, MatchAllRegExp, RegExpMatchResult, ReplaceWithRegExp } from 'type-level-regexp/regexp';
export { spreadRegExpIterator, spreadRegExpMatchArray } from 'type-level-regexp/regexp';
import { F as Flag, J as Join, I as InputSource, b as MapToValues, c as MapToGroups, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.js';
export { h as Input, a as MagicRegExpMatchArray, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.js';
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, Flags extends Flag[] | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[ValueS]: Value;
[FlagsS]: Flags;
};
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, []>;
<Inputs extends InputSource[], FlagUnion extends Flag | undefined = undefined, CloneFlagUnion extends Flag | undefined = FlagUnion, Flags extends Flag[] = CloneFlagUnion extends undefined ? [] : UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, [...Flags] | string | Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, Flags>;
};
declare global {
interface String {
match<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(regexp: R): never;
matchAll<InputString extends string, RegExpPattern extends string, Flags extends Flag[]>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>): MatchAllRegExp<InputString, ParseRegExp<RegExpPattern>, Flag[] extends Flags ? never : Flags[number]>;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, never>>(regexp: R): never;
replace<InputString extends string, RegExpPattern extends string, Flags extends Flag[], ReplaceValue extends string, RegExpParsedAST extends any[] = string extends RegExpPattern ? never : ParseRegExp<RegExpPattern>, MatchResult = MatchRegExp<InputString, RegExpParsedAST, Flags[number]>, Match extends any[] = MatchResult extends RegExpMatchResult<{
matched: infer MatchArray extends any[];
namedCaptures: [string, any];
input: infer Input extends string;
restInput: string | undefined;
}, {
index: infer Index extends number;
groups: infer Groups;
input: string;
keys: (...arg: any) => any;
}> ? [...MatchArray, Index, Input, Groups] : never>(this: InputString, regexp: MagicRegExp<`/${RegExpPattern}/${Join<Flags, '', ''>}`, string, Flags>, replaceValue: ReplaceValue | ((...match: Match) => ReplaceValue)): any[] extends RegExpParsedAST ? never : ReplaceWithRegExp<InputString, RegExpParsedAST, ReplaceValue, Flags[number]>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, Exclude<Flag, 'g'>[]>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, type MagicRegExp, createRegExp };

View file

@ -0,0 +1,10 @@
import { e as exactly } from './shared/magic-regexp.DKp_q_HX.mjs';
export { f as anyOf, q as carriageReturn, c as caseInsensitive, h as char, a as charIn, b as charNotIn, l as digit, d as dotAll, g as global, o as letter, p as linefeed, v as maybe, m as multiline, r as not, x as oneOrMore, s as sticky, t as tab, u as unicode, n as whitespace, w as withIndices, i as word, k as wordBoundary, j as wordChar } from './shared/magic-regexp.DKp_q_HX.mjs';
export { spreadRegExpIterator, spreadRegExpMatchArray } from 'type-level-regexp/regexp';
const createRegExp = (...inputs) => {
const flags = inputs.length > 1 && (Array.isArray(inputs[inputs.length - 1]) || inputs[inputs.length - 1] instanceof Set) ? inputs.pop() : void 0;
return new RegExp(exactly(...inputs).toString(), [...flags || ""].join(""));
};
export { createRegExp, exactly };

View file

@ -0,0 +1,34 @@
'use strict';
const flags = require('./shared/magic-regexp.DNdg2jII.cjs');
const createRegExp = (...inputs) => {
const flags$1 = inputs.length > 1 && (Array.isArray(inputs[inputs.length - 1]) || inputs[inputs.length - 1] instanceof Set) ? inputs.pop() : void 0;
return new RegExp(flags.exactly(...inputs).toString(), [...flags$1 || ""].join(""));
};
exports.anyOf = flags.anyOf;
exports.carriageReturn = flags.carriageReturn;
exports.caseInsensitive = flags.caseInsensitive;
exports.char = flags.char;
exports.charIn = flags.charIn;
exports.charNotIn = flags.charNotIn;
exports.digit = flags.digit;
exports.dotAll = flags.dotAll;
exports.exactly = flags.exactly;
exports.global = flags.global;
exports.letter = flags.letter;
exports.linefeed = flags.linefeed;
exports.maybe = flags.maybe;
exports.multiline = flags.multiline;
exports.not = flags.not;
exports.oneOrMore = flags.oneOrMore;
exports.sticky = flags.sticky;
exports.tab = flags.tab;
exports.unicode = flags.unicode;
exports.whitespace = flags.whitespace;
exports.withIndices = flags.withIndices;
exports.word = flags.word;
exports.wordBoundary = flags.wordBoundary;
exports.wordChar = flags.wordChar;
exports.createRegExp = createRegExp;

View file

@ -0,0 +1,27 @@
import { M as MagicRegExp, F as Flag, a as MagicRegExpMatchArray, I as InputSource, J as Join, b as MapToValues, c as MapToGroups, d as MapToCapturedGroupsArr, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.cjs';
export { h as Input, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.cjs';
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, never>;
<Inputs extends InputSource[], Flags extends Flag[] = never[]>(...inputs: [...Inputs, [...Flags]]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
<Inputs extends InputSource[], FlagUnion extends Flag = never, Flags extends Flag[] = UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
};
declare global {
interface String {
match<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): MagicRegExpMatchArray<R> | null;
match<R extends MagicRegExp<string, string, (string | undefined)[], 'g'>>(regexp: R): string[] | null;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(regexp: R): never;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): never;
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], string>>(regexp: R): IterableIterator<MagicRegExpMatchArray<R>>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, MagicRegExp, MagicRegExpMatchArray, createRegExp };

View file

@ -0,0 +1,27 @@
import { M as MagicRegExp, F as Flag, a as MagicRegExpMatchArray, I as InputSource, J as Join, b as MapToValues, c as MapToGroups, d as MapToCapturedGroupsArr, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.mjs';
export { h as Input, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.mjs';
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, never>;
<Inputs extends InputSource[], Flags extends Flag[] = never[]>(...inputs: [...Inputs, [...Flags]]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
<Inputs extends InputSource[], FlagUnion extends Flag = never, Flags extends Flag[] = UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
};
declare global {
interface String {
match<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): MagicRegExpMatchArray<R> | null;
match<R extends MagicRegExp<string, string, (string | undefined)[], 'g'>>(regexp: R): string[] | null;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(regexp: R): never;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): never;
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], string>>(regexp: R): IterableIterator<MagicRegExpMatchArray<R>>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, MagicRegExp, MagicRegExpMatchArray, createRegExp };

View file

@ -0,0 +1,27 @@
import { M as MagicRegExp, F as Flag, a as MagicRegExpMatchArray, I as InputSource, J as Join, b as MapToValues, c as MapToGroups, d as MapToCapturedGroupsArr, U as UnionToTuple } from './shared/magic-regexp.Cp7m-ws-.js';
export { h as Input, D as MapToStringCapturedBy, S as StringCapturedBy, k as anyOf, y as carriageReturn, e as caseInsensitive, l as char, i as charIn, j as charNotIn, q as digit, f as dotAll, B as exactly, g as global, t as letter, x as linefeed, A as maybe, m as multiline, z as not, C as oneOrMore, s as sticky, v as tab, u as unicode, r as whitespace, w as withIndices, n as word, p as wordBoundary, o as wordChar } from './shared/magic-regexp.Cp7m-ws-.js';
declare const createRegExp: {
/** Create Magic RegExp from Input helpers and string (string will be sanitized) */
<Inputs extends InputSource[]>(...inputs: Inputs): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, never>;
<Inputs extends InputSource[], Flags extends Flag[] = never[]>(...inputs: [...Inputs, [...Flags]]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
<Inputs extends InputSource[], FlagUnion extends Flag = never, Flags extends Flag[] = UnionToTuple<FlagUnion> extends infer F extends Flag[] ? F : never>(...inputs: [...Inputs, Set<FlagUnion>]): MagicRegExp<`/${Join<MapToValues<Inputs>, '', ''>}/${Join<Flags, '', ''>}`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>, Flags[number]>;
};
declare global {
interface String {
match<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): MagicRegExpMatchArray<R> | null;
match<R extends MagicRegExp<string, string, (string | undefined)[], 'g'>>(regexp: R): string[] | null;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(regexp: R): never;
/** @deprecated String.matchAll requires global flag to be set. */
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(regexp: R): never;
matchAll<R extends MagicRegExp<string, string, (string | undefined)[], string>>(regexp: R): IterableIterator<MagicRegExpMatchArray<R>>;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], never>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
/** @deprecated String.replaceAll requires global flag to be set. */
replaceAll<R extends MagicRegExp<string, string, (string | undefined)[], Exclude<Flag, 'g'>>>(searchValue: R, replaceValue: string | ((substring: string, ...args: any[]) => string)): never;
}
}
export { Flag, MagicRegExp, MagicRegExpMatchArray, createRegExp };

View file

@ -0,0 +1,9 @@
import { e as exactly } from './shared/magic-regexp.DKp_q_HX.mjs';
export { f as anyOf, q as carriageReturn, c as caseInsensitive, h as char, a as charIn, b as charNotIn, l as digit, d as dotAll, g as global, o as letter, p as linefeed, v as maybe, m as multiline, r as not, x as oneOrMore, s as sticky, t as tab, u as unicode, n as whitespace, w as withIndices, i as word, k as wordBoundary, j as wordChar } from './shared/magic-regexp.DKp_q_HX.mjs';
const createRegExp = (...inputs) => {
const flags = inputs.length > 1 && (Array.isArray(inputs[inputs.length - 1]) || inputs[inputs.length - 1] instanceof Set) ? inputs.pop() : void 0;
return new RegExp(exactly(...inputs).toString(), [...flags || ""].join(""));
};
export { createRegExp, exactly };

View file

@ -0,0 +1,224 @@
type Flag = 'd' | 'g' | 'i' | 'm' | 's' | 'u' | 'y';
/** Generate indices for substring matches */
declare const withIndices = "d";
/** Case-insensitive search */
declare const caseInsensitive = "i";
/** Global search */
declare const global = "g";
/** Multi-line search */
declare const multiline = "m";
/** Allows `.` to match newline characters */
declare const dotAll = "s";
/** Treat a pattern as a sequence of unicode code points */
declare const unicode = "u";
/** Perform a "sticky" search that matches starting at the current position in the target string */
declare const sticky = "y";
type Join<T extends string[], Prefix extends string = '', Joiner extends string = '|'> = T extends [infer F, ...infer R] ? F extends string ? `${Prefix}${F}${R extends string[] ? Join<R, Joiner, Joiner> : ''}` : '' : '';
type UnionToIntersection<Union> = (Union extends Union ? (a: Union) => any : never) extends (a: infer I) => any ? I : never;
type UnionToTuple<Union, Tuple extends any[] = []> = UnionToIntersection<Union extends any ? () => Union : never> extends () => infer Item ? UnionToTuple<Exclude<Union, Item>, [...Tuple, Item]> : Tuple;
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const CapturedGroupsArrS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, CapturedGroupsArr extends (string | undefined)[] = [], Flags extends string | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[CapturedGroupsArrS]: CapturedGroupsArr;
[ValueS]: Value;
[FlagsS]: Flags;
};
type ExtractGroups<T extends MagicRegExp<string, string, (string | undefined)[], string>> = T extends MagicRegExp<string, infer V, (string | undefined)[], string> ? V : never;
type StringWithHint<S extends string> = string & {
_capturedBy: S;
};
type StringCapturedBy<S extends string> = StringWithHint<S>;
type MapToStringCapturedBy<Ar extends (string | undefined)[]> = {
[K in keyof Ar]: Ar[K] extends string ? StringCapturedBy<Ar[K]> | undefined : undefined;
};
type MagicRegExpMatchArray<T extends MagicRegExp<string, string, any[], string>> = Omit<RegExpMatchArray, 'groups'> & {
groups: Record<ExtractGroups<T>, string | undefined>;
} & {
[index: number | string | symbol]: never;
} & (T extends MagicRegExp<string, string, infer CapturedGroupsArr, string> ? readonly [string | undefined, ...MapToStringCapturedBy<CapturedGroupsArr>] : {});
type IfUnwrapped<Value extends string, Yes, No> = Value extends `(${string})` ? No : StripEscapes<Value> extends `${infer A}${infer B}` ? A extends '' ? No : B extends '' ? No : Yes : never;
/** This matches any character in the string provided */
declare const charIn: (<T extends string>(chars: T) => CharInput<Escape<T, "^" | "]" | "\\" | "-">>) & CharInput<"">;
/** This matches any character that is not in the string provided */
declare const charNotIn: (<T extends string>(chars: T) => CharInput<`^${Escape<T, "^" | "]" | "\\" | "-">}`>) & CharInput<"^">;
/**
* This takes a variable number of inputs and matches any of them
* @example
* anyOf('foo', maybe('bar'), 'baz') // => /(?:foo|(?:bar)?|baz)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function anyOf<Inputs extends InputSource[]>(...inputs: Inputs): Input<`(?:${Join<MapToValues<Inputs>>})`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
declare const char: Input<".", never, []>;
declare const word: Input<"\\b\\w+\\b", never, []>;
declare const wordChar: Input<"\\w", never, []>;
declare const wordBoundary: Input<"\\b", never, []>;
declare const digit: Input<"\\d", never, []>;
declare const whitespace: Input<"\\s", never, []>;
declare const letter: Input<"[a-zA-Z]", never, []> & {
lowercase: Input<"[a-z]", never, []>;
uppercase: Input<"[A-Z]", never, []>;
};
declare const tab: Input<"\\t", never, []>;
declare const linefeed: Input<"\\n", never, []>;
declare const carriageReturn: Input<"\\r", never, []>;
declare const not: {
word: Input<"\\W+", never, []>;
wordChar: Input<"\\W", never, []>;
wordBoundary: Input<"\\B", never, []>;
digit: Input<"\\D", never, []>;
whitespace: Input<"\\S", never, []>;
letter: Input<"[^a-zA-Z]", never, []> & {
lowercase: Input<"[^a-z]", never, []>;
uppercase: Input<"[^A-Z]", never, []>;
};
tab: Input<"[^\\t]", never, []>;
linefeed: Input<"[^\\n]", never, []>;
carriageReturn: Input<"[^\\r]", never, []>;
};
/**
* Equivalent to `?` - takes a variable number of inputs and marks them as optional
* @example
* maybe('foo', exactly('ba?r')) // => /(?:fooba\?r)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function maybe<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})?`, `${Value}?`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* This takes a variable number of inputs and concatenate their patterns, and escapes string inputs to match it exactly
* @example
* exactly('fo?o', maybe('bar')) // => /fo\?o(?:bar)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function exactly<Inputs extends InputSource[]>(...inputs: Inputs): Input<Join<MapToValues<Inputs>, '', ''>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* Equivalent to `+` - this takes a variable number of inputs and marks them as repeatable, any number of times but at least once
* @example
* oneOrMore('foo', maybe('bar')) // => /(?:foo(?:bar)?)+/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function oneOrMore<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})+`, `${Value}+`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
type Escape<T extends string, EscapeChar extends string> = T extends `${infer Start}${EscapeChar}${string}` ? Start extends `${string}${EscapeChar}${string}` ? never : T extends `${Start}${infer Char}${string}` ? Char extends EscapeChar ? T extends `${Start}${Char}${infer Rest}` ? `${Start}\\${Char}${Escape<Rest, EscapeChar>}` : never : never : never : T;
type EscapeChar<T extends string> = Escape<T, '\\' | '^' | '-' | ']'>;
type StripEscapes<T extends string> = T extends `${infer A}\\${infer B}` ? `${A}${B}` : T;
type ExactEscapeChar = '.' | '*' | '+' | '?' | '^' | '$' | '{' | '}' | '(' | ')' | '|' | '[' | ']' | '/';
type GetValue<T extends InputSource> = T extends string ? Escape<T, ExactEscapeChar> : T extends Input<infer R> ? R : never;
interface Input<V extends string, G extends string = never, C extends (string | undefined)[] = []> {
/**
* this takes a variable number of inputs and adds them as new pattern to the current input, or you can use `and.referenceTo(groupName)` to adds a new pattern referencing to a named group
* @example
* exactly('foo').and('bar', maybe('baz')) // => /foobar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
and: {
<I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I): Input<`${V}${Join<MapToValues<I>, '', ''>}`, G | MapToGroups<I>, [...C, ...CG]>;
/** this adds a new pattern to the current input, with the pattern reference to a named group. */
referenceTo: <N extends G>(groupName: N) => Input<`${V}\\k<${N}>`, G, C>;
};
/**
* this takes a variable number of inputs and provides as an alternative to the current input
* @example
* exactly('foo').or('bar', maybe('baz')) // => /foo|bar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
or: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?:${V}|${Join<MapToValues<I>, '', ''>})`, G | MapToGroups<I>, [...C, ...CG]>;
/**
* this takes a variable number of inputs and activate a positive lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').after('bar', maybe('baz')) // => /(?<=bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
after: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?<=${Join<MapToValues<I>, '', ''>})${V}`, G | MapToGroups<I>, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a positive lookahead
* @example
* exactly('foo').before('bar', maybe('baz')) // => /foo(?=bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
before: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`${V}(?=${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/**
* these takes a variable number of inputs and activate a negative lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').notAfter('bar', maybe('baz')) // => /(?<!bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notAfter: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`(?<!${Join<MapToValues<I>, '', ''>})${V}`, G, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a negative lookahead
* @example
* exactly('foo').notBefore('bar', maybe('baz')) // => /foo(?!bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notBefore: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`${V}(?!${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/** repeat the previous pattern an exact number of times */
times: {
<N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N}}`, `${V}{${N}}`>>(number: N): Input<NV, G, C>;
/** specify that the expression can repeat any number of times, _including none_ */
any: <NV extends string = IfUnwrapped<V, `(?:${V})*`, `${V}*`>>() => Input<NV, G, C>;
/** specify that the expression must occur at least `N` times */
atLeast: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N},}`, `${V}{${N},}`>>(number: N) => Input<NV, G, C>;
/** specify that the expression must occur at most `N` times */
atMost: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){0,${N}}`, `${V}{0,${N}}`>>(number: N) => Input<NV, G, C>;
/** specify a range of times to repeat the previous pattern */
between: <Min extends number, Max extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${Min},${Max}}`, `${V}{${Min},${Max}}`>>(min: Min, max: Max) => Input<NV, G, C>;
};
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()`. Alias for `groupedAs` */
as: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()` */
groupedAs: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this capture the entire input so far as an anonymous group */
grouped: () => Input<V extends `(?:${infer S})${infer E}` ? `(${S})${E}` : `(${V})`, G, [
V extends `(?:${infer S})${'' | '?' | '+' | '*' | `{${string}}`}` ? `(${S})` : `(${V})`,
...C
]>;
/** this allows you to match beginning/ends of lines with `at.lineStart()` and `at.lineEnd()` */
at: {
lineStart: () => Input<`^${V}`, G, C>;
lineEnd: () => Input<`${V}$`, G, C>;
};
/** this allows you to mark the input so far as optional */
optionally: <NV extends string = IfUnwrapped<V, `(?:${V})?`, `${V}?`>>() => Input<NV, G, C>;
toString: () => string;
}
interface CharInput<T extends string> extends Input<`[${T}]`> {
orChar: (<Or extends string>(chars: Or) => CharInput<`${T}${EscapeChar<Or>}`>) & CharInput<T>;
from: <From extends string, To extends string>(charFrom: From, charTo: To) => CharInput<`${T}${EscapeChar<From>}-${EscapeChar<To>}`>;
}
type InputSource<S extends string = string, T extends string = never> = S | Input<any, T>;
type MapToValues<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends InputSource ? [GetValue<First>, ...MapToValues<Rest>] : [] : [];
type MapToGroups<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends Input<any, infer K> ? K | MapToGroups<Rest> : MapToGroups<Rest> : never;
type MapToCapturedGroupsArr<Inputs extends any[], MapToUndefined extends boolean = false, CapturedGroupsArr extends any[] = [], Count extends any[] = []> = Count['length'] extends Inputs['length'] ? CapturedGroupsArr : Inputs[Count['length']] extends Input<any, any, infer CaptureGroups> ? [CaptureGroups] extends [never] ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']> : MapToUndefined extends true ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
undefined
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
...CaptureGroups
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']>;
export { maybe as A, exactly as B, oneOrMore as C, type MapToStringCapturedBy as D, type Flag as F, type InputSource as I, type Join as J, type MagicRegExp as M, type StringCapturedBy as S, type UnionToTuple as U, type MagicRegExpMatchArray as a, type MapToValues as b, type MapToGroups as c, type MapToCapturedGroupsArr as d, caseInsensitive as e, dotAll as f, global as g, type Input as h, charIn as i, charNotIn as j, anyOf as k, char as l, multiline as m, word as n, wordChar as o, wordBoundary as p, digit as q, whitespace as r, sticky as s, letter as t, unicode as u, tab as v, withIndices as w, linefeed as x, carriageReturn as y, not as z };

View file

@ -0,0 +1,224 @@
type Flag = 'd' | 'g' | 'i' | 'm' | 's' | 'u' | 'y';
/** Generate indices for substring matches */
declare const withIndices = "d";
/** Case-insensitive search */
declare const caseInsensitive = "i";
/** Global search */
declare const global = "g";
/** Multi-line search */
declare const multiline = "m";
/** Allows `.` to match newline characters */
declare const dotAll = "s";
/** Treat a pattern as a sequence of unicode code points */
declare const unicode = "u";
/** Perform a "sticky" search that matches starting at the current position in the target string */
declare const sticky = "y";
type Join<T extends string[], Prefix extends string = '', Joiner extends string = '|'> = T extends [infer F, ...infer R] ? F extends string ? `${Prefix}${F}${R extends string[] ? Join<R, Joiner, Joiner> : ''}` : '' : '';
type UnionToIntersection<Union> = (Union extends Union ? (a: Union) => any : never) extends (a: infer I) => any ? I : never;
type UnionToTuple<Union, Tuple extends any[] = []> = UnionToIntersection<Union extends any ? () => Union : never> extends () => infer Item ? UnionToTuple<Exclude<Union, Item>, [...Tuple, Item]> : Tuple;
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const CapturedGroupsArrS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, CapturedGroupsArr extends (string | undefined)[] = [], Flags extends string | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[CapturedGroupsArrS]: CapturedGroupsArr;
[ValueS]: Value;
[FlagsS]: Flags;
};
type ExtractGroups<T extends MagicRegExp<string, string, (string | undefined)[], string>> = T extends MagicRegExp<string, infer V, (string | undefined)[], string> ? V : never;
type StringWithHint<S extends string> = string & {
_capturedBy: S;
};
type StringCapturedBy<S extends string> = StringWithHint<S>;
type MapToStringCapturedBy<Ar extends (string | undefined)[]> = {
[K in keyof Ar]: Ar[K] extends string ? StringCapturedBy<Ar[K]> | undefined : undefined;
};
type MagicRegExpMatchArray<T extends MagicRegExp<string, string, any[], string>> = Omit<RegExpMatchArray, 'groups'> & {
groups: Record<ExtractGroups<T>, string | undefined>;
} & {
[index: number | string | symbol]: never;
} & (T extends MagicRegExp<string, string, infer CapturedGroupsArr, string> ? readonly [string | undefined, ...MapToStringCapturedBy<CapturedGroupsArr>] : {});
type IfUnwrapped<Value extends string, Yes, No> = Value extends `(${string})` ? No : StripEscapes<Value> extends `${infer A}${infer B}` ? A extends '' ? No : B extends '' ? No : Yes : never;
/** This matches any character in the string provided */
declare const charIn: (<T extends string>(chars: T) => CharInput<Escape<T, "^" | "]" | "\\" | "-">>) & CharInput<"">;
/** This matches any character that is not in the string provided */
declare const charNotIn: (<T extends string>(chars: T) => CharInput<`^${Escape<T, "^" | "]" | "\\" | "-">}`>) & CharInput<"^">;
/**
* This takes a variable number of inputs and matches any of them
* @example
* anyOf('foo', maybe('bar'), 'baz') // => /(?:foo|(?:bar)?|baz)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function anyOf<Inputs extends InputSource[]>(...inputs: Inputs): Input<`(?:${Join<MapToValues<Inputs>>})`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
declare const char: Input<".", never, []>;
declare const word: Input<"\\b\\w+\\b", never, []>;
declare const wordChar: Input<"\\w", never, []>;
declare const wordBoundary: Input<"\\b", never, []>;
declare const digit: Input<"\\d", never, []>;
declare const whitespace: Input<"\\s", never, []>;
declare const letter: Input<"[a-zA-Z]", never, []> & {
lowercase: Input<"[a-z]", never, []>;
uppercase: Input<"[A-Z]", never, []>;
};
declare const tab: Input<"\\t", never, []>;
declare const linefeed: Input<"\\n", never, []>;
declare const carriageReturn: Input<"\\r", never, []>;
declare const not: {
word: Input<"\\W+", never, []>;
wordChar: Input<"\\W", never, []>;
wordBoundary: Input<"\\B", never, []>;
digit: Input<"\\D", never, []>;
whitespace: Input<"\\S", never, []>;
letter: Input<"[^a-zA-Z]", never, []> & {
lowercase: Input<"[^a-z]", never, []>;
uppercase: Input<"[^A-Z]", never, []>;
};
tab: Input<"[^\\t]", never, []>;
linefeed: Input<"[^\\n]", never, []>;
carriageReturn: Input<"[^\\r]", never, []>;
};
/**
* Equivalent to `?` - takes a variable number of inputs and marks them as optional
* @example
* maybe('foo', exactly('ba?r')) // => /(?:fooba\?r)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function maybe<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})?`, `${Value}?`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* This takes a variable number of inputs and concatenate their patterns, and escapes string inputs to match it exactly
* @example
* exactly('fo?o', maybe('bar')) // => /fo\?o(?:bar)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function exactly<Inputs extends InputSource[]>(...inputs: Inputs): Input<Join<MapToValues<Inputs>, '', ''>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* Equivalent to `+` - this takes a variable number of inputs and marks them as repeatable, any number of times but at least once
* @example
* oneOrMore('foo', maybe('bar')) // => /(?:foo(?:bar)?)+/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function oneOrMore<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})+`, `${Value}+`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
type Escape<T extends string, EscapeChar extends string> = T extends `${infer Start}${EscapeChar}${string}` ? Start extends `${string}${EscapeChar}${string}` ? never : T extends `${Start}${infer Char}${string}` ? Char extends EscapeChar ? T extends `${Start}${Char}${infer Rest}` ? `${Start}\\${Char}${Escape<Rest, EscapeChar>}` : never : never : never : T;
type EscapeChar<T extends string> = Escape<T, '\\' | '^' | '-' | ']'>;
type StripEscapes<T extends string> = T extends `${infer A}\\${infer B}` ? `${A}${B}` : T;
type ExactEscapeChar = '.' | '*' | '+' | '?' | '^' | '$' | '{' | '}' | '(' | ')' | '|' | '[' | ']' | '/';
type GetValue<T extends InputSource> = T extends string ? Escape<T, ExactEscapeChar> : T extends Input<infer R> ? R : never;
interface Input<V extends string, G extends string = never, C extends (string | undefined)[] = []> {
/**
* this takes a variable number of inputs and adds them as new pattern to the current input, or you can use `and.referenceTo(groupName)` to adds a new pattern referencing to a named group
* @example
* exactly('foo').and('bar', maybe('baz')) // => /foobar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
and: {
<I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I): Input<`${V}${Join<MapToValues<I>, '', ''>}`, G | MapToGroups<I>, [...C, ...CG]>;
/** this adds a new pattern to the current input, with the pattern reference to a named group. */
referenceTo: <N extends G>(groupName: N) => Input<`${V}\\k<${N}>`, G, C>;
};
/**
* this takes a variable number of inputs and provides as an alternative to the current input
* @example
* exactly('foo').or('bar', maybe('baz')) // => /foo|bar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
or: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?:${V}|${Join<MapToValues<I>, '', ''>})`, G | MapToGroups<I>, [...C, ...CG]>;
/**
* this takes a variable number of inputs and activate a positive lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').after('bar', maybe('baz')) // => /(?<=bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
after: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?<=${Join<MapToValues<I>, '', ''>})${V}`, G | MapToGroups<I>, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a positive lookahead
* @example
* exactly('foo').before('bar', maybe('baz')) // => /foo(?=bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
before: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`${V}(?=${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/**
* these takes a variable number of inputs and activate a negative lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').notAfter('bar', maybe('baz')) // => /(?<!bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notAfter: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`(?<!${Join<MapToValues<I>, '', ''>})${V}`, G, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a negative lookahead
* @example
* exactly('foo').notBefore('bar', maybe('baz')) // => /foo(?!bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notBefore: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`${V}(?!${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/** repeat the previous pattern an exact number of times */
times: {
<N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N}}`, `${V}{${N}}`>>(number: N): Input<NV, G, C>;
/** specify that the expression can repeat any number of times, _including none_ */
any: <NV extends string = IfUnwrapped<V, `(?:${V})*`, `${V}*`>>() => Input<NV, G, C>;
/** specify that the expression must occur at least `N` times */
atLeast: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N},}`, `${V}{${N},}`>>(number: N) => Input<NV, G, C>;
/** specify that the expression must occur at most `N` times */
atMost: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){0,${N}}`, `${V}{0,${N}}`>>(number: N) => Input<NV, G, C>;
/** specify a range of times to repeat the previous pattern */
between: <Min extends number, Max extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${Min},${Max}}`, `${V}{${Min},${Max}}`>>(min: Min, max: Max) => Input<NV, G, C>;
};
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()`. Alias for `groupedAs` */
as: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()` */
groupedAs: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this capture the entire input so far as an anonymous group */
grouped: () => Input<V extends `(?:${infer S})${infer E}` ? `(${S})${E}` : `(${V})`, G, [
V extends `(?:${infer S})${'' | '?' | '+' | '*' | `{${string}}`}` ? `(${S})` : `(${V})`,
...C
]>;
/** this allows you to match beginning/ends of lines with `at.lineStart()` and `at.lineEnd()` */
at: {
lineStart: () => Input<`^${V}`, G, C>;
lineEnd: () => Input<`${V}$`, G, C>;
};
/** this allows you to mark the input so far as optional */
optionally: <NV extends string = IfUnwrapped<V, `(?:${V})?`, `${V}?`>>() => Input<NV, G, C>;
toString: () => string;
}
interface CharInput<T extends string> extends Input<`[${T}]`> {
orChar: (<Or extends string>(chars: Or) => CharInput<`${T}${EscapeChar<Or>}`>) & CharInput<T>;
from: <From extends string, To extends string>(charFrom: From, charTo: To) => CharInput<`${T}${EscapeChar<From>}-${EscapeChar<To>}`>;
}
type InputSource<S extends string = string, T extends string = never> = S | Input<any, T>;
type MapToValues<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends InputSource ? [GetValue<First>, ...MapToValues<Rest>] : [] : [];
type MapToGroups<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends Input<any, infer K> ? K | MapToGroups<Rest> : MapToGroups<Rest> : never;
type MapToCapturedGroupsArr<Inputs extends any[], MapToUndefined extends boolean = false, CapturedGroupsArr extends any[] = [], Count extends any[] = []> = Count['length'] extends Inputs['length'] ? CapturedGroupsArr : Inputs[Count['length']] extends Input<any, any, infer CaptureGroups> ? [CaptureGroups] extends [never] ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']> : MapToUndefined extends true ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
undefined
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
...CaptureGroups
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']>;
export { maybe as A, exactly as B, oneOrMore as C, type MapToStringCapturedBy as D, type Flag as F, type InputSource as I, type Join as J, type MagicRegExp as M, type StringCapturedBy as S, type UnionToTuple as U, type MagicRegExpMatchArray as a, type MapToValues as b, type MapToGroups as c, type MapToCapturedGroupsArr as d, caseInsensitive as e, dotAll as f, global as g, type Input as h, charIn as i, charNotIn as j, anyOf as k, char as l, multiline as m, word as n, wordChar as o, wordBoundary as p, digit as q, whitespace as r, sticky as s, letter as t, unicode as u, tab as v, withIndices as w, linefeed as x, carriageReturn as y, not as z };

View file

@ -0,0 +1,224 @@
type Flag = 'd' | 'g' | 'i' | 'm' | 's' | 'u' | 'y';
/** Generate indices for substring matches */
declare const withIndices = "d";
/** Case-insensitive search */
declare const caseInsensitive = "i";
/** Global search */
declare const global = "g";
/** Multi-line search */
declare const multiline = "m";
/** Allows `.` to match newline characters */
declare const dotAll = "s";
/** Treat a pattern as a sequence of unicode code points */
declare const unicode = "u";
/** Perform a "sticky" search that matches starting at the current position in the target string */
declare const sticky = "y";
type Join<T extends string[], Prefix extends string = '', Joiner extends string = '|'> = T extends [infer F, ...infer R] ? F extends string ? `${Prefix}${F}${R extends string[] ? Join<R, Joiner, Joiner> : ''}` : '' : '';
type UnionToIntersection<Union> = (Union extends Union ? (a: Union) => any : never) extends (a: infer I) => any ? I : never;
type UnionToTuple<Union, Tuple extends any[] = []> = UnionToIntersection<Union extends any ? () => Union : never> extends () => infer Item ? UnionToTuple<Exclude<Union, Item>, [...Tuple, Item]> : Tuple;
declare const NamedGroupsS: unique symbol;
declare const ValueS: unique symbol;
declare const CapturedGroupsArrS: unique symbol;
declare const FlagsS: unique symbol;
type MagicRegExp<Value extends string, NamedGroups extends string | never = never, CapturedGroupsArr extends (string | undefined)[] = [], Flags extends string | never = never> = RegExp & {
[NamedGroupsS]: NamedGroups;
[CapturedGroupsArrS]: CapturedGroupsArr;
[ValueS]: Value;
[FlagsS]: Flags;
};
type ExtractGroups<T extends MagicRegExp<string, string, (string | undefined)[], string>> = T extends MagicRegExp<string, infer V, (string | undefined)[], string> ? V : never;
type StringWithHint<S extends string> = string & {
_capturedBy: S;
};
type StringCapturedBy<S extends string> = StringWithHint<S>;
type MapToStringCapturedBy<Ar extends (string | undefined)[]> = {
[K in keyof Ar]: Ar[K] extends string ? StringCapturedBy<Ar[K]> | undefined : undefined;
};
type MagicRegExpMatchArray<T extends MagicRegExp<string, string, any[], string>> = Omit<RegExpMatchArray, 'groups'> & {
groups: Record<ExtractGroups<T>, string | undefined>;
} & {
[index: number | string | symbol]: never;
} & (T extends MagicRegExp<string, string, infer CapturedGroupsArr, string> ? readonly [string | undefined, ...MapToStringCapturedBy<CapturedGroupsArr>] : {});
type IfUnwrapped<Value extends string, Yes, No> = Value extends `(${string})` ? No : StripEscapes<Value> extends `${infer A}${infer B}` ? A extends '' ? No : B extends '' ? No : Yes : never;
/** This matches any character in the string provided */
declare const charIn: (<T extends string>(chars: T) => CharInput<Escape<T, "^" | "]" | "\\" | "-">>) & CharInput<"">;
/** This matches any character that is not in the string provided */
declare const charNotIn: (<T extends string>(chars: T) => CharInput<`^${Escape<T, "^" | "]" | "\\" | "-">}`>) & CharInput<"^">;
/**
* This takes a variable number of inputs and matches any of them
* @example
* anyOf('foo', maybe('bar'), 'baz') // => /(?:foo|(?:bar)?|baz)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function anyOf<Inputs extends InputSource[]>(...inputs: Inputs): Input<`(?:${Join<MapToValues<Inputs>>})`, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
declare const char: Input<".", never, []>;
declare const word: Input<"\\b\\w+\\b", never, []>;
declare const wordChar: Input<"\\w", never, []>;
declare const wordBoundary: Input<"\\b", never, []>;
declare const digit: Input<"\\d", never, []>;
declare const whitespace: Input<"\\s", never, []>;
declare const letter: Input<"[a-zA-Z]", never, []> & {
lowercase: Input<"[a-z]", never, []>;
uppercase: Input<"[A-Z]", never, []>;
};
declare const tab: Input<"\\t", never, []>;
declare const linefeed: Input<"\\n", never, []>;
declare const carriageReturn: Input<"\\r", never, []>;
declare const not: {
word: Input<"\\W+", never, []>;
wordChar: Input<"\\W", never, []>;
wordBoundary: Input<"\\B", never, []>;
digit: Input<"\\D", never, []>;
whitespace: Input<"\\S", never, []>;
letter: Input<"[^a-zA-Z]", never, []> & {
lowercase: Input<"[^a-z]", never, []>;
uppercase: Input<"[^A-Z]", never, []>;
};
tab: Input<"[^\\t]", never, []>;
linefeed: Input<"[^\\n]", never, []>;
carriageReturn: Input<"[^\\r]", never, []>;
};
/**
* Equivalent to `?` - takes a variable number of inputs and marks them as optional
* @example
* maybe('foo', exactly('ba?r')) // => /(?:fooba\?r)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function maybe<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})?`, `${Value}?`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* This takes a variable number of inputs and concatenate their patterns, and escapes string inputs to match it exactly
* @example
* exactly('fo?o', maybe('bar')) // => /fo\?o(?:bar)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function exactly<Inputs extends InputSource[]>(...inputs: Inputs): Input<Join<MapToValues<Inputs>, '', ''>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
/**
* Equivalent to `+` - this takes a variable number of inputs and marks them as repeatable, any number of times but at least once
* @example
* oneOrMore('foo', maybe('bar')) // => /(?:foo(?:bar)?)+/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
declare function oneOrMore<Inputs extends InputSource[], Value extends string = Join<MapToValues<Inputs>, '', ''>>(...inputs: Inputs): Input<IfUnwrapped<Value, `(?:${Value})+`, `${Value}+`>, MapToGroups<Inputs>, MapToCapturedGroupsArr<Inputs>>;
type Escape<T extends string, EscapeChar extends string> = T extends `${infer Start}${EscapeChar}${string}` ? Start extends `${string}${EscapeChar}${string}` ? never : T extends `${Start}${infer Char}${string}` ? Char extends EscapeChar ? T extends `${Start}${Char}${infer Rest}` ? `${Start}\\${Char}${Escape<Rest, EscapeChar>}` : never : never : never : T;
type EscapeChar<T extends string> = Escape<T, '\\' | '^' | '-' | ']'>;
type StripEscapes<T extends string> = T extends `${infer A}\\${infer B}` ? `${A}${B}` : T;
type ExactEscapeChar = '.' | '*' | '+' | '?' | '^' | '$' | '{' | '}' | '(' | ')' | '|' | '[' | ']' | '/';
type GetValue<T extends InputSource> = T extends string ? Escape<T, ExactEscapeChar> : T extends Input<infer R> ? R : never;
interface Input<V extends string, G extends string = never, C extends (string | undefined)[] = []> {
/**
* this takes a variable number of inputs and adds them as new pattern to the current input, or you can use `and.referenceTo(groupName)` to adds a new pattern referencing to a named group
* @example
* exactly('foo').and('bar', maybe('baz')) // => /foobar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
and: {
<I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I): Input<`${V}${Join<MapToValues<I>, '', ''>}`, G | MapToGroups<I>, [...C, ...CG]>;
/** this adds a new pattern to the current input, with the pattern reference to a named group. */
referenceTo: <N extends G>(groupName: N) => Input<`${V}\\k<${N}>`, G, C>;
};
/**
* this takes a variable number of inputs and provides as an alternative to the current input
* @example
* exactly('foo').or('bar', maybe('baz')) // => /foo|bar(?:baz)?/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
or: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?:${V}|${Join<MapToValues<I>, '', ''>})`, G | MapToGroups<I>, [...C, ...CG]>;
/**
* this takes a variable number of inputs and activate a positive lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').after('bar', maybe('baz')) // => /(?<=bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
after: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`(?<=${Join<MapToValues<I>, '', ''>})${V}`, G | MapToGroups<I>, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a positive lookahead
* @example
* exactly('foo').before('bar', maybe('baz')) // => /foo(?=bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
before: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I>>(...inputs: I) => Input<`${V}(?=${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/**
* these takes a variable number of inputs and activate a negative lookbehind. Make sure to check [browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#browser_compatibility) as not all browsers support lookbehinds (notably Safari)
* @example
* exactly('foo').notAfter('bar', maybe('baz')) // => /(?<!bar(?:baz)?)foo/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notAfter: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`(?<!${Join<MapToValues<I>, '', ''>})${V}`, G, [...CG, ...C]>;
/**
* this takes a variable number of inputs and activate a negative lookahead
* @example
* exactly('foo').notBefore('bar', maybe('baz')) // => /foo(?!bar(?:baz)?)/
* @argument inputs - arbitrary number of `string` or `Input`, where `string` will be escaped
*/
notBefore: <I extends InputSource[], CG extends any[] = MapToCapturedGroupsArr<I, true>>(...inputs: I) => Input<`${V}(?!${Join<MapToValues<I>, '', ''>})`, G, [...C, ...CG]>;
/** repeat the previous pattern an exact number of times */
times: {
<N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N}}`, `${V}{${N}}`>>(number: N): Input<NV, G, C>;
/** specify that the expression can repeat any number of times, _including none_ */
any: <NV extends string = IfUnwrapped<V, `(?:${V})*`, `${V}*`>>() => Input<NV, G, C>;
/** specify that the expression must occur at least `N` times */
atLeast: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${N},}`, `${V}{${N},}`>>(number: N) => Input<NV, G, C>;
/** specify that the expression must occur at most `N` times */
atMost: <N extends number, NV extends string = IfUnwrapped<V, `(?:${V}){0,${N}}`, `${V}{0,${N}}`>>(number: N) => Input<NV, G, C>;
/** specify a range of times to repeat the previous pattern */
between: <Min extends number, Max extends number, NV extends string = IfUnwrapped<V, `(?:${V}){${Min},${Max}}`, `${V}{${Min},${Max}}`>>(min: Min, max: Max) => Input<NV, G, C>;
};
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()`. Alias for `groupedAs` */
as: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this defines the entire input so far as a named capture group. You will get type safety when using the resulting RegExp with `String.match()` */
groupedAs: <K extends string>(key: K) => Input<V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`, G | K, [
V extends `(?:${infer S})` ? `(?<${K}>${S})` : `(?<${K}>${V})`,
...C
]>;
/** this capture the entire input so far as an anonymous group */
grouped: () => Input<V extends `(?:${infer S})${infer E}` ? `(${S})${E}` : `(${V})`, G, [
V extends `(?:${infer S})${'' | '?' | '+' | '*' | `{${string}}`}` ? `(${S})` : `(${V})`,
...C
]>;
/** this allows you to match beginning/ends of lines with `at.lineStart()` and `at.lineEnd()` */
at: {
lineStart: () => Input<`^${V}`, G, C>;
lineEnd: () => Input<`${V}$`, G, C>;
};
/** this allows you to mark the input so far as optional */
optionally: <NV extends string = IfUnwrapped<V, `(?:${V})?`, `${V}?`>>() => Input<NV, G, C>;
toString: () => string;
}
interface CharInput<T extends string> extends Input<`[${T}]`> {
orChar: (<Or extends string>(chars: Or) => CharInput<`${T}${EscapeChar<Or>}`>) & CharInput<T>;
from: <From extends string, To extends string>(charFrom: From, charTo: To) => CharInput<`${T}${EscapeChar<From>}-${EscapeChar<To>}`>;
}
type InputSource<S extends string = string, T extends string = never> = S | Input<any, T>;
type MapToValues<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends InputSource ? [GetValue<First>, ...MapToValues<Rest>] : [] : [];
type MapToGroups<T extends InputSource[]> = T extends [
infer First,
...infer Rest extends InputSource[]
] ? First extends Input<any, infer K> ? K | MapToGroups<Rest> : MapToGroups<Rest> : never;
type MapToCapturedGroupsArr<Inputs extends any[], MapToUndefined extends boolean = false, CapturedGroupsArr extends any[] = [], Count extends any[] = []> = Count['length'] extends Inputs['length'] ? CapturedGroupsArr : Inputs[Count['length']] extends Input<any, any, infer CaptureGroups> ? [CaptureGroups] extends [never] ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']> : MapToUndefined extends true ? MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
undefined
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [
...CapturedGroupsArr,
...CaptureGroups
], [
...Count,
''
]> : MapToCapturedGroupsArr<Inputs, MapToUndefined, [...CapturedGroupsArr], [...Count, '']>;
export { maybe as A, exactly as B, oneOrMore as C, type MapToStringCapturedBy as D, type Flag as F, type InputSource as I, type Join as J, type MagicRegExp as M, type StringCapturedBy as S, type UnionToTuple as U, type MagicRegExpMatchArray as a, type MapToValues as b, type MapToGroups as c, type MapToCapturedGroupsArr as d, caseInsensitive as e, dotAll as f, global as g, type Input as h, charIn as i, charNotIn as j, anyOf as k, char as l, multiline as m, word as n, wordChar as o, wordBoundary as p, digit as q, whitespace as r, sticky as s, letter as t, unicode as u, tab as v, withIndices as w, linefeed as x, carriageReturn as y, not as z };

View file

@ -0,0 +1,104 @@
const NO_WRAP_RE = /^(?:\(.*\)|\\?.)$/;
function wrap(s) {
const v = s.toString();
return NO_WRAP_RE.test(v) ? v : `(?:${v})`;
}
const GROUPED_AS_REPLACE_RE = /^(?:\(\?:(.+)\)|(.+))$/;
const GROUPED_REPLACE_RE = /^(?:\(\?:(.+)\)([?+*]|\{[\d,]+\})?|(.+))$/;
function createInput(s) {
const groupedAsFn = (key) => createInput(`(?<${key}>${`${s}`.replace(GROUPED_AS_REPLACE_RE, "$1$2")})`);
return {
toString: () => s.toString(),
and: Object.assign((...inputs) => createInput(`${s}${exactly(...inputs)}`), {
referenceTo: (groupName) => createInput(`${s}\\k<${groupName}>`)
}),
or: (...inputs) => createInput(`(?:${s}|${inputs.map((v) => exactly(v)).join("|")})`),
after: (...input) => createInput(`(?<=${exactly(...input)})${s}`),
before: (...input) => createInput(`${s}(?=${exactly(...input)})`),
notAfter: (...input) => createInput(`(?<!${exactly(...input)})${s}`),
notBefore: (...input) => createInput(`${s}(?!${exactly(...input)})`),
times: Object.assign((number) => createInput(`${wrap(s)}{${number}}`), {
any: () => createInput(`${wrap(s)}*`),
atLeast: (min) => createInput(`${wrap(s)}{${min},}`),
atMost: (max) => createInput(`${wrap(s)}{0,${max}}`),
between: (min, max) => createInput(`${wrap(s)}{${min},${max}}`)
}),
optionally: () => createInput(`${wrap(s)}?`),
as: groupedAsFn,
groupedAs: groupedAsFn,
grouped: () => createInput(`${s}`.replace(GROUPED_REPLACE_RE, "($1$3)$2")),
at: {
lineStart: () => createInput(`^${s}`),
lineEnd: () => createInput(`${s}$`)
}
};
}
const ESCAPE_REPLACE_RE = /[.*+?^${}()|[\]\\/]/g;
function createCharInput(raw) {
const input = createInput(`[${raw}]`);
const from = (charFrom, charTo) => createCharInput(`${raw}${escapeCharInput(charFrom)}-${escapeCharInput(charTo)}`);
const orChar = Object.assign((chars) => createCharInput(`${raw}${escapeCharInput(chars)}`), { from });
return Object.assign(input, { orChar, from });
}
function escapeCharInput(raw) {
return raw.replace(/[-\\^\]]/g, "\\$&");
}
const charIn = Object.assign((chars) => {
return createCharInput(escapeCharInput(chars));
}, createCharInput(""));
const charNotIn = Object.assign((chars) => {
return createCharInput(`^${escapeCharInput(chars)}`);
}, createCharInput("^"));
function anyOf(...inputs) {
return createInput(`(?:${inputs.map((a) => exactly(a)).join("|")})`);
}
const char = createInput(".");
const word = createInput("\\b\\w+\\b");
const wordChar = createInput("\\w");
const wordBoundary = createInput("\\b");
const digit = createInput("\\d");
const whitespace = createInput("\\s");
const letter = Object.assign(createInput("[a-zA-Z]"), {
lowercase: createInput("[a-z]"),
uppercase: createInput("[A-Z]")
});
const tab = createInput("\\t");
const linefeed = createInput("\\n");
const carriageReturn = createInput("\\r");
const not = {
word: createInput("\\W+"),
wordChar: createInput("\\W"),
wordBoundary: createInput("\\B"),
digit: createInput("\\D"),
whitespace: createInput("\\S"),
letter: Object.assign(createInput("[^a-zA-Z]"), {
lowercase: createInput("[^a-z]"),
uppercase: createInput("[^A-Z]")
}),
tab: createInput("[^\\t]"),
linefeed: createInput("[^\\n]"),
carriageReturn: createInput("[^\\r]")
};
function maybe(...inputs) {
return createInput(`${wrap(exactly(...inputs))}?`);
}
function exactly(...inputs) {
return createInput(
inputs.map((input) => typeof input === "string" ? input.replace(ESCAPE_REPLACE_RE, "\\$&") : input).join("")
);
}
function oneOrMore(...inputs) {
return createInput(`${wrap(exactly(...inputs))}+`);
}
const withIndices = "d";
const caseInsensitive = "i";
const global = "g";
const multiline = "m";
const dotAll = "s";
const unicode = "u";
const sticky = "y";
export { charIn as a, charNotIn as b, caseInsensitive as c, dotAll as d, exactly as e, anyOf as f, global as g, char as h, word as i, wordChar as j, wordBoundary as k, digit as l, multiline as m, whitespace as n, letter as o, linefeed as p, carriageReturn as q, not as r, sticky as s, tab as t, unicode as u, maybe as v, withIndices as w, oneOrMore as x };

View file

@ -0,0 +1,129 @@
'use strict';
const NO_WRAP_RE = /^(?:\(.*\)|\\?.)$/;
function wrap(s) {
const v = s.toString();
return NO_WRAP_RE.test(v) ? v : `(?:${v})`;
}
const GROUPED_AS_REPLACE_RE = /^(?:\(\?:(.+)\)|(.+))$/;
const GROUPED_REPLACE_RE = /^(?:\(\?:(.+)\)([?+*]|\{[\d,]+\})?|(.+))$/;
function createInput(s) {
const groupedAsFn = (key) => createInput(`(?<${key}>${`${s}`.replace(GROUPED_AS_REPLACE_RE, "$1$2")})`);
return {
toString: () => s.toString(),
and: Object.assign((...inputs) => createInput(`${s}${exactly(...inputs)}`), {
referenceTo: (groupName) => createInput(`${s}\\k<${groupName}>`)
}),
or: (...inputs) => createInput(`(?:${s}|${inputs.map((v) => exactly(v)).join("|")})`),
after: (...input) => createInput(`(?<=${exactly(...input)})${s}`),
before: (...input) => createInput(`${s}(?=${exactly(...input)})`),
notAfter: (...input) => createInput(`(?<!${exactly(...input)})${s}`),
notBefore: (...input) => createInput(`${s}(?!${exactly(...input)})`),
times: Object.assign((number) => createInput(`${wrap(s)}{${number}}`), {
any: () => createInput(`${wrap(s)}*`),
atLeast: (min) => createInput(`${wrap(s)}{${min},}`),
atMost: (max) => createInput(`${wrap(s)}{0,${max}}`),
between: (min, max) => createInput(`${wrap(s)}{${min},${max}}`)
}),
optionally: () => createInput(`${wrap(s)}?`),
as: groupedAsFn,
groupedAs: groupedAsFn,
grouped: () => createInput(`${s}`.replace(GROUPED_REPLACE_RE, "($1$3)$2")),
at: {
lineStart: () => createInput(`^${s}`),
lineEnd: () => createInput(`${s}$`)
}
};
}
const ESCAPE_REPLACE_RE = /[.*+?^${}()|[\]\\/]/g;
function createCharInput(raw) {
const input = createInput(`[${raw}]`);
const from = (charFrom, charTo) => createCharInput(`${raw}${escapeCharInput(charFrom)}-${escapeCharInput(charTo)}`);
const orChar = Object.assign((chars) => createCharInput(`${raw}${escapeCharInput(chars)}`), { from });
return Object.assign(input, { orChar, from });
}
function escapeCharInput(raw) {
return raw.replace(/[-\\^\]]/g, "\\$&");
}
const charIn = Object.assign((chars) => {
return createCharInput(escapeCharInput(chars));
}, createCharInput(""));
const charNotIn = Object.assign((chars) => {
return createCharInput(`^${escapeCharInput(chars)}`);
}, createCharInput("^"));
function anyOf(...inputs) {
return createInput(`(?:${inputs.map((a) => exactly(a)).join("|")})`);
}
const char = createInput(".");
const word = createInput("\\b\\w+\\b");
const wordChar = createInput("\\w");
const wordBoundary = createInput("\\b");
const digit = createInput("\\d");
const whitespace = createInput("\\s");
const letter = Object.assign(createInput("[a-zA-Z]"), {
lowercase: createInput("[a-z]"),
uppercase: createInput("[A-Z]")
});
const tab = createInput("\\t");
const linefeed = createInput("\\n");
const carriageReturn = createInput("\\r");
const not = {
word: createInput("\\W+"),
wordChar: createInput("\\W"),
wordBoundary: createInput("\\B"),
digit: createInput("\\D"),
whitespace: createInput("\\S"),
letter: Object.assign(createInput("[^a-zA-Z]"), {
lowercase: createInput("[^a-z]"),
uppercase: createInput("[^A-Z]")
}),
tab: createInput("[^\\t]"),
linefeed: createInput("[^\\n]"),
carriageReturn: createInput("[^\\r]")
};
function maybe(...inputs) {
return createInput(`${wrap(exactly(...inputs))}?`);
}
function exactly(...inputs) {
return createInput(
inputs.map((input) => typeof input === "string" ? input.replace(ESCAPE_REPLACE_RE, "\\$&") : input).join("")
);
}
function oneOrMore(...inputs) {
return createInput(`${wrap(exactly(...inputs))}+`);
}
const withIndices = "d";
const caseInsensitive = "i";
const global = "g";
const multiline = "m";
const dotAll = "s";
const unicode = "u";
const sticky = "y";
exports.anyOf = anyOf;
exports.carriageReturn = carriageReturn;
exports.caseInsensitive = caseInsensitive;
exports.char = char;
exports.charIn = charIn;
exports.charNotIn = charNotIn;
exports.digit = digit;
exports.dotAll = dotAll;
exports.exactly = exactly;
exports.global = global;
exports.letter = letter;
exports.linefeed = linefeed;
exports.maybe = maybe;
exports.multiline = multiline;
exports.not = not;
exports.oneOrMore = oneOrMore;
exports.sticky = sticky;
exports.tab = tab;
exports.unicode = unicode;
exports.whitespace = whitespace;
exports.withIndices = withIndices;
exports.word = word;
exports.wordBoundary = wordBoundary;
exports.wordChar = wordChar;

View file

@ -0,0 +1,96 @@
'use strict';
const node_url = require('node:url');
const node_vm = require('node:vm');
const estreeWalker = require('estree-walker');
const magicRegExp = require('magic-regexp');
const MagicString = require('magic-string');
const mlly = require('mlly');
const ufo = require('ufo');
const unplugin = require('unplugin');
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
function _interopNamespaceCompat(e) {
if (e && typeof e === 'object' && 'default' in e) return e;
const n = Object.create(null);
if (e) {
for (const k in e) {
n[k] = e[k];
}
}
n.default = e;
return n;
}
const magicRegExp__namespace = /*#__PURE__*/_interopNamespaceCompat(magicRegExp);
const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
const MagicRegExpTransformPlugin = unplugin.createUnplugin(() => {
return {
name: "MagicRegExpTransformPlugin",
enforce: "post",
transformInclude(id) {
const { pathname, search } = ufo.parseURL(decodeURIComponent(node_url.pathToFileURL(id).href));
const { type } = ufo.parseQuery(search);
if (pathname.endsWith(".vue") && (type === "script" || !search))
return true;
if (pathname.match(/\.((c|m)?j|t)sx?$/g))
return true;
return false;
},
transform(code, id) {
if (!code.includes("magic-regexp"))
return;
const statements = mlly.findStaticImports(code).filter(
(i) => i.specifier === "magic-regexp" || i.specifier === "magic-regexp/further-magic"
);
if (!statements.length)
return;
const contextMap = { ...magicRegExp__namespace };
const wrapperNames = [];
let namespace;
for (const i of statements.flatMap((i2) => mlly.parseStaticImport(i2))) {
if (i.namespacedImport) {
namespace = i.namespacedImport;
contextMap[i.namespacedImport] = magicRegExp__namespace;
}
if (i.namedImports) {
for (const key in i.namedImports)
contextMap[i.namedImports[key]] = magicRegExp__namespace[key];
if (i.namedImports.createRegExp)
wrapperNames.push(i.namedImports.createRegExp);
}
}
const context = node_vm.createContext(contextMap);
const s = new MagicString__default(code);
estreeWalker.walk(this.parse(code), {
enter(_node) {
if (_node.type !== "CallExpression")
return;
const node = _node;
if (
// Normal call
!wrapperNames.includes(node.callee.name) && (node.callee.type !== "MemberExpression" || node.callee.object.type !== "Identifier" || node.callee.object.name !== namespace || node.callee.property.type !== "Identifier" || node.callee.property.name !== "createRegExp")
) {
return;
}
const { start, end } = node;
try {
const value = node_vm.runInContext(code.slice(start, end), context);
s.overwrite(start, end, value.toString());
} catch {
}
}
});
if (s.hasChanged()) {
return {
code: s.toString(),
map: s.generateMap({ includeContent: true, source: id })
};
}
}
};
});
exports.MagicRegExpTransformPlugin = MagicRegExpTransformPlugin;

View file

@ -0,0 +1,5 @@
import * as unplugin from 'unplugin';
declare const MagicRegExpTransformPlugin: unplugin.UnpluginInstance<unknown, boolean>;
export { MagicRegExpTransformPlugin };

View file

@ -0,0 +1,5 @@
import * as unplugin from 'unplugin';
declare const MagicRegExpTransformPlugin: unplugin.UnpluginInstance<unknown, boolean>;
export { MagicRegExpTransformPlugin };

View file

@ -0,0 +1,5 @@
import * as unplugin from 'unplugin';
declare const MagicRegExpTransformPlugin: unplugin.UnpluginInstance<unknown, boolean>;
export { MagicRegExpTransformPlugin };

View file

@ -0,0 +1,77 @@
import { pathToFileURL } from 'node:url';
import { createContext, runInContext } from 'node:vm';
import { walk } from 'estree-walker';
import * as magicRegExp from 'magic-regexp';
import MagicString from 'magic-string';
import { findStaticImports, parseStaticImport } from 'mlly';
import { parseURL, parseQuery } from 'ufo';
import { createUnplugin } from 'unplugin';
const MagicRegExpTransformPlugin = createUnplugin(() => {
return {
name: "MagicRegExpTransformPlugin",
enforce: "post",
transformInclude(id) {
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
const { type } = parseQuery(search);
if (pathname.endsWith(".vue") && (type === "script" || !search))
return true;
if (pathname.match(/\.((c|m)?j|t)sx?$/g))
return true;
return false;
},
transform(code, id) {
if (!code.includes("magic-regexp"))
return;
const statements = findStaticImports(code).filter(
(i) => i.specifier === "magic-regexp" || i.specifier === "magic-regexp/further-magic"
);
if (!statements.length)
return;
const contextMap = { ...magicRegExp };
const wrapperNames = [];
let namespace;
for (const i of statements.flatMap((i2) => parseStaticImport(i2))) {
if (i.namespacedImport) {
namespace = i.namespacedImport;
contextMap[i.namespacedImport] = magicRegExp;
}
if (i.namedImports) {
for (const key in i.namedImports)
contextMap[i.namedImports[key]] = magicRegExp[key];
if (i.namedImports.createRegExp)
wrapperNames.push(i.namedImports.createRegExp);
}
}
const context = createContext(contextMap);
const s = new MagicString(code);
walk(this.parse(code), {
enter(_node) {
if (_node.type !== "CallExpression")
return;
const node = _node;
if (
// Normal call
!wrapperNames.includes(node.callee.name) && (node.callee.type !== "MemberExpression" || node.callee.object.type !== "Identifier" || node.callee.object.name !== namespace || node.callee.property.type !== "Identifier" || node.callee.property.name !== "createRegExp")
) {
return;
}
const { start, end } = node;
try {
const value = runInContext(code.slice(start, end), context);
s.overwrite(start, end, value.toString());
} catch {
}
}
});
if (s.hasChanged()) {
return {
code: s.toString(),
map: s.generateMap({ includeContent: true, source: id })
};
}
}
};
});
export { MagicRegExpTransformPlugin };

View file

@ -0,0 +1,3 @@
// Legacy stub for previous TS versions
export * from './dist/further-magic'

View file

@ -0,0 +1,7 @@
Copyright (c) 2015-20 [these people](https://github.com/Rich-Harris/estree-walker/graphs/contributors)
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.

View file

@ -0,0 +1,48 @@
# estree-walker
Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn).
## Installation
```bash
npm i estree-walker
```
## Usage
```js
var walk = require('estree-walker').walk;
var acorn = require('acorn');
ast = acorn.parse(sourceCode, options); // https://github.com/acornjs/acorn
walk(ast, {
enter(node, parent, prop, index) {
// some code happens
},
leave(node, parent, prop, index) {
// some code happens
}
});
```
Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called.
Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one.
Call `this.remove()` in either `enter` or `leave` to remove the current node.
## Why not use estraverse?
The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys.
estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.)
None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful.
## License
MIT

View file

@ -0,0 +1,38 @@
{
"name": "estree-walker",
"description": "Traverse an ESTree-compliant AST",
"version": "3.0.3",
"private": false,
"author": "Rich Harris",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Rich-Harris/estree-walker"
},
"type": "module",
"module": "./src/index.js",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./types/index.d.ts",
"import": "./src/index.js"
}
},
"types": "types/index.d.ts",
"scripts": {
"prepublishOnly": "tsc && npm test",
"test": "uvu test"
},
"dependencies": {
"@types/estree": "^1.0.0"
},
"devDependencies": {
"typescript": "^4.9.0",
"uvu": "^0.5.1"
},
"files": [
"src",
"types",
"README.md"
]
}

View file

@ -0,0 +1,152 @@
import { WalkerBase } from './walker.js';
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => Promise<void>} AsyncHandler
*/
export class AsyncWalker extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {AsyncHandler | undefined} */
this.enter = enter;
/** @type {AsyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
async visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
await this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!(await this.visit(item, node, key, i))) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
await this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
await this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}

View file

@ -0,0 +1,34 @@
import { SyncWalker } from './sync.js';
import { AsyncWalker } from './async.js';
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
export function walk(ast, { enter, leave }) {
const instance = new SyncWalker(enter, leave);
return instance.visit(ast, null);
}
/**
* @param {Node} ast
* @param {{
* enter?: AsyncHandler
* leave?: AsyncHandler
* }} walker
* @returns {Promise<Node | null>}
*/
export async function asyncWalk(ast, { enter, leave }) {
const instance = new AsyncWalker(enter, leave);
return await instance.visit(ast, null);
}

View file

@ -0,0 +1,152 @@
import { WalkerBase } from './walker.js';
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
export class SyncWalker extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {SyncHandler | undefined} */
this.enter = enter;
/** @type {SyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}

View file

@ -0,0 +1,61 @@
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
export class WalkerBase {
constructor() {
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) {
if (index != null) {
/** @type {Array<Node>} */ (parent[prop])[index] = node;
} else {
/** @type {Node} */ (parent[prop]) = node;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== undefined) {
/** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
} else {
delete parent[prop];
}
}
}
}

View file

@ -0,0 +1,36 @@
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => Promise<void>} AsyncHandler
*/
export class AsyncWalker extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter?: AsyncHandler | undefined, leave?: AsyncHandler | undefined);
/** @type {AsyncHandler | undefined} */
enter: AsyncHandler | undefined;
/** @type {AsyncHandler | undefined} */
leave: AsyncHandler | undefined;
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
visit<Parent extends import("estree").Node>(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Promise<Node | null>;
}
export type Node = import('estree').Node;
export type WalkerContext = import('./walker.js').WalkerContext;
export type AsyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => Promise<void>;
import { WalkerBase } from "./walker.js";

View file

@ -0,0 +1,32 @@
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
* enter?: SyncHandler
* leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
export function walk(ast: Node, { enter, leave }: {
enter?: SyncHandler;
leave?: SyncHandler;
}): Node | null;
/**
* @param {Node} ast
* @param {{
* enter?: AsyncHandler
* leave?: AsyncHandler
* }} walker
* @returns {Promise<Node | null>}
*/
export function asyncWalk(ast: Node, { enter, leave }: {
enter?: AsyncHandler;
leave?: AsyncHandler;
}): Promise<Node | null>;
export type Node = import('estree').Node;
export type SyncHandler = import('./sync.js').SyncHandler;
export type AsyncHandler = import('./async.js').AsyncHandler;

View file

@ -0,0 +1,36 @@
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => void} SyncHandler
*/
export class SyncWalker extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter?: SyncHandler | undefined, leave?: SyncHandler | undefined);
/** @type {SyncHandler | undefined} */
enter: SyncHandler | undefined;
/** @type {SyncHandler | undefined} */
leave: SyncHandler | undefined;
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit<Parent extends import("estree").Node>(node: Node, parent: Parent | null, prop?: keyof Parent | undefined, index?: number | null | undefined): Node | null;
}
export type Node = import('estree').Node;
export type WalkerContext = import('./walker.js').WalkerContext;
export type SyncHandler = (this: WalkerContext, node: Node, parent: Node | null, key: string | number | symbol | null | undefined, index: number | null | undefined) => void;
import { WalkerBase } from "./walker.js";

View file

@ -0,0 +1,39 @@
/**
* @typedef { import('estree').Node} Node
* @typedef {{
* skip: () => void;
* remove: () => void;
* replace: (node: Node) => void;
* }} WalkerContext
*/
export class WalkerBase {
/** @type {boolean} */
should_skip: boolean;
/** @type {boolean} */
should_remove: boolean;
/** @type {Node | null} */
replacement: Node | null;
/** @type {WalkerContext} */
context: WalkerContext;
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace<Parent extends import("estree").Node>(parent: Parent | null | undefined, prop: keyof Parent | null | undefined, index: number | null | undefined, node: Node): void;
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove<Parent_1 extends import("estree").Node>(parent: Parent_1 | null | undefined, prop: keyof Parent_1 | null | undefined, index: number | null | undefined): void;
}
export type Node = import('estree').Node;
export type WalkerContext = {
skip: () => void;
remove: () => void;
replace: (node: Node) => void;
};

19
Frontend-Learner/node_modules/magic-regexp/nuxt.mjs generated vendored Normal file
View file

@ -0,0 +1,19 @@
import { addImportsSources, addVitePlugin, addWebpackPlugin, defineNuxtModule } from '@nuxt/kit'
import * as magicRegexp from 'magic-regexp'
import { MagicRegExpTransformPlugin } from 'magic-regexp/transform'
export default defineNuxtModule({
setup(_options, nuxt) {
addImportsSources({
from: 'magic-regexp',
imports: Object.keys(magicRegexp),
})
// Disable RegExp code transformation in development mode
if (nuxt.options.dev)
return
addWebpackPlugin(MagicRegExpTransformPlugin.webpack())
addVitePlugin(MagicRegExpTransformPlugin.vite())
},
})

View file

@ -0,0 +1,93 @@
{
"name": "magic-regexp",
"version": "0.10.0",
"packageManager": "pnpm@10.9.0",
"description": "A compiled-away, type-safe, readable RegExp alternative",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/unjs/magic-regexp.git"
},
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./converter": {
"import": "./dist/converter.mjs",
"require": "./dist/converter.cjs"
},
"./transform": {
"import": "./dist/transform.mjs",
"require": "./dist/transform.cjs"
},
"./further-magic": {
"import": "./dist/further-magic.mjs",
"require": "./dist/further-magic.cjs"
},
"./nuxt": "./nuxt.mjs"
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist",
"further-magic.d.ts",
"nuxt.mjs",
"transform.d.ts"
],
"scripts": {
"build": "unbuild",
"dev": "vitest dev",
"docs:generate": "nuxi generate docs",
"lint": "eslint .",
"prepare": "npx simple-git-hooks && pnpm build",
"prepublishOnly": "pnpm lint && pnpm test",
"release": "bumpp && npm publish",
"test": "vitest run",
"test:types": "tsc --noEmit"
},
"dependencies": {
"estree-walker": "^3.0.3",
"magic-string": "^0.30.12",
"mlly": "^1.7.2",
"regexp-tree": "^0.1.27",
"type-level-regexp": "~0.1.17",
"ufo": "^1.5.4",
"unplugin": "^2.0.0"
},
"devDependencies": {
"@antfu/eslint-config": "4.12.0",
"@codspeed/vitest-plugin": "4.0.1",
"@nuxt/kit": "3.16.2",
"@types/estree": "1.0.7",
"@types/node": "22.14.1",
"@vitest/coverage-v8": "3.1.2",
"acorn": "8.14.1",
"bumpp": "10.1.0",
"eslint": "9.25.0",
"expect-type": "1.2.1",
"lint-staged": "latest",
"rollup": "4.40.0",
"simple-git-hooks": "2.12.1",
"typescript": "5.8.3",
"unbuild": "3.5.0",
"vite": "6.3.2",
"vitest": "3.1.2"
},
"resolutions": {
"magic-regexp": "link:.",
"nuxt": "3.16.2",
"vite": "6.3.2",
"vue": "3.5.13"
},
"simple-git-hooks": {
"pre-commit": "npx lint-staged"
},
"lint-staged": {
"*": [
"npx eslint --fix"
]
}
}

View file

@ -0,0 +1,3 @@
// Legacy stub for previous TS versions
export * from './dist/transform'