"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, { uniRouteImport: () => uniRouteImport }); module.exports = __toCommonJS(src_exports); // src/utils.ts var import_path = require("path"); // src/pino.config.ts var import_pino = __toESM(require("pino"), 1); var logLevel = process.env.LOG_LEVEL || "info"; var logger = (0, import_pino.default)({ level: logLevel, timestamp: import_pino.default.stdTimeFunctions.isoTime, messageKey: "msg", // 指定消息键 formatters: { // 自定义日志格式化器 level: (label) => { return { level: label }; } }, // 如果乱码问题仍然存在,确保你的环境支持UTF-8编码 transport: { target: "pino-pretty", options: { translateTime: "SYS:standard", // 使用系统时间格式 colorize: true, // 开启颜色 ignore: "pid,hostname" // 忽略pid和hostname字段 } } }); var pino_config_default = logger; // src/utils.ts var import_fs = __toESM(require("fs"), 1); // src/module/strip-json-comments/index.js var singleComment = Symbol("singleComment"); var multiComment = Symbol("multiComment"); var stripWithoutWhitespace = () => ""; var stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, " "); var isEscaped = (jsonString, quotePosition) => { let index = quotePosition - 1; let backslashCount = 0; while (jsonString[index] === "\\") { index -= 1; backslashCount += 1; } return Boolean(backslashCount % 2); }; function stripJsonComments(jsonString, { whitespace = true, trailingCommas = false } = {}) { if (typeof jsonString !== "string") { throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``); } const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace; let isInsideString = false; let isInsideComment = false; let offset = 0; let buffer = ""; let result = ""; let commaIndex = -1; for (let index = 0; index < jsonString.length; index++) { const currentCharacter = jsonString[index]; const nextCharacter = jsonString[index + 1]; if (!isInsideComment && currentCharacter === '"') { const escaped = isEscaped(jsonString, index); if (!escaped) { isInsideString = !isInsideString; } } if (isInsideString) { continue; } if (!isInsideComment && currentCharacter + nextCharacter === "//") { buffer += jsonString.slice(offset, index); offset = index; isInsideComment = singleComment; index++; } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") { index++; isInsideComment = false; buffer += strip(jsonString, offset, index); offset = index; continue; } else if (isInsideComment === singleComment && currentCharacter === "\n") { isInsideComment = false; buffer += strip(jsonString, offset, index); offset = index; } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") { buffer += jsonString.slice(offset, index); offset = index; isInsideComment = multiComment; index++; continue; } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") { index++; isInsideComment = false; buffer += strip(jsonString, offset, index + 1); offset = index + 1; continue; } else if (trailingCommas && !isInsideComment) { if (commaIndex !== -1) { if (currentCharacter === "}" || currentCharacter === "]") { buffer += jsonString.slice(offset, index); result += strip(buffer, 0, 1) + buffer.slice(1); buffer = ""; offset = index; commaIndex = -1; } else if (currentCharacter !== " " && currentCharacter !== " " && currentCharacter !== "\r" && currentCharacter !== "\n") { buffer += jsonString.slice(offset, index); offset = index; commaIndex = -1; } } else if (currentCharacter === ",") { result += buffer + jsonString.slice(offset, index); buffer = ""; offset = index; commaIndex = index; } } } return result + buffer + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset)); } // src/utils.ts var import_chokidar = __toESM(require("chokidar"), 1); var rootPath = process.env.UNI_INPUT_DIR || process.env.INIT_CWD + "\\src"; var isUpdating = false; var updatePromise = null; var rootDTSPath = (process.env.VITE_ROOT_DIR || process.env.INIT_CWD) + "\\src\\composables\\useRouter\\types.ts"; var useRouterPath = (process.env.VITE_ROOT_DIR || process.env.INIT_CWD) + "\\src\\composables\\useRouter\\index.ts"; var initPages = (that) => { let pagesPath = ((that == null ? void 0 : that.query) || {}).pagesPath; if (!pagesPath) { pagesPath = (0, import_path.resolve)(rootPath, "pages.json"); } else { rootPath = (0, import_path.resolve)((0, import_path.dirname)(pagesPath)); } return new Promise((resolve2, reject) => { import_fs.default.readFile(pagesPath, "utf8", (err, data) => { if (err) { reject(new Error(`Failed to read pages JSON: ${err.message}`)); } const pagesJson = JSON.parse(stripJsonComments(data)); resolve2(pagesJson); }); }); }; var getPagesRouteMap = (pagesJson) => { const pages = pagesJson.pages || []; const subpackages = pagesJson.subpackages || pagesJson.subPackages || []; const tabBar = pagesJson.tabBar || null; const pagrs_update = () => { const tabBar_names = tabBar != null ? tabBar.list.map((item) => extractSecondPathSegment(item == null ? void 0 : item.pagePath)) : null; return pages.map((page) => { const name = extractSecondPathSegment(page.path); return { ...page, name, type: (tabBar_names == null ? void 0 : tabBar_names.includes(name)) ? "tabBar" : "default" }; }); }; const subpackages_update = () => { return subpackages.map((subPackage) => { const root = subPackage.root; const processedSubPages = subPackage.pages.map((subItem) => { const name = extractSecondPathSegment(root + "/" + subItem.path); return { ...subItem, name, type: "default" // 子包不包含 tabBar 路由 }; }); return { root, pages: processedSubPages }; }); }; const routeNameList = pages.reduce( (obj, item) => { const name = extractSecondPathSegment(item.path); obj.push(`'${name}'`); return obj; }, subpackages.reduce( (obj, item) => { const root = item.root; item.pages.forEach((page) => { const name = extractSecondPathSegment(`${root}/${page.path}`); obj.push(`'${name}'`); }); return obj; }, [] ) ); return { content: { ...pagesJson, pages: pagrs_update(), subPackages: subpackages_update() }, routeNameList }; }; var updatePagesJson = async (pagesJson) => { if (isUpdating) { if (updatePromise) { await updatePromise; } } isUpdating = true; updatePromise = new Promise((resolveUpdate) => { try { const { content, routeNameList } = getPagesRouteMap(pagesJson); const pagesPath = (0, import_path.resolve)(rootPath, "pages.json"); ensureFileOrDirectoryExists(rootDTSPath); import_fs.default.writeFileSync(pagesPath, JSON.stringify(content, null, 2), "utf8"); pino_config_default.info("pages.json has been successfully updated."); import_fs.default.writeFileSync( rootDTSPath, `export type Path = ${routeNameList.join("|")};`, "utf8" ); pino_config_default.info("auto-route.d.ts has been successfully updated."); isUpdating = false; updatePromise = null; resolveUpdate(); } catch (error) { pino_config_default.error("Error updating files:", error); isUpdating = false; updatePromise = null; resolveUpdate(); } }); await updatePromise; }; function extractSecondPathSegment(url) { const segments = url.split("/").slice(1, -1); return segments.length === 1 ? segments[0] : segments.join("_"); } var clearModuleCache = (modulePath) => { try { const resolvedPath = require.resolve(modulePath); delete require.cache[resolvedPath]; } catch (error) { pino_config_default.error("Failed to clear module cache:", error); } }; function ensureFileOrDirectoryExists(filePath) { const directory = (0, import_path.dirname)(filePath); if (!import_fs.default.existsSync(directory)) { import_fs.default.mkdirSync(directory, { recursive: true }); } if (!import_fs.default.existsSync(filePath)) { if (filePath.endsWith("/")) { import_fs.default.mkdirSync(filePath); } else { import_fs.default.writeFileSync(filePath, ""); } } } var setupWatcher = (that) => { const pagesPath = (0, import_path.resolve)(rootPath, "pages.json"); const watcher = import_chokidar.default.watch(pagesPath); watcher.on("change", async (path) => { clearModuleCache(path); try { const pagesJson = await initPages(that); await updatePagesJson(pagesJson); } catch (error) { pino_config_default.error("Error updating files:", error); } }); watcher.on("error", (error) => { pino_config_default.error("Watcher error:", error); }); }; // src/plugin.ts var isConfigResolvedExecuted = false; var uniRouteImport = () => { return { name: "vite-uni-route", async configResolved(config) { if (isConfigResolvedExecuted) { return; } isConfigResolvedExecuted = true; try { const pagesJson = await initPages(this); updatePagesJson(pagesJson); if (config.build.watch && config.command === "build") { setupWatcher(this); } } catch (error) { pino_config_default.error("Error initializing pages:", error); } } }; }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { uniRouteImport });