UNPKG

directory-import

Version:

Module will allow you to synchronously or asynchronously import (requires) all modules from the folder you specify

212 lines (204 loc) 8.24 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { directoryImport: () => directoryImport }); module.exports = __toCommonJS(src_exports); // src/import-modules.ts var import_node_path3 = __toESM(require("path")); // src/directory-reader-async.ts var import_node_fs = require("fs"); var import_node_path = __toESM(require("path")); async function readDirectoryAsync(options, targetDirectoryPath) { const receivedItemsPaths = await import_node_fs.promises.readdir(targetDirectoryPath); const result = await Promise.all( receivedItemsPaths.map(async (itemPath) => { const receivedFilesPaths = []; const relativeItemPath = import_node_path.default.join(`${targetDirectoryPath}`, `${itemPath}`); const stat = await import_node_fs.promises.stat(relativeItemPath); if (stat.isDirectory() && options.includeSubdirectories) { const files = await readDirectoryAsync(options, relativeItemPath); receivedFilesPaths.push(...files); } else if (stat.isFile()) { receivedFilesPaths.push(relativeItemPath); } return receivedFilesPaths; }) ); return result.flat(); } // src/directory-reader-sync.ts var import_node_fs2 = __toESM(require("fs")); var import_node_path2 = __toESM(require("path")); function readDirectorySync(options, targetDirectoryPath) { const receivedItemsPaths = import_node_fs2.default.readdirSync(targetDirectoryPath); const receivedDirectoriesPaths = []; const receivedFilesPaths = []; let itemsCounter = 0; for (itemsCounter; itemsCounter < receivedItemsPaths.length; itemsCounter += 1) { const itemPath = import_node_path2.default.join(`${targetDirectoryPath}`, `${receivedItemsPaths[itemsCounter]}`); const stat = import_node_fs2.default.statSync(itemPath); if (stat.isDirectory() && options.includeSubdirectories) { receivedDirectoriesPaths.push(itemPath); } else if (stat.isFile()) { receivedFilesPaths.push(itemPath); } } let directoriesCounter = 0; for (directoriesCounter; directoriesCounter < receivedDirectoriesPaths.length; directoriesCounter += 1) { const files = readDirectorySync(options, receivedDirectoriesPaths[directoriesCounter]); receivedFilesPaths.push(...files); } return receivedFilesPaths; } // src/import-modules.ts var VALID_IMPORT_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".mjs", ".ts", ".json"]); var handlers = { async: asyncHandler, sync: syncHandler }; function syncHandler(options) { const modules = {}; const filesPaths = readDirectorySync(options, options.targetDirectoryPath); let index = 0; for (const filePath of filesPaths) { const isModuleImported = importModule(filePath, index, options, modules); if (isModuleImported) index += 1; if (index === options.limit) break; } return modules; } async function asyncHandler(options) { const modules = {}; const filesPaths = await readDirectoryAsync(options, options.targetDirectoryPath); let index = 0; for (const filePath of filesPaths) { const isModuleImported = importModule(filePath, index, options, modules); if (isModuleImported) index += 1; if (index === options.limit) break; } return modules; } function importModule(filePath, index, options, modules) { const { name: fileName, ext: fileExtension } = import_node_path3.default.parse(filePath); const isValidModuleExtension = VALID_IMPORT_EXTENSIONS.has(fileExtension); const isDeclarationFile = filePath.endsWith(".d.ts"); const isValidFilePath = options.importPattern ? options.importPattern.test(filePath) : true; if (!isValidModuleExtension) return false; if (!isValidFilePath) return false; if (isDeclarationFile) return false; const relativeModulePath = filePath.slice(options.targetDirectoryPath.length); if (options.forceReload) { delete require.cache[filePath]; } const importedModule = require(filePath); modules[relativeModulePath] = importedModule; if (options.callback) { options.callback(fileName, relativeModulePath, importedModule, index); } return true; } function importModules(options) { if (!handlers[options.importMode]) { throw new Error(`Expected sync or async import method, but got: ${options.importMode}`); } return handlers[options.importMode](options); } // src/prepare-private-options.ts var import_node_path4 = __toESM(require("path")); var getDefaultOptions = () => { const options = { includeSubdirectories: true, importMode: "sync", importPattern: /.*/, limit: Number.POSITIVE_INFINITY, callerFilePath: import_node_path4.default.resolve("/"), callerDirectoryPath: import_node_path4.default.resolve("/"), targetDirectoryPath: import_node_path4.default.resolve("/"), forceReload: false }; options.callerFilePath = new Error("functional-error").stack.split("\n")[4]?.match(/(?:\/|[A-Za-z]:\\)[/\\]?(?:[^:]+){1,2}/)?.[0] || options.callerFilePath; options.callerDirectoryPath = import_node_path4.default.dirname(options.callerFilePath); options.targetDirectoryPath = options.callerDirectoryPath; return options; }; function preparePrivateOptions(...arguments_) { const options = { ...getDefaultOptions() }; if (arguments_[0] === void 0) { return options; } else if (typeof arguments_[0] === "object") { const result = { ...getDefaultOptions(), ...arguments_[0] }; result.targetDirectoryPath = import_node_path4.default.resolve(result.callerDirectoryPath, result.targetDirectoryPath); result.callback = typeof arguments_[1] === "function" ? arguments_[1] : void 0; return result; } else if (typeof arguments_[0] === "string") { options.targetDirectoryPath = import_node_path4.default.resolve(options.callerDirectoryPath, arguments_[0]); } else if (typeof arguments_[0] === "function") { options.callback = arguments_[0]; } else { throw new TypeError( `Expected undefined, object, string or function as first argument, but got: ${typeof arguments_[0]}` ); } if (typeof arguments_[1] === "string") { if (arguments_[1] !== "sync" && arguments_[1] !== "async") { throw new TypeError(`Expected sync or async as second argument, but got: ${arguments_[1]}`); } options.importMode = arguments_[1]; } else if (typeof arguments_[1] === "function") { options.callback = arguments_[1]; } if (typeof arguments_[2] === "function") { options.callback = arguments_[2]; } return options; } // src/index.ts function directoryImport(...arguments_) { const options = preparePrivateOptions(...arguments_); try { return importModules(options); } catch (error) { Object.assign(error, options); throw error; } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { directoryImport });