UNPKG

@svelteuse/router

Version:
147 lines (143 loc) 5.76 kB
import "../chunk-ME6M5CRB.mjs"; // node_modules/@nbhr/utils/dist/chunk-BZ42Z6RD.mjs var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; // node_modules/@nbhr/utils/dist/chunk-CZXSWUCG.mjs import { readdirSync, statSync } from "fs"; import { resolve, join, normalize } from "path"; var fs_exports = {}; __export(fs_exports, { walkSync: () => walkSync }); function walkSync(path) { let files = []; const filesInPath = readdirSync(path); filesInPath.forEach((file) => { const filePath = normalize(resolve(join(path, file))); const stats = statSync(filePath); if (stats.isDirectory()) { files = files.concat(walkSync(filePath)); } else if (stats.isFile()) { files.push(filePath); } }); return files; } // src/node/node.ts import { readFileSync } from "fs"; import { basename, join as join2, relative, resolve as resolve2, sep } from "path"; function createRoutes(options) { const { rootDir, pageDir, layoutDir, rootPath, entryFile, errorsDir } = options; return { script: ({ content, attributes, filename }) => { if (filename && filename.endsWith(entryFile)) { const routes = /* @__PURE__ */ new Map(); const pageFiles = walkSync(resolve2(join2(rootDir, pageDir))); const layoutFiles = walkSync(resolve2(join2(rootDir, layoutDir))); const errorFiles = walkSync(resolve2(join2(rootDir, errorsDir))); let importScriptBlock = ""; for (const file of errorFiles) { const parsedPath = relative(resolve2(rootDir), file); const { identifier, path } = parseFile(parsedPath, layoutDir, rootPath); const importPath = generateImportPath(parsedPath); importScriptBlock += ` import ${identifier} from ${importPath};`; const layoutConfig = readFileSync(file, "utf8").match(/router-layout-(\w+)/i)?.[1] || "default"; const layoutName = layoutConfig?.charAt(0).toUpperCase() + layoutConfig?.slice(1); routes.set(identifier, { path, layout: layoutName, loader: `async () => { return Promise.resolve(${identifier}) }` }); } for (const file of layoutFiles) { const parsedPath = relative(resolve2(rootDir), file); const { identifier } = parseFile(parsedPath, layoutDir, rootPath); const importPath = generateImportPath(parsedPath); importScriptBlock += ` import ${identifier} from ${importPath};`; } for (const file of pageFiles) { const parsedPath = relative(resolve2(rootDir), file); const { identifier, path, isAsync } = parseFile(parsedPath, pageDir, rootPath); const importPath = generateImportPath(parsedPath); importScriptBlock += isAsync ? ` let ${identifier} = null;` : ` import ${identifier} from ${importPath};`; const layoutConfig = readFileSync(file, "utf8").match(/router-layout-(\w+)/i)?.[1] || "default"; const layoutName = layoutConfig?.charAt(0).toUpperCase() + layoutConfig?.slice(1); routes.set(identifier, { path, layout: layoutName, loader: isAsync ? `async () => { console.log('async import'); console.log(${identifier}); return (await import(${importPath.replaceAll('"', "'")})).default; }` : `async () => { return Promise.resolve(${identifier}) }` }); } const routesDefinition = ` $useRouter.routes = ${JSON.stringify([...routes.values()].sort((a, b) => { const splittedB = b["path"].split("/"); const splittedA = a["path"].split("/"); if (splittedB.slice(0, -1).join("/") > splittedA.slice(0, -1).join("/")) { return -1; } else if (splittedB.slice(0, -1).join("/") == splittedA.slice(0, -1).join("/")) { return splittedB[splittedB.length - 1] < splittedA[splittedA.length - 1] ? -1 : 1; } else { return 1; } })).replace(/(?<=layout":)"(\w+)"/g, "$1").replace(/(?<=loader":)"(.+?)"/g, "$1")}; `; let processedContent = content; if (attributes["su-router-imports"] === true) { processedContent = importScriptBlock + "\n" + routesDefinition + "\n\n" + content; } return { code: processedContent }; } else { return { code: content }; } } }; } function parseFile(path, pageDir = "pages", rootPath = "/") { let ivalue = ""; let pvalue = ""; if (rootPath && rootPath !== "/") { pvalue += rootPath; } const extension = path.endsWith(".svelte") ? ".svelte" : ".svx"; const segments = path.split(sep); let file = basename(segments.pop() || "", extension); const isAsync = file.startsWith("~") ? true : false; file = file.replace("~", ""); for (const dir of segments) { if (dir != pageDir) { isDynamic(dir) ? ivalue += dir.slice(1, -1).toUpperCase() + "_" : ivalue += dir.charAt(0).toUpperCase() + dir.slice(1) + "_"; pvalue += isDynamic(dir) ? "/:" + dir.slice(1, -1).toLowerCase() : "/" + dir.toLowerCase(); } } ivalue += isDynamic(file) ? file.slice(1, -1).toUpperCase() : file.charAt(0).toUpperCase() + file.slice(1); if (file.toLowerCase() !== "index") { pvalue += isDynamic(file) ? "/:" + file.slice(1, -1).toLowerCase() : "/" + file.toLowerCase(); } return { identifier: ivalue, path: pvalue, isAsync }; } function generateImportPath(path) { return `"./${path.replaceAll(sep, "/")}"`; } function isDynamic(str) { return str.startsWith("[") && str.endsWith("]"); } export { createRoutes, generateImportPath, parseFile };