@ptolemy2002/regex-utils 1.2.0 → 2.0.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
@@ -2,13 +2,26 @@
2
2
  This library contains utilities that are useful when working with JavaScript regular expressions.
3
3
 
4
4
  The functions are not exported as default, so you can import them in one of the following ways:
5
- ```
5
+ ```javascript
6
6
  // ES6
7
7
  import { functionName } from '@ptolemy2002/regex-utils';
8
8
  // CommonJS
9
9
  const { functionName } = require('@ptolemy2002/regex-utils');
10
10
  ```
11
11
 
12
+ ## Type Reference
13
+ ```typescript
14
+ type RegexInput = string | RegExp;
15
+ type TransformRegexOptions = {
16
+ flags?: string;
17
+ caseInsensitive?: boolean;
18
+ accentInsensitive?: boolean;
19
+ matchWhole?: boolean;
20
+ };
21
+ export type ZodValidator<O> = (v: O) => boolean;
22
+ export type ZodValidatorWithErrors<O> = (v: O) => true | string | string[];
23
+ ```
24
+
12
25
  ## Functions
13
26
  The following functions are available in the library:
14
27
 
@@ -17,18 +30,18 @@ The following functions are available in the library:
17
30
  Combines two sets of flags into one string. If a flag is present in both sets, it will only appear once in the result.
18
31
 
19
32
  #### Parameters
20
- - `...flags` (`String[]`): The sets of flags to be combined. Falsey values will be ignored.
33
+ - `...flags` (`string[]`): The sets of flags to be combined. Falsey values will be ignored.
21
34
 
22
35
  #### Returns
23
- `String` - The combined flags.
36
+ `string` - The combined flags.
24
37
 
25
38
  ### escapeRegex
26
39
  #### Description
27
- Escapes a string so that it can be used as a literal in a regular expression. If spefifying a `RegExp` object, the flags are added after transforming the source to a literal.
40
+ Escapes a value so that it can be used as a literal in a regular expression. If spefifying a `RegExp` object, the flags are added after transforming the source to a literal.
28
41
 
29
42
  #### Parameters
30
- - `value` (`String | RegExp`): The value to be escaped.
31
- - `flags` (`String`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
43
+ - `value` (`RegexInput`): The value to be escaped.
44
+ - `flags` (`string`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
32
45
 
33
46
  #### Returns
34
47
  `RegExp` - The escaped regular expression.
@@ -38,8 +51,8 @@ Escapes a string so that it can be used as a literal in a regular expression. If
38
51
  Attempts to transform a `RegExp` object to be accent insensitive. Note that this is done using a static list of common characters and their accented versions, so it is not perfect.
39
52
 
40
53
  #### Parameters
41
- - `value` (`String | RegExp`): The value to be transformed to be accent insensitive.
42
- - `flags` (`String`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
54
+ - `value` (`RegexInput`): The value to be transformed to be accent insensitive.
55
+ - `flags` (`string`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
43
56
 
44
57
  #### Returns
45
58
  `RegExp` - The accent insensitive regular expression.
@@ -49,18 +62,18 @@ Attempts to transform a `RegExp` object to be accent insensitive. Note that this
49
62
  Attempts to remove accents from a string. Note that this is done using a static list of common characters and their accented versions, so it is not perfect.
50
63
 
51
64
  #### Parameters
52
- - `value` (`String`): The value to be transformed to remove accents.
65
+ - `value` (`string`): The value to be transformed to remove accents.
53
66
 
54
67
  #### Returns
55
- `String` - The string with accents removed.
68
+ `string` - The string with accents removed.
56
69
 
57
70
  ### regexCaseInsensitive
58
71
  #### Description
59
72
  Transforms a `RegExp` object to be case insensitive by adding the `i` flag.
60
73
 
61
74
  #### Parameters
62
- - `value` (`String | RegExp`): The value to be transformed to be case insensitive.
63
- - `flags` (`String`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
75
+ - `value` (`RegexInput`): The value to be transformed to be case insensitive.
76
+ - `flags` (`string`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
64
77
 
65
78
  #### Returns
66
79
  `RegExp` - The case insensitive regular expression.
@@ -70,8 +83,11 @@ Transforms a `RegExp` object to be case insensitive by adding the `i` flag.
70
83
  Transforms a `RegExp` object to match the whole string by adding `^` and `$` to the beginning and end of the source, respectively.
71
84
 
72
85
  #### Parameters
73
- - `value` (`String | RegExp`): The value to be transformed to match the whole string.
74
- - `flags` (`String`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
86
+ - `value` (`RegexInput`): The value to be transformed to match the whole string.
87
+ - `flags` (`string`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
88
+
89
+ #### Returns
90
+ `RegExp` - The regular expression that matches the whole string.
75
91
 
76
92
  ### transformRegex
77
93
  #### Description
@@ -79,11 +95,11 @@ This function is a quick way to apply multiple supported transformations to a re
79
95
 
80
96
  #### Parameters
81
97
  - `value` (`String | RegExp`): The value to be transformed.
82
- - `args` (`Object`): Used to specify optional arguments.
83
- - `accentInsensitive` (`Boolean`): Whether to make the regular expression accent insensitive. Default is `false`.
84
- - `caseInsensitive` (`Boolean`): Whether to make the regular expression case insensitive. Default is `false`.
85
- - `matchWhole` (`Boolean`): Whether to make the regular expression match the whole string. Default is `false`.
86
- - `flags` (`String`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
98
+ - `args` (`TransformRegexOptions`): Used to specify optional arguments.
99
+ - `accentInsensitive` (`boolean`): Whether to make the regular expression accent insensitive. Default is `false`.
100
+ - `caseInsensitive` (`boolean`): Whether to make the regular expression case insensitive. Default is `false`.
101
+ - `matchWhole` (`boolean`): Whether to make the regular expression match the whole string. Default is `false`.
102
+ - `flags` (`string`): The flags to be used in the regular expression. If a `RegExp` object is passed, these flags will be added to the existing flags.
87
103
 
88
104
  #### Returns
89
105
  `RegExp` - The transformed regular expression.
@@ -93,99 +109,102 @@ This function is a quick way to apply multiple supported transformations to a re
93
109
  Checks if a string is a valid regular expression by attempting to create a `RegExp` object with it.
94
110
 
95
111
  #### Parameters
96
- - `value` (`String`): The value to be checked.
97
- - `flags` (`String`): The flags to be used in the regular expression.
112
+ - `value` (`string`): The value to be checked.
113
+ - `flags` (`string`): The flags to be used in the regular expression.
98
114
 
99
115
  #### Returns
100
- `Boolean` - `true` if the string is a valid regular expression, `false` otherwise.
116
+ `boolean` - `true` if the string is a valid regular expression, `false` otherwise.
101
117
 
102
118
  ### isValidRegexFlags
103
119
  #### Description
104
120
  Checks if a string is a valid set of regular expression flags.
105
121
 
106
122
  #### Parameters
107
- - `value` (`String`): The value to be checked.
123
+ - `value` (`string`): The value to be checked.
108
124
 
109
125
  #### Returns
110
- `Boolean` - `true` if the string is a valid set of regular expression flags, `false` otherwise.
126
+ `boolean` - `true` if the string is a valid set of regular expression flags, `false` otherwise.
111
127
 
112
- ### zodValidate
128
+ ### zodValidate<O>
113
129
  #### Description
114
- This is a simple function that takes a zod schema, returning a function that takes a value. If the value matches, the function returns `true`. Otherwise, it returns whatever error message the zod schema provides by default, or `false` if the `returnError` flag is disabled.
130
+ This is a simple function that takes a zod schema, returning a function that takes a value. If the value matches, the function returns `true`. Otherwise, it returns `false`. `O` refers to the output type of the zod schema, which should be the same as its input type.
115
131
 
116
132
  #### Parameters
117
- - `p` (`ZodSchema`): The zod schema to be used for validation.
118
- - `returnError` (`Boolean`): Whether to return the error message if the value does not match the schema. Default is `true`. If `false`, the function will return `false` on failure instead.
133
+ - `p` (`ZodSchema<O>`): The zod schema to be used for validation.
119
134
 
120
135
  #### Returns
121
- `Function` - A function that takes a value and returns `true` if the value matches the schema, an error message if the value does not match the schema and `returnError` is `true`, or `false` if the value does not match the schema and `returnError` is `false`.
136
+ `ZodValidator<O>` - A function that takes a value and returns `true` if the value matches the schema, `false` otherwise.
137
+
138
+ ### zodValidateWithErrors<O>
139
+ #### Description
140
+ This is a simple function that takes a zod schema, returning a function that takes a value. If the value matches, the function returns `true`. Otherwise, it returns a single error message or an array of error messages if there are multiple errors. `O` refers to the output type of the zod schema, which should be the same as its input type.
141
+
142
+ #### Parameters
143
+ - `p` (`ZodSchema<O>`): The zod schema to be used for validation.
122
144
 
123
145
  #### Returns
124
- `Function` - A function that takes a value and returns `true` if the value matches the schema, or an error message otherwise.
146
+ `ZodValidatorWithErrors<O>` - A function that takes a value and returns `true` if the value matches the schema, an error message if there is a single error, or an array of error messages if there are multiple errors.
125
147
 
126
148
  ### isAlphanumeric
127
149
  #### Description
128
150
  Uses `zodValidate` to check if a string is alphanumeric, that is, if it only contains letters, numbers, dashes, and underscores. Empty strings are not considered alphanumeric.
129
151
 
130
152
  #### Parameters
131
- - `str` (`String`): The value to be checked.
153
+ - `str` (`string`): The value to be checked.
132
154
 
133
155
  #### Returns
134
- `Boolean` - `true` if the string is alphanumeric, `false` otherwise.
156
+ `boolean` - `true` if the string is alphanumeric, `false` otherwise.
135
157
 
136
158
  ### toAlphanumeric
137
159
  #### Description
138
160
  Transforms a string to be alphanumeric by removing accents, separating it by non-alphanumeric segments, and then joining the words with the specified `separator`.
139
161
 
140
162
  #### Parameters
141
- - `str` (`String`): The value to be transformed.
142
- - `separator` (`String`): The separator to be used between words. Default is `'-'`.
163
+ - `str` (`string`): The value to be transformed.
164
+ - `separator` (`string`): The separator to be used between words. Default is `'-'`.
143
165
 
144
166
  #### Returns
145
- `String` - The transformed string.
167
+ `string` - The transformed string.
146
168
 
147
169
  ### isValidEmail
148
170
  #### Description
149
171
  Uses `zodValidate` to check if a string is a valid email address. Note that this is a simple check and may not cover all cases, but it should be good enough for most purposes.
150
172
 
151
173
  #### Parameters
152
- - `value` (`String`): The value to be checked.
174
+ - `value` (`string`): The value to be checked.
153
175
 
154
176
  #### Returns
155
- `Boolean` - `true` if the string is a valid email address, `false` otherwise.
177
+ `boolean` - `true` if the string is a valid email address, `false` otherwise.
156
178
 
157
179
  ### isValidPhoneNumber
158
180
  #### Description
159
181
  Uses `zodValidate` to check if a string is a valid phone number. Note that this is a simple check and may not cover all cases, but it should be good enough for most purposes.
160
182
 
161
183
  #### Parameters
162
- - `value` (`String`): The value to be checked.
184
+ - `value` (`string`): The value to be checked.
163
185
 
164
186
  #### Returns
165
- `Boolean` - `true` if the string is a valid phone number, `false` otherwise.
187
+ `boolean` - `true` if the string is a valid phone number, `false` otherwise.
166
188
 
167
189
  ### isValidURL
168
190
  #### Description
169
191
  Uses `zodValidate` to check if a string is a valid URL. Note that this is a simple check and may not cover all cases, but it should be good enough for most purposes.
170
192
 
171
193
  #### Parameters
172
- - `value` (`String`): The value to be checked.
194
+ - `value` (`string`): The value to be checked.
173
195
 
174
196
  #### Returns
175
- `Boolean` - `true` if the string is a valid URL, `false` otherwise.
197
+ `boolean` - `true` if the string is a valid URL, `false` otherwise.
176
198
 
177
199
  ### isValidSSN
178
200
  #### Description
179
201
  Uses `zodValidate` to check if a string is a valid Social Security Number (SSN). Note that this is a simple check and may not cover all cases, but it should be good enough for most purposes.
180
202
 
181
203
  #### Parameters
182
- - `value` (`String`): The value to be checked.
204
+ - `value` (`string`): The value to be checked.
183
205
 
184
206
  #### Returns
185
- `Boolean` - `true` if the string is a valid SSN, `false` otherwise.
186
-
187
- ## Meta
188
- This is a React Library Created by Ptolemy2002's [cra-template-react-library](https://www.npmjs.com/package/@ptolemy2002/cra-template-react-library) template in combination with [create-react-app](https://www.npmjs.com/package/create-react-app). However, it does not actually depend on React - it has been modified to work out of the box. It contains methods of building and publishing your library to npm.
207
+ `boolean` - `true` if the string is a valid SSN, `false` otherwise.
189
208
 
190
209
  ## Peer Dependencies
191
210
  These should be installed in order to use the library, as npm does not automatically add peer dependencies to your project.
@@ -0,0 +1,27 @@
1
+ import { ZodSchema } from "zod";
2
+ export type RegexInput = string | RegExp;
3
+ export declare function combineFlags(...flags: string[]): string;
4
+ export declare function escapeRegex(value: RegexInput, flags?: string): RegExp;
5
+ export declare function regexAccentInsensitive(value: RegexInput, flags?: string): RegExp;
6
+ export declare function removeAccents(value: string): string;
7
+ export declare function regexCaseInsensitive(value: RegexInput, flags?: string): RegExp;
8
+ export declare function regexMatchWhole(value: RegexInput, flags?: string): RegExp;
9
+ export type TransformRegexOptions = {
10
+ flags?: string;
11
+ caseInsensitive?: boolean;
12
+ accentInsensitive?: boolean;
13
+ matchWhole?: boolean;
14
+ };
15
+ export declare function transformRegex(value: RegexInput, { flags, accentInsensitive, caseInsensitive, matchWhole }: TransformRegexOptions): RegExp;
16
+ export declare function isValidRegex(value: string, flags?: string): boolean;
17
+ export declare function isValidRegexFlags(value: string): boolean;
18
+ export type ZodValidator<O> = (v: O) => boolean;
19
+ export type ZodValidatorWithErrors<O> = (v: O) => true | string | string[];
20
+ export declare function zodValidate<O>(p: ZodSchema<O>): ZodValidator<O>;
21
+ export declare function zodValidateWithErrors<O>(p: ZodSchema<O>): ZodValidatorWithErrors<O>;
22
+ export declare function isAlphanumeric(str: string): boolean;
23
+ export declare function toAlphanumeric(str: string, separator?: string): string;
24
+ export declare function isValidEmail(v: string): boolean;
25
+ export declare function isValidURL(v: string): boolean;
26
+ export declare function isValidPhoneNumber(v: string): boolean;
27
+ export declare function isValidSSN(v: string): boolean;
package/dist/index.js ADDED
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.combineFlags = combineFlags;
4
+ exports.escapeRegex = escapeRegex;
5
+ exports.regexAccentInsensitive = regexAccentInsensitive;
6
+ exports.removeAccents = removeAccents;
7
+ exports.regexCaseInsensitive = regexCaseInsensitive;
8
+ exports.regexMatchWhole = regexMatchWhole;
9
+ exports.transformRegex = transformRegex;
10
+ exports.isValidRegex = isValidRegex;
11
+ exports.isValidRegexFlags = isValidRegexFlags;
12
+ exports.zodValidate = zodValidate;
13
+ exports.zodValidateWithErrors = zodValidateWithErrors;
14
+ exports.isAlphanumeric = isAlphanumeric;
15
+ exports.toAlphanumeric = toAlphanumeric;
16
+ exports.isValidEmail = isValidEmail;
17
+ exports.isValidURL = isValidURL;
18
+ exports.isValidPhoneNumber = isValidPhoneNumber;
19
+ exports.isValidSSN = isValidSSN;
20
+ const zod_1 = require("zod");
21
+ const accentPatterns = [
22
+ "(a|á|à|ä|â|ã)", "(A|Á|À|Ä|Â|Ã)",
23
+ "(e|é|è|ë|ê)", "(E|É|È|Ë|Ê)",
24
+ "(i|í|ì|ï|î)", "(I|Í|Ì|Ï|Î)",
25
+ "(o|ó|ò|ö|ô|õ)", "(O|Ó|Ò|Ö|Ô|Õ)",
26
+ "(u|ú|ù|ü|û)", "(U|Ú|Ù|Ü|Û)"
27
+ ];
28
+ function combineFlags(...flags) {
29
+ const result = new Set();
30
+ flags.forEach((flag) => {
31
+ if (flag) {
32
+ flag.split("").forEach((c) => {
33
+ if (!result.has(c))
34
+ result.add(c);
35
+ });
36
+ }
37
+ });
38
+ return [...result].join("");
39
+ }
40
+ function escapeRegex(value, flags = "") {
41
+ if (typeof value === 'string') {
42
+ return new RegExp(value.replaceAll(/[\-\^\$.*+?^${}()|[\]\\]/g, '\\$&'), flags);
43
+ }
44
+ else {
45
+ return escapeRegex(value.source, combineFlags(value.flags, flags));
46
+ }
47
+ }
48
+ function regexAccentInsensitive(value, flags = "") {
49
+ if (typeof value === 'string') {
50
+ let stringValue = value;
51
+ accentPatterns.forEach((pattern) => {
52
+ stringValue = stringValue.replaceAll(new RegExp(pattern, "g"), pattern);
53
+ });
54
+ return new RegExp(stringValue, flags);
55
+ }
56
+ else {
57
+ return regexAccentInsensitive(value.source, combineFlags(value.flags, flags));
58
+ }
59
+ }
60
+ function removeAccents(value) {
61
+ accentPatterns.forEach((pattern) => {
62
+ value = value.replaceAll(new RegExp(pattern, "g"), pattern[1]);
63
+ });
64
+ return value;
65
+ }
66
+ function regexCaseInsensitive(value, flags = "") {
67
+ if (typeof value === 'string') {
68
+ if (!flags.includes("i")) {
69
+ flags += "i";
70
+ }
71
+ return new RegExp(value, flags);
72
+ }
73
+ else {
74
+ return regexCaseInsensitive(value.source, combineFlags(value.flags, flags));
75
+ }
76
+ }
77
+ function regexMatchWhole(value, flags = "") {
78
+ if (typeof value === 'string') {
79
+ return new RegExp(`^${value}$`, flags);
80
+ }
81
+ else {
82
+ return regexMatchWhole(value.source, combineFlags(value.flags, flags));
83
+ }
84
+ }
85
+ function transformRegex(value, { flags = "", accentInsensitive = false, caseInsensitive = false, matchWhole = false }) {
86
+ if (accentInsensitive)
87
+ value = regexAccentInsensitive(value, flags);
88
+ if (caseInsensitive)
89
+ value = regexCaseInsensitive(value, flags);
90
+ if (matchWhole)
91
+ value = regexMatchWhole(value, flags);
92
+ if (typeof value === 'string') {
93
+ value = new RegExp(value, flags);
94
+ }
95
+ else {
96
+ value = new RegExp(value.source, combineFlags(value.flags, flags));
97
+ }
98
+ return value;
99
+ }
100
+ function isValidRegex(value, flags = "") {
101
+ try {
102
+ new RegExp(value, flags);
103
+ return true;
104
+ }
105
+ catch {
106
+ return false;
107
+ }
108
+ }
109
+ function isValidRegexFlags(value) {
110
+ return /^[gimsuy]*$/.test(value);
111
+ }
112
+ function zodValidate(p) {
113
+ return (v) => {
114
+ const result = p.safeParse(v);
115
+ return result.success;
116
+ };
117
+ }
118
+ function zodValidateWithErrors(p) {
119
+ return (v) => {
120
+ const result = p.safeParse(v);
121
+ if (result.success)
122
+ return true;
123
+ if (result.error.errors.length === 1)
124
+ return result.error.errors[0].message;
125
+ return result.error.errors.map((e) => e.message);
126
+ };
127
+ }
128
+ const alphanumericPattern = /[\w_-]+/i;
129
+ const nonAlphanumericPattern = /[^\w_-]+/i;
130
+ function isAlphanumeric(str) {
131
+ return zodValidate(zod_1.z.string().regex(transformRegex(alphanumericPattern, { matchWhole: true })))(str);
132
+ }
133
+ function toAlphanumeric(str, separator = "-") {
134
+ const globalNonAlphanumericPattern = transformRegex(nonAlphanumericPattern, { flags: "g" });
135
+ str = removeAccents(str);
136
+ const words = str.split(globalNonAlphanumericPattern);
137
+ return words.map((word) => {
138
+ return word.replaceAll(globalNonAlphanumericPattern, "");
139
+ }).filter((word) => word).join(separator);
140
+ }
141
+ function isValidEmail(v) {
142
+ return zodValidate(zod_1.z.string().email())(v);
143
+ }
144
+ function isValidURL(v) {
145
+ return zodValidate(zod_1.z.string().url())(v);
146
+ }
147
+ function isValidPhoneNumber(v) {
148
+ return zodValidate(zod_1.z.coerce.string().regex(/^\+?\d?\s*(\(\d{3}\)|\d{3})(\s*|-)\d{3}(\s*|-)\d{4}$/))(v);
149
+ }
150
+ function isValidSSN(v) {
151
+ return zodValidate(zod_1.z.coerce.string().regex(/^\d{3}-?\d{2}-?\d{4}$/))(v);
152
+ }
package/package.json CHANGED
@@ -1,12 +1,19 @@
1
1
  {
2
2
  "name": "@ptolemy2002/regex-utils",
3
- "version": "1.2.0",
4
- "main": "index.js",
3
+ "version": "2.0.0",
4
+ "private": false,
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
5
7
  "files": [
6
- "index.js"
8
+ "/dist"
7
9
  ],
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/Ptolemy2002/regex-utils",
13
+ "directory": "lib"
14
+ },
8
15
  "scripts": {
9
- "build": "esbuild src/index.js --bundle --format=cjs --outfile=index.js --loader:.js=jsx --external:zod",
16
+ "build": "tsc --project ./tsconfig.json",
10
17
  "postinstall": "npx typesync",
11
18
  "uninstall": "bash ./scripts/uninstall.sh",
12
19
  "reinstall": "bash ./scripts/reinstall.sh",
@@ -19,17 +26,10 @@
19
26
  "release-minor": "bash ./scripts/release.sh minor",
20
27
  "release-major": "bash ./scripts/release.sh major"
21
28
  },
22
- "repository": {
23
- "type": "git",
24
- "url": "https://github.com/Ptolemy2002/regex-utils",
25
- "directory": "lib"
29
+ "peerDependencies": {
30
+ "zod": "^3.23.8"
26
31
  },
27
- "description": "Utilities for working with regular expressions",
28
- "license": "ISC",
29
32
  "devDependencies": {
30
- "esbuild": "^0.23.0"
31
- },
32
- "peerDependencies": {
33
33
  "zod": "^3.23.8"
34
34
  }
35
35
  }
package/index.js DELETED
@@ -1,171 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
-
19
- // src/index.js
20
- var src_exports = {};
21
- __export(src_exports, {
22
- combineFlags: () => combineFlags,
23
- escapeRegex: () => escapeRegex,
24
- isAlphanumeric: () => isAlphanumeric,
25
- isValidEmail: () => isValidEmail,
26
- isValidPhoneNumber: () => isValidPhoneNumber,
27
- isValidRegex: () => isValidRegex,
28
- isValidRegexFlags: () => isValidRegexFlags,
29
- isValidSSN: () => isValidSSN,
30
- isValidURL: () => isValidURL,
31
- regexAccentInsensitive: () => regexAccentInsensitive,
32
- regexCaseInsensitive: () => regexCaseInsensitive,
33
- regexMatchWhole: () => regexMatchWhole,
34
- removeAccents: () => removeAccents,
35
- toAlphanumeric: () => toAlphanumeric,
36
- transformRegex: () => transformRegex,
37
- zodValidate: () => zodValidate
38
- });
39
- module.exports = __toCommonJS(src_exports);
40
- var import_zod = require("zod");
41
- var accentPatterns = [
42
- "(a|\xE1|\xE0|\xE4|\xE2|\xE3)",
43
- "(A|\xC1|\xC0|\xC4|\xC2|\xC3)",
44
- "(e|\xE9|\xE8|\xEB|\xEA)",
45
- "(E|\xC9|\xC8|\xCB|\xCA)",
46
- "(i|\xED|\xEC|\xEF|\xEE)",
47
- "(I|\xCD|\xCC|\xCF|\xCE)",
48
- "(o|\xF3|\xF2|\xF6|\xF4|\xF5)",
49
- "(O|\xD3|\xD2|\xD6|\xD4|\xD5)",
50
- "(u|\xFA|\xF9|\xFC|\xFB)",
51
- "(U|\xDA|\xD9|\xDC|\xDB)"
52
- ];
53
- function combineFlags(...flags) {
54
- const result = /* @__PURE__ */ new Set();
55
- flags.forEach((flag) => {
56
- if (flag) {
57
- flag.split("").forEach((c) => {
58
- if (!result.has(c)) result.add(c);
59
- });
60
- }
61
- });
62
- return [...result].join("");
63
- }
64
- function escapeRegex(value, flags = "") {
65
- if (typeof value === "string") {
66
- return new RegExp(value.replaceAll(/[\-\^\$.*+?^${}()|[\]\\]/g, "\\$&"), flags);
67
- } else if (value instanceof RegExp) {
68
- return escapeRegex(value.source, combineFlags(value.flags, flags));
69
- } else {
70
- throw new TypeError("Expected string or RegExp, got " + typeof value);
71
- }
72
- }
73
- function regexAccentInsensitive(value, flags = "") {
74
- if (typeof value === "string") {
75
- accentPatterns.forEach((pattern) => {
76
- value = value.replaceAll(new RegExp(pattern, "g"), pattern);
77
- });
78
- return new RegExp(value, flags);
79
- } else if (value instanceof RegExp) {
80
- return regexAccentInsensitive(value.source, combineFlags(value.flags, flags));
81
- } else {
82
- throw new TypeError("Expected string or RegExp, got " + typeof value);
83
- }
84
- }
85
- function removeAccents(value) {
86
- if (typeof value === "string") {
87
- accentPatterns.forEach((pattern) => {
88
- value = value.replaceAll(new RegExp(pattern, "g"), pattern[1]);
89
- });
90
- return value;
91
- } else {
92
- throw new TypeError("Expected string, got " + typeof value);
93
- }
94
- }
95
- function regexCaseInsensitive(value, flags = "") {
96
- if (typeof value === "string") {
97
- if (!flags.includes("i")) {
98
- flags += "i";
99
- }
100
- return new RegExp(value, flags);
101
- } else if (value instanceof RegExp) {
102
- return regexCaseInsensitive(value.source, combineFlags(value.flags, flags));
103
- } else {
104
- throw new TypeError("Expected string or RegExp, got " + typeof value);
105
- }
106
- }
107
- function regexMatchWhole(value, flags = "") {
108
- if (typeof value === "string") {
109
- return new RegExp(`^${value}$`, flags);
110
- } else if (value instanceof RegExp) {
111
- return regexMatchWhole(value.source, combineFlags(value.flags, flags));
112
- } else {
113
- throw new TypeError("Expected string or RegExp, got " + typeof value);
114
- }
115
- }
116
- function transformRegex(value, { flags = "", accentInsensitive = false, caseInsensitive = false, matchWhole = false }) {
117
- if (accentInsensitive) value = regexAccentInsensitive(value, flags);
118
- if (caseInsensitive) value = regexCaseInsensitive(value, flags);
119
- if (matchWhole) value = regexMatchWhole(value, flags);
120
- if (value instanceof RegExp) {
121
- value = new RegExp(value.source, combineFlags(value.flags, flags));
122
- } else {
123
- value = new RegExp(value, flags);
124
- }
125
- return value;
126
- }
127
- function isValidRegex(value, flags = "") {
128
- try {
129
- new RegExp(value, flags);
130
- return true;
131
- } catch {
132
- return false;
133
- }
134
- }
135
- function isValidRegexFlags(value) {
136
- return /^[gimsuy]*$/.test(value);
137
- }
138
- function zodValidate(p, returnError = true) {
139
- return (v) => {
140
- const result = p.safeParse(v);
141
- if (result.success) return true;
142
- if (!returnError) return false;
143
- if (result.error.errors.length === 1) return result.error.errors[0].message;
144
- return result.error.errors.map((e) => e.message);
145
- };
146
- }
147
- var alphanumericPattern = /[\w_-]+/i;
148
- var nonAlphanumericPattern = /[^\w_-]+/i;
149
- function isAlphanumeric(str) {
150
- return zodValidate(import_zod.z.string().regex(transformRegex(alphanumericPattern, { matchWhole: true })), false)(str);
151
- }
152
- function toAlphanumeric(str, separator = "-") {
153
- const globalNonAlphanumericPattern = transformRegex(nonAlphanumericPattern, { flags: "g" });
154
- str = removeAccents(str);
155
- const words = str.split(globalNonAlphanumericPattern);
156
- return words.map((word) => {
157
- return word.replaceAll(globalNonAlphanumericPattern, "");
158
- }).filter((word) => word).join(separator);
159
- }
160
- function isValidEmail(v) {
161
- return zodValidate(import_zod.z.string().email(), false)(v);
162
- }
163
- function isValidURL(v) {
164
- return zodValidate(import_zod.z.string().url(), false)(v);
165
- }
166
- function isValidPhoneNumber(v) {
167
- return zodValidate(import_zod.z.coerce.string().regex(/^\+?\d?\s*(\(\d{3}\)|\d{3})(\s*|-)\d{3}(\s*|-)\d{4}$/), false)(v);
168
- }
169
- function isValidSSN(v) {
170
- return zodValidate(import_zod.z.coerce.string().regex(/^\d{3}-?\d{2}-?\d{4}$/), false)(v);
171
- }