(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs'), require('path'), require('prettier'), require('axios'), require('lodash'), require('@vue/compiler-sfc'), require('magic-string'), require('glob'), require('node:util'), require('svgo'), require('postcss-value-parser')) : typeof define === 'function' && define.amd ? define(['exports', 'fs', 'path', 'prettier', 'axios', 'lodash', '@vue/compiler-sfc', 'magic-string', 'glob', 'node:util', 'svgo', 'postcss-value-parser'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.index = {}, global.fs, global.path, global.prettier, global.axios, global.lodash, global.compilerSfc, global.magicString, global.glob, global.util, global.svgo, global.valueParser)); })(this, (function (exports, fs, path, prettier, axios, lodash, compilerSfc, magicString, glob, util, svgo, valueParser) { 'use strict'; const config = { type: "admin", reqUrl: "", nameTag: true, eps: { enable: true, api: "", dist: "./build/cool", mapping: [ { // 自定义匹配 custom: ({ propertyName, type }) => { // 如果没有,返回null或者不返回,则继续遍历其他匹配规则 return null; }, }, { type: "string", test: ["varchar", "text", "simple-json"], }, { type: "string[]", test: ["simple-array"], }, { type: "Date", test: ["datetime", "date"], }, { type: "number", test: ["tinyint", "int", "decimal"], }, { type: "BigInt", test: ["bigint"], }, { type: "any", test: ["json"], }, ], }, svg: { skipNames: ["base"], }, tailwind: { enable: true, remUnit: 14, remPrecision: 6, rpxRatio: 2, darkTextClass: "dark:text-surface-50", }, }; // 根目录 function rootDir(path$1) { switch (config.type) { case "app": case "uniapp-x": return path.join(process.env.UNI_INPUT_DIR, path$1); default: return path.join(process.cwd(), path$1); } } // 首字母大写 function firstUpperCase(value) { return value.replace(/\b(\w)(\w*)/g, function ($0, $1, $2) { return $1.toUpperCase() + $2; }); } // 横杠转驼峰 function toCamel(str) { return str.replace(/([^-])(?:-+([^-]))/g, function ($0, $1, $2) { return $1 + $2.toUpperCase(); }); } // 创建目录 function createDir(path, recursive) { try { if (!fs.existsSync(path)) fs.mkdirSync(path, { recursive }); } catch (err) { } } // 读取文件 function readFile(path, json) { try { const content = fs.readFileSync(path, "utf8"); return json ? JSON.parse(content.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")) : content; } catch (err) { } return ""; } // 写入文件 function writeFile(path, data) { try { return fs.writeFileSync(path, data); } catch (err) { } return ""; } // 解析body function parseJson(req) { return new Promise((resolve) => { let d = ""; req.on("data", function (chunk) { d += chunk; }); req.on("end", function () { try { resolve(JSON.parse(d)); } catch { resolve({}); } }); }); } // 格式化内容 function formatContent(content, options) { return prettier.format(content, { parser: "typescript", useTabs: true, tabWidth: 4, endOfLine: "lf", semi: true, ...options, }); } function error(message) { console.log("\x1B[31m%s\x1B[0m", message); } /** * 将模板字符串扁平化处理,转换为 Service 类型定义 * @param template - 包含 Service 类型定义的模板字符串 * @returns 处理后的 Service 类型定义字符串 * @throws {Error} 当模板中找不到 Service 类型定义时抛出错误 */ function flatten(template) { // 查找 Service 类型定义的起始位置 const startIndex = template.indexOf("export type Service = {"); // 保留 Service 类型定义前的内容 let header = template.substring(0, startIndex); // 获取 Service 类型定义及其内容,去除换行和制表符 const serviceContent = template.substring(startIndex).replace(/\n|\t/g, ""); let interfaces = ""; let serviceFields = ""; // 解析内容并生成接口定义 parse(serviceContent).forEach(({ key, content, level }) => { interfaces += `\nexport interface ${firstUpperCase(key)}Interface {${content}}\n`; serviceFields += `${key}: ${firstUpperCase(key)}Interface;`; }); return `${header}${interfaces}\nexport type Service = {${serviceFields}}`; } /** * 查找匹配的右花括号位置 * @param str - 要搜索的字符串 * @param startIndex - 开始搜索的位置 * @returns 匹配的右花括号位置 * @throws {Error} 当找不到匹配的右花括号时抛出错误 */ function findClosingBrace(str, startIndex) { let braceCount = 1; let currentIndex = startIndex; while (currentIndex < str.length && braceCount > 0) { if (str[currentIndex] === "{") braceCount++; if (str[currentIndex] === "}") braceCount--; currentIndex++; } if (braceCount !== 0) { throw new Error("Unmatched braces in the template"); } return currentIndex - 1; } /** * 解析内容中的嵌套结构 * @param content - 要解析的内容字符串 * @returns 解析结果数组,包含解析出的键值对 */ function parse(content, level = 0) { // 匹配形如 xxx: { ... } 的结构 const interfacePattern = /(\w+)\s*:\s*\{/g; const result = []; let match; while ((match = interfacePattern.exec(content)) !== null) { const startIndex = match.index + match[0].length; const endIndex = findClosingBrace(content, startIndex); if (endIndex > startIndex) { let parsedContent = content.substring(startIndex, endIndex).trim(); // 处理嵌套结构 if (parsedContent.includes("{") && parsedContent.includes("}")) { const nestedInterfaces = parse(parsedContent, level + 1); // 替换嵌套的内容为接口引用 if (nestedInterfaces.length > 0) { nestedInterfaces.forEach((nestedInterface) => { const pattern = `${nestedInterface.key}: {${nestedInterface.content}};`; const replacement = `${nestedInterface.key}: ${firstUpperCase(nestedInterface.key)}Interface`; parsedContent = parsedContent.replace(pattern, replacement); }); } } // 将解析结果添加到数组开头 result.unshift({ key: match[1], level, content: parsedContent, }); } } return result; } /** * 获取动态类名 */ const getDynamicClassNames = (value) => { const names = new Set(); // 匹配数组中的字符串元素(如 'text-center') const arrayRegex = /['"](.*?)['"]/g; let arrayMatch; while ((arrayMatch = arrayRegex.exec(value)) !== null) { arrayMatch[1].trim() && names.add(arrayMatch[1]); } // 匹配对象键(如 { 'text-a': 1 }) const objKeyRegex = /[{,]\s*['"](.*?)['"]\s*:/g; let objKeyMatch; while ((objKeyMatch = objKeyRegex.exec(value)) !== null) { objKeyMatch[1].trim() && names.add(objKeyMatch[1]); } // 匹配三元表达式中的字符串(如 'dark' 和 'light') const ternaryRegex = /(\?|:)\s*['"](.*?)['"]/g; let ternaryMatch; while ((ternaryMatch = ternaryRegex.exec(value)) !== null) { ternaryMatch[2].trim() && names.add(ternaryMatch[2]); } // 匹配反引号模板字符串 const templateRegex = /`([^`]*)`/g; let templateMatch; while ((templateMatch = templateRegex.exec(value)) !== null) { const templateContent = templateMatch[1]; // 提取模板字符串中的普通文本部分(排除 ${} 表达式) const textParts = templateContent.split(/\$\{[^}]*\}/); textParts.forEach((part) => { part.trim() .split(/\s+/) .forEach((className) => { className.trim() && names.add(className.trim()); }); }); // 提取模板字符串中 ${} 表达式内的字符串 const expressionRegex = /\$\{([^}]*)\}/g; let expressionMatch; while ((expressionMatch = expressionRegex.exec(templateContent)) !== null) { const expression = expressionMatch[1]; // 递归处理表达式中的动态类名 getDynamicClassNames(expression).forEach((name) => names.add(name)); } } return Array.from(names); }; /** * 获取类名 */ function getClassNames(html) { const classRegex = /(?:class|:class|:pt)\s*=\s*(['"`])([\s\S]*?)\1/gi; const classNames = new Set(); let match; while ((match = classRegex.exec(html)) !== null) { const isStaticClass = match[0].startsWith("class"); const value = match[2].trim(); if (isStaticClass) { // 处理静态 class value.split(/\s+/).forEach((name) => name && classNames.add(name)); } else { // 处理动态 :class getDynamicClassNames(value).forEach((name) => classNames.add(name)); } } return Array.from(classNames); } /** * 获取 class 内容 */ function getClassContent(html) { const regex = /(?:class|:class|:pt)\s*=\s*(['"`])([\s\S]*?)\1/g; const texts = []; let match; while ((match = regex.exec(html)) !== null) { texts.push(match[2]); } return texts; } /** * 获取节点 */ function getNodes(code) { const nodes = []; const templateMatch = /