UNPKG

esbuild-plugin-autoload

Version:
85 lines (84 loc) 3.4 kB
// @bun // src/index.ts import fs from "fs"; import path from "path"; var IS_BUN = typeof Bun !== "undefined"; if (!IS_BUN && !fs.globSync) throw new Error("Node@>=22 or Bun is required"); function globSync(globPattern, globOptions) { return IS_BUN ? Array.from(new Bun.Glob(globPattern).scanSync(globOptions)) : fs.globSync(globPattern, globOptions); } var fsUsageMock = `{ default: { existsSync() { return true; }, statSync() { return { isDirectory() { return true; } } } } }`; var DEFAULT_PATTERN = "**/*.{ts,tsx,js,jsx,mjs,cjs}"; var DEFAULT_DIRECTORY = "./example/routes"; function autoload(options) { const pattern = typeof options === "object" ? options?.pattern ?? DEFAULT_PATTERN : DEFAULT_PATTERN; const directory = typeof options === "string" ? options : options?.directory ?? DEFAULT_DIRECTORY; const debug = typeof options === "object" ? options?.debug ?? false : false; return { name: "autoload", setup(build) { build.onLoad({ filter: /(.*)(@gramio|GRAMIO)[/\\]autoload[/\\]dist[/\\]index\.(js|mjs|cjs)$/i }, async (args) => { let content = String(await fs.promises.readFile(args.path)); const files = globSync(pattern, { cwd: directory }); content = content.replace("autoload(options) {", ` autoload(options) { const fileSources = { ${files.map((file) => ` "${file}": await import("${path.resolve(directory, file).replace(/\\/gi, "\\\\")}"), `).join(` `)} } `); content = content.replace(/const file = (.*);/i, "const file = fileSources[filePath];"); content = content.replace("var fdir = require('fdir');", "").replace('import { fdir } from "fdir";', ""); content = content.replace(/const paths = ([\s\S]*?);/m, `const paths = [${files.map((file) => `"${file}"`).join(", ")}];`); if (debug) console.log(content); return { contents: content }; }); build.onLoad({ filter: /(.*)elysia-autoload(\/|\\)dist(\/|\\)index\.(js|mjs|cjs)/i }, async (args) => { let content = String(await fs.promises.readFile(args.path)); const files = globSync(pattern, { cwd: directory }); content = content.replace("const files = globSync(globPattern, globOptions);", `const files = [${files.map((file) => `"${file}"`).join(",")}];`); content = content.replace(`import fs from 'node:fs';`, `var { default: fs} = ${fsUsageMock}`); content = content.replace("autoload(options = {}) {", `autoload(options = {}) { const fileSources = { ${files.map((file) => ` "${file}": await import("${path.resolve(directory, file).replace(/\\/gi, "\\\\")}"), `).join(` `)} } `); content = content.replace(/const file = (.*);/i, "const file = fileSources[filePath];"); if (debug) console.log(content); return { contents: content }; }); } }; } var src_default = autoload; export { globSync, src_default as default, autoload, IS_BUN };