locter 1.2.1 → 1.2.2

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/dist/index.mjs CHANGED
@@ -8,12 +8,13 @@ import createJITI from 'jiti';
8
8
  import { pathToFileURL } from 'node:url';
9
9
 
10
10
 
11
- import __cjs_url__ from 'url';
12
- import __cjs_path__ from 'path';
13
- import __cjs_mod__ from 'module';
14
- const __filename = __cjs_url__.fileURLToPath(import.meta.url);
15
- const __dirname = __cjs_path__.dirname(__filename);
16
- const require = __cjs_mod__.createRequire(import.meta.url);
11
+ // -- Shims --
12
+ import cjsUrl from 'url';
13
+ import cjsPath from 'path';
14
+ import cjsModule from 'module';
15
+ const __filename = cjsUrl.fileURLToPath(import.meta.url);
16
+ const __dirname = cjsPath.dirname(__filename);
17
+ const require = cjsModule.createRequire(import.meta.url);
17
18
  function hasOwnProperty(obj, prop) {
18
19
  return Object.prototype.hasOwnProperty.call(obj, prop);
19
20
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/utils/has-property.ts","../src/utils/object.ts","../src/utils/error.ts","../src/utils/file-name.ts","../src/utils/to-array.ts","../src/utils/file-path.ts","../src/locator/utils.ts","../src/locator/async.ts","../src/locator/sync.ts","../src/loader/built-in/conf/module.ts","../src/loader/built-in/module/utils.ts","../src/loader/built-in/module/module.ts","../src/loader/built-in/json/module.ts","../src/loader/constants.ts","../src/loader/module.ts","../src/loader/singleton.ts","../src/loader/helpers.ts"],"sourcesContent":["export function hasOwnProperty<X extends Record<string, any>, Y extends PropertyKey>(obj: X, prop: Y): obj is X & Record<Y, unknown> {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nexport function hasStringProperty<X extends Record<string, any>, Y extends PropertyKey>(obj: X, prop: Y): obj is X & Record<Y, string> {\n return hasOwnProperty(obj, prop) && typeof obj[prop] === 'string';\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport function isObject(item: unknown) : item is Record<string, any> {\n return (\n !!item &&\n typeof item === 'object' &&\n !Array.isArray(item)\n );\n}\n\nexport function isSafeObjectKey(key: string) : boolean {\n return key !== '__proto__' &&\n key !== 'prototype' &&\n key !== 'constructor';\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { hasOwnProperty } from './has-property';\nimport { isObject } from './object';\n\nexport function handleException(e: unknown) : void {\n if (e instanceof Error) {\n throw e;\n }\n\n const error = new Error('Can not process thrown exception.');\n\n if (isObject(e)) {\n if (\n hasOwnProperty(e, 'message') &&\n typeof e.message === 'string'\n ) {\n error.message = e.message;\n }\n\n if (\n hasOwnProperty(e, 'stack') &&\n typeof e.stack === 'string'\n ) {\n error.stack = e.stack;\n }\n }\n\n throw error;\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport path from 'node:path';\n\nexport function getFileNameExtension(\n input: string,\n allowed?: string[],\n) : string | undefined {\n const extension = path.extname(input);\n if (extension === '' || extension === '.') {\n return undefined;\n }\n\n if (\n typeof allowed === 'undefined' ||\n allowed.indexOf(extension) !== -1\n ) {\n return extension;\n }\n\n return undefined;\n}\n\nexport function removeFileNameExtension(\n input: string,\n extensions?: string[],\n) {\n const extension = getFileNameExtension(input, extensions);\n if (extension) {\n return input.substring(0, input.length - extension.length);\n }\n\n return input;\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport function toArray(input: string | string[]) : string[] {\n return Array.isArray(input) ? input : [input];\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\nimport path from 'node:path';\n\nexport function isFilePath(input: string) {\n const extension = path.extname(input);\n return extension && extension !== '';\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport path from 'node:path';\nimport { isObject, toArray } from '../utils';\nimport type { LocatorInfo, LocatorOptions } from './type';\n\nexport function buildLocatorOptions(options?: Partial<LocatorOptions>) : LocatorOptions {\n options = options || {};\n\n options.path = options.path || [];\n options.path = toArray(options.path);\n if (options.path.length === 0) {\n options.path.push(process.cwd());\n }\n\n options.ignore ??= [];\n\n return options as LocatorOptions;\n}\n\nexport function pathToLocatorInfo(\n input: string,\n skipResolve?: boolean,\n) : LocatorInfo {\n if (\n !skipResolve &&\n !path.isAbsolute(input)\n ) {\n input = path.resolve(process.cwd(), input);\n }\n\n const info = path.parse(input);\n\n return {\n path: info.dir.split('/').join(path.sep),\n name: info.name,\n extension: info.ext,\n };\n}\n\nexport function isLocatorInfo(\n input: unknown,\n) : input is LocatorInfo {\n return isObject(input) &&\n typeof input.path === 'string' &&\n typeof input.name === 'string' &&\n typeof input.extension === 'string';\n}\n\nexport function buildFilePath(input: LocatorInfo | string) {\n if (typeof input === 'string') {\n return input;\n }\n\n if (input.extension) {\n return path.join(input.path, input.name) + input.extension;\n }\n\n return path.join(input.path, input.name);\n}\n\nexport function buildFilePathWithoutExtension(input: LocatorInfo | string) {\n let info: LocatorInfo;\n\n if (typeof input === 'string') {\n info = pathToLocatorInfo(input);\n } else {\n info = input;\n }\n\n return path.join(info.path, info.name);\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { glob } from 'glob';\nimport type { LocatorInfo, LocatorOptions } from './type';\nimport { buildLocatorOptions, pathToLocatorInfo } from './utils';\n\nexport async function locateMany(\n pattern: string | string[],\n options?: Partial<LocatorOptions>,\n) : Promise<LocatorInfo[]> {\n options = buildLocatorOptions(options);\n\n const patterns = Array.isArray(pattern) ?\n pattern :\n [pattern];\n\n const items : LocatorInfo[] = [];\n\n for (let i = 0; i < patterns.length; i++) {\n for (let j = 0; j < (options as LocatorOptions).path.length; j++) {\n const files = await glob(patterns[i] as string, {\n absolute: true,\n cwd: (options as LocatorOptions).path[j],\n nodir: true,\n ignore: options.ignore,\n });\n\n for (let k = 0; k < files.length; k++) {\n items.push(pathToLocatorInfo(files[k] as string, true));\n }\n }\n }\n\n return items;\n}\n\nexport async function locate(\n pattern: string | string[],\n options?: Partial<LocatorOptions>,\n) : Promise<LocatorInfo | undefined> {\n options = buildLocatorOptions(options);\n\n const patterns = Array.isArray(pattern) ?\n pattern :\n [pattern];\n\n for (let i = 0; i < patterns.length; i++) {\n for (let j = 0; j < (options as LocatorOptions).path.length; j++) {\n const files = await glob(patterns[i] as string, {\n absolute: true,\n cwd: (options as LocatorOptions).path[j],\n nodir: true,\n ignore: options.ignore,\n });\n\n const element = files.shift();\n if (element) {\n return pathToLocatorInfo(element, true);\n }\n }\n }\n\n return undefined;\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { globSync } from 'glob';\nimport type { LocatorInfo, LocatorOptions } from './type';\nimport { buildLocatorOptions, pathToLocatorInfo } from './utils';\n\nexport function locateManySync(\n pattern: string | string[],\n options?: Partial<LocatorOptions>,\n) : LocatorInfo[] {\n options = buildLocatorOptions(options);\n\n const patterns = Array.isArray(pattern) ?\n pattern :\n [pattern];\n\n const items : LocatorInfo[] = [];\n\n for (let i = 0; i < patterns.length; i++) {\n for (let j = 0; j < (options as LocatorOptions).path.length; j++) {\n const files = globSync(patterns[i] as string, {\n absolute: true,\n cwd: (options as LocatorOptions).path[j],\n nodir: true,\n ignore: options.ignore,\n });\n\n for (let k = 0; k < files.length; k++) {\n items.push(pathToLocatorInfo(files[k] as string, true));\n }\n }\n }\n\n return items;\n}\n\nexport function locateSync(\n pattern: string | string[],\n options?: Partial<LocatorOptions>,\n) : LocatorInfo | undefined {\n options = buildLocatorOptions(options);\n\n const patterns = Array.isArray(pattern) ?\n pattern :\n [pattern];\n\n for (let i = 0; i < patterns.length; i++) {\n for (let j = 0; j < (options as LocatorOptions).path.length; j++) {\n const files = globSync(patterns[i] as string, {\n absolute: true,\n cwd: (options as LocatorOptions).path[j],\n nodir: true,\n ignore: options.ignore,\n });\n\n const element = files.shift();\n if (element) {\n return pathToLocatorInfo(element, true);\n }\n }\n }\n\n return undefined;\n}\n","/*\n * Copyright (c) 2022-2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n// Based on https://github.com/unjs/rc9 (MIT)\n\nimport { destr } from 'destr';\nimport flat from 'flat';\nimport fs from 'node:fs';\nimport { buildFilePath } from '../../../locator';\nimport { handleException, isSafeObjectKey } from '../../../utils';\nimport type { Loader } from '../../type';\n\nexport class ConfLoader implements Loader {\n async execute(input: string) {\n const filePath = buildFilePath(input);\n\n try {\n const file = await fs.promises.readFile(filePath, { encoding: 'utf-8' });\n\n return this.parse(file);\n } catch (e) {\n return handleException(e);\n }\n }\n\n executeSync(input: string) {\n const filePath = buildFilePath(input);\n\n try {\n const file = fs.readFileSync(filePath, { encoding: 'utf-8' });\n\n return this.parse(file);\n } catch (e) {\n return handleException(e);\n }\n }\n\n parse(contents: string): Record<string, any> {\n const config: Record<string, any> = {};\n\n const lines = contents.split(/\\n|\\r|\\r\\n/);\n\n for (let i = 0; i < lines.length; i++) {\n const match = lines[i].match(/^\\s*([^\\s=]+)\\s*=\\s*(.*)?\\s*$/);\n if (!match) {\n continue;\n }\n\n // Key\n const key = match[1];\n\n if (!key || !isSafeObjectKey(key)) {\n continue;\n }\n\n const value = destr(match[2].trim() /* val */);\n\n if (key.endsWith('[]')) {\n const arrKey = key.slice(0, Math.max(0, key.length - 2));\n config[arrKey] = (config[arrKey] || []).concat(value);\n continue;\n }\n\n config[key] = value;\n }\n\n return flat.unflatten(config, { overwrite: true });\n }\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { BaseError } from 'ebec';\nimport { hasOwnProperty, isObject } from '../../../utils';\nimport type { LoaderFilterFn, ModuleExport } from './type';\n\nexport function isJestRuntimeEnvironment() : boolean {\n return process.env &&\n process.env.JEST_WORKER_ID !== undefined;\n}\n\nexport function isTsNodeRuntimeEnvironment() : boolean {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return !!process[Symbol.for('ts-node.register.instance')];\n}\n\nexport function getModuleExport(\n data: Record<string, any>,\n filterFn?: LoaderFilterFn,\n): ModuleExport {\n if (filterFn) {\n const keys = Object.keys(data);\n for (let i = 0; i < keys.length; i++) {\n if (filterFn(keys[i] as string, data[keys[i] as string])) {\n return {\n key: keys[i] as string,\n value: data[keys[i] as string],\n };\n }\n }\n\n throw new BaseError('Cannot find specific module export.');\n }\n\n let value: any;\n\n if (\n hasOwnProperty(data, '__esModule') &&\n // eslint-disable-next-line no-underscore-dangle\n !!data.__esModule &&\n hasOwnProperty(data, 'default')\n ) {\n value = data.default;\n } else {\n value = data;\n }\n\n if (\n isObject(value) &&\n hasOwnProperty(value, 'default')\n ) {\n value = value.default;\n }\n\n return {\n key: 'default',\n value,\n };\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { BaseError } from 'ebec';\nimport type { JITI } from 'jiti';\nimport createJITI from 'jiti';\nimport { pathToFileURL } from 'node:url';\nimport type { LocatorInfo } from '../../../locator';\nimport {\n buildFilePath,\n buildFilePathWithoutExtension,\n isLocatorInfo,\n pathToLocatorInfo,\n} from '../../../locator';\nimport {\n handleException,\n hasStringProperty, isFilePath,\n isObject,\n} from '../../../utils';\nimport type { Loader } from '../../type';\nimport type { ModuleLoadOptions } from './type';\nimport { isJestRuntimeEnvironment, isTsNodeRuntimeEnvironment } from './utils';\n\nexport class ModuleLoader implements Loader {\n protected jiti : JITI;\n\n constructor() {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.jiti = createJITI(undefined, {\n extensions: ['.js', '.mjs', '.mts', '.cjs', '.cts', '.ts'],\n });\n }\n\n async execute(input: string) {\n let output : any;\n\n try {\n output = await this.load(input);\n } catch (e) {\n if (\n e instanceof SyntaxError ||\n e instanceof ReferenceError\n ) {\n throw e;\n }\n\n // jiti + ts-node\n // issue: https://github.com/nuxt/bridge/issues/228\n if (isTsNodeRuntimeEnvironment()) {\n output = this.loadSync(input);\n } else {\n output = this.jiti(input);\n }\n }\n\n return output;\n }\n\n executeSync(input: string) {\n let output : any;\n\n try {\n output = this.loadSync(input);\n } catch (e) {\n if (\n e instanceof SyntaxError ||\n e instanceof ReferenceError\n ) {\n throw e;\n }\n\n output = this.jiti(input);\n }\n\n return output;\n }\n\n // ---------------------------------------------------------------------------\n\n async load(\n data: LocatorInfo | string,\n options?: ModuleLoadOptions,\n ) : Promise<unknown> {\n options = options || {};\n const [name, locatorInfo] = this.build(data, options);\n\n try {\n // segmentation fault\n // issue: https://github.com/nodejs/node/issues/35889\n if (isJestRuntimeEnvironment()) {\n // eslint-disable-next-line global-require,import/no-dynamic-require\n return require(name);\n }\n\n return await import(name);\n } catch (e) {\n /* istanbul ignore next */\n if (\n isObject(e) &&\n hasStringProperty(e, 'code')\n ) {\n if (locatorInfo) {\n if (\n !options.withExtension &&\n (\n e.code === 'ERR_MODULE_NOT_FOUND' ||\n e.code === 'MODULE_NOT_FOUND'\n )\n ) {\n return this.load(locatorInfo, {\n ...options,\n withExtension: true,\n });\n }\n\n if (\n !options.withFilePrefix &&\n (\n e.code === 'ERR_UNSUPPORTED_ESM_URL_SCHEME' ||\n e.code === 'UNSUPPORTED_ESM_URL_SCHEME'\n )\n ) {\n return this.load(locatorInfo, {\n ...options,\n withExtension: true,\n withFilePrefix: true,\n });\n }\n }\n\n throw new BaseError({\n code: e.code,\n message: hasStringProperty(e, 'message') ? e.message : undefined,\n stack: hasStringProperty(e, 'stack') ? e.stack : undefined,\n });\n }\n\n /* istanbul ignore next */\n return handleException(e);\n }\n }\n\n loadSync(\n data: LocatorInfo | string,\n options?: ModuleLoadOptions,\n ) : unknown {\n options = options || {};\n const [name, locatorInfo] = this.build(data, options);\n\n try {\n // eslint-disable-next-line global-require,import/no-dynamic-require\n return require(name);\n } catch (e) {\n /* istanbul ignore next */\n if (\n isObject(e) &&\n hasStringProperty(e, 'code')\n ) {\n if (locatorInfo) {\n if (\n !options.withExtension &&\n (\n e.code === 'ERR_MODULE_NOT_FOUND' ||\n e.code === 'MODULE_NOT_FOUND'\n )\n ) {\n return this.loadSync(locatorInfo, {\n ...options,\n withExtension: true,\n });\n }\n }\n\n throw new BaseError({\n code: e.code,\n message: hasStringProperty(e, 'message') ? e.message : undefined,\n stack: hasStringProperty(e, 'stack') ? e.stack : undefined,\n });\n }\n\n return handleException(e);\n }\n }\n\n private build(\n data: LocatorInfo | string,\n options: ModuleLoadOptions,\n ) : [string, LocatorInfo | undefined] {\n let name : string;\n let locatorInfo : LocatorInfo | undefined;\n\n options = options || {};\n\n if (isLocatorInfo(data) || isFilePath(data)) {\n if (typeof data === 'string') {\n locatorInfo = pathToLocatorInfo(data);\n } else {\n locatorInfo = data;\n }\n\n if (options.withExtension) {\n name = buildFilePath(locatorInfo);\n } else {\n name = buildFilePathWithoutExtension(locatorInfo);\n }\n\n if (options.withFilePrefix) {\n name = pathToFileURL(name).href;\n }\n } else {\n name = data;\n }\n\n return [name, locatorInfo];\n }\n}\n","/*\n * Copyright (c) 2022-2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport fs from 'node:fs';\nimport { buildFilePath } from '../../../locator';\nimport { handleException } from '../../../utils';\nimport type { Loader } from '../../type';\n\nexport class JSONLoader implements Loader {\n async execute(input: string) {\n const filePath = buildFilePath(input);\n\n try {\n const file = await fs.promises.readFile(filePath, { encoding: 'utf-8' });\n return JSON.parse(file);\n } catch (e) {\n return handleException(e);\n }\n }\n\n executeSync(input: string) {\n const filePath = buildFilePath(input);\n\n try {\n const file = fs.readFileSync(filePath, { encoding: 'utf-8' });\n return JSON.parse(file);\n } catch (e) {\n return handleException(e);\n }\n }\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum LoaderId {\n MODULE = 'module',\n JSON = 'json',\n CONF = 'conf',\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport path from 'node:path';\nimport { buildFilePath, pathToLocatorInfo } from '../locator';\nimport { isFilePath } from '../utils';\nimport { ConfLoader, JSONLoader, ModuleLoader } from './built-in';\nimport { LoaderId } from './constants';\nimport type { Loader, Rule } from './type';\n\nexport class LoaderManager implements Loader {\n protected loaders : Record<string, Loader>;\n\n protected rules : Rule[];\n\n constructor() {\n this.loaders = {};\n this.rules = [\n {\n test: ['.js', '.mjs', '.mts', '.cjs', '.cts', '.ts'],\n loader: LoaderId.MODULE,\n },\n {\n test: ['.conf'], loader: LoaderId.CONF,\n },\n {\n test: ['.json'], loader: LoaderId.JSON,\n },\n ];\n }\n\n register(rule: Rule) : void;\n\n register(test: string[] | RegExp, loader: Loader) : void;\n\n register(test: any, loader?: Loader) : void {\n if (typeof loader !== 'undefined') {\n this.rules.push({ test, loader });\n return;\n }\n\n this.rules.push(test);\n }\n\n async execute(input: string) : Promise<any> {\n const id = this.findLoader(input);\n if (!id) {\n const info = pathToLocatorInfo(input);\n throw new Error(`No loader registered for extension: \"${info.extension}\"`);\n }\n\n const loader = this.resolve(id);\n return loader.execute(input);\n }\n\n executeSync(input: string) : any {\n const id = this.findLoader(input);\n if (!id) {\n const info = pathToLocatorInfo(input);\n throw new Error(`No loader registered for extension: ${info.extension || 'unknown'}`);\n }\n\n const loader = this.resolve(id);\n return loader.executeSync(input);\n }\n\n findLoader(input: string) : Loader | string | undefined {\n if (!isFilePath(input)) {\n return LoaderId.MODULE;\n }\n\n const info = pathToLocatorInfo(input);\n for (let i = 0; i < this.rules.length; i++) {\n const { test } = this.rules[i] as Rule;\n if (Array.isArray(test)) {\n if (test.indexOf(info.extension) !== -1) {\n return this.rules[i].loader;\n }\n } else if (test.test(buildFilePath(info))) {\n return this.rules[i].loader;\n }\n }\n\n return undefined;\n }\n\n /**\n * Resolve loader by id.\n *\n * @param id\n */\n resolve(id: string | Loader) : Loader {\n if (typeof id !== 'string') {\n return id;\n }\n\n if (Object.prototype.hasOwnProperty.call(this.loaders, id)) {\n return this.loaders[id] as Loader;\n }\n\n let loader : Loader | undefined;\n\n // built-in\n switch (id) {\n case LoaderId.CONF: {\n loader = new ConfLoader();\n break;\n }\n case LoaderId.MODULE: {\n loader = new ModuleLoader();\n break;\n }\n case LoaderId.JSON: {\n loader = new JSONLoader();\n break;\n }\n /* istanbul ignore next */\n default: {\n const pluginPath = this.normalizePath(id);\n const moduleLoader = this.resolve(LoaderId.MODULE);\n loader = moduleLoader.executeSync(pluginPath);\n\n break;\n }\n }\n\n if (typeof loader !== 'undefined') {\n this.loaders[id] = loader;\n\n return loader;\n }\n\n throw new Error(`The loader ${id} could not be resolved.`);\n }\n\n /* istanbul ignore next */\n normalizePath(input: string) {\n if (path.isAbsolute(input) || input.startsWith('./')) {\n return input;\n }\n\n if (input.startsWith('module:')) {\n return input.substring(0, 'module:'.length);\n }\n\n if (!input.startsWith('@')) {\n return `@locter/${input}`;\n }\n\n return input;\n }\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { LoaderManager } from './module';\n\nlet instance : LoaderManager;\nexport function useLoader() {\n if (typeof instance !== 'undefined') {\n return instance;\n }\n\n instance = new LoaderManager();\n\n return instance;\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { buildFilePath } from '../locator';\nimport type { LocatorInfo } from '../locator';\nimport { useLoader } from './singleton';\nimport type { Loader, Rule } from './type';\n\nexport function registerLoader(rule: Rule) : void;\nexport function registerLoader(test: string[] | RegExp, loader: Loader) : void;\nexport function registerLoader(test: any, loader?: Loader) : void {\n const manager = useLoader();\n if (typeof loader !== 'undefined') {\n manager.register(test, loader);\n\n return;\n }\n\n manager.register(test);\n}\n\nexport async function load(input: LocatorInfo | string) : Promise<any> {\n const manager = useLoader();\n if (typeof input === 'string') {\n return manager.execute(input);\n }\n\n return manager.execute(buildFilePath(input));\n}\n\nexport function loadSync(input: LocatorInfo | string) : any {\n const manager = useLoader();\n if (typeof input === 'string') {\n return manager.executeSync(input);\n }\n\n return manager.executeSync(buildFilePath(input));\n}\n"],"names":["input","options","name","extension","info","pattern","cwd","ignore","items","executeSync","parse","config","value","output","code","message","stack","locatorInfo","LoaderId","test","loader","findLoader","instance","manager"],"mappings":";;;;;;;;;;;;;;;;AAAO;AACH;AACJ;AAEO;AACH;AACJ;;ACNA;;;;;;;AAaA;AAEO;AACH;AAGJ;;ACTO;AACH;;AAEA;;AAIA;AACI;;AAKA;AAEA;;AAKA;AACJ;;AAGJ;;ACzBO;;;;AAOH;;;AAOA;;AAGJ;AAEO;;AAKH;;AAEA;;AAGJ;;ACtCA;;;;;;AAQI;AAAuCA;AAAM;AACjD;;ACDO;;AAEH;AACJ;;ACAO;AASHC;AARAA;AAEAA;AACAA;AACA;AACIA;AACJ;AAEAA;;AAGJ;AAEO;AAIH;AAIID;AACJ;;;;AAMIE;AACAC;AACJ;AACJ;AAEO;AAGH;AAIJ;AAEO;;;AAGH;;;AAIA;AAEA;AACJ;AAEO;;;AAICC;;;AAGJ;AAEA;AACJ;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;AACAC;AACAC;AACJ;AACJ;AAEA;AACJ;AACJ;;;;AASIf;;;AAIQgB;;;AAGJ;;AAGIf;;AAEAA;AACJ;;;AAIA;;;AAGJ;;AAEQA;AAAMe;AAAY;AAC9B;;;;AA1LI;;AACiB;AAAO;AAAQ;AAAQ;AAAQ;AAAQ;AAAM;AAC9D;AACJ;AAwLJ;;AChNO;;AAEC;;AAGI;;AAAsE;;AAE1E;AACI;AACJ;AACJ;AAEAR;AACI;;AAGI;;AAA2D;;AAE/D;AACI;AACJ;AACJ;AACJ;;AClCA;;;;;;;AAOYS;AAAAA;AAAAA;;;ACOL;;;AA2BK;AAAkBC;AAAMC;AAAO;AAC/B;AACJ;AAEA;AACJ;;AAGI;AACA;AACI;;AAEJ;AAEA;;AAEJ;AAEAX;AACI;AACA;AACI;;AAEJ;AAEA;;AAEJ;AAEAY;;AAEQ;AACJ;AAEA;;;;AAIQ;AACI;AACJ;AACJ;AACI;AACJ;AACJ;;AAGJ;AAEA;;;;;;;AAQI;;AAGI;AACJ;;;;AAMI;AAAoB;AAChBD;AACA;AACJ;AACA;AAAsB;AAClBA;AACA;AACJ;AACA;AAAoB;AAChBA;AACA;AACJ;AACA;AACS;AACL;AACA;;AAGA;AACJ;AACJ;;AAGI;;AAGJ;AAEA;AACJ;;AAII;;AAEA;;AAGI;AACJ;AAEA;AACI;AACJ;;AAGJ;;;;AApIQ;;AACW;AAAO;AAAQ;AAAQ;AAAQ;AAAQ;AAAM;AACpDA;AACJ;AACA;;AACW;AAAQ;AAAEA;AACrB;AACA;;AACW;AAAQ;AAAEA;AACrB;AACH;AACL;AA0HJ;;AClJA;AACO;;;AAGH;AAEAE;;AAGJ;;ACJO;AACH;;;AAII;AACJ;AAEAC;AACJ;AAEO;AACH;;;AAGA;;AAGJ;AAEO;AACH;;;AAGA;;AAGJ;;"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/utils/has-property.ts","../src/utils/object.ts","../src/utils/error.ts","../src/utils/file-name.ts","../src/utils/to-array.ts","../src/utils/file-path.ts","../src/locator/utils.ts","../src/locator/async.ts","../src/locator/sync.ts","../src/loader/built-in/conf/module.ts","../src/loader/built-in/module/utils.ts","../src/loader/built-in/module/module.ts","../src/loader/built-in/json/module.ts","../src/loader/constants.ts","../src/loader/module.ts","../src/loader/singleton.ts","../src/loader/helpers.ts"],"sourcesContent":["export function hasOwnProperty<X extends Record<string, any>, Y extends PropertyKey>(obj: X, prop: Y): obj is X & Record<Y, unknown> {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nexport function hasStringProperty<X extends Record<string, any>, Y extends PropertyKey>(obj: X, prop: Y): obj is X & Record<Y, string> {\n return hasOwnProperty(obj, prop) && typeof obj[prop] === 'string';\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport function isObject(item: unknown) : item is Record<string, any> {\n return (\n !!item &&\n typeof item === 'object' &&\n !Array.isArray(item)\n );\n}\n\nexport function isSafeObjectKey(key: string) : boolean {\n return key !== '__proto__' &&\n key !== 'prototype' &&\n key !== 'constructor';\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { hasOwnProperty } from './has-property';\nimport { isObject } from './object';\n\nexport function handleException(e: unknown) : void {\n if (e instanceof Error) {\n throw e;\n }\n\n const error = new Error('Can not process thrown exception.');\n\n if (isObject(e)) {\n if (\n hasOwnProperty(e, 'message') &&\n typeof e.message === 'string'\n ) {\n error.message = e.message;\n }\n\n if (\n hasOwnProperty(e, 'stack') &&\n typeof e.stack === 'string'\n ) {\n error.stack = e.stack;\n }\n }\n\n throw error;\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport path from 'node:path';\n\nexport function getFileNameExtension(\n input: string,\n allowed?: string[],\n) : string | undefined {\n const extension = path.extname(input);\n if (extension === '' || extension === '.') {\n return undefined;\n }\n\n if (\n typeof allowed === 'undefined' ||\n allowed.indexOf(extension) !== -1\n ) {\n return extension;\n }\n\n return undefined;\n}\n\nexport function removeFileNameExtension(\n input: string,\n extensions?: string[],\n) {\n const extension = getFileNameExtension(input, extensions);\n if (extension) {\n return input.substring(0, input.length - extension.length);\n }\n\n return input;\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport function toArray(input: string | string[]) : string[] {\n return Array.isArray(input) ? input : [input];\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\nimport path from 'node:path';\n\nexport function isFilePath(input: string) {\n const extension = path.extname(input);\n return extension && extension !== '';\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport path from 'node:path';\nimport { isObject, toArray } from '../utils';\nimport type { LocatorInfo, LocatorOptions } from './type';\n\nexport function buildLocatorOptions(options?: Partial<LocatorOptions>) : LocatorOptions {\n options = options || {};\n\n options.path = options.path || [];\n options.path = toArray(options.path);\n if (options.path.length === 0) {\n options.path.push(process.cwd());\n }\n\n options.ignore ??= [];\n\n return options as LocatorOptions;\n}\n\nexport function pathToLocatorInfo(\n input: string,\n skipResolve?: boolean,\n) : LocatorInfo {\n if (\n !skipResolve &&\n !path.isAbsolute(input)\n ) {\n input = path.resolve(process.cwd(), input);\n }\n\n const info = path.parse(input);\n\n return {\n path: info.dir.split('/').join(path.sep),\n name: info.name,\n extension: info.ext,\n };\n}\n\nexport function isLocatorInfo(\n input: unknown,\n) : input is LocatorInfo {\n return isObject(input) &&\n typeof input.path === 'string' &&\n typeof input.name === 'string' &&\n typeof input.extension === 'string';\n}\n\nexport function buildFilePath(input: LocatorInfo | string) {\n if (typeof input === 'string') {\n return input;\n }\n\n if (input.extension) {\n return path.join(input.path, input.name) + input.extension;\n }\n\n return path.join(input.path, input.name);\n}\n\nexport function buildFilePathWithoutExtension(input: LocatorInfo | string) {\n let info: LocatorInfo;\n\n if (typeof input === 'string') {\n info = pathToLocatorInfo(input);\n } else {\n info = input;\n }\n\n return path.join(info.path, info.name);\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { glob } from 'glob';\nimport type { LocatorInfo, LocatorOptions } from './type';\nimport { buildLocatorOptions, pathToLocatorInfo } from './utils';\n\nexport async function locateMany(\n pattern: string | string[],\n options?: Partial<LocatorOptions>,\n) : Promise<LocatorInfo[]> {\n options = buildLocatorOptions(options);\n\n const patterns = Array.isArray(pattern) ?\n pattern :\n [pattern];\n\n const items : LocatorInfo[] = [];\n\n for (let i = 0; i < patterns.length; i++) {\n for (let j = 0; j < (options as LocatorOptions).path.length; j++) {\n const files = await glob(patterns[i] as string, {\n absolute: true,\n cwd: (options as LocatorOptions).path[j],\n nodir: true,\n ignore: options.ignore,\n });\n\n for (let k = 0; k < files.length; k++) {\n items.push(pathToLocatorInfo(files[k] as string, true));\n }\n }\n }\n\n return items;\n}\n\nexport async function locate(\n pattern: string | string[],\n options?: Partial<LocatorOptions>,\n) : Promise<LocatorInfo | undefined> {\n options = buildLocatorOptions(options);\n\n const patterns = Array.isArray(pattern) ?\n pattern :\n [pattern];\n\n for (let i = 0; i < patterns.length; i++) {\n for (let j = 0; j < (options as LocatorOptions).path.length; j++) {\n const files = await glob(patterns[i] as string, {\n absolute: true,\n cwd: (options as LocatorOptions).path[j],\n nodir: true,\n ignore: options.ignore,\n });\n\n const element = files.shift();\n if (element) {\n return pathToLocatorInfo(element, true);\n }\n }\n }\n\n return undefined;\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { globSync } from 'glob';\nimport type { LocatorInfo, LocatorOptions } from './type';\nimport { buildLocatorOptions, pathToLocatorInfo } from './utils';\n\nexport function locateManySync(\n pattern: string | string[],\n options?: Partial<LocatorOptions>,\n) : LocatorInfo[] {\n options = buildLocatorOptions(options);\n\n const patterns = Array.isArray(pattern) ?\n pattern :\n [pattern];\n\n const items : LocatorInfo[] = [];\n\n for (let i = 0; i < patterns.length; i++) {\n for (let j = 0; j < (options as LocatorOptions).path.length; j++) {\n const files = globSync(patterns[i] as string, {\n absolute: true,\n cwd: (options as LocatorOptions).path[j],\n nodir: true,\n ignore: options.ignore,\n });\n\n for (let k = 0; k < files.length; k++) {\n items.push(pathToLocatorInfo(files[k] as string, true));\n }\n }\n }\n\n return items;\n}\n\nexport function locateSync(\n pattern: string | string[],\n options?: Partial<LocatorOptions>,\n) : LocatorInfo | undefined {\n options = buildLocatorOptions(options);\n\n const patterns = Array.isArray(pattern) ?\n pattern :\n [pattern];\n\n for (let i = 0; i < patterns.length; i++) {\n for (let j = 0; j < (options as LocatorOptions).path.length; j++) {\n const files = globSync(patterns[i] as string, {\n absolute: true,\n cwd: (options as LocatorOptions).path[j],\n nodir: true,\n ignore: options.ignore,\n });\n\n const element = files.shift();\n if (element) {\n return pathToLocatorInfo(element, true);\n }\n }\n }\n\n return undefined;\n}\n","/*\n * Copyright (c) 2022-2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n// Based on https://github.com/unjs/rc9 (MIT)\n\nimport { destr } from 'destr';\nimport flat from 'flat';\nimport fs from 'node:fs';\nimport { buildFilePath } from '../../../locator';\nimport { handleException, isSafeObjectKey } from '../../../utils';\nimport type { Loader } from '../../type';\n\nexport class ConfLoader implements Loader {\n async execute(input: string) {\n const filePath = buildFilePath(input);\n\n try {\n const file = await fs.promises.readFile(filePath, { encoding: 'utf-8' });\n\n return this.parse(file);\n } catch (e) {\n return handleException(e);\n }\n }\n\n executeSync(input: string) {\n const filePath = buildFilePath(input);\n\n try {\n const file = fs.readFileSync(filePath, { encoding: 'utf-8' });\n\n return this.parse(file);\n } catch (e) {\n return handleException(e);\n }\n }\n\n parse(contents: string): Record<string, any> {\n const config: Record<string, any> = {};\n\n const lines = contents.split(/\\n|\\r|\\r\\n/);\n\n for (let i = 0; i < lines.length; i++) {\n const match = lines[i].match(/^\\s*([^\\s=]+)\\s*=\\s*(.*)?\\s*$/);\n if (!match) {\n continue;\n }\n\n // Key\n const key = match[1];\n\n if (!key || !isSafeObjectKey(key)) {\n continue;\n }\n\n const value = destr(match[2].trim() /* val */);\n\n if (key.endsWith('[]')) {\n const arrKey = key.slice(0, Math.max(0, key.length - 2));\n config[arrKey] = (config[arrKey] || []).concat(value);\n continue;\n }\n\n config[key] = value;\n }\n\n return flat.unflatten(config, { overwrite: true });\n }\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { BaseError } from 'ebec';\nimport { hasOwnProperty, isObject } from '../../../utils';\nimport type { LoaderFilterFn, ModuleExport } from './type';\n\nexport function isJestRuntimeEnvironment() : boolean {\n return process.env &&\n process.env.JEST_WORKER_ID !== undefined;\n}\n\nexport function isTsNodeRuntimeEnvironment() : boolean {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return !!process[Symbol.for('ts-node.register.instance')];\n}\n\nexport function getModuleExport(\n data: Record<string, any>,\n filterFn?: LoaderFilterFn,\n): ModuleExport {\n if (filterFn) {\n const keys = Object.keys(data);\n for (let i = 0; i < keys.length; i++) {\n if (filterFn(keys[i] as string, data[keys[i] as string])) {\n return {\n key: keys[i] as string,\n value: data[keys[i] as string],\n };\n }\n }\n\n throw new BaseError('Cannot find specific module export.');\n }\n\n let value: any;\n\n if (\n hasOwnProperty(data, '__esModule') &&\n // eslint-disable-next-line no-underscore-dangle\n !!data.__esModule &&\n hasOwnProperty(data, 'default')\n ) {\n value = data.default;\n } else {\n value = data;\n }\n\n if (\n isObject(value) &&\n hasOwnProperty(value, 'default')\n ) {\n value = value.default;\n }\n\n return {\n key: 'default',\n value,\n };\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { BaseError } from 'ebec';\nimport type { JITI } from 'jiti';\nimport createJITI from 'jiti';\nimport { pathToFileURL } from 'node:url';\nimport type { LocatorInfo } from '../../../locator';\nimport {\n buildFilePath,\n buildFilePathWithoutExtension,\n isLocatorInfo,\n pathToLocatorInfo,\n} from '../../../locator';\nimport {\n handleException,\n hasStringProperty, isFilePath,\n isObject,\n} from '../../../utils';\nimport type { Loader } from '../../type';\nimport type { ModuleLoadOptions } from './type';\nimport { isJestRuntimeEnvironment, isTsNodeRuntimeEnvironment } from './utils';\n\nexport class ModuleLoader implements Loader {\n protected jiti : JITI;\n\n constructor() {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.jiti = createJITI(undefined, {\n extensions: ['.js', '.mjs', '.mts', '.cjs', '.cts', '.ts'],\n });\n }\n\n async execute(input: string) {\n let output : any;\n\n try {\n output = await this.load(input);\n } catch (e) {\n if (\n e instanceof SyntaxError ||\n e instanceof ReferenceError\n ) {\n throw e;\n }\n\n // jiti + ts-node\n // issue: https://github.com/nuxt/bridge/issues/228\n if (isTsNodeRuntimeEnvironment()) {\n output = this.loadSync(input);\n } else {\n output = this.jiti(input);\n }\n }\n\n return output;\n }\n\n executeSync(input: string) {\n let output : any;\n\n try {\n output = this.loadSync(input);\n } catch (e) {\n if (\n e instanceof SyntaxError ||\n e instanceof ReferenceError\n ) {\n throw e;\n }\n\n output = this.jiti(input);\n }\n\n return output;\n }\n\n // ---------------------------------------------------------------------------\n\n async load(\n data: LocatorInfo | string,\n options?: ModuleLoadOptions,\n ) : Promise<unknown> {\n options = options || {};\n const [name, locatorInfo] = this.build(data, options);\n\n try {\n // segmentation fault\n // issue: https://github.com/nodejs/node/issues/35889\n if (isJestRuntimeEnvironment()) {\n // eslint-disable-next-line global-require,import/no-dynamic-require\n return require(name);\n }\n\n return await import(name);\n } catch (e) {\n /* istanbul ignore next */\n if (\n isObject(e) &&\n hasStringProperty(e, 'code')\n ) {\n if (locatorInfo) {\n if (\n !options.withExtension &&\n (\n e.code === 'ERR_MODULE_NOT_FOUND' ||\n e.code === 'MODULE_NOT_FOUND'\n )\n ) {\n return this.load(locatorInfo, {\n ...options,\n withExtension: true,\n });\n }\n\n if (\n !options.withFilePrefix &&\n (\n e.code === 'ERR_UNSUPPORTED_ESM_URL_SCHEME' ||\n e.code === 'UNSUPPORTED_ESM_URL_SCHEME'\n )\n ) {\n return this.load(locatorInfo, {\n ...options,\n withExtension: true,\n withFilePrefix: true,\n });\n }\n }\n\n throw new BaseError({\n code: e.code,\n message: hasStringProperty(e, 'message') ? e.message : undefined,\n stack: hasStringProperty(e, 'stack') ? e.stack : undefined,\n });\n }\n\n /* istanbul ignore next */\n return handleException(e);\n }\n }\n\n loadSync(\n data: LocatorInfo | string,\n options?: ModuleLoadOptions,\n ) : unknown {\n options = options || {};\n const [name, locatorInfo] = this.build(data, options);\n\n try {\n // eslint-disable-next-line global-require,import/no-dynamic-require\n return require(name);\n } catch (e) {\n /* istanbul ignore next */\n if (\n isObject(e) &&\n hasStringProperty(e, 'code')\n ) {\n if (locatorInfo) {\n if (\n !options.withExtension &&\n (\n e.code === 'ERR_MODULE_NOT_FOUND' ||\n e.code === 'MODULE_NOT_FOUND'\n )\n ) {\n return this.loadSync(locatorInfo, {\n ...options,\n withExtension: true,\n });\n }\n }\n\n throw new BaseError({\n code: e.code,\n message: hasStringProperty(e, 'message') ? e.message : undefined,\n stack: hasStringProperty(e, 'stack') ? e.stack : undefined,\n });\n }\n\n return handleException(e);\n }\n }\n\n private build(\n data: LocatorInfo | string,\n options: ModuleLoadOptions,\n ) : [string, LocatorInfo | undefined] {\n let name : string;\n let locatorInfo : LocatorInfo | undefined;\n\n options = options || {};\n\n if (isLocatorInfo(data) || isFilePath(data)) {\n if (typeof data === 'string') {\n locatorInfo = pathToLocatorInfo(data);\n } else {\n locatorInfo = data;\n }\n\n if (options.withExtension) {\n name = buildFilePath(locatorInfo);\n } else {\n name = buildFilePathWithoutExtension(locatorInfo);\n }\n\n if (options.withFilePrefix) {\n name = pathToFileURL(name).href;\n }\n } else {\n name = data;\n }\n\n return [name, locatorInfo];\n }\n}\n","/*\n * Copyright (c) 2022-2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport fs from 'node:fs';\nimport { buildFilePath } from '../../../locator';\nimport { handleException } from '../../../utils';\nimport type { Loader } from '../../type';\n\nexport class JSONLoader implements Loader {\n async execute(input: string) {\n const filePath = buildFilePath(input);\n\n try {\n const file = await fs.promises.readFile(filePath, { encoding: 'utf-8' });\n return JSON.parse(file);\n } catch (e) {\n return handleException(e);\n }\n }\n\n executeSync(input: string) {\n const filePath = buildFilePath(input);\n\n try {\n const file = fs.readFileSync(filePath, { encoding: 'utf-8' });\n return JSON.parse(file);\n } catch (e) {\n return handleException(e);\n }\n }\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nexport enum LoaderId {\n MODULE = 'module',\n JSON = 'json',\n CONF = 'conf',\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport path from 'node:path';\nimport { buildFilePath, pathToLocatorInfo } from '../locator';\nimport { isFilePath } from '../utils';\nimport { ConfLoader, JSONLoader, ModuleLoader } from './built-in';\nimport { LoaderId } from './constants';\nimport type { Loader, Rule } from './type';\n\nexport class LoaderManager implements Loader {\n protected loaders : Record<string, Loader>;\n\n protected rules : Rule[];\n\n constructor() {\n this.loaders = {};\n this.rules = [\n {\n test: ['.js', '.mjs', '.mts', '.cjs', '.cts', '.ts'],\n loader: LoaderId.MODULE,\n },\n {\n test: ['.conf'], loader: LoaderId.CONF,\n },\n {\n test: ['.json'], loader: LoaderId.JSON,\n },\n ];\n }\n\n register(rule: Rule) : void;\n\n register(test: string[] | RegExp, loader: Loader) : void;\n\n register(test: any, loader?: Loader) : void {\n if (typeof loader !== 'undefined') {\n this.rules.push({ test, loader });\n return;\n }\n\n this.rules.push(test);\n }\n\n async execute(input: string) : Promise<any> {\n const id = this.findLoader(input);\n if (!id) {\n const info = pathToLocatorInfo(input);\n throw new Error(`No loader registered for extension: \"${info.extension}\"`);\n }\n\n const loader = this.resolve(id);\n return loader.execute(input);\n }\n\n executeSync(input: string) : any {\n const id = this.findLoader(input);\n if (!id) {\n const info = pathToLocatorInfo(input);\n throw new Error(`No loader registered for extension: ${info.extension || 'unknown'}`);\n }\n\n const loader = this.resolve(id);\n return loader.executeSync(input);\n }\n\n findLoader(input: string) : Loader | string | undefined {\n if (!isFilePath(input)) {\n return LoaderId.MODULE;\n }\n\n const info = pathToLocatorInfo(input);\n for (let i = 0; i < this.rules.length; i++) {\n const { test } = this.rules[i] as Rule;\n if (Array.isArray(test)) {\n if (test.indexOf(info.extension) !== -1) {\n return this.rules[i].loader;\n }\n } else if (test.test(buildFilePath(info))) {\n return this.rules[i].loader;\n }\n }\n\n return undefined;\n }\n\n /**\n * Resolve loader by id.\n *\n * @param id\n */\n resolve(id: string | Loader) : Loader {\n if (typeof id !== 'string') {\n return id;\n }\n\n if (Object.prototype.hasOwnProperty.call(this.loaders, id)) {\n return this.loaders[id] as Loader;\n }\n\n let loader : Loader | undefined;\n\n // built-in\n switch (id) {\n case LoaderId.CONF: {\n loader = new ConfLoader();\n break;\n }\n case LoaderId.MODULE: {\n loader = new ModuleLoader();\n break;\n }\n case LoaderId.JSON: {\n loader = new JSONLoader();\n break;\n }\n /* istanbul ignore next */\n default: {\n const pluginPath = this.normalizePath(id);\n const moduleLoader = this.resolve(LoaderId.MODULE);\n loader = moduleLoader.executeSync(pluginPath);\n\n break;\n }\n }\n\n if (typeof loader !== 'undefined') {\n this.loaders[id] = loader;\n\n return loader;\n }\n\n throw new Error(`The loader ${id} could not be resolved.`);\n }\n\n /* istanbul ignore next */\n normalizePath(input: string) {\n if (path.isAbsolute(input) || input.startsWith('./')) {\n return input;\n }\n\n if (input.startsWith('module:')) {\n return input.substring(0, 'module:'.length);\n }\n\n if (!input.startsWith('@')) {\n return `@locter/${input}`;\n }\n\n return input;\n }\n}\n","/*\n * Copyright (c) 2023.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { LoaderManager } from './module';\n\nlet instance : LoaderManager;\nexport function useLoader() {\n if (typeof instance !== 'undefined') {\n return instance;\n }\n\n instance = new LoaderManager();\n\n return instance;\n}\n","/*\n * Copyright (c) 2022.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { buildFilePath } from '../locator';\nimport type { LocatorInfo } from '../locator';\nimport { useLoader } from './singleton';\nimport type { Loader, Rule } from './type';\n\nexport function registerLoader(rule: Rule) : void;\nexport function registerLoader(test: string[] | RegExp, loader: Loader) : void;\nexport function registerLoader(test: any, loader?: Loader) : void {\n const manager = useLoader();\n if (typeof loader !== 'undefined') {\n manager.register(test, loader);\n\n return;\n }\n\n manager.register(test);\n}\n\nexport async function load(input: LocatorInfo | string) : Promise<any> {\n const manager = useLoader();\n if (typeof input === 'string') {\n return manager.execute(input);\n }\n\n return manager.execute(buildFilePath(input));\n}\n\nexport function loadSync(input: LocatorInfo | string) : any {\n const manager = useLoader();\n if (typeof input === 'string') {\n return manager.executeSync(input);\n }\n\n return manager.executeSync(buildFilePath(input));\n}\n"],"names":["input","options","name","extension","info","pattern","cwd","ignore","items","executeSync","parse","config","value","output","code","message","stack","locatorInfo","LoaderId","test","loader","findLoader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;AACJ;AACA;AACS;AACL;AACA;;AAGA;AACJ;AACJ;;AAGI;;AAGJ;AAEA;AACJ;;AAII;;AAEA;;AAGI;AACJ;AAEA;AACI;AACJ;;AAGJ;;;;AApIQ;;AACW;AAAO;AAAQ;AAAQ;AAAQ;AAAQ;AAAM;AACpDA;AACJ;AACA;;AACW;AAAQ;AAAEA;AACrB;AACA;;AACW;AAAQ;AAAEA;AACrB;AACH;AACL;AA0HJ;;AClJA;AACO;;;AAGH;AAEAE;;AAGJ;;ACJO;AACH;;;AAII;AACJ;AAEAC;AACJ;AAEO;AACH;;;AAGA;;AAGJ;AAEO;AACH;;;AAGA;;AAGJ;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "locter",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
4
4
  "description": "A library to locate a file/module by criteria and load it!",
5
5
  "author": {
6
6
  "name": "Peter Placzek",
@@ -49,33 +49,31 @@
49
49
  ],
50
50
  "license": "MIT",
51
51
  "devDependencies": {
52
+ "@rollup/plugin-esm-shim": "^0.1.2",
52
53
  "@rollup/plugin-node-resolve": "^15.1.0",
53
- "@swc/core": "^1.3.70",
54
+ "@swc/core": "^1.3.82",
54
55
  "@swc/jest": "^0.2.27",
55
56
  "@tada5hi/commitlint-config": "^1.1.0",
56
- "@tada5hi/eslint-config-typescript": "^1.2.2",
57
+ "@tada5hi/eslint-config-typescript": "^1.2.3",
57
58
  "@tada5hi/semantic-release": "^0.2.0",
58
59
  "@tada5hi/tsconfig": "^0.5.0",
59
60
  "@types/flat": "^5.0.2",
60
- "@types/jest": "^29.5.3",
61
- "@types/node": "^20.4.2",
61
+ "@types/jest": "^29.5.4",
62
+ "@types/node": "^20.5.8",
62
63
  "cross-env": "^7.0.3",
63
- "eslint": "^8.45.0",
64
+ "eslint": "^8.48.0",
64
65
  "husky": "^8.0.3",
65
- "jest": "^29.6.1",
66
- "magic-string": "^0.30.1",
67
- "mlly": "^1.4.0",
66
+ "jest": "^29.6.4",
68
67
  "rimraf": "^4.4.1",
69
68
  "rollup": "^3.26.3",
70
- "semantic-release": "^19.0.5",
71
- "sourcemap-codec": "^1.4.8",
69
+ "semantic-release": "^21.1.1",
72
70
  "typescript": "^5.1.6"
73
71
  },
74
72
  "dependencies": {
75
73
  "destr": "^2.0.0",
76
- "ebec": "^1.1.0",
74
+ "ebec": "^1.1.1",
77
75
  "flat": "^5.0.2",
78
76
  "glob": "^10.3.3",
79
- "jiti": "^1.19.1"
77
+ "jiti": "^1.19.3"
80
78
  }
81
79
  }