|
| 1 | +/** |
| 2 | + * @file Utilities - extRegex |
| 3 | + * @module ext-regex/utils/extRegex |
| 4 | + */ |
| 5 | + |
| 6 | +import type { Options } from '#src/interfaces' |
| 7 | +import * as internal from '#src/internal' |
| 8 | +import * as errnode from '@flex-development/errnode' |
| 9 | +import * as pathe from '@flex-development/pathe' |
| 10 | +import { isNIL, type LiteralUnion } from '@flex-development/tutils' |
| 11 | + |
| 12 | +/** |
| 13 | + * Creates a regular expression matching the given file extension, `ext`. |
| 14 | + * |
| 15 | + * The file extension need not begin with a dot character (`'.'`). |
| 16 | + * |
| 17 | + * Throws `ERR_INVALID_ARG_TYPE` if the given file extension is not a string. |
| 18 | + * |
| 19 | + * @see {@linkcode pathe.Ext} |
| 20 | + * @see {@linkcode errnode.ERR_INVALID_ARG_TYPE} |
| 21 | + * |
| 22 | + * @param {LiteralUnion<pathe.Ext, string>} ext - File extension to evaluate |
| 23 | + * @param {Options?} [options] - Regular expression options |
| 24 | + * @return {RegExp} Regular expression matching `ext` |
| 25 | + * @throws {errnode.NodeError<TypeError>} If `ext` is not a string |
| 26 | + */ |
| 27 | +const extRegex = ( |
| 28 | + ext: LiteralUnion<pathe.Ext, string>, |
| 29 | + options: Options = {} |
| 30 | +): RegExp => { |
| 31 | + const { flags } = options |
| 32 | + |
| 33 | + // ensure ext is a string |
| 34 | + internal.validateString(ext, 'ext') |
| 35 | + |
| 36 | + // ensure flags is a string if defined |
| 37 | + !isNIL(flags) && internal.validateString(flags, 'flags') |
| 38 | + |
| 39 | + /** |
| 40 | + * Regex pattern for {@linkcode ext}. |
| 41 | + * |
| 42 | + * Special characters are escaped. A backslash escape (`\\`) is used whenever |
| 43 | + * valid. A `\x2d` escape is used when the former would be disallowed by |
| 44 | + * stricter Unicode pattern grammar. |
| 45 | + * |
| 46 | + * @const {string} pattern |
| 47 | + */ |
| 48 | + const pattern: string = pathe |
| 49 | + .formatExt(ext.trim()) |
| 50 | + .replace(/[$()*+.?[\\\]^{|}]/g, '\\$&') |
| 51 | + .replace(/-/g, '\\x2d') |
| 52 | + |
| 53 | + return new RegExp(pattern + '(?=\\s*$)', flags?.trim()) |
| 54 | +} |
| 55 | + |
| 56 | +export default extRegex |
0 commit comments