@flex-development/ext-regex
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

ext-regex

github release npm codecov module type: esm license conventional commits typescript vitest yarn

File extension regex

Contents

What is this?

This package exports regular expressions suitable for matching file extensions. It also provides a regular expression factory function to create file extension expressions.

When should I use this?

Regular expressions exported from this package can be used to test both file extensions and names. A factory function is also exported that can be used to create a regular expression for any given file extension.

Note:

  • Expressions are ECMAScript-compatible. They have not been tested with other flavors (PCRE, PCRE2, etc)

Install

This package is ESM only.

yarn add @flex-development/ext-regex

From Git:

yarn add @flex-development/ext-regex@flex-development/ext-regex
See Git - Protocols | Yarn  for details on requesting a specific branch, commit, or tag.

Use

import { DECORATOR_REGEX } from '@flex-development/ext-regex'
import { EXT_DTS_REGEX, EXT_TS_REGEX } from '@flex-development/ext-regex'
import * as mlly from '@flex-development/mlly'
import pathe from '@flex-development/pathe'
import * as tscu from '@flex-development/tsconfig-utils'
import type { Nullable } from '@flex-development/tutils'
import type {
  OnLoadArgs,
  OnLoadOptions,
  OnLoadResult,
  Plugin,
  PluginBuild
} from 'esbuild'
import type { URL } from 'node:url'

/**
 * Returns a plugin that allows esbuild to handle [`emitDecoratorMetadata`][1].
 *
 * [1]: https://www.typescriptlang.org/tsconfig#emitDecoratorMetadata
 *
 * @param {tscu.LoadTsconfigOptions?} [options] - Plugin options
 * @return {Plugin} Decorator metadata plugin
 */
const plugin = (options?: tscu.LoadTsconfigOptions): Plugin => ({
  name: 'decorators',
  setup: async ({ initialOptions, onLoad }: PluginBuild): Promise<void> => {
    const { absWorkingDir = '.', tsconfig = 'tsconfig.json' } = initialOptions

    /**
     * User compiler options.
     *
     * @const {tscu.CompilerOptions} compilerOptions
     */
    const compilerOptions: tscu.CompilerOptions = tscu.loadCompilerOptions(
      pathe.resolve(absWorkingDir, tsconfig),
      options
    )

    // exit early if decorator metadata should not be emitted
    if (!compilerOptions.emitDecoratorMetadata) return void 0

    /**
     * TypeScript module.
     *
     * @const {typeof import('typescript')} ts
     */
    const ts: typeof import('typescript') = (await import('typescript')).default

    /**
     * {@linkcode onLoad} callback options.
     *
     * @const {OnLoadOptions}
     */
    const opts: OnLoadOptions = { filter: /.*/ }

    // transpile typescript modules containing decorators
    onLoad(opts, async (args: OnLoadArgs): Promise<Nullable<OnLoadResult>> => {
      /**
       * Callback result.
       *
       * @var {Nullable<OnLoadResult>} result
       */
      let result: Nullable<OnLoadResult> = null

      // transpile typescript modules, but skip typescript declaration modules
      if (EXT_TS_REGEX.test(args.path) && !EXT_DTS_REGEX.test(args.path)) {
        /**
         * URL of module to load.
         *
         * @const {URL} url
         */
        const url: URL = mlly.toURL(args.path)

        /**
         * File content at {@linkcode args.path}.
         *
         * @const {string} source
         */
        const source: string = (await mlly.getSource(url)) as string

        // do nothing if module does not use decorators
        if (!DECORATOR_REGEX.test(source)) return null

        // transpile module to emit decorator metadata
        const { outputText: contents } = ts.transpileModule(source, {
          compilerOptions: tscu.normalizeCompilerOptions(compilerOptions)
        })

        result = { contents }
      }

      return result
    })

    return void 0
  }
})

export default plugin
Looking for a plugin like this? Check out  mkbuild 😉

API

This package exports the following identifiers:

There is no default export.

EXT_DTS_REGEX

TypeScript declaration file extension regex.

Supported extensions:

  • .d.cts
  • .d.mts
  • .d.ts

Named capturing groups:

  • type: Letter between '.' and 'ts' in file extension

Source

src/regex/dts.ts

EXT_JS_REGEX

JavaScript file extension regex.

Supported extensions:

  • .cjs
  • .js
  • .jsx
  • .mjs

Named capturing groups:

  • type: Letter between '.' and 'js' in file extension

Source

src/regex/js.ts

EXT_JSON_REGEX

JSON file extension regex.

Supported extensions:

  • .json
  • .json5
  • .jsonc

Named capturing groups:

  • type: Character after 'json' in file extension

Source

src/regex/json.ts

EXT_TS_REGEX

TypeScript file extension regex.

Supported extensions:

  • .cts
  • .d.cts
  • .d.mts
  • .d.ts
  • .mts
  • .ts
  • .tsx

Named capturing groups:

Source

src/regex/ts.ts

extRegex(ext[, options])

Creates a regular expression matching the given file extension, ext.

The file extension does not need to begin with a dot character ('.'). If it doesn't, however, it will be formatted before being converted into a regular expression pattern. The returned regular expression will match the formatted file extension instead.

Parameters

  • {string} ext — File extension to evaluate
  • {Options?} [options] — Regular expression options

Returns

{RegExp} Regular expression matching ext.

Throws

{errnode.NodeError<TypeError>} If ext is not a string.

Source

src/utils/ext-regex.ts

Types

This package is fully typed with TypeScript.

Interfaces

Related

Contribute

See CONTRIBUTING.md.

Package Sidebar

Install

npm i @flex-development/ext-regex

Weekly Downloads

0

Version

2.0.0

License

BSD-3-Clause

Unpacked Size

61.5 kB

Total Files

50

Last publish

Collaborators

  • unicornware