UNPKG

@svelteuse/router

Version:
178 lines (173 loc) 7.54 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __reExport = (target, module2, copyDefault, desc) => { if (module2 && typeof module2 === "object" || typeof module2 === "function") { for (let key of __getOwnPropNames(module2)) if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default")) __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable }); } return target; }; var __toCommonJS = /* @__PURE__ */ ((cache) => { return (module2, temp) => { return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp); }; })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0); // src/node/node.ts var node_exports = {}; __export(node_exports, { createRoutes: () => createRoutes, generateImportPath: () => generateImportPath, parseFile: () => parseFile }); // node_modules/@nbhr/utils/dist/chunk-BZ42Z6RD.mjs var __defProp2 = Object.defineProperty; var __export2 = (target, all) => { for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true }); }; // node_modules/@nbhr/utils/dist/chunk-CZXSWUCG.mjs var import_fs = require("fs"); var import_path = require("path"); var fs_exports = {}; __export2(fs_exports, { walkSync: () => walkSync }); function walkSync(path) { let files = []; const filesInPath = (0, import_fs.readdirSync)(path); filesInPath.forEach((file) => { const filePath = (0, import_path.normalize)((0, import_path.resolve)((0, import_path.join)(path, file))); const stats = (0, import_fs.statSync)(filePath); if (stats.isDirectory()) { files = files.concat(walkSync(filePath)); } else if (stats.isFile()) { files.push(filePath); } }); return files; } // src/node/node.ts var import_node_fs = require("fs"); var import_node_path = require("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((0, import_node_path.resolve)((0, import_node_path.join)(rootDir, pageDir))); const layoutFiles = walkSync((0, import_node_path.resolve)((0, import_node_path.join)(rootDir, layoutDir))); const errorFiles = walkSync((0, import_node_path.resolve)((0, import_node_path.join)(rootDir, errorsDir))); let importScriptBlock = ""; for (const file of errorFiles) { const parsedPath = (0, import_node_path.relative)((0, import_node_path.resolve)(rootDir), file); const { identifier, path } = parseFile(parsedPath, layoutDir, rootPath); const importPath = generateImportPath(parsedPath); importScriptBlock += ` import ${identifier} from ${importPath};`; const layoutConfig = (0, import_node_fs.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 = (0, import_node_path.relative)((0, import_node_path.resolve)(rootDir), file); const { identifier } = parseFile(parsedPath, layoutDir, rootPath); const importPath = generateImportPath(parsedPath); importScriptBlock += ` import ${identifier} from ${importPath};`; } for (const file of pageFiles) { const parsedPath = (0, import_node_path.relative)((0, import_node_path.resolve)(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 = (0, import_node_fs.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(import_node_path.sep); let file = (0, import_node_path.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(import_node_path.sep, "/")}"`; } function isDynamic(str) { return str.startsWith("[") && str.endsWith("]"); } module.exports = __toCommonJS(node_exports); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { createRoutes, generateImportPath, parseFile });