arkregex 0.0.15 → 0.0.16-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,8 +12,8 @@ import { regex } from "arkregex"
12
12
  const ok = regex("^ok$", "i")
13
13
  // Regex<"ok" | "oK" | "Ok" | "OK", { flags: "i" }>
14
14
 
15
- const semver = regex("^(\\d*)\\.(\\d*)\\.(\\d*)$")
16
- // Regex<`${number}.${number}.${number}`, { captures: [`${number}`, `${number}`, `${number}`] }>
15
+ const date = regex("^(\\d{4})-(\\d{2})-(\\d{2})$")
16
+ // Regex<`${number}-${number}-${number}`, { captures: [`${number}`, `${number}`, `${number}`] }>
17
17
 
18
18
  const email = regex("^(?<name>\\w+)@(?<domain>\\w+\\.\\w+)$")
19
19
  // Regex<`${string}@${string}.${string}`, { names: { name: string; domain: `${string}.${string}`; }; ...>
@@ -26,36 +26,16 @@ Performs best with TS 5.9+
26
26
  ### Features
27
27
 
28
28
  - **Types**: Infers string types for your existing regular expressions, including positional and named captures
29
- - **Parity**: Supports 100% of [features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions) allowed by `new RegExp()`
29
+ - **Syntax**: Parses the [syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions) `new RegExp()` accepts, including named groups, lookarounds, backreferences, modifiers and Unicode properties
30
30
  - **Safety**: Syntax errors like referencing a group that doesn't exist are now type errors
31
31
  - **Zero Runtime**: Improves your type safety without impacting your bundle size
32
32
 
33
- ### FAQ
33
+ ## Docs
34
34
 
35
- #### Why aren't some patterns like `[a-Z]` inferred more precisely?
35
+ See [arktype.io/docs/regex](https://arktype.io/docs/regex) for:
36
36
 
37
- Constructing string literal types for these sorts of expressions is combinatorial and will explode very quickly if we infer character ranges like this as literal characters.
38
-
39
- We've tried to strike a balance between performance and precision while guaranteeing that the inferred types are at worst imprecise and never incorrect.
40
-
41
- #### Why doesn't it work with my massive RegExp?
42
-
43
- If your expression is especially long or complex, TypeScript won't be able to infer it.
44
-
45
- If your types start to slow down or you see the dreaded `Type is excessively deep...`, you can manually type your expression using `regex.as`:
46
-
47
- ```ts
48
- const complexPattern = regex.as<`pattern-${string}`, { captures: [string] }>(
49
- "very-long-complex-expression-here"
50
- )
51
- ```
52
-
53
- #### Is it robust?
54
-
55
- `arkregex` types are [extensively tested](https://github.com/arktypeio/arktype/tree/main/ark/regex/__tests__/regex.test.ts) and [benchmarked](https://github.com/arktypeio/arktype/tree/main/ark/regex/__tests__/regex.bench.ts) using [attest](https://github.com/arktypeio/arktype/tree/main/ark/attest#readme).
56
-
57
- If anything not covered by the other FAQs is not behaving how you'd expect, please don't hesitate to [create an issue](https://github.com/arktypeio/arktype/issues/new).
58
-
59
- #### How can I get syntax highlighting for `regex`?
60
-
61
- The [ArkType extension](https://marketplace.visualstudio.com/items?itemName=arktypeio.arkdark) can be installed to add syntax highlighting to `regex` calls.
37
+ - [Inference](https://arktype.io/docs/regex/inference) of patterns, captures and flags
38
+ - [Errors](https://arktype.io/docs/regex/errors) reported for invalid syntax
39
+ - [Types](https://arktype.io/docs/regex/types) like `Regex`, `regex.infer` and `regex.as`
40
+ - [ArkType](https://arktype.io/docs/regex/arktype) integration
41
+ - [FAQ](https://arktype.io/docs/regex/faq)
package/out/charset.d.ts CHANGED
@@ -1,15 +1,24 @@
1
- import type { Backslash, ErrorMessage, noSuggest, Scanner, writeUnclosedGroupMessage } from "@ark/util";
2
- import type { parseEscapedChar, StringDigit } from "./escape.ts";
3
- import type { s, State } from "./state.ts";
4
- export type parseCharset<s extends State, unscanned extends string> = Scanner.shiftUntilEscapable<unscanned, "]", Backslash> extends (Scanner.shiftResult<infer scanned, infer nextUnscanned>) ? nextUnscanned extends `]${infer remaining}` ? scanned extends Scanner.shift<"^", string> ? s.shiftQuantifiable<s, string, remaining> : parseNonNegatedCharset<scanned, never, null> extends (infer result extends string) ? [
1
+ import type { Backslash, contains, ErrorMessage, noSuggest, Scanner, writeUnclosedGroupMessage } from "@ark/util";
2
+ import type { NonZeroDigit, RegexClassChar, StringDigit, writeUnnecessaryEscapeMessage } from "./escape.ts";
3
+ import type { UnicodeFlag } from "./regex.ts";
4
+ import type { Control, s, State } from "./state.ts";
5
+ export type parseCharset<s extends State, unscanned extends string> = Scanner.shiftUntilEscapable<unscanned, "]", Backslash> extends (Scanner.shiftResult<infer scanned, infer nextUnscanned>) ? nextUnscanned extends `]${infer remaining}` ? scanned extends Scanner.shift<"^", string> ? s.shiftQuantifiable<s, string, remaining> : parseNonNegatedCharset<scanned, never, null, contains<s["flags"], UnicodeFlag>> extends infer result extends string ? [
5
6
  result
6
- ] extends [never] ? s.error<emptyCharacterSetMessage> : s.shiftQuantifiable<s, result, remaining> : never : s.error<writeUnclosedGroupMessage<"]">> : never;
7
- type parseNonNegatedCharset<chars extends string, set extends string, lastChar extends string | null> = parseChar<chars> extends Scanner.shiftResult<infer result, infer unscanned> ? result extends UnescapedDashMarker ? parseDash<unscanned, set, lastChar> : result extends ErrorMessage ? result : parseNonNegatedCharset<unscanned, set | result, result> : set;
8
- type parseDash<unscanned extends string, set extends string, lastChar extends string | null> = lastChar extends string ? parseChar<unscanned> extends (Scanner.shiftResult<infer rangeEnd, infer next>) ? parseNonNegatedCharset<next, set | inferRange<lastChar, rangeEnd>, null> : // trailing -, treat as literal
9
- set | "-" : parseNonNegatedCharset<unscanned, set | "-", "-">;
7
+ ] extends [never] ? s.error<emptyCharacterSetMessage> : result extends ErrorMessage ? s.error<result> : s.shiftQuantifiable<s, result, remaining> : never : s.error<writeUnclosedGroupMessage<"]">> : never;
8
+ type parseNonNegatedCharset<chars extends string, set extends string, lastChar extends string | null, unicode extends boolean> = parseChar<chars, unicode> extends (Scanner.shiftResult<infer result, infer unscanned>) ? result extends UnescapedDashMarker ? parseDash<unscanned, set, lastChar, unicode> : result extends ErrorMessage ? result : parseNonNegatedCharset<unscanned, set | result, result, unicode> : set;
9
+ type parseDash<unscanned extends string, set extends string, lastChar extends string | null, unicode extends boolean> = lastChar extends string ? parseChar<unscanned, unicode> extends (Scanner.shiftResult<infer rangeEnd, infer next>) ? rangeEnd extends ErrorMessage ? rangeEnd : parseNonNegatedCharset<next, set | inferRange<lastChar, rangeEnd>, null, unicode> : // trailing -, treat as literal
10
+ set | "-" : parseNonNegatedCharset<unscanned, set | "-", "-", unicode>;
10
11
  type inferRange<start extends string, end extends string> = start | end extends StringDigit ? `${number}` : string;
11
12
  type UnescapedDashMarker = noSuggest<"dash">;
12
- type parseChar<unscanned extends string> = unscanned extends Scanner.shift<infer lookahead, infer next> ? lookahead extends Backslash ? next extends Scanner.shift<infer escaped, infer postEscaped> ? Scanner.shiftResult<parseEscapedChar<escaped>, postEscaped> : never : Scanner.shiftResult<lookahead extends "-" ? UnescapedDashMarker : lookahead, next> : null;
13
+ type parseChar<unscanned extends string, unicode extends boolean> = unscanned extends Scanner.shift<infer lookahead, infer next> ? lookahead extends Backslash ? next extends Scanner.shift<infer escaped, infer postEscaped> ? Scanner.shiftResult<parseEscapedSetChar<escaped, unicode>, postEscaped> : never : Scanner.shiftResult<lookahead extends "-" ? UnescapedDashMarker : lookahead, next> : null;
14
+ type parseEscapedSetChar<char extends string, unicode extends boolean> = char extends "b" ? "\b" : char extends "d" ? `${number}` : char extends keyof EscapedControlChars ? EscapedControlChars[char] : char extends "0" | "c" | "x" | "u" | "p" | "P" | "s" | RegexClassChar ? string : unicode extends true ? char extends Control | "/" ? char : ErrorMessage<writeUnnecessaryEscapeMessage<char>> : char extends NonZeroDigit ? string : char;
15
+ type EscapedControlChars = {
16
+ n: "\n";
17
+ t: "\t";
18
+ r: "\r";
19
+ f: "\f";
20
+ v: "\v";
21
+ };
13
22
  export declare const emptyCharacterSetMessage = "Empty character set [] is unsatisfiable";
14
23
  export type emptyCharacterSetMessage = typeof emptyCharacterSetMessage;
15
24
  export {};
@@ -0,0 +1,7 @@
1
+ // out/regex.js
2
+ var regex = ((src, flags) => new RegExp(src, flags));
3
+ Object.assign(regex, { as: regex });
4
+
5
+ export {
6
+ regex
7
+ };
package/out/escape.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import type { ErrorMessage, Scanner, WhitespaceChar } from "@ark/util";
1
+ import type { ErrorMessage, Scanner } from "@ark/util";
2
2
  import type { Control, ReferenceNode, s, State } from "./state.ts";
3
3
  export type parseEscape<s extends State, unscanned extends string> = unscanned extends Scanner.shift<infer char, infer nextUnscanned> ? char extends NonZeroDigit ? parseNumericBackreference<s, unscanned> : char extends "k" ? parseNamedBackreference<s, nextUnscanned> : char extends UnicodePropertyChar ? parseUnicodeProperty<s, char, nextUnscanned> : parseSingleEscapedCharacter<s, char, nextUnscanned> : s.error<trailingBackslashMessage>;
4
4
  type parseNumericBackreference<s extends State, fullUnscanned extends string> = Scanner.shiftUntilNot<fullUnscanned, StringDigit> extends (Scanner.shiftResult<infer ref, infer remaining>) ? s.shiftQuantifiable<s, ReferenceNode<ref>, remaining> : never;
5
5
  type parseNamedBackreference<s extends State, unscanned extends string> = unscanned extends `<${infer ref}>${infer following}` ? s.shiftQuantifiable<s, ReferenceNode<ref>, following> : s.error<missingBackreferenceNameMessage>;
6
6
  type parseUnicodeProperty<s extends State, char extends UnicodePropertyChar, unscanned extends string> = unscanned extends `{${string}}${infer following}` ? s.shiftQuantifiable<s, string, following> : s.error<writeInvalidUnicodePropertyMessage<char>>;
7
7
  type parseSingleEscapedCharacter<s extends State, char extends string, remaining extends string> = parseEscapedChar<char> extends infer result extends string ? result extends ErrorMessage ? s.error<result> : s.shiftQuantifiable<s, result, remaining> : never;
8
- export type parseEscapedChar<char extends string> = char extends RegexClassChar ? string : char extends "d" ? `${number}` : char extends "s" ? WhitespaceChar : char extends BoundaryChar ? "" : char extends Control ? char : char extends "c" ? ErrorMessage<caretNotationMessage> : char extends StringEscapableChar ? ErrorMessage<writeStringEscapableMessage<char>> : ErrorMessage<writeUnnecessaryEscapeMessage<char>>;
8
+ export type parseEscapedChar<char extends string> = char extends RegexClassChar | "s" ? string : char extends "d" ? `${number}` : char extends BoundaryChar ? "" : char extends Control ? char : char extends "c" ? ErrorMessage<caretNotationMessage> : char extends StringEscapableChar ? ErrorMessage<writeStringEscapableMessage<char>> : ErrorMessage<writeUnnecessaryEscapeMessage<char>>;
9
9
  export declare const trailingBackslashMessage = "A regex cannot end with \\";
10
10
  export type trailingBackslashMessage = typeof trailingBackslashMessage;
11
11
  export declare const writeUnresolvableBackreferenceMessage: <ref extends string | number>(ref: ref) => writeUnresolvableBackreferenceMessage<ref>;
package/out/group.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type { ErrorMessage, Scanner, writeUnclosedGroupMessage } from "@ark/util";
2
2
  import type { State, s } from "./state.ts";
3
3
  type LookaroundChar = "=" | "!";
4
+ type lookaroundKindOf<char extends LookaroundChar> = char extends "=" ? State.UnnamedCaptureKind.lookaround : State.UnnamedCaptureKind.negativeLookaround;
4
5
  export type ModifiableFlag = "i" | "m" | "s";
5
6
  export type parseGroup<s extends State, unscanned extends string> = unscanned extends Scanner.shift<infer lookahead, infer next> ? lookahead extends "?" ? parseNonCapturingGroup<s, next> : s.pushGroup<s, State.UnnamedCaptureKind.indexed, unscanned, undefined> : s.error<writeUnclosedGroupMessage<")">>;
6
- type parseNonCapturingGroup<s extends State, unscanned extends string> = unscanned extends Scanner.shift<infer lookahead, infer next> ? lookahead extends ":" ? s.pushGroup<s, State.UnnamedCaptureKind.noncapturing, next, undefined> : lookahead extends LookaroundChar ? s.pushGroup<s, State.UnnamedCaptureKind.lookaround, next, undefined> : lookahead extends "<" ? parseNamedGroupOrLookbehind<s, next> : shiftModifiers<unscanned> extends (ShiftedModifiers<infer flags, infer negated, infer following>) ? following extends ErrorMessage<infer message> ? s.error<message> : s.pushGroup<s, State.UnnamedCaptureKind.noncapturing, following, "i" extends flags ? true : "i" extends negated ? false : undefined> : never : s.error<writeUnclosedGroupMessage<")">>;
7
+ type parseNonCapturingGroup<s extends State, unscanned extends string> = unscanned extends Scanner.shift<infer lookahead, infer next> ? lookahead extends ":" ? s.pushGroup<s, State.UnnamedCaptureKind.noncapturing, next, undefined> : lookahead extends LookaroundChar ? s.pushGroup<s, lookaroundKindOf<lookahead>, next, undefined> : lookahead extends "<" ? parseNamedGroupOrLookbehind<s, next> : shiftModifiers<unscanned> extends (ShiftedModifiers<infer flags, infer negated, infer following>) ? following extends ErrorMessage<infer message> ? s.error<message> : s.pushGroup<s, State.UnnamedCaptureKind.noncapturing, following, "i" extends flags ? true : "i" extends negated ? false : undefined> : never : s.error<writeUnclosedGroupMessage<")">>;
7
8
  type ShiftedModifiers<flags extends ModifiableFlag = ModifiableFlag, negated extends ModifiableFlag = ModifiableFlag, unscanned extends string = string> = [ParsedModifiers<flags, negated>, unscanned];
8
9
  type ParsedModifiers<flags extends ModifiableFlag = ModifiableFlag, negated extends ModifiableFlag = ModifiableFlag> = {
9
10
  flags: flags;
@@ -24,7 +25,7 @@ export declare const missingNegatedModifierMessage = "- must be followed by the
24
25
  type missingNegatedModifierMessage = typeof missingNegatedModifierMessage;
25
26
  export declare const writeInvalidModifierMessage: <char extends string>(char: char) => writeInvalidModifierMessage<char>;
26
27
  type writeInvalidModifierMessage<char extends string> = `Modifier flag ${char} must be 'i', 'm' or 's'`;
27
- type parseNamedGroupOrLookbehind<s extends State, unscanned extends string> = unscanned extends Scanner.shift<LookaroundChar, infer next> ? s.pushGroup<s, State.UnnamedCaptureKind.lookaround, next, undefined> : shiftNamedGroup<unscanned> extends (Scanner.shiftResult<infer name, infer following>) ? s.pushGroup<s, name, following, undefined> : s.error<writeUnclosedGroupMessage<")">>;
28
+ type parseNamedGroupOrLookbehind<s extends State, unscanned extends string> = unscanned extends (Scanner.shift<infer char extends LookaroundChar, infer next>) ? s.pushGroup<s, lookaroundKindOf<char>, next, undefined> : shiftNamedGroup<unscanned> extends (Scanner.shiftResult<infer name, infer following>) ? s.pushGroup<s, name, following, undefined> : s.error<writeUnclosedGroupMessage<")">>;
28
29
  type shiftNamedGroup<unscanned extends string> = unscanned extends `${infer name}>${infer next}` ? name extends "" ? Scanner.shiftResult<"", ErrorMessage<unnamedCaptureGroupMessage>> : Scanner.shiftResult<name, next> : Scanner.shiftResult<"", ErrorMessage<writeUnclosedGroupMessage<">">>>;
29
30
  export declare const unnamedCaptureGroupMessage = "Capture group <> requires a name";
30
31
  export type unnamedCaptureGroupMessage = typeof unnamedCaptureGroupMessage;
package/out/index.js CHANGED
@@ -1 +1 @@
1
- export { regex } from "./regex.js";
1
+ export { regex } from "./chunk-PT4BOQED.js";
@@ -0,0 +1,9 @@
1
+ export * from "./index.ts";
2
+ export * from "./charset.ts";
3
+ export * from "./escape.ts";
4
+ export * from "./execArray.ts";
5
+ export * from "./group.ts";
6
+ export * from "./parse.ts";
7
+ export * from "./quantify.ts";
8
+ export * from "./regex.ts";
9
+ export * from "./state.ts";
@@ -0,0 +1,49 @@
1
+ export { regex } from "./chunk-PT4BOQED.js";
2
+
3
+ // out/charset.js
4
+ var emptyCharacterSetMessage = "Empty character set [] is unsatisfiable";
5
+
6
+ // out/escape.js
7
+ var trailingBackslashMessage = "A regex cannot end with \\";
8
+ var writeUnresolvableBackreferenceMessage = (ref) => `Group ${ref} does not exist`;
9
+ var missingBackreferenceNameMessage = "\\k must be followed by a named reference like <name>";
10
+ var writeInvalidUnicodePropertyMessage = (char) => `\\${char} must be followed by a property like \\${char}{Emoji_Presentation}`;
11
+ var writeUnnecessaryEscapeMessage = (char) => `Escape preceding ${char} is unnecessary and should be removed.`;
12
+ var writeStringEscapableMessage = (char) => `\\${char} should be specified with a single backslash like regex('\\n')`;
13
+ var caretNotationMessage = "\\\\cX notation is not supported. Use hex (\\\\x) or unicode (\\\\u) instead.";
14
+
15
+ // out/group.js
16
+ var writeDuplicateModifierMessage = (modifier) => `Modifier ${modifier} cannot appear multiple times in a single group`;
17
+ var multipleModifierDashesMessage = "Modifiers can include at most one '-' to negate subsequent flags";
18
+ var missingNegatedModifierMessage = `- must be followed by the modifier flag to negate ('i', 'm' or 's')`;
19
+ var writeInvalidModifierMessage = (char) => `Modifier flag ${char} must be 'i', 'm' or 's'`;
20
+ var unnamedCaptureGroupMessage = "Capture group <> requires a name";
21
+ var unescapedLiteralQuestionMarkMessage = "literal ? must be escaped at the start of a group";
22
+
23
+ // out/quantify.js
24
+ var writeUnmatchedQuantifierError = (quantifier) => `Quantifier ${quantifier} requires a preceding token`;
25
+ var writeUnnaturalNumberQuantifierError = (quantifier) => `Quantifier ${quantifier} must use natural numbers`;
26
+
27
+ // out/state.js
28
+ var writeIncompleteReferenceError = (ref) => `Reference to incomplete group '${ref}' has no effect`;
29
+ var writeMidAnchorError = (anchor) => `Anchor ${anchor} may not appear mid-pattern`;
30
+ export {
31
+ caretNotationMessage,
32
+ emptyCharacterSetMessage,
33
+ missingBackreferenceNameMessage,
34
+ missingNegatedModifierMessage,
35
+ multipleModifierDashesMessage,
36
+ trailingBackslashMessage,
37
+ unescapedLiteralQuestionMarkMessage,
38
+ unnamedCaptureGroupMessage,
39
+ writeDuplicateModifierMessage,
40
+ writeIncompleteReferenceError,
41
+ writeInvalidModifierMessage,
42
+ writeInvalidUnicodePropertyMessage,
43
+ writeMidAnchorError,
44
+ writeStringEscapableMessage,
45
+ writeUnmatchedQuantifierError,
46
+ writeUnnaturalNumberQuantifierError,
47
+ writeUnnecessaryEscapeMessage,
48
+ writeUnresolvableBackreferenceMessage
49
+ };
package/out/parse.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import type { Backslash, ErrorMessage, Scanner } from "@ark/util";
1
+ import type { Backslash, contains, ErrorMessage, Scanner } from "@ark/util";
2
2
  import type { parseCharset } from "./charset.ts";
3
3
  import type { parseEscape } from "./escape.ts";
4
4
  import type { parseGroup } from "./group.ts";
5
5
  import type { parseBuiltinQuantifier, parsePossibleRange, QuantifyingChar } from "./quantify.ts";
6
6
  import type { Anchor, AnchorMarker, s, State, UnionTree } from "./state.ts";
7
7
  export type parseState<s extends State> = s["unscanned"] extends ErrorMessage ? s["unscanned"] : s["unscanned"] extends "" ? s.finalize<s> : parseState<next<s>>;
8
- export type next<s extends State> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "." ? s.shiftQuantifiable<s, string, unscanned> : lookahead extends Backslash ? parseEscape<s, unscanned> : lookahead extends "|" ? s.finalizeBranch<s, unscanned> : lookahead extends Anchor ? s.anchor<s, AnchorMarker<lookahead>, unscanned> : lookahead extends "(" ? parseGroup<s, unscanned> : lookahead extends ")" ? s.popGroup<s, unscanned> : lookahead extends QuantifyingChar ? parseBuiltinQuantifier<s, lookahead, unscanned> : lookahead extends "{" ? parsePossibleRange<s, unscanned> : lookahead extends "[" ? parseCharset<s, unscanned> : s.shiftQuantifiable<s, maybeSplitCasing<s["caseInsensitive"], lookahead>, unscanned> : never;
8
+ export type next<s extends State> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "." ? s.shiftQuantifiable<s, string, unscanned> : lookahead extends Backslash ? parseEscape<s, unscanned> : lookahead extends "|" ? s.finalizeBranch<s, unscanned> : lookahead extends Anchor ? contains<s["flags"], "m"> extends true ? s.shiftQuantifiable<s, "", unscanned> : s.anchor<s, AnchorMarker<lookahead>, unscanned> : lookahead extends "(" ? parseGroup<s, unscanned> : lookahead extends ")" ? s.popGroup<s, unscanned> : lookahead extends QuantifyingChar ? parseBuiltinQuantifier<s, lookahead, unscanned> : lookahead extends "{" ? parsePossibleRange<s, unscanned> : lookahead extends "[" ? parseCharset<s, unscanned> : s.shiftQuantifiable<s, maybeSplitCasing<s["caseInsensitive"], lookahead>, unscanned> : never;
9
9
  type maybeSplitCasing<caseInsensitive extends boolean, char extends string> = caseInsensitive extends false ? char : Lowercase<char> extends Uppercase<char> ? char : UnionTree<[Lowercase<char>, Capitalize<char>]>;
10
10
  export {};
package/out/quantify.d.ts CHANGED
@@ -30,7 +30,7 @@ export type parsePossibleRange<s extends State, unscanned extends string, parsed
30
30
  unknown
31
31
  ] | [unknown, never]) ? s.error<writeUnnaturalNumberQuantifierError<parseQuantifier<unscanned, parsed>>> : s.pushQuantifier<s, parsed["min"], parsed["max"], parsed["unscanned"] extends Scanner.shift<"?", infer lazyUnscanned> ? lazyUnscanned : parsed["unscanned"]> : s.shiftQuantifiable<s, "{", unscanned>;
32
32
  export type quantify<pattern extends string, min extends number, max extends number | null> = tryFastPath<pattern, min, max>;
33
- type tryFastPath<pattern extends string, min extends number, max extends number | null> = max extends 0 ? "" : string extends pattern ? string : `${number}` extends pattern ? min extends 0 ? "" | `${number}` : `${number}` : min extends 0 ? max extends 1 ? "" | pattern : max extends number ? loopFromZero<pattern, max, "", []> : // max is null, all we can do is append ${string}
33
+ type tryFastPath<pattern extends string, min extends number, max extends number | null> = max extends 0 ? "" : string extends pattern ? string : [pattern, `${number}`] extends [`${number}`, pattern] ? max extends null ? string : min extends 0 ? "" | `${number}` : `${number}` : min extends 0 ? max extends 1 ? "" | pattern : max extends number ? loopFromZero<pattern, max, "", []> : // max is null, all we can do is append ${string}
34
34
  "" | `${pattern}${string}` : loopUntilMin<pattern, min, max, "", []>;
35
35
  type loopFromZero<base extends string, max extends number, acc extends string, repetitions extends 1[]> = repetitions["length"] extends max ? acc : loopFromZero<base, max, acc | `${acc}${base}`, [...repetitions, 1]>;
36
36
  type loopUntilMin<base extends string, min extends number, max extends number | null, acc extends string, repetitions extends 1[]> = repetitions["length"] extends min ? max extends number ? loopUntilMax<base, min, max, acc, repetitions> : repetitions["length"] extends 0 ? acc | `${acc}${base}${string}` : `${acc}${string}` : loopUntilMin<base, min, max, `${acc}${base}`, [...repetitions, 1]>;
package/out/state.d.ts CHANGED
@@ -23,6 +23,7 @@ export declare namespace State {
23
23
  enum UnnamedCaptureKind {
24
24
  indexed,
25
25
  lookaround,
26
+ negativeLookaround,
26
27
  noncapturing
27
28
  }
28
29
  type CaptureKind = string | UnnamedCaptureKind;
@@ -131,8 +132,8 @@ export declare namespace s {
131
132
  groups: init;
132
133
  capture: last["capture"];
133
134
  branches: last["branches"];
134
- sequence: pushQuantifiable<last["sequence"], last["root"]>;
135
- root: s["capture"] extends CapturedGroupKind ? GroupTree<State.Group.finalize<s>, s["capture"]> : s["capture"] extends State.UnnamedCaptureKind.lookaround ? "" : State.Group.finalize<s>;
135
+ sequence: s["capture"] extends LookaroundKind ? pushQuantifiable<pushQuantifiable<last["sequence"], last["root"]>, GroupTree<State.Group.finalize<s>, s["capture"]>> : pushQuantifiable<last["sequence"], last["root"]>;
136
+ root: s["capture"] extends CapturedGroupKind ? GroupTree<State.Group.finalize<s>, s["capture"]> : s["capture"] extends LookaroundKind ? "" : State.Group.finalize<s>;
136
137
  caseInsensitive: last["caseInsensitive"];
137
138
  flags: s["flags"];
138
139
  }> : s.error<writeUnmatchedGroupCloseMessage<")", unscanned>>;
@@ -203,7 +204,7 @@ export interface UnionTree<ast extends RegexAst[] = RegexAst[]> {
203
204
  ast: ast;
204
205
  }
205
206
  export declare namespace UnionTree {
206
- type finalize<self extends UnionTree, ctx extends FinalizationContext> = _finalize<self["ast"], [], ctx>;
207
+ type finalize<self extends UnionTree, ctx extends FinalizationContext> = _finalize<self["ast"], [], ctx, ctx["captures"]>;
207
208
  type FinalizedBranch = {
208
209
  pattern: string;
209
210
  captures: IndexedCaptures;
@@ -212,33 +213,43 @@ export declare namespace UnionTree {
212
213
  namespace FinalizedBranch {
213
214
  type from<b extends FinalizedBranch> = b;
214
215
  }
215
- type _finalize<astBranches extends unknown[], acc extends FinalizedBranch[], ctx extends FinalizationContext> = astBranches extends [infer head, ...infer tail] ? finalizeTree<head, ctx> extends infer r ? r extends FinalizationResult ? _finalize<tail, finalizeBranch<acc, ctx, r>, ctx> : never : never : finalizeBranches<keyof acc, acc, ctx>;
216
- type finalizeBranch<acc extends FinalizedBranch[], ctx extends FinalizationContext, r extends FinalizationResult> = [
216
+ type _finalize<astBranches extends unknown[], acc extends FinalizedBranch[], ctx extends FinalizationContext, priorCaptures extends IndexedCaptures> = astBranches extends [infer head, ...infer tail] ? finalizeTree<head, branchContextOf<ctx, priorCaptures>> extends (infer r extends FinalizationResult) ? _finalize<tail, [
217
217
  ...acc,
218
- FinalizedBranch.from<{
219
- pattern: r["pattern"];
220
- captures: finalizeBranchCaptures<acc, ctx, r>;
221
- names: r["ctx"]["names"];
222
- }>
223
- ];
224
- type finalizeBranchCaptures<acc extends FinalizedBranch[], ctx extends FinalizationContext, r extends FinalizationResult, branchCaptures extends IndexedCaptures = extractNewCaptures<ctx["captures"], r["ctx"]["captures"]>> = acc extends [] ? branchCaptures : acc[0]["captures"] extends (infer firstCaptureBranch extends IndexedCaptures) ? branchCaptures extends [] ? {
225
- [i in keyof firstCaptureBranch]: undefined;
226
- } : [...{
227
- [i in keyof firstCaptureBranch]: undefined;
228
- }, ...branchCaptures] : never;
229
- type finalizeBranches<i, acc extends FinalizedBranch[], ctx extends FinalizationContext> = i extends keyof acc & NumberLiteral ? FinalizationResult.from<{
230
- pattern: acc[i]["pattern"];
218
+ finalizeBranch<ctx, r>
219
+ ], ctx, r["ctx"]["captures"]> : never : finalizeBranches<keyof acc, acc, ctx, extractNewCaptures<ctx["captures"], priorCaptures>>;
220
+ type branchContextOf<ctx extends FinalizationContext, priorCaptures extends IndexedCaptures> = priorCaptures["length"] extends ctx["captures"]["length"] ? ctx : FinalizationContext.from<{
221
+ captures: {
222
+ [i in keyof priorCaptures]: i extends keyof ctx["captures"] ? priorCaptures[i] : undefined;
223
+ };
224
+ names: ctx["names"];
225
+ flags: ctx["flags"];
226
+ errors: ctx["errors"];
227
+ }>;
228
+ type finalizeBranch<ctx extends FinalizationContext, r extends FinalizationResult> = r extends unknown ? FinalizedBranch.from<{
229
+ pattern: r["pattern"];
230
+ captures: extractNewCaptures<ctx["captures"], r["ctx"]["captures"]>;
231
+ names: r["ctx"]["names"];
232
+ }> : never;
233
+ type finalizeBranches<i, acc extends FinalizedBranch[], ctx extends FinalizationContext, unionCaptures extends IndexedCaptures> = i extends keyof acc & NumberLiteral ? finalizeBranchResult<acc[i], acc, ctx, unionCaptures> : never;
234
+ type finalizeBranchResult<branch extends FinalizedBranch, acc extends FinalizedBranch[], ctx extends FinalizationContext, unionCaptures extends IndexedCaptures> = branch extends unknown ? FinalizationResult.from<{
235
+ pattern: branch["pattern"];
231
236
  ctx: {
232
237
  flags: ctx["flags"];
233
- captures: [...ctx["captures"], ...acc[i]["captures"]];
238
+ captures: [
239
+ ...ctx["captures"],
240
+ ...{
241
+ [j in keyof unionCaptures]: j extends keyof branch["captures"] ? branch["captures"][j] : undefined;
242
+ }
243
+ ];
234
244
  names: {
235
- [k in unionKeyOf<acc[number]["names"]>]: k extends (keyof acc[i]["names"]) ? acc[i]["names"][k] : undefined;
245
+ [k in unionKeyOf<acc[number]["names"]>]: k extends (keyof branch["names"]) ? branch["names"][k] : undefined;
236
246
  };
237
247
  errors: ctx["errors"];
238
248
  };
239
249
  }> : never;
240
250
  }
241
251
  export type CapturedGroupKind = string | State.UnnamedCaptureKind.indexed;
252
+ export type LookaroundKind = State.UnnamedCaptureKind.lookaround | State.UnnamedCaptureKind.negativeLookaround;
242
253
  export type IncompleteCaptureGroup = noSuggest<"incompleteCaptureGroup">;
243
254
  export type IndexedCaptureOffset = noSuggest<"indexedCaptureOffset">;
244
255
  /**
@@ -246,7 +257,7 @@ export type IndexedCaptureOffset = noSuggest<"indexedCaptureOffset">;
246
257
  * (i.e so that \1 would match the first capture group)
247
258
  */
248
259
  export type EmptyCaptures = [IndexedCaptureOffset];
249
- export interface GroupTree<ast extends RegexAst = RegexAst, capture extends CapturedGroupKind = CapturedGroupKind> {
260
+ export interface GroupTree<ast extends RegexAst = RegexAst, capture extends CapturedGroupKind | LookaroundKind = CapturedGroupKind | LookaroundKind> {
250
261
  kind: "group";
251
262
  capture: capture;
252
263
  ast: ast;
@@ -267,8 +278,21 @@ export declare namespace GroupTree {
267
278
  errors: ctx["errors"];
268
279
  } : ctx>;
269
280
  type finalizeGroupResult<self extends GroupTree, ctx extends FinalizationContext, r extends FinalizationResult> = FinalizationResult.from<{
270
- pattern: r["pattern"];
271
- ctx: self["capture"] extends string ? finalizeNamedCapture<self["capture"], ctx["captures"]["length"], r["pattern"], r["ctx"]> : self["capture"] extends State.UnnamedCaptureKind.indexed ? finalizeUnnamedCapture<ctx["captures"]["length"], r["pattern"], r["ctx"]> : r["ctx"];
281
+ pattern: self["capture"] extends LookaroundKind ? "" : r["pattern"];
282
+ ctx: self["capture"] extends string ? finalizeNamedCapture<self["capture"], ctx["captures"]["length"], r["pattern"], r["ctx"]> : self["capture"] extends State.UnnamedCaptureKind.indexed ? finalizeUnnamedCapture<ctx["captures"]["length"], r["pattern"], r["ctx"]> : self["capture"] extends State.UnnamedCaptureKind.negativeLookaround ? finalizeNegativeLookaround<ctx, r["ctx"]> : r["ctx"];
283
+ }>;
284
+ type finalizeNegativeLookaround<base extends FinalizationContext, result extends FinalizationContext, lookaroundCaptures extends IndexedCaptures = extractNewCaptures<base["captures"], result["captures"]>> = FinalizationContext.from<{
285
+ captures: [
286
+ ...base["captures"],
287
+ ...{
288
+ [i in keyof lookaroundCaptures]: undefined;
289
+ }
290
+ ];
291
+ names: {
292
+ [k in keyof result["names"]]: k extends keyof base["names"] ? result["names"][k] : undefined;
293
+ };
294
+ flags: result["flags"];
295
+ errors: result["errors"];
272
296
  }>;
273
297
  type finalizeNamedCapture<name extends string, index extends number, pattern extends string, ctx extends FinalizationContext> = FinalizationContext.from<{
274
298
  captures: setIndex<ctx["captures"], index, anchorsAway<pattern>>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "arkregex",
3
3
  "description": "A drop-in replacement for new RegExp() with types",
4
- "version": "0.0.15",
4
+ "version": "0.0.16-beta.0",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -16,25 +16,42 @@
16
16
  "type": "module",
17
17
  "main": "./out/index.js",
18
18
  "types": "./out/index.d.ts",
19
+ "typesVersions": {
20
+ "*": {
21
+ "internal": [
22
+ "./out/internal.d.ts"
23
+ ],
24
+ "internal/*": [
25
+ "./out/*"
26
+ ]
27
+ }
28
+ },
29
+ "sideEffects": false,
19
30
  "exports": {
20
31
  ".": {
21
32
  "ark-ts": "./index.ts",
22
33
  "default": "./out/index.js"
23
34
  },
35
+ "./internal": {
36
+ "ark-ts": "./internal.ts",
37
+ "default": "./out/internal.js"
38
+ },
24
39
  "./internal/*.ts": {
25
40
  "ark-ts": "./*.ts",
26
- "default": "./out/*.js"
41
+ "types": "./out/*.d.ts",
42
+ "default": "./out/internal.js"
27
43
  },
28
44
  "./internal/*.js": {
29
45
  "ark-ts": "./*.ts",
30
- "default": "./out/*.js"
46
+ "types": "./out/*.d.ts",
47
+ "default": "./out/internal.js"
31
48
  }
32
49
  },
33
50
  "files": [
34
51
  "out"
35
52
  ],
36
53
  "dependencies": {
37
- "@ark/util": "0.56.9"
54
+ "@ark/util": "0.57.0-beta.0"
38
55
  },
39
56
  "publishConfig": {
40
57
  "access": "public"
package/out/charset.js DELETED
@@ -1 +0,0 @@
1
- export const emptyCharacterSetMessage = "Empty character set [] is unsatisfiable";
package/out/escape.js DELETED
@@ -1,10 +0,0 @@
1
- export const trailingBackslashMessage = "A regex cannot end with \\";
2
- export const writeUnresolvableBackreferenceMessage = (ref) => `Group ${ref} does not exist`;
3
- export const missingBackreferenceNameMessage = "\\k must be followed by a named reference like <name>";
4
- export const writeInvalidUnicodePropertyMessage = (char) => `\\${char} must be followed by a property like \\${char}{Emoji_Presentation}`;
5
- export const writeUnnecessaryEscapeMessage = (char) => `Escape preceding ${char} is unnecessary and should be removed.`;
6
- // we have to add extra backslashes to the runtime variants of these
7
- // so that attest can compare them correctly to their type-level equivalents
8
- // the runtime variants are only used for the tests
9
- export const writeStringEscapableMessage = (char) => `\\${char} should be specified with a single backslash like regex('\\n')`;
10
- export const caretNotationMessage = "\\\\cX notation is not supported. Use hex (\\\\x) or unicode (\\\\u) instead.";
package/out/execArray.js DELETED
@@ -1 +0,0 @@
1
- export {};
package/out/group.js DELETED
@@ -1,6 +0,0 @@
1
- export const writeDuplicateModifierMessage = (modifier) => `Modifier ${modifier} cannot appear multiple times in a single group`;
2
- export const multipleModifierDashesMessage = "Modifiers can include at most one '-' to negate subsequent flags";
3
- export const missingNegatedModifierMessage = `- must be followed by the modifier flag to negate ('i', 'm' or 's')`;
4
- export const writeInvalidModifierMessage = (char) => `Modifier flag ${char} must be 'i', 'm' or 's'`;
5
- export const unnamedCaptureGroupMessage = "Capture group <> requires a name";
6
- export const unescapedLiteralQuestionMarkMessage = "literal ? must be escaped at the start of a group";
package/out/parse.js DELETED
@@ -1 +0,0 @@
1
- export {};
package/out/quantify.js DELETED
@@ -1,2 +0,0 @@
1
- export const writeUnmatchedQuantifierError = (quantifier) => `Quantifier ${quantifier} requires a preceding token`;
2
- export const writeUnnaturalNumberQuantifierError = (quantifier) => `Quantifier ${quantifier} must use natural numbers`;
package/out/regex.js DELETED
@@ -1,2 +0,0 @@
1
- export const regex = ((src, flags) => new RegExp(src, flags));
2
- Object.assign(regex, { as: regex });
package/out/state.js DELETED
@@ -1,2 +0,0 @@
1
- export const writeIncompleteReferenceError = (ref) => `Reference to incomplete group '${ref}' has no effect`;
2
- export const writeMidAnchorError = (anchor) => `Anchor ${anchor} may not appear mid-pattern`;