@ptolemy2002/rgx 4.8.0 → 4.11.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
@@ -1,9 +1,13 @@
1
1
  # RGX
2
2
  A library for easy construction and validation of regular expressions in TypeScript. You can use `rgx` to concatenate various types of tokens into a valid regular expression string, with type safety and validation.
3
3
 
4
+ **Note**: This library is tested with nearly 100% coverage, but any override of `RGXClassToken.clone()` does not have the depth parameter fully tested, as that is ultimately part of `@ptolemy2002/immutability-utils`, which is tested, and setting up tests for that functionality is exceedingly complex.
5
+
4
6
  ## Type Reference
5
7
  ```typescript
6
8
  import { Branded } from "@ptolemy2002/ts-brand-utils";
9
+ import { CloneDepth } from "@ptolemy2002/immutability-utils";
10
+ // type CloneDepth = number | "max";
7
11
 
8
12
  type RGXNoOpToken = null | undefined;
9
13
  type RGXLiteralToken = RegExp;
@@ -253,7 +257,7 @@ constructor(tokens: RGXTokenCollectionInput = [], mode: RGXTokenCollectionMode =
253
257
  - `toRgx() => RegExp`: A method that resolves the collection to a `RegExp` object based on the collection mode. In 'union' mode, the tokens are resolved as alternatives (using the `|` operator), while in 'concat' mode, the tokens are resolved as concatenated together. No flags are applied to the resulting `RegExp`. Since this method returns a `RegExp` (which is `RGXLiteralToken`), `RGXTokenCollection` instances satisfy the `RGXConvertibleToken` interface and can be used directly as tokens in `rgx`, `rgxa`, and other token-accepting functions.
254
258
  - `getTokens() => RGXToken[]`: A method that returns a copy of the array of RGX tokens managed by the collection. This is used to prevent external mutation of the internal `tokens` array.
255
259
  - `toArray() => RGXToken[]`: An alias for `getTokens()`, provided for convenience.
256
- - `clone() => RGXTokenCollection`: A method that creates and returns a deep clone of the RGXTokenCollection instance. This is useful for creating a new collection with the same tokens and mode without affecting the original collection.
260
+ - `clone(depth: CloneDepth = "max") => RGXTokenCollection`: A method that creates and returns a deep clone of the RGXTokenCollection instance. This is useful for creating a new collection with the same tokens and mode without affecting the original collection. The `depth` parameter controls how deeply nested collections are cloned: `0` for no clone, `1` for a shallow clone of the top-level collection, any other number for that many levels down, and `"max"` (the default) for a full deep clone.
257
261
  - `asConcat() => RGXTokenCollection`: If this collection is in 'union' mode, this method returns a new RGXTokenCollection instance with the same tokens but in 'concat' mode. If the collection is already in 'concat' mode, it simply returns itself.
258
262
  - `asUnion() => RGXTokenCollection`: If this collection is in 'concat' mode, this method returns a new RGXTokenCollection instance with the same tokens but in 'union' mode. If the collection is already in 'union' mode, it simply returns itself.
259
263
 
@@ -272,6 +276,7 @@ An abstract base class for creating custom RGX token classes. Subclasses must im
272
276
 
273
277
  #### Abstract Methods
274
278
  - `toRgx() => RGXToken`: Must be implemented by subclasses to return the token's regex representation as any valid RGX token (native, literal, convertible, or array of tokens).
279
+ - `clone(depth: CloneDepth = "max") => RGXClassToken`: Must be implemented by subclasses to return a deep clone of the token instance. The `depth` parameter controls how deeply nested tokens are cloned: `0` for no clone, `1` for a shallow clone of the top-level token, any other number for that many levels down, and `"max"` (the default) for a full deep clone.
275
280
 
276
281
  #### Properties
277
282
  - `isGroup` (`boolean`): Returns `false` by default. Subclasses can override this to indicate whether the token represents a group.
@@ -419,6 +424,30 @@ A function `rgxLookbehind` is provided with the same parameters as this class' c
419
424
  - `reverse() => RGXLookaheadToken`: Returns a new `RGXLookaheadToken` with the same tokens and positivity.
420
425
  - `toRgx() => RegExp`: Resolves the lookbehind to a `RegExp`. Positive lookbehinds produce `(?<=...)` and negative lookbehinds produce `(?<!...)`.
421
426
 
427
+ ### RGXClassWrapperToken extends RGXClassToken
428
+ A class that wraps any `RGXToken` as an `RGXClassToken`, giving you access to the extended API class tokens provide. It delegates `isGroup` and `isRepeatable` to the wrapped token where possible.
429
+
430
+ A function `rgxClassWrapper` is provided with the same parameters as this class' constructor, for easier instantiation without needing to use the `new` keyword.
431
+
432
+ #### Static Properties
433
+ - `check(value: unknown): value is RGXClassWrapperToken`: A type guard that checks if the given value is an instance of `RGXClassWrapperToken`.
434
+ - `assert(value: unknown): asserts value is RGXClassWrapperToken`: An assertion that checks if the given value is an instance of `RGXClassWrapperToken`. If the assertion fails, an `RGXInvalidTokenError` will be thrown.
435
+
436
+ #### Constructor
437
+ ```typescript
438
+ constructor(token: RGXToken)
439
+ ```
440
+ - `token` (`RGXToken`): The token to wrap.
441
+
442
+ #### Properties
443
+ - `token` (`RGXToken`): The wrapped token.
444
+ - `isGroup` (`boolean`): Delegates to the wrapped token's group status via `isRGXGroupedToken`. Returns `true` if the wrapped token is a grouped token, otherwise `false`.
445
+ - `isRepeatable` (`boolean`): If the wrapped token is an `RGXClassToken`, delegates to its `isRepeatable` property. Otherwise, returns `true`.
446
+
447
+ #### Methods
448
+ - `unwrap() => RGXToken`: Returns the original wrapped token.
449
+ - `toRgx() => RGXToken`: Returns the original wrapped token (alias for `unwrap()`).
450
+
422
451
  ### ExtRegExp extends RegExp
423
452
  A subclass of `RegExp` that supports custom flag transformers in addition to the standard vanilla regex flags (g, i, m, s, u, y). When constructed, custom flags are extracted, their corresponding transformers are applied to the pattern and vanilla flags, and the resulting transformed `RegExp` is created. The `flags` getter returns both the vanilla flags and any custom flags.
424
453
 
@@ -816,24 +845,27 @@ Escapes special regex characters in the given string and brands the result as a
816
845
 
817
846
  ### resolveRGXToken
818
847
  ```typescript
819
- function resolveRGXToken(token: RGXToken, groupWrap?: boolean, topLevel?: boolean): ValidRegexString
848
+ function resolveRGXToken(token: RGXToken, groupWrap?: boolean, topLevel?: boolean, currentFlags?: string): ValidRegexString
820
849
  ```
821
850
 
822
851
  Resolves an RGX token to a string. No-op tokens resolve to an empty string, literal tokens are included as-is (wrapped in a non-capturing group when `groupWrap` is `true`), native tokens are converted to strings and escaped, convertible tokens are converted using their `toRgx` method and then resolved recursively, and arrays of tokens are resolved as unions of their resolved elements (repeats removed, placed in a non-capturing group when `groupWrap` is `true`).
823
852
 
853
+ For literal tokens (`RegExp` instances), if the token's flags differ from `currentFlags` in any of the localizable flags (`i`, `m`, `s`), the token is wrapped in an inline modifier group (e.g., `(?i:...)`, `(?-i:...)`, `(?ms-i:...)`) instead of a plain non-capturing group. Non-localizable flags (such as `g`, `u`, `y`, `d`, `v`) are ignored when computing the diff. When an inline modifier group is used, it always wraps the token regardless of the `groupWrap` setting, since the modifier group itself serves as a group.
854
+
824
855
  For convertible tokens, if the token has an `rgxGroupWrap` property, that value always takes precedence. If `rgxGroupWrap` is not present, the behavior depends on whether the call is top-level: at the top level, the `groupWrap` parameter is passed through; in recursive calls, it falls back to `true` regardless of the `groupWrap` parameter. This ensures that the caller's `groupWrap` preference only affects the outermost convertible token and does not leak into deeply nested resolution.
825
856
 
826
857
  #### Parameters
827
858
  - `token` (`RGXToken`): The RGX token to resolve.
828
- - `groupWrap` (`boolean`, optional): Whether to wrap literal tokens and array unions in non-capturing groups (`(?:...)`). Defaults to `true`. When `false`, literals use their raw source and array unions omit the wrapping group. For convertible tokens, the token's `rgxGroupWrap` property always takes precedence; otherwise, this value is only passed through at the top level (in recursive calls it falls back to `true`). Array union elements always use `groupWrap=true` internally.
859
+ - `groupWrap` (`boolean`, optional): Whether to wrap literal tokens and array unions in non-capturing groups (`(?:...)`). Defaults to `true`. When `false`, literals use their raw source and array unions omit the wrapping group. For convertible tokens, the token's `rgxGroupWrap` property always takes precedence; otherwise, this value is only passed through at the top level (in recursive calls it falls back to `true`). Array union elements always use `groupWrap=true` internally. Note that when a literal token requires an inline modifier group due to a localizable flag diff, it is always wrapped regardless of this setting.
829
860
  - `topLevel` (`boolean`, optional): Tracks whether the current call is the initial (top-level) invocation. Defaults to `true`. **Warning**: This parameter is intended for internal use by the resolver's own recursion. External callers should not set this parameter, as doing so may produce unexpected wrapping behavior.
861
+ - `currentFlags` (`string`, optional): The flags of the current regex context, used to compute inline modifier groups for literal tokens. Defaults to `''`. When a literal token's localizable flags (`i`, `m`, `s`) differ from this value, the resolver wraps the token in an inline modifier group that adds or removes the differing flags locally.
830
862
 
831
863
  #### Returns
832
864
  - `ValidRegexString`: The resolved string representation of the RGX token. This is guaranteed to be a valid regex string, as convertible tokens are validated to only produce valid regex strings or arrays of valid regex strings.
833
865
 
834
866
  ### rgxConcat
835
867
  ```typescript
836
- function rgxConcat(tokens: RGXToken[], groupWrap?: boolean): ValidRegexString
868
+ function rgxConcat(tokens: RGXToken[], groupWrap?: boolean, currentFlags?: string): ValidRegexString
837
869
  ```
838
870
 
839
871
  A helper function that resolves an array of RGX tokens and concatenates their resolved string representations together. This is useful for cases where you want to concatenate multiple tokens without creating a union between them.
@@ -841,6 +873,7 @@ A helper function that resolves an array of RGX tokens and concatenates their re
841
873
  #### Parameters
842
874
  - `tokens` (`RGXToken[]`): The array of RGX tokens to resolve and concatenate.
843
875
  - `groupWrap` (`boolean`, optional): Whether to wrap individual resolved tokens in non-capturing groups. Passed through to `resolveRGXToken`. Defaults to `true`.
876
+ - `currentFlags` (`string`, optional): The flags of the current regex context, passed through to `resolveRGXToken` as its `currentFlags` parameter. Used to compute inline modifier groups for literal tokens whose localizable flags differ. Defaults to `''`.
844
877
 
845
878
  #### Returns
846
879
  - `ValidRegexString`: The concatenated string representation of the resolved RGX tokens. This is guaranteed to be a valid regex string, as it is composed of the resolved forms of RGX tokens, which are all valid regex strings.
@@ -852,6 +885,8 @@ function rgx(flags?: string): (strings: TemplateStringsArray, ...tokens: RGXToke
852
885
 
853
886
  Creates and returns a template tag function that constructs an `ExtRegExp` object from the provided template literal with the provided flags. The template literal can contain RGX tokens, which will be resolved and concatenated with the literal parts to form the final regex pattern.
854
887
 
888
+ The provided `flags` are passed as `currentFlags` to the resolver, enabling inline modifier groups for any `RegExp` literal tokens whose localizable flags (`i`, `m`, `s`) differ from the parent flags. For example, embedding `/foo/i` in a no-flag context produces `(?i:foo)`, while embedding `/bar/` in an `i`-flag context produces `(?-i:bar)`.
889
+
855
890
  Example usages:
856
891
  ```typescript
857
892
  const beginning = /^/;
@@ -863,6 +898,9 @@ const optionalDigit = /\d?/;
863
898
  const pattern2 = rgx()`${beginning}optional digit: ${optionalDigit}${end}`; // /^optional digit: \d?$/ - matches the string "optional digit: " followed by an optional digit, anchored to the start and end of the string
864
899
 
865
900
  const pattern3 = rgx()`${beginning}value: ${[word, optionalDigit]}${end}`; // /^value: (?:\w+|\d?)$/ - matches the string "value: " followed by either a word or an optional digit, anchored to the start and end of the string
901
+
902
+ const caseInsensitiveWord = /hello/i;
903
+ const pattern4 = rgx()`${beginning}${caseInsensitiveWord} world${end}`; // /^(?i:hello) world$/ - "hello" matches case-insensitively via an inline modifier group, while " world" remains case-sensitive
866
904
  ```
867
905
 
868
906
  #### Parameters
@@ -880,7 +918,7 @@ const pattern3 = rgx()`${beginning}value: ${[word, optionalDigit]}${end}`; // /^
880
918
  ```typescript
881
919
  function rgxa(tokens: RGXToken[], flags?: string): ExtRegExp
882
920
  ```
883
- As an alternative to using the `rgx` template tag, you can directly call `rgxa` with an array of RGX tokens and optional flags to get an `ExtRegExp` object. This is useful in cases where you don't want to use a template literal.
921
+ As an alternative to using the `rgx` template tag, you can directly call `rgxa` with an array of RGX tokens and optional flags to get an `ExtRegExp` object. This is useful in cases where you don't want to use a template literal. Like `rgx`, the provided `flags` are passed as `currentFlags` to the resolver, enabling inline modifier groups for `RegExp` literal tokens whose localizable flags differ.
884
922
 
885
923
  #### Parameters
886
924
  - `tokens` (`RGXToken[]`): The RGX tokens to be resolved and concatenated to form the regex pattern.
@@ -922,6 +960,22 @@ function rgxClassInit(): void
922
960
 
923
961
  Initializes internal method patches required for `RGXClassToken` subclass methods (such as `or`, `group`, `repeat`, `asLookahead`, and `asLookbehind`) to work correctly. This function is called automatically when importing from the main module entry point, so you typically do not need to call it yourself. It only needs to be called manually if you import directly from sub-modules.
924
962
 
963
+ ### toRGXClassToken
964
+ ```typescript
965
+ function toRGXClassToken(token: RGXToken): RGXClassToken
966
+ ```
967
+
968
+ Converts any `RGXToken` into an appropriate `RGXClassToken` subclass, giving you access to the extended API that class tokens provide. Tokens that are already class tokens are returned as-is. Array tokens and `RGXTokenCollection` instances in union mode are converted to `RGXClassUnionToken`. `RGXTokenCollection` instances in concat mode are converted to a non-capturing `RGXGroupToken`. All other tokens are wrapped in an `RGXClassWrapperToken`.
969
+
970
+ #### Parameters
971
+ - `token` (`RGXToken`): The token to convert.
972
+
973
+ #### Returns
974
+ - `RGXClassToken`: The corresponding class token:
975
+ - `RGXClassUnionToken` for array tokens and union-mode `RGXTokenCollection` instances.
976
+ - `RGXGroupToken` (non-capturing) for concat-mode `RGXTokenCollection` instances.
977
+ - `RGXClassWrapperToken` for all other tokens.
978
+
925
979
  ### isInRange
926
980
  ```typescript
927
981
  function isInRange(value: number, { min, max, inclusiveLeft, inclusiveRight }?: RangeObject): boolean
@@ -1159,6 +1213,19 @@ Tests whether the given regular expression matches at a specific position in the
1159
1213
  #### Returns
1160
1214
  - `boolean`: `true` if the regex matches at the specified position, otherwise `false`.
1161
1215
 
1216
+ ### cloneRGXToken
1217
+ ```typescript
1218
+ function cloneRGXTokeN<T extends RGXToken>(token: T, depth: CloneDepth="max"): T
1219
+ ```
1220
+ Creates a clone of the given RGX token to the given depth, provided that the token is not a no-op or native token.
1221
+
1222
+ #### Parameters
1223
+ - `token` (`T`): The RGX token to clone. Must not be a no-op or native token, or an error will be thrown.
1224
+ - `depth` (`CloneDepth`, optional): The depth to which to clone the token. Can be a number (with 0 resulting in no clone at all and 1 resulting in a shallow clone) or the string `"max"` for a full deep clone. Defaults to `"max"`.
1225
+
1226
+ #### Returns
1227
+ - `T`: The cloned token.
1228
+
1162
1229
  ## Peer Dependencies
1163
1230
  - `@ptolemy2002/immutability-utils` ^2.0.0
1164
1231
  - `@ptolemy2002/js-utils` ^3.2.2
@@ -1,5 +1,6 @@
1
1
  import { RGXToken, ValidRegexString } from "../types";
2
2
  import { RGXTokenCollectionInput } from "../collection";
3
+ import { CloneDepth } from "@ptolemy2002/immutability-utils";
3
4
  import type { RGXClassUnionToken } from "./union";
4
5
  import type { RGXGroupToken, RGXGroupTokenArgs } from "./group";
5
6
  import type { RGXRepeatToken } from "./repeat";
@@ -7,6 +8,7 @@ import type { RGXLookaheadToken } from "./lookahead";
7
8
  import type { RGXLookbehindToken } from "./lookbehind";
8
9
  export declare abstract class RGXClassToken {
9
10
  abstract toRgx(): RGXToken;
11
+ abstract clone(depth?: CloneDepth): ThisType<this>;
10
12
  static check: (value: unknown) => value is RGXClassToken;
11
13
  static assert: (value: unknown) => asserts value is RGXClassToken;
12
14
  get isGroup(): boolean;
@@ -1,5 +1,6 @@
1
1
  import { RGXTokenCollection, RGXTokenCollectionInput } from "../collection";
2
2
  import { RGXClassToken } from "./base";
3
+ import { CloneDepth } from "@ptolemy2002/immutability-utils";
3
4
  export type RGXGroupTokenArgs = {
4
5
  name?: string | null;
5
6
  capturing?: boolean;
@@ -18,5 +19,6 @@ export declare class RGXGroupToken extends RGXClassToken {
18
19
  get rgxGroupWrap(): false;
19
20
  constructor({ name, capturing }?: RGXGroupTokenArgs, tokens?: RGXTokenCollectionInput);
20
21
  toRgx(): RegExp;
22
+ clone(depth?: CloneDepth): RGXGroupToken;
21
23
  }
22
24
  export declare const rgxGroup: (args_0?: RGXGroupTokenArgs | undefined, tokens?: RGXTokenCollectionInput) => RGXGroupToken;
@@ -5,6 +5,7 @@ const collection_1 = require("../collection");
5
5
  const base_1 = require("./base");
6
6
  const internal_1 = require("../internal");
7
7
  const typeGuards_1 = require("../typeGuards");
8
+ const immutability_utils_1 = require("@ptolemy2002/immutability-utils");
8
9
  class RGXGroupToken extends base_1.RGXClassToken {
9
10
  get name() {
10
11
  return this._name;
@@ -52,6 +53,11 @@ class RGXGroupToken extends base_1.RGXClassToken {
52
53
  result = `(${result})`;
53
54
  return new RegExp(result);
54
55
  }
56
+ clone(depth = "max") {
57
+ if (depth === 0)
58
+ return this;
59
+ return new RGXGroupToken({ name: this.name, capturing: this._capturing }, this.tokens.clone((0, immutability_utils_1.depthDecrement)(depth, 1)));
60
+ }
55
61
  }
56
62
  exports.RGXGroupToken = RGXGroupToken;
57
63
  RGXGroupToken.check = (0, internal_1.createClassGuardFunction)(RGXGroupToken);
@@ -6,3 +6,5 @@ export * from "./repeat";
6
6
  export * from "./lookaround";
7
7
  export * from "./lookahead";
8
8
  export * from "./lookbehind";
9
+ export * from "./wrapper";
10
+ export * from "./toRGXClassToken";
@@ -22,3 +22,5 @@ __exportStar(require("./repeat"), exports);
22
22
  __exportStar(require("./lookaround"), exports);
23
23
  __exportStar(require("./lookahead"), exports);
24
24
  __exportStar(require("./lookbehind"), exports);
25
+ __exportStar(require("./wrapper"), exports);
26
+ __exportStar(require("./toRGXClassToken"), exports);
@@ -36,11 +36,15 @@ function rgxClassInit() {
36
36
  base_1.RGXClassToken.prototype.asLookahead = function (positive = true) {
37
37
  if (lookahead_1.RGXLookaheadToken.check(this))
38
38
  return this;
39
+ if (lookbehind_1.RGXLookbehindToken.check(this))
40
+ return this.negate();
39
41
  return new lookahead_1.RGXLookaheadToken([this], positive);
40
42
  };
41
43
  base_1.RGXClassToken.prototype.asLookbehind = function (positive = true) {
42
44
  if (lookbehind_1.RGXLookbehindToken.check(this))
43
45
  return this;
46
+ if (lookahead_1.RGXLookaheadToken.check(this))
47
+ return this.negate();
44
48
  return new lookbehind_1.RGXLookbehindToken([this], positive);
45
49
  };
46
50
  }
@@ -1,11 +1,13 @@
1
1
  import { RGXToken } from "../types";
2
2
  import { RGXLookaroundToken } from "./lookaround";
3
3
  import { RGXLookbehindToken } from "./lookbehind";
4
+ import { CloneDepth } from "@ptolemy2002/immutability-utils";
4
5
  export declare class RGXLookaheadToken extends RGXLookaroundToken {
5
6
  static check: (value: unknown) => value is RGXLookaheadToken;
6
7
  static assert: (value: unknown) => asserts value is RGXLookaheadToken;
7
8
  negate(): RGXLookaheadToken;
8
9
  reverse(): RGXLookbehindToken;
9
10
  toRgx(): RGXToken;
11
+ clone(depth?: CloneDepth): RGXLookaheadToken;
10
12
  }
11
13
  export declare const rgxLookahead: (tokens?: import("..").RGXTokenCollectionInput, positive?: boolean | undefined) => RGXLookaheadToken;
@@ -4,6 +4,7 @@ exports.rgxLookahead = exports.RGXLookaheadToken = void 0;
4
4
  const internal_1 = require("../internal");
5
5
  const lookaround_1 = require("./lookaround");
6
6
  const lookbehind_1 = require("./lookbehind");
7
+ const immutability_utils_1 = require("@ptolemy2002/immutability-utils");
7
8
  class RGXLookaheadToken extends lookaround_1.RGXLookaroundToken {
8
9
  negate() {
9
10
  return new RGXLookaheadToken(this.tokens, !this.positive);
@@ -19,6 +20,11 @@ class RGXLookaheadToken extends lookaround_1.RGXLookaroundToken {
19
20
  result = `(?!${result})`;
20
21
  return new RegExp(result);
21
22
  }
23
+ clone(depth = "max") {
24
+ if (depth === 0)
25
+ return this;
26
+ return new RGXLookaheadToken(this.tokens.clone((0, immutability_utils_1.depthDecrement)(depth, 1)), this.positive);
27
+ }
22
28
  }
23
29
  exports.RGXLookaheadToken = RGXLookaheadToken;
24
30
  RGXLookaheadToken.check = (0, internal_1.createClassGuardFunction)(RGXLookaheadToken);
@@ -1,12 +1,13 @@
1
- import { RGXTokenCollectionInput } from "../collection";
2
1
  import { RGXToken } from "../types";
3
2
  import { RGXLookaheadToken } from "./lookahead";
4
3
  import { RGXLookaroundToken } from "./lookaround";
4
+ import { CloneDepth } from "@ptolemy2002/immutability-utils";
5
5
  export declare class RGXLookbehindToken extends RGXLookaroundToken {
6
6
  static check: (value: unknown) => value is RGXLookbehindToken;
7
7
  static assert: (value: unknown) => asserts value is RGXLookbehindToken;
8
8
  negate(): RGXLookbehindToken;
9
9
  reverse(): RGXLookaheadToken;
10
10
  toRgx(): RGXToken;
11
+ clone(depth?: CloneDepth): RGXLookbehindToken;
11
12
  }
12
- export declare const rgxLookbehind: (tokens?: RGXTokenCollectionInput, positive?: boolean | undefined) => RGXLookbehindToken;
13
+ export declare const rgxLookbehind: (tokens?: import("..").RGXTokenCollectionInput, positive?: boolean | undefined) => RGXLookbehindToken;
@@ -4,6 +4,7 @@ exports.rgxLookbehind = exports.RGXLookbehindToken = void 0;
4
4
  const internal_1 = require("../internal");
5
5
  const lookahead_1 = require("./lookahead");
6
6
  const lookaround_1 = require("./lookaround");
7
+ const immutability_utils_1 = require("@ptolemy2002/immutability-utils");
7
8
  class RGXLookbehindToken extends lookaround_1.RGXLookaroundToken {
8
9
  negate() {
9
10
  return new RGXLookbehindToken(this.tokens, !this.positive);
@@ -19,6 +20,11 @@ class RGXLookbehindToken extends lookaround_1.RGXLookaroundToken {
19
20
  result = `(?<!${result})`;
20
21
  return new RegExp(result);
21
22
  }
23
+ clone(depth = "max") {
24
+ if (depth === 0)
25
+ return this;
26
+ return new RGXLookbehindToken(this.tokens.clone((0, immutability_utils_1.depthDecrement)(depth, 1)), this.positive);
27
+ }
22
28
  }
23
29
  exports.RGXLookbehindToken = RGXLookbehindToken;
24
30
  RGXLookbehindToken.check = (0, internal_1.createClassGuardFunction)(RGXLookbehindToken);
@@ -1,5 +1,6 @@
1
1
  import { RGXGroupedToken, RGXToken } from "../types";
2
2
  import { RGXClassToken } from "./base";
3
+ import { CloneDepth } from "@ptolemy2002/immutability-utils";
3
4
  export declare class RGXRepeatToken extends RGXClassToken {
4
5
  _token: RGXGroupedToken;
5
6
  _min: number;
@@ -10,11 +11,12 @@ export declare class RGXRepeatToken extends RGXClassToken {
10
11
  set min(value: number);
11
12
  get max(): number | null;
12
13
  set max(value: number | null);
13
- get token(): RGXToken;
14
+ get token(): RGXGroupedToken;
14
15
  set token(value: RGXToken);
15
16
  get rgxGroupWrap(): false;
16
17
  constructor(token: RGXToken, min?: number, max?: number | null);
17
18
  get repeaterSuffix(): string;
18
19
  toRgx(): RGXToken;
20
+ clone(depth?: CloneDepth): RGXRepeatToken;
19
21
  }
20
22
  export declare const rgxRepeat: (token: RGXToken, min?: number | undefined, max?: number | null | undefined) => RGXRepeatToken;
@@ -7,6 +7,8 @@ const typeGuards_1 = require("../typeGuards");
7
7
  const errors_1 = require("../errors");
8
8
  const resolve_1 = require("../resolve");
9
9
  const internal_1 = require("../internal");
10
+ const immutability_utils_1 = require("@ptolemy2002/immutability-utils");
11
+ const clone_1 = require("../clone");
10
12
  class RGXRepeatToken extends base_1.RGXClassToken {
11
13
  get min() {
12
14
  return this._min;
@@ -76,6 +78,11 @@ class RGXRepeatToken extends base_1.RGXClassToken {
76
78
  const resolvedSource = (0, resolve_1.resolveRGXToken)(this.token);
77
79
  return new RegExp(`${resolvedSource}${this.repeaterSuffix}`);
78
80
  }
81
+ clone(depth = "max") {
82
+ if (depth === 0)
83
+ return this;
84
+ return new RGXRepeatToken((0, clone_1.cloneRGXToken)(this.token, (0, immutability_utils_1.depthDecrement)(depth, 1)), this.min, this.max);
85
+ }
79
86
  }
80
87
  exports.RGXRepeatToken = RGXRepeatToken;
81
88
  RGXRepeatToken.check = (0, internal_1.createClassGuardFunction)(RGXRepeatToken);
@@ -0,0 +1,3 @@
1
+ import { RGXToken } from "../types";
2
+ import { RGXClassToken } from "./base";
3
+ export declare function toRGXClassToken(token: RGXToken): RGXClassToken;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toRGXClassToken = toRGXClassToken;
4
+ const base_1 = require("./base");
5
+ const typeGuards_1 = require("../typeGuards");
6
+ const union_1 = require("./union");
7
+ const collection_1 = require("../collection");
8
+ const group_1 = require("./group");
9
+ const wrapper_1 = require("./wrapper");
10
+ function toRGXClassToken(token) {
11
+ if (base_1.RGXClassToken.check(token))
12
+ return token;
13
+ if ((0, typeGuards_1.isRGXArrayToken)(token))
14
+ return new union_1.RGXClassUnionToken(token);
15
+ if (collection_1.RGXTokenCollection.check(token) && token.mode === 'union')
16
+ return new union_1.RGXClassUnionToken(token.tokens);
17
+ if (collection_1.RGXTokenCollection.check(token) && token.mode === 'concat')
18
+ return new group_1.RGXGroupToken({ capturing: false }, token);
19
+ return new wrapper_1.RGXClassWrapperToken(token);
20
+ }
@@ -1,6 +1,7 @@
1
1
  import { RGXToken } from "../types";
2
2
  import { RGXTokenCollection, RGXTokenCollectionInput } from "../collection";
3
3
  import { RGXClassToken } from "./base";
4
+ import { CloneDepth } from "@ptolemy2002/immutability-utils";
4
5
  export type RGXUnionInsertionPosition = 'prefix' | 'suffix';
5
6
  export declare class RGXClassUnionToken extends RGXClassToken {
6
7
  tokens: RGXTokenCollection;
@@ -11,6 +12,7 @@ export declare class RGXClassUnionToken extends RGXClassToken {
11
12
  add(token: RGXToken, pos?: RGXUnionInsertionPosition): this;
12
13
  concat(pos?: RGXUnionInsertionPosition, ...others: RGXTokenCollectionInput[]): this;
13
14
  toRgx(): RegExp;
15
+ clone(depth?: CloneDepth): RGXClassUnionToken;
14
16
  }
15
17
  export declare function expandRgxUnionTokens(...tokens: RGXTokenCollectionInput[]): RGXTokenCollection;
16
18
  export declare function removeRgxUnionDuplicates(...tokens: RGXTokenCollectionInput[]): RGXTokenCollection;
@@ -6,6 +6,7 @@ exports.removeRgxUnionDuplicates = removeRgxUnionDuplicates;
6
6
  const internal_1 = require("../internal");
7
7
  const collection_1 = require("../collection");
8
8
  const base_1 = require("./base");
9
+ const immutability_utils_1 = require("@ptolemy2002/immutability-utils");
9
10
  class RGXClassUnionToken extends base_1.RGXClassToken {
10
11
  constructor(tokens = []) {
11
12
  super();
@@ -44,6 +45,11 @@ class RGXClassUnionToken extends base_1.RGXClassToken {
44
45
  toRgx() {
45
46
  return this.tokens.toRgx();
46
47
  }
48
+ clone(depth = "max") {
49
+ if (depth === 0)
50
+ return this;
51
+ return new RGXClassUnionToken(this.tokens.clone((0, immutability_utils_1.depthDecrement)(depth, 1)));
52
+ }
47
53
  }
48
54
  exports.RGXClassUnionToken = RGXClassUnionToken;
49
55
  RGXClassUnionToken.check = (0, internal_1.createClassGuardFunction)(RGXClassUnionToken);
@@ -0,0 +1,15 @@
1
+ import { RGXToken } from "../types";
2
+ import { RGXClassToken } from "./base";
3
+ import { CloneDepth } from "@ptolemy2002/immutability-utils";
4
+ export declare class RGXClassWrapperToken extends RGXClassToken {
5
+ token: RGXToken;
6
+ static check: (value: unknown) => value is RGXClassWrapperToken;
7
+ static assert: (value: unknown) => asserts value is RGXClassWrapperToken;
8
+ constructor(token: RGXToken);
9
+ get isGroup(): boolean;
10
+ get isRepeatable(): boolean;
11
+ unwrap(): RGXToken;
12
+ toRgx(): RGXToken;
13
+ clone(depth?: CloneDepth): RGXClassWrapperToken;
14
+ }
15
+ export declare const rgxClassWrapper: (token: RGXToken) => RGXClassWrapperToken;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.rgxClassWrapper = exports.RGXClassWrapperToken = void 0;
4
+ const base_1 = require("./base");
5
+ const typeGuards_1 = require("../typeGuards");
6
+ const internal_1 = require("../internal");
7
+ const immutability_utils_1 = require("@ptolemy2002/immutability-utils");
8
+ const clone_1 = require("../clone");
9
+ class RGXClassWrapperToken extends base_1.RGXClassToken {
10
+ constructor(token) {
11
+ super();
12
+ this.token = token;
13
+ }
14
+ get isGroup() {
15
+ return (0, typeGuards_1.isRGXGroupedToken)(this.token);
16
+ }
17
+ get isRepeatable() {
18
+ if ((0, typeGuards_1.isRGXToken)(this.token, 'class'))
19
+ return this.token.isRepeatable;
20
+ // Assume any other token is repeatable, since we don't know its implementation.
21
+ return true;
22
+ }
23
+ unwrap() {
24
+ return this.token;
25
+ }
26
+ toRgx() {
27
+ return this.unwrap();
28
+ }
29
+ clone(depth = "max") {
30
+ if (depth === 0)
31
+ return this;
32
+ return new RGXClassWrapperToken((0, clone_1.cloneRGXToken)(this.token, (0, immutability_utils_1.depthDecrement)(depth, 1)));
33
+ }
34
+ }
35
+ exports.RGXClassWrapperToken = RGXClassWrapperToken;
36
+ RGXClassWrapperToken.check = (0, internal_1.createClassGuardFunction)(RGXClassWrapperToken);
37
+ RGXClassWrapperToken.assert = (0, internal_1.createAssertClassGuardFunction)(RGXClassWrapperToken);
38
+ exports.rgxClassWrapper = (0, internal_1.createConstructFunction)(RGXClassWrapperToken);
@@ -0,0 +1,3 @@
1
+ import { CloneDepth } from "@ptolemy2002/immutability-utils";
2
+ import { RGXToken } from "./types";
3
+ export declare function cloneRGXToken<T extends RGXToken>(token: T, depth?: CloneDepth): T;
package/dist/clone.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cloneRGXToken = cloneRGXToken;
4
+ const immutability_utils_1 = require("@ptolemy2002/immutability-utils");
5
+ const typeGuards_1 = require("./typeGuards");
6
+ function cloneRGXToken(token, depth = "max") {
7
+ if (depth === 0)
8
+ return token;
9
+ if ((0, typeGuards_1.isRGXToken)(token, "no-op") || (0, typeGuards_1.isRGXToken)(token, "native"))
10
+ return token;
11
+ return (0, immutability_utils_1.extClone)(token, (0, immutability_utils_1.depthDecrement)(depth, 1));
12
+ }
package/dist/concat.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  import * as t from "./types";
2
- export declare function rgxConcat(tokens: t.RGXToken[], groupWrap?: boolean): t.ValidRegexString;
2
+ export declare function rgxConcat(tokens: t.RGXToken[], groupWrap?: boolean, currentFlags?: string): t.ValidRegexString;
package/dist/concat.js CHANGED
@@ -3,6 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.rgxConcat = rgxConcat;
4
4
  const resolve_1 = require("./resolve");
5
5
  // Wrapper for letting an array of tokens be resolved as a concatenation instead of a union.
6
- function rgxConcat(tokens, groupWrap = true) {
7
- return tokens.map(t => (0, resolve_1.resolveRGXToken)(t, groupWrap)).join('');
6
+ function rgxConcat(tokens, groupWrap = true, currentFlags = '') {
7
+ return tokens.map(t => (0, resolve_1.resolveRGXToken)(t, groupWrap, true, currentFlags)).join('');
8
8
  }
package/dist/index.d.ts CHANGED
@@ -10,5 +10,6 @@ export * from "./concat";
10
10
  export * from "./utils";
11
11
  export * from "./ExtRegExp";
12
12
  export * from "./flag-transformer";
13
+ export * from "./clone";
13
14
  export declare function rgxa(tokens: t.RGXToken[], flags?: string): ExtRegExp;
14
15
  export default function rgx(flags?: string): (strings: TemplateStringsArray, ...tokens: t.RGXToken[]) => ExtRegExp;
package/dist/index.js CHANGED
@@ -31,13 +31,14 @@ __exportStar(require("./concat"), exports);
31
31
  __exportStar(require("./utils"), exports);
32
32
  __exportStar(require("./ExtRegExp"), exports);
33
33
  __exportStar(require("./flag-transformer"), exports);
34
+ __exportStar(require("./clone"), exports);
34
35
  // Call this for certain class methods to work correctly
35
36
  (0, class_1.rgxClassInit)();
36
37
  // Call this for our custom flags to work correctly
37
38
  (0, flag_transformer_1.registerCustomFlagTransformers)();
38
39
  function rgxa(tokens, flags = '') {
39
40
  (0, ExtRegExp_1.assertValidRegexFlags)(flags);
40
- const pattern = (0, concat_1.rgxConcat)(tokens);
41
+ const pattern = (0, concat_1.rgxConcat)(tokens, true, flags);
41
42
  return (0, ExtRegExp_1.extRegExp)(pattern, flags);
42
43
  }
43
44
  function rgx(flags = '') {
package/dist/resolve.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import * as t from "./types";
2
2
  export declare function escapeRegex(value: string): t.ValidRegexString;
3
- export declare function resolveRGXToken(token: t.RGXToken, groupWrap?: boolean, topLevel?: boolean): t.ValidRegexString;
3
+ export declare function resolveRGXToken(token: t.RGXToken, groupWrap?: boolean, topLevel?: boolean, currentFlags?: string): t.ValidRegexString;
package/dist/resolve.js CHANGED
@@ -41,21 +41,42 @@ const tg = __importStar(require("./typeGuards"));
41
41
  function escapeRegex(value) {
42
42
  return value.replaceAll(/[\-\^\$.*+?^${}()|[\]\\]/g, '\\$&');
43
43
  }
44
- function resolveRGXToken(token, groupWrap = true, topLevel = true) {
44
+ function localizableVanillaRegexFlagDiff(prev, next) {
45
+ // Remove anything other than the "ims" flags from both strings, as
46
+ // other flags are not localizable (including our custom flags).
47
+ prev = prev.replaceAll(/[^ims]/g, '');
48
+ next = next.replaceAll(/[^ims]/g, '');
49
+ // Format <added flags>-<removed flags>
50
+ const added = [...new Set(next.split(''))].filter(flag => !prev.includes(flag)).join('');
51
+ const removed = [...new Set(prev.split(''))].filter(flag => !next.includes(flag)).join('');
52
+ if (added === '' && removed === '')
53
+ return '';
54
+ if (removed === '')
55
+ return `${added}`;
56
+ return `${added}-${removed}`;
57
+ }
58
+ function resolveRGXToken(token, groupWrap = true, topLevel = true, currentFlags = '') {
45
59
  if (tg.isRGXNoOpToken(token))
46
60
  return '';
47
61
  if (tg.isRGXLiteralToken(token)) {
48
- if (groupWrap)
49
- return '(?:' + token.source + ')';
50
- else
51
- return token.source;
62
+ const localizableFlagDiff = localizableVanillaRegexFlagDiff(currentFlags, token.flags);
63
+ currentFlags = token.flags;
64
+ if (!localizableFlagDiff) {
65
+ if (groupWrap)
66
+ return '(?:' + token.source + ')';
67
+ else
68
+ return token.source;
69
+ }
70
+ else {
71
+ return `(?${localizableFlagDiff}:${token.source})`;
72
+ }
52
73
  }
53
74
  if (tg.isRGXNativeToken(token))
54
75
  return escapeRegex(String(token));
55
76
  if (tg.isRGXConvertibleToken(token)) {
56
77
  // The top-level group-wrapping preference propogates to a direct convertible token, but after that
57
78
  // the preference falls back to true whenever a token doesn't explicitly specify a preference.
58
- return resolveRGXToken(token.toRgx(), token.rgxGroupWrap ?? (topLevel ? groupWrap : true), false);
79
+ return resolveRGXToken(token.toRgx(), token.rgxGroupWrap ?? (topLevel ? groupWrap : true), false, currentFlags);
59
80
  }
60
81
  // Interpret arrays as unions
61
82
  if (tg.isRGXArrayToken(token, false)) {
@@ -66,11 +87,11 @@ function resolveRGXToken(token, groupWrap = true, topLevel = true) {
66
87
  token = [...(0, class_1.removeRgxUnionDuplicates)(...token)];
67
88
  // Don't preserve group wrapping preference for the recursive calls
68
89
  if (groupWrap)
69
- return '(?:' + token.map(t => resolveRGXToken(t, true, false)).join('|') + ')';
90
+ return '(?:' + token.map(t => resolveRGXToken(t, true, false, currentFlags)).join('|') + ')';
70
91
  else
71
- return token.map(t => resolveRGXToken(t, true, false)).join('|');
92
+ return token.map(t => resolveRGXToken(t, true, false, currentFlags)).join('|');
72
93
  }
73
- return resolveRGXToken(token[0]);
94
+ return resolveRGXToken(token[0], true, false, currentFlags);
74
95
  }
75
96
  // Ignoring this line since it should be impossible to reach if the types are correct, but we need it to satisfy the return type
76
97
  /* istanbul ignore next */
@@ -223,7 +223,7 @@ function assertValidRegexString(value) {
223
223
  }
224
224
  }
225
225
  function isValidVanillaRegexFlags(value) {
226
- const patternMatch = /^[gimsuy]*$/.test(value);
226
+ const patternMatch = /^[gimsuydv]*$/.test(value);
227
227
  if (!patternMatch)
228
228
  return false;
229
229
  // No repeated flags allowed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptolemy2002/rgx",
3
- "version": "4.8.0",
3
+ "version": "4.11.0",
4
4
  "private": false,
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",