@vtj/coder
Version:
VVTJ.PRO 是一个开源的、AI 驱动的 Vue3 企业级应用开发平台,通过 AI 智能体与可视化编排实现高效开发,并支持导出标准 Vue 代码以避免平台锁定。
1,583 lines (1,582 loc) • 44.3 kB
JavaScript
import { mitt as ye, base64 as Se, dedupArray as M, toArray as je, kebabCase as J, camelCase as A, isPlainObject as ke, isString as we, template as H, cloneDeep as Ie } from "@vtj/base";
import { format as V } from "prettier/standalone";
import * as Oe from "prettier/plugins/html";
import * as X from "prettier/plugins/babel";
import * as Y from "prettier/plugins/postcss";
import * as K from "prettier/plugins/estree";
/**!
* Copyright (c) 2026, VTJ.PRO All rights reserved.
* @name @vtj/coder
* @author CHC chenhuachun1549@dingtalk.com
* @version 0.18.29
* @license <a href="https://vtj.pro/license.html">MIT License</a>
*/
const Tt = "0.18.29";
/**!
* Copyright (c) 2026, VTJ.PRO All rights reserved.
* @name @vtj/core
* @author CHC chenhuachun1549@dingtalk.com
* @version 0.18.29
* @license <a href="https://vtj.pro/license.html">MIT License</a>
*/
const Ce = [
"slot",
"template",
"component",
"img",
"div",
"p",
"h1",
"h2",
"h3",
"span",
"a"
];
ye();
const q = {
arrowParens: "always",
bracketSpacing: !0,
bracketSameLine: !0,
endOfLine: "lf",
htmlWhitespaceSensitivity: "css",
insertPragma: !1,
jsxBracketSameLine: !0,
jsxSingleQuote: !0,
printWidth: 80,
proseWrap: "preserve",
quoteProps: "as-needed",
requirePragma: !1,
semi: !0,
singleQuote: !0,
tabWidth: 2,
trailingComma: "none",
useTabs: !1,
vueIndentScriptAndStyle: !0,
removeBlankLines: !0
};
async function ee(t, e) {
return e ? t : await V(t, {
parser: "vue",
...q,
plugins: [Oe, X, K, Y]
});
}
async function xe(t, e) {
if (e) return t;
try {
return (await V(t, {
parser: "babel-ts",
...q,
plugins: [X, K]
})).replace(/;\n$/gi, "");
} catch (s) {
return console.warn(s), t;
}
}
async function z(t, e) {
return e ? t : V(t, {
parser: "scss",
...q,
plugins: [Y]
});
}
function R(t) {
return t && t.type === "JSExpression";
}
function U(t) {
return typeof t == "object" && t && t.type === "JSFunction";
}
function S(t) {
return R(t) || U(t);
}
function te(t) {
return t.replace(new RegExp("this.", "g"), "");
}
function W(t) {
return t.replace(/this\.context\??\./g, "");
}
function _(t, e = !0, s = !0, n = [], o = !0) {
let r = t;
return S(t) ? (r = t.value.trim().replace(/;$/, ""), o && (r = r.replace(/\"/g, "'"))) : r = e ? JSON.stringify(r) : t, r = D(r, n), s ? te(W(r)) : W(r);
}
function D(t = "", e = []) {
let s = t;
for (const n of e)
s = s.replace(
new RegExp(`this.${n}.value`, "g"),
`this.${n}`
);
return s;
}
function se(t) {
let e = t.trim().replace(/;$/, "");
if (e = /^\((\(|async|function)/.test(e) ? e.substring(1, e.length - 1) : e, e.startsWith("{")) return e;
if (e.startsWith("async function"))
e = e.replace(/^async function/, "async");
else if (e.startsWith("function"))
e = e.replace(/^function/, "");
else {
const o = /^(async\s)?\([\w]*\)\s+\=\>\s([\w\W]+)/, r = e.match(o);
r && r[2] && (r[2].startsWith("{") || (e = e.replace(r[2], `{ return ${r[2]} }`))), e = e.replace("=>", "");
}
return e;
}
function Ae(t = {}) {
return Object.entries(t).map(([e, s]) => `"${e}": ${_(s)}`);
}
function ne(t = {}, e = !1) {
const s = Object.keys(t);
return e ? s.map((n) => "." + n) : s;
}
function Pe(t) {
let e = "";
for (var s in t)
if (t.hasOwnProperty(s)) {
var n = t[s];
e += s + ": " + n + ";";
}
return e;
}
function Ee(t = [], e = []) {
return t.filter((s) => !e.includes(s));
}
function Z(t) {
return Se(JSON.stringify(t));
}
class Ne {
constructor(e, s) {
this.dsl = e, this.dependencies = s, this.collectEasycom(), this.libraryRegex = this.collectLibrary(), this.walk(e), this.walkNodes(e), this.members = this.getLibraryMember();
}
/**
* { 'element-plus': ['ElButton', 'ElInput' ...] }
*/
imports = {};
context = {};
style = {};
members = [];
urlSchemas = {};
blockPlugins = {};
/** 配置了 easycom 的依赖包名集合,出码时不需要 import */
easycomPackages = /* @__PURE__ */ new Set();
libraryRegex = [];
collectEasycom() {
for (const e of this.dependencies)
e.easycom?.key && e.easycom?.value && e.package && this.easycomPackages.add(e.package);
}
collectLibrary() {
return this.dependencies.filter((e) => !!e.library).map((e) => new RegExp(`(this.\\$libs.${e.library}.([\\w]+))`, "g"));
}
/**
* 收集 import 信息
* @param regexMatchItem ex: this.$libs.ElementPlus.ElButton
* @returns ex: { name: 'ElButton', path: 'this.$libs.ElementPlus.', library: 'ElementPlus' }
*/
collectImport(e) {
const s = e.split(".");
if (s.length === 4) {
const n = s.pop(), o = s.join(".") + ".", r = s.pop();
if (n && r) {
const c = this.dependencies.find(
(a) => a.library === r
)?.package;
c && !this.easycomPackages.has(c) && (this.imports[c] || (this.imports[c] = /* @__PURE__ */ new Set())).add(n);
}
return {
name: n,
path: o,
library: r
};
}
return null;
}
// 代码中包含依赖库的引用,需要从代码中移除
replaceLibraryPath(e) {
const { libraryRegex: s } = this;
let n = e.value;
for (const o of s) {
const r = e.value?.match(o) || [];
for (const c of r) {
const a = this.collectImport(c);
if (a) {
const l = a.path.replace(/\$/g, "\\$");
n = n.replace(new RegExp(l, "g"), "");
}
}
}
return n;
}
walk(e) {
const s = (n) => {
if (!n || typeof n != "object") return;
if (Array.isArray(n)) {
for (let r of n)
s(r);
return;
}
const o = Object.values(n);
for (const r of o)
S(r) ? r.value = this.replaceLibraryPath(r) : s(r);
};
s(e);
}
getLibraryMember(e = []) {
let s = [...e];
const n = { ...this.imports };
delete n["uni-h5"], delete n["@dcloudio/uni-h5"], delete n["uni-ui"], delete n["@dcloudio/uni-ui"];
for (const o of Object.values(n))
s = s.concat(Array.from(o));
return M(s);
}
collectContext(e, s) {
const n = new Set(s?.id ? this.context[s.id] : []), o = (e.directives || []).find((a) => a.name === "vFor");
let r = new Set(Array.from(n));
if (o) {
const { item: a = "item", index: l = "index" } = o.iterator || {};
r = /* @__PURE__ */ new Set([a, l, ...Array.from(r)]);
}
const c = e.slot;
if (c) {
const a = typeof c == "string" ? [] : c.params || [], l = a.length ? a : [`scope_${s?.id}`];
r = /* @__PURE__ */ new Set([...l, ...Array.from(r)]);
}
this.context[e.id] = r;
}
collectStyle(e) {
e.id && e.props?.style && Object.keys(e.props.style).length && !S(e.props.style) && (this.style[`.${e.name}_${e.id}`] = e.props.style);
}
collectUrlSchema(e) {
typeof e.from == "object" && e.from.type === "UrlSchema" && (this.urlSchemas[e.name] = e.from);
}
collectBlockPlugin(e) {
typeof e.from == "object" && e.from.type === "Plugin" && (this.blockPlugins[e.name] = e.from);
}
walkNodes(e) {
const s = (n, o) => {
this.collectContext(n, o), this.collectStyle(n), this.collectUrlSchema(n), this.collectBlockPlugin(n), Array.isArray(n.children) && n.children.forEach((r) => s(r, n));
};
Array.isArray(e.nodes) && e.nodes.forEach((n) => s(n));
}
}
function Be(t = {}) {
return Object.entries(t).map(([e, s]) => {
const n = _(s, !1, !0, [], !1);
return `${e}:${n}`;
});
}
function Te(t = []) {
return t.map((e) => `${e.name}: {
from: '${e.from || e.name}',
default: ${_(e.default, !0, !1, [], !1)}
}`);
}
function re(t = []) {
const e = (s) => s ? `[${je(s).map((r) => r.replace(/\'|\"/gi, "")).join(",")}]` : void 0;
return t.map((s) => typeof s == "string" ? `${s}: {}` : (S(s.default) && !s.default.value && (s.default.value = "undefined"), `${s.name}: {
type:${e(s.type)},
required: ${_(!!s.required, !0, !1, [], !1)},
default: ${s.default ? _(s.default, !0, !1, [], !1) : "undefined"}
}`));
}
function oe(t = []) {
return t.map((e) => `'${typeof e == "string" ? e : e.name}'`);
}
function F(t = {}, e = []) {
return Object.entries(t).map(([s, n]) => {
let o = se(
_(n, !1, !1, [], !1)
);
return o = D(o, e)?.trim(), o.startsWith("async") ? `async ${s}${o.replace(/^async/, "")}` : o.startsWith("(") || o.startsWith("{") ? `${s}${o}` : null;
}).filter((s) => !!s);
}
function Me(t = [], e = []) {
const s = t.reduce(
(r, c) => (c.id && U(c.source) && (r[`watcher_${c.id}`] = c.source), r),
{}
), n = F(s, e), o = t.map((r) => r.handler && r.handler.value ? `watcher_${r.id}: {
deep: ${r.deep},
immediate:${r.immediate},
handler${se(r.handler.value)}
}` : null).filter((r) => !!r);
return {
computed: n,
watches: o
};
}
function Re(t = {}) {
return Object.values(t).map((e) => {
if (e.type === "mock") {
const s = U(e.mockTemplate) && e.mockTemplate.value || "(params) => ({})";
return `async ${e.name}(...args) {
// DataSource: ${Z(e)}
const mock = this.provider.createMock(${s});
return await mock.apply(this, args);
}`;
} else {
const s = U(e.transform) && e.transform.value || "(res) => res";
return `async ${e.name}(...args) {
// DataSource: ${Z(e)}
return await this.provider.apis['${e.ref}'].apply(this, args).then(${s});
}`;
}
});
}
const De = [
"img",
"input",
"br",
"hr",
"area",
"base",
"col",
"embed",
"link",
"meta",
"param",
"source",
"track",
"wbr"
], Q = [
"vIf",
"vElseIf",
"vElse",
"vShow",
"vModel",
"vFor",
"vBind",
"vHtml"
];
function G(t, e, s = [], n = {}, o, r = /* @__PURE__ */ new Set()) {
const c = [];
let a = {}, l = [];
const p = [];
let m = [];
return Le(t).forEach((u) => {
const f = [];
for (const g of u.children) {
let { id: w, name: d, invisible: v, from: h } = g;
if (v)
continue;
const y = Fe(d, e, h);
y && l.push(y), ce(h) && m.push({ id: h.id, name: d });
const { props: $, events: k } = qe(
g,
w,
g.props,
g.events,
n,
s
), C = Ge(
g.directives,
s,
p
).join(" "), O = g.children ? Qe(
g.children,
s,
e,
n,
g,
r
) : "";
let N = "";
typeof O == "string" ? N = O : (N = (O?.nodes || []).join(`
`), Object.assign(a, O?.methods || {}), l = l.concat(O?.components || []), m = m.concat(O?.importBlocks || []));
const B = h || e.get(d)?.package, T = r.has(B) ? J(d) : ["@dcloudio/uni-h5", "@dcloudio/uni-ui"].includes(B) ? J(d) : ae(h) || ie(h) ? "component" : d;
f.push(
De.includes(T) ? `<${T} ${C} ${$} ${k} />` : `<${T} ${C} ${$} ${k}>${N ? `
` + N.trim() : ""}</${T}>`
);
}
const b = Xe(u.slot, f.join(`
`), o?.id);
c.push(b);
}), {
nodes: c,
methods: a,
directives: Ue(p),
components: M(l),
importBlocks: M(m, "id")
};
}
function Ue(t) {
return M(t).map((e) => `${e.startsWith("v") ? e.substring(1) : e}:${e}`);
}
function Le(t = []) {
const e = /* @__PURE__ */ new Map();
for (const s of t) {
const n = typeof s.slot == "string" ? s.slot : s.slot?.name, o = e.get(n);
o ? o.children.push(s) : e.set(n, { slot: s.slot, children: [s] });
}
return e;
}
function Fe(t, e, s) {
if (Ce.includes(t)) return null;
const n = e.get(t);
if (n && n.alias) {
const o = n.parent ? `${n.parent}.${n.alias}` : n.alias;
return `${t}: ${o}`;
}
return ce(s) || n ? t : null;
}
function ce(t) {
return !!t && typeof t == "object" && t.type === "Schema";
}
function ae(t) {
return typeof t == "object" && t.type === "UrlSchema";
}
function ie(t) {
return typeof t == "object" && t.type === "Plugin";
}
function Je(t, e, s = []) {
return t === "style" ? S(e) ? `:style="${_({
...e,
value: D(e.value, s)
})}"` : "" : t === "__class" && S(e) ? `:class="${_({
...e,
value: D(e.value, s)
})}"` : typeof e == "string" ? `${t}="${e}"` : S(e) ? `:${t}="${_({
...e,
value: D(e.value, s)
})}"` : ke(e) ? `:${t}='{${Ae(
e
).join(", ")}}'` : `:${t}='${JSON.stringify(e)}'`;
}
function We(t, e = {}, s = []) {
if (!!Object.keys(e.style || {}).length) {
const r = `${t.name}_${t.id}`;
e.class ? typeof e.class == "string" ? e.class = [e.class, r].join(" ") : (e.__class = e.class, e.class = r) : e.class = r, S(e.style) || delete e.style;
}
const o = t.from;
return (ae(o) || ie(o)) && (e.is = {
type: "JSExpression",
value: t.name
}), Object.entries(e).map(([r, c]) => Je(r, c, s));
}
function He(t, e, s) {
const n = ne(e.modifiers, !0);
return `@${t}${n.join("")}="${s}"`;
}
function Ve(t, e = {}, s = {}) {
const n = {};
return {
binders: Object.entries(e).map(([r, c]) => {
const a = te(W(c.handler.value)).replace(
/\"/g,
"'"
);
return He(r, c, a);
}),
handlers: n
};
}
function qe(t, e, s = {}, n = {}, o = {}, r) {
const { binders: c, handlers: a } = Ve(e, n, o);
return {
props: We(t, s, r).join(" "),
handlers: a,
binders: c,
events: c.join(" ")
};
}
function Ge(t = [], e = [], s = []) {
const n = [], {
vIf: o,
vElse: r,
vElseIf: c,
vShow: a,
vModels: l,
vFor: p,
vBind: m,
vHtml: i,
customDirectives: u
} = ze(t);
if (o && n.push(`v-if="${_(o.value, !0, !0, e)}"`), c && n.push(
`v-else-if="${_(c.value, !0, !0, e)}"`
), r && n.push("v-else"), a && n.push(
`v-show="${_(a.value, !0, !0, e)}"`
), m && n.push(
`v-bind="${_(m.value, !0, !0, e)}"`
), l.forEach((f) => {
const b = ne(f.modifiers, !0), g = f.arg ? R(f.arg) ? `:[${_(f.arg, !0, !0, e)}]` : `:${f.arg}` : "";
n.push(
`v-model${g}${b}="${_(f.value, !0, !0, e)}"`
);
}), p) {
const { item: f, index: b } = { item: "item", index: "index", ...p.iterator };
n.push(
`v-for="(${f}, ${b}) in ${_(p.value, !0, !0, e)}"`
);
}
return i && n.push(
`v-html="${_(i.value, !0, !0, e)}"`
), u && u.length && u.forEach((f) => {
if (!f.name) return;
let b = "", g = "";
R(f.name) ? (g = _(f.name, !0, !0, e), s.push(g)) : g = f.name;
const w = g?.startsWith("v") ? J(g) : J("v-" + g);
if (b += w, f.arg && (R(f.arg) ? b += `:[${_(f.name, !0, !0, e)}]` : b += `:${f.arg}`), f.modifiers) {
const d = Object.keys(f.modifiers);
d.length && (b += d.map((v) => "." + v));
}
f.value ? n.push(
`${b}="${_(f.value, !0, !0, e)}"`
) : n.push(b);
}), n;
}
function ze(t = []) {
const e = t.filter(
(i) => Q.includes(i.name)
), s = t.filter(
(i) => !Q.includes(i.name)
), n = e.find(
(i) => A(i.name) === "vIf"
), o = e.find(
(i) => A(i.name) === "vElseIf"
), r = e.find(
(i) => A(i.name) === "vElse"
), c = e.find(
(i) => A(i.name) === "vFor"
), a = e.find(
(i) => A(i.name) === "vShow"
), l = e.find(
(i) => A(i.name) === "vBind"
), p = e.find(
(i) => A(i.name) === "vHtml"
), m = e.filter(
(i) => A(i.name) === "vModel"
);
return {
vIf: n,
vElseIf: o,
vElse: r,
vFor: c,
vShow: a,
vModels: m,
vBind: l,
vHtml: p,
customDirectives: s
};
}
function Ze(t) {
return t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
function Qe(t, e, s, n, o, r = /* @__PURE__ */ new Set()) {
return typeof t == "string" ? Ze(t) : R(t) ? `{{ ${_(t, !1, !0, e)} }}` : Array.isArray(t) ? G(
t,
s,
e,
n,
o,
r
) : "";
}
function Xe(t, e, s) {
if (!t) return e;
const n = typeof t == "string" ? { name: t, params: [], scope: "" } : { params: [], scope: "", ...t };
return `<template ${`#${n.name}="${n.scope ? n.scope : n.params?.length > 0 ? `{${n.params?.join(",")}}` : `scope_${s}`}"`}>
${e}
</template>`;
}
function Ye(t, e = [], s = [], n = {}, o = "web", r = /* @__PURE__ */ new Set()) {
const c = [
"@dcloudio/uni-h5",
"uni-h5",
"@dcloudio/uni-ui",
"uni-ui"
], a = {
vue: ["defineComponent", "reactive"]
}, l = [];
for (const m of e) {
const i = t.get(m.split(":")[0]);
if (i && i.package) {
if (r.has(i.package)) continue;
const u = a[i.package] ?? (a[i.package] = []), f = i.parent || (i.alias || "").split(".")[0] || i.name;
u.push(f), o === "uniapp" && c.includes(i.package) && l.push(f);
}
}
for (const [m, i] of Object.entries(n))
(a[m] ?? (a[m] = [])).push(...Array.from(i)), o === "uniapp" && c.includes(m) && l.push(...Array.from(i));
return {
imports: Object.entries(a).filter(([m, i]) => o === "uniapp" ? !c.includes(m) && !!i.length : !!i.length).map(([m, i]) => `import { ${M(i).join(
","
)}} from '${m}';`).concat(s),
uniComponents: l
};
}
function le(t = {}) {
const e = [];
for (const [s, n] of Object.entries(t))
e.push(`
${s} {
${Pe(n)}
}
`);
return e.join(`
`);
}
function ue(t = {}) {
const e = [];
return Object.entries(t).forEach(([s, n]) => {
e.push(
`const ${s} = provider.defineUrlSchemaComponent('${n.url}');`
);
}), e;
}
function pe(t = {}) {
const e = [];
return Object.entries(t).forEach(([s, n]) => {
e.push(
`const ${s} = provider.definePluginComponent(${JSON.stringify(n)});`
);
}), e;
}
function Ke(t, e, s = "web") {
const { dsl: n } = t, o = Object.keys(n.computed || {}), r = F(n.lifeCycles, o), c = F(n.computed, o), a = Me(n.watch, o), l = Re(n.dataSources), { methods: p, nodes: m, components: i, importBlocks: u, directives: f } = G(
n.nodes || [],
e,
o,
t.context,
void 0,
t.easycomPackages
), b = [...c, ...a.computed], g = F(
{
...p,
...n.methods || {}
},
o
), w = u.map((k) => `import ${k.name} from './${k.id}.vue';`);
let { imports: d, uniComponents: v } = Ye(
e,
i,
w,
t.imports,
s,
t.easycomPackages
);
const h = Object.keys({
...t.urlSchemas,
...t.blockPlugins
}), y = ue(t.urlSchemas), $ = pe(t.blockPlugins);
return {
id: n.id,
version: n.__VERSION__,
name: n.name,
state: Be(n.state).join(","),
inject: Te(n.inject).join(","),
props: re(n.props).join(","),
emits: oe(n.emits).join(","),
expose: n.expose && n.expose.length ? JSON.stringify(n.expose || []) : "",
watch: a.watches.join(","),
lifeCycles: r.join(","),
computed: b.join(","),
methods: [...l, ...g].join(","),
imports: `
` + d.join(`
`),
components: Ee(i, v).join(","),
directives: f.join(","),
returns: t.members.join(","),
template: m.join(`
`),
css: n.css || "",
style: le(t.style),
urlSchemas: y.join(`
`),
blockPlugins: $.join(`
`),
asyncComponents: h.join(","),
uniComponents: v,
renderer: s === "uniapp" ? "@vtj/uni-app" : "@vtj/renderer"
};
}
const E = {
state: {
composable: null,
from: "self",
declare: null,
replace: "__state"
},
$uni: {
composable: null,
from: "self",
declare: null,
replace: "uni"
},
$getApp: {
composable: null,
from: "self",
declare: null,
replace: "getApp"
},
// ---- Vue 原生 ----
$emit: {
composable: null,
from: "vue",
declare: null,
replace: "__emit"
},
$props: {
composable: null,
from: "vue",
declare: null,
replace: "__props"
},
$attrs: {
composable: "useAttrs",
from: "vue",
declare: "const __attrs = useAttrs();",
replace: "__attrs"
},
$slots: {
composable: "useSlots",
from: "vue",
declare: "const __slots = useSlots();",
replace: "__slots"
},
$nextTick: {
composable: "nextTick",
from: "vue",
declare: null,
replace: "nextTick"
},
$watch: {
composable: "watch",
from: "vue",
declare: null,
replace: "watch"
},
$refs: {
composable: "getCurrentInstance",
from: "vue",
declare: "const __instance = getCurrentInstance();",
replace: "__instance.proxy.$refs"
},
$el: {
composable: "getCurrentInstance",
from: "vue",
declare: "const __instance = getCurrentInstance();",
replace: "__instance.proxy.$el"
},
$root: {
composable: "getCurrentInstance",
from: "vue",
declare: "const __instance = getCurrentInstance();",
replace: "__instance.proxy.$root"
},
$parent: {
composable: "getCurrentInstance",
from: "vue",
declare: "const __instance = getCurrentInstance();",
replace: "__instance.proxy.$parent"
},
$options: {
composable: "getCurrentInstance",
from: "vue",
declare: "const __instance = getCurrentInstance();",
replace: "__instance.proxy.$options"
},
$forceUpdate: {
composable: "getCurrentInstance",
from: "vue",
declare: "const __instance = getCurrentInstance();",
replace: "__instance.proxy.$forceUpdate"
},
// ---- vue-router ----
$router: {
composable: "useRouter",
from: "vue-router",
declare: "const __router = useRouter();",
replace: "__router"
},
$route: {
composable: "useRoute",
from: "vue-router",
declare: "const __route = useRoute();",
replace: "__route"
},
// ---- vue-i18n ----
$i18n: {
composable: "useI18n",
from: "vue-i18n",
declare: "const __i18n = useI18n();",
replace: "__i18n"
},
$t: {
composable: "useI18n",
from: "vue-i18n",
declare: "const __i18n = useI18n();",
replace: "__i18n.t"
},
$n: {
composable: "useI18n",
from: "vue-i18n",
declare: "const __i18n = useI18n();",
replace: "__i18n.n"
},
$d: {
composable: "useI18n",
from: "vue-i18n",
declare: "const __i18n = useI18n();",
replace: "__i18n.d"
},
$rt: {
composable: "useI18n",
from: "vue-i18n",
declare: "const __i18n = useI18n();",
replace: "__i18n.rt"
},
$te: {
composable: "useI18n",
from: "vue-i18n",
declare: "const __i18n = useI18n();",
replace: "__i18n.te"
},
$tm: {
composable: "useI18n",
from: "vue-i18n",
declare: "const __i18n = useI18n();",
replace: "__i18n.tm"
},
// ---- @vtj/renderer ----
// 注:from 使用特殊标记 '__renderer__',运行时会与 useProvider 合并到同一条 import 语句
$provider: {
composable: "useStore",
from: "__renderer__",
declare: null,
replace: "__provider"
},
$store: {
composable: "useStore",
from: "__renderer__",
declare: "const __store = useStore();",
replace: "__store"
},
$pinia: {
composable: "usePinia",
from: "__renderer__",
declare: "const __pinia = usePinia();",
replace: "__pinia"
},
$request: {
composable: "useRequest",
from: "__renderer__",
declare: "const __request = useRequest();",
replace: "__request"
},
$libs: {
composable: "useLibs",
from: "__renderer__",
declare: "const __libs = useLibs();",
replace: "__libs"
},
$access: {
composable: "useAccess",
from: "__renderer__",
declare: "const __access = useAccess();",
replace: "__access"
},
$apis: {
composable: "useApis",
from: "__renderer__",
declare: "const __apis = useApis();",
replace: "__apis"
}
}, fe = {
"element-plus": {
$loading: {
composable: "ElLoading",
from: "element-plus",
declare: null,
replace: "ElLoading.service"
},
$message: {
composable: "ElMessage",
from: "element-plus",
declare: null,
replace: "ElMessage"
},
$notify: {
composable: "ElNotification",
from: "element-plus",
declare: null,
replace: "ElNotification"
},
$messageBox: {
composable: "ElMessageBox",
from: "element-plus",
declare: null,
replace: "ElMessageBox"
},
$msgbox: {
composable: "ElMessageBox",
from: "element-plus",
declare: null,
replace: "ElMessageBox"
},
$confirm: {
composable: "ElMessageBox",
from: "element-plus",
declare: null,
replace: "ElMessageBox.confirm"
},
$prompt: {
composable: "ElMessageBox",
from: "element-plus",
declare: null,
replace: "ElMessageBox.prompt"
}
},
"ant-design-vue": {
$confirm: {
composable: "Modal",
from: "ant-design-vue",
declare: null,
replace: "Modal.confirm"
},
$message: {
composable: "message",
from: "ant-design-vue",
declare: null,
replace: "message"
},
$notification: {
composable: "notification",
from: "ant-design-vue",
declare: null,
replace: "notification"
},
$info: {
composable: "message",
from: "ant-design-vue",
declare: null,
replace: "message.info"
},
$success: {
composable: "message",
from: "ant-design-vue",
declare: null,
replace: "message.success"
},
$warning: {
composable: "message",
from: "ant-design-vue",
declare: null,
replace: "message.warning"
},
$error: {
composable: "message",
from: "ant-design-vue",
declare: null,
replace: "message.error"
}
}
}, et = Object.keys(fe);
function tt(t) {
for (const [, e] of t)
if (et.includes(e.package))
return e.package;
return null;
}
function st(t) {
const e = t ? fe[t] ?? {} : {};
return { ...E, ...e };
}
function nt(t, e = E) {
const s = /* @__PURE__ */ new Set(), n = /this\.\$(\w+)\b/g, o = (r) => {
if (r && typeof r == "object") {
if (Array.isArray(r)) {
for (const c of r) o(c);
return;
}
if (S(r) && r.value) {
let c;
for (n.lastIndex = 0; (c = n.exec(r.value)) !== null; ) {
const a = "$" + c[1];
a in e && s.add(a);
}
return;
}
for (const c of Object.values(r))
o(c);
}
};
return o(t.refs), o(t.reactives), o(t.state), o(t.computed), o(t.methods), o(t.watch), o(t.lifeCycles), o(t.inject), o(t.composables), o(t.provide), o(t.dataSources), o(t.setup), o(t.nodes), s;
}
function rt(t, e = E) {
const s = [];
for (const n of t) {
const o = e[n];
o && o.declare && !s.includes(o.declare) && s.push(o.declare);
}
return s;
}
function ot(t, e = E) {
const s = {};
for (const n of t) {
const o = e[n];
if (o && o.composable) {
const r = s[o.from] ?? (s[o.from] = []);
r.includes(o.composable) || r.push(o.composable);
}
}
return s;
}
function ct(t, e = E) {
const s = new Set(Object.keys(t.refs ?? {})), n = new Set(Object.keys(t.reactives ?? {})), r = Object.keys(t.state ?? {}).length > 0;
r && n.add("__state");
const c = new Set(Object.keys(t.computed ?? {})), a = new Set(Object.keys(t.methods ?? {})), l = /* @__PURE__ */ new Set();
for (const u of t.props ?? [])
we(u) ? l.add(u) : l.add(u.name);
const p = /* @__PURE__ */ new Set();
for (const u of t.composables ?? [])
if (u.destructure && u.destructure.length > 0)
for (const f of u.destructure) p.add(f);
else u.name && p.add(u.name);
const m = /* @__PURE__ */ new Set();
for (const u of t.inject ?? [])
u.name && m.add(u.name);
const i = /* @__PURE__ */ new Set();
for (const [, u] of Object.entries(t.dataSources ?? {}))
u.name && i.add(u.name);
return {
refs: s,
reactives: n,
computed: c,
methods: a,
props: l,
composables: p,
injects: m,
dataSources: i,
hasState: r,
effectiveApiMap: e
};
}
function j(t, e, s = "script") {
if (!t) return t;
let n = t;
for (const [o, r] of Object.entries(e.effectiveApiMap)) {
const c = o.replace(/\$/g, "\\$"), a = new RegExp(`this\\.${c}\\b`, "g");
n = n.replace(a, r.replace);
}
return n = n.replace(
/this\.([A-Za-z_$][\w$]*)\.value\b/g,
(o, r) => e.refs.has(r) || e.computed.has(r) ? s === "script" ? `${r}.value` : r : o
), n = n.replace(/this\.([A-Za-z_$][\w$]*)/g, (o, r) => e.refs.has(r) || e.computed.has(r) ? s === "script" ? `${r}.value` : r : r === "state" ? "__state" : e.reactives.has(r) || e.methods.has(r) || e.composables.has(r) || e.injects.has(r) || e.dataSources.has(r) ? r : e.props.has(r) ? s === "script" ? `__props.${r}` : r : o), n;
}
function P(t) {
let e = t.trim().replace(/;$/, "");
return /^\((\(|async|function)/.test(e) && (e = e.substring(1, e.length - 1).trim()), e;
}
function at(t = {}, e) {
return Object.entries(t).map(([s, n]) => {
let o;
return S(n) ? o = j(n.value || "undefined", e, "script") : o = JSON.stringify(n), `const ${s} = ref(${o});`;
});
}
function it(t = {}, e) {
return Object.entries(t).map(([s, n]) => {
let o;
return S(n) ? o = j(n.value || "{}", e, "script") : o = JSON.stringify(n ?? {}), `const ${s} = reactive(${o});`;
});
}
function lt(t = {}, e) {
const s = Object.entries(t);
return s.length === 0 ? "" : `const __state = reactive({ ${s.map(([o, r]) => {
let c;
return S(r) ? c = j(r.value || "undefined", e, "script") : c = JSON.stringify(r), `${o}: ${c}`;
}).join(", ")} });`;
}
function ut(t = [], e) {
const s = [], n = {}, o = /* @__PURE__ */ new Set();
for (const r of t) {
if (!r || !r.composable) continue;
let c = "";
if (S(r.composable) ? c = r.composable.value || "" : typeof r.composable == "string" && (c = r.composable), !c || c === "useProvider") continue;
if (r.name) {
if (o.has(r.name)) continue;
o.add(r.name);
}
const l = (r.args ?? []).map((p) => S(p) ? j(p.value || "", e, "script") : JSON.stringify(p)).join(", ");
r.destructure && r.destructure.length > 0 ? s.push(
`const { ${r.destructure.join(", ")} } = ${c}(${l});`
) : r.name ? s.push(`const ${r.name} = ${c}(${l});`) : s.push(`${c}(${l});`);
}
return { statements: s, imports: n };
}
function pt(t = [], e) {
return t.map((s) => {
const n = S(s.from) ? j(
s.from.value || `'${s.name}'`,
e,
"script"
) : `'${s.from || s.name}'`;
let o = "undefined";
return s.default !== void 0 && s.default !== null && (S(s.default) ? o = j(
s.default.value || "undefined",
e,
"script"
) : o = JSON.stringify(s.default)), `const ${s.name} = inject(${n}, ${o});`;
});
}
function ft(t = {}, e) {
return Object.entries(t).map(([s, n]) => {
if (!n || !n.value) return null;
const o = j(n.value, e, "script"), r = P(o);
return `const ${s} = computed(${r});`;
}).filter((s) => !!s);
}
function mt(t = {}, e) {
return Object.entries(t).map(([s, n]) => {
if (!n || !n.value) return null;
const o = j(n.value, e, "script"), r = P(o);
return `const ${s} = ${r};`;
}).filter((s) => !!s);
}
function dt(t = {}, e) {
return Object.values(t).map((s) => {
if (!s || !s.name) return null;
if (s.type === "mock") {
const n = s.mockTemplate && s.mockTemplate.value ? s.mockTemplate.value : "(params) => ({})", o = e ? j(n, e, "script") : n;
return `const ${s.name} = async (...args) => {
const mock = __provider.createMock(${o});
return await mock.apply(null, args);
};`;
} else {
const n = s.transform && s.transform.value ? s.transform.value : "(res) => res", o = e ? j(n, e, "script") : n;
return `const ${s.name} = async (...args) => {
return await __provider.apis['${s.ref}'].apply(null, args).then(${o});
};`;
}
}).filter((s) => !!s);
}
function ht(t = [], e) {
return t.map((s) => {
if (!s || !s.handler || !s.handler.value) return null;
const n = s.source && s.source.value ? j(s.source.value, e, "script") : "() => null", o = P(n), r = j(
s.handler.value,
e,
"script"
), c = P(r), a = [];
s.deep && a.push("deep: true"), s.immediate && a.push("immediate: true"), s.flush && a.push(`flush: '${s.flush}'`);
const l = a.length > 0 ? `, { ${a.join(", ")} }` : "";
return `watch(${o}, ${c}${l});`;
}).filter((s) => !!s);
}
function gt(t = {}, e) {
return Object.entries(t).map(([s, n]) => {
let o;
if (U(n)) {
const r = j(
n.value || "",
e,
"script"
);
o = P(r);
} else S(n) ? o = j(n.value || "undefined", e, "script") : o = JSON.stringify(n);
return `provide('${s}', ${o});`;
});
}
function me(t) {
let e = t.trim().replace(/;$/, "");
/^\((\(|async|function)/.test(e) && (e = e.substring(1, e.length - 1).trim());
const s = e.match(/^(?:async\s+)?\([^)]*\)\s*=>\s*([\s\S]+)$/);
if (s) {
let o = s[1].trim();
return o.startsWith("{") && o.endsWith("}") ? o = o.slice(1, -1).trim() : o = o.replace(/;$/, "") + ";", o;
}
const n = e.match(
/^(?:async\s+)?function\s*\w*\s*\([^)]*\)\s*\{([\s\S]*)\}$/
);
return n ? n[1].trim() : e;
}
function vt(t, e) {
if (!t || !t.value) return "";
const s = j(t.value, e, "script");
return me(s);
}
function $t(t = {}, e) {
const s = [];
for (const n of ["beforeCreate", "created"]) {
const o = t[n];
if (o && o.value) {
const r = j(o.value, e, "script"), c = me(r);
c && s.push(`// ${n}
${c}`);
}
}
return s.join(`
`);
}
const bt = {
beforeMount: "onBeforeMount",
mounted: "onMounted",
beforeUpdate: "onBeforeUpdate",
updated: "onUpdated",
beforeUnmount: "onBeforeUnmount",
unmounted: "onUnmounted",
errorCaptured: "onErrorCaptured",
renderTracked: "onRenderTracked",
renderTriggered: "onRenderTriggered",
activated: "onActivated",
deactivated: "onDeactivated"
}, _t = /* @__PURE__ */ new Set([
"onBeforeMount",
"onMounted",
"onBeforeUpdate",
"onUpdated",
"onBeforeUnmount",
"onUnmounted",
"onErrorCaptured",
"onRenderTracked",
"onRenderTriggered",
"onActivated",
"onDeactivated"
]), yt = /* @__PURE__ */ new Set([
"onLoad",
"onShow",
"onReady",
"onHide",
"onUnload",
"onResize",
"onPullDownRefresh",
"onReachBottom",
"onTabItemTap",
"onShareAppMessage",
"onPageScroll",
"onNavigationBarButtonTap",
"onBackPress",
"onNavigationBarSearchInputChanged",
"onNavigationBarSearchInputConfirmed",
"onNavigationBarSearchInputClicked",
"onShareTimeline",
"onAddToFavorites"
]);
function St(t = {}, e) {
const s = [], n = /* @__PURE__ */ new Set(), o = /* @__PURE__ */ new Set();
for (const [r, c] of Object.entries(t)) {
if (!c || !c.value || r === "created" || r === "beforeCreate") continue;
const a = bt[r] || r;
if (_t.has(a)) {
const l = j(c.value, e, "script"), p = P(l);
s.push(`${a}(${p});`), n.add(a);
} else if (yt.has(a)) {
const l = j(c.value, e, "script"), p = P(l);
s.push(`${a}(${p});`), o.add(a);
}
}
return { statements: s, usedHooks: n, usedUniHooks: o };
}
function jt(t) {
const {
componentMap: e,
components: s,
importBlocks: n,
collectImports: o,
platform: r,
vueImports: c,
composableImports: a,
globalApiImports: l,
uniHookImports: p,
easycomPackages: m
} = t, i = [
"@dcloudio/uni-h5",
"uni-h5",
"@dcloudio/uni-ui",
"uni-ui"
], u = {
vue: [...c]
}, f = [], b = [], g = {};
for (const d of s) {
const v = d.split(":")[0], h = e.get(v);
if (!h || !h.package || h.parent || m.has(h.package)) continue;
const y = u[h.package] ?? (u[h.package] = []), $ = (h.alias || "").split(".")[0] || h.name, k = v, C = $ !== k ? `${$} as ${k}` : $;
y.push(C), g[$] = k, r === "uniapp" && i.includes(h.package) && f.push($);
}
for (const d of s) {
const v = d.split(":")[0], h = e.get(v);
if (!h || !h.package || !h.parent || m.has(h.package)) continue;
const y = h.parent, $ = g[y] ?? y, k = h.alias || "";
b.push(
`const ${v} = ${$}.${k};`
), g[y] || ((u[h.package] ?? (u[h.package] = [])).push(y), g[y] = y);
}
for (const [d, v] of Object.entries(o))
(u[d] ?? (u[d] = [])).push(...Array.from(v)), r === "uniapp" && i.includes(d) && f.push(...Array.from(v));
for (const [d, v] of Object.entries(a))
(u[d] ?? (u[d] = [])).push(...v);
for (const [d, v] of Object.entries(l))
(u[d] ?? (u[d] = [])).push(...v);
return r === "uniapp" && p.length > 0 && (u["@dcloudio/uni-app"] ?? (u["@dcloudio/uni-app"] = [])).push(...p), { imports: Object.entries(u).filter(([d, v]) => r === "uniapp" ? !i.includes(d) && !!v.length : !!v.length).map(([d, v]) => `import { ${M(v).join(
","
)}} from '${d}';`).concat(n), uniComponents: f, componentDeclarations: b };
}
function kt(t, e = E, s = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set()) {
const o = Object.entries(e), r = (c) => {
if (c == null || typeof c != "object") return c;
if (Array.isArray(c))
return c.map(r);
if (S(c) && typeof c.value == "string") {
let l = c.value;
for (const [p, m] of o) {
const i = p.replace(/\$/g, "\\$"), u = new RegExp(`this\\.${i}\\b`, "g");
l = l.replace(u, m.replace);
}
return l = l.replace(/this\.([A-Za-z_$][\w$]*)\.value\b/g, (p, m) => s.has(m) || n.has(m) ? m : p), { ...c, value: l };
}
const a = {};
for (const [l, p] of Object.entries(c))
a[l] = r(p);
return a;
};
return t.map(r);
}
function wt(t, e, s = [], n = {}, o, r = E, c = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Set()) {
const p = kt(
t,
r,
c,
a
);
return G(
p,
e,
s,
n,
o,
l
);
}
function It(t, e, s = "web") {
const { dsl: n } = t, o = tt(e), r = st(o), c = ct(n, r), a = nt(n, r), l = rt(a, r), p = ot(a, r), m = p.__renderer__ || [];
delete p.__renderer__;
const i = wt(
n.nodes || [],
e,
Object.keys(n.computed || {}),
t.context,
void 0,
r,
c.refs,
c.computed,
t.easycomPackages
), u = i.importBlocks.map(
(I) => `import ${I.name} from './${I.id}.vue';`
), f = at(n.refs || {}, c), b = it(n.reactives || {}, c), g = lt(n.state || {}, c), w = ft(n.computed || {}, c), d = {
...i.methods || {},
...n.methods || {}
}, v = mt(d, c), h = dt(n.dataSources || {}, c), y = ht(n.watch || [], c), $ = pt(n.inject || [], c), k = gt(n.provide || {}, c), C = ut(
n.composables || [],
c
), O = /* @__PURE__ */ new Set();
for (const I of n.composables || [])
if (I.destructure && I.destructure.length > 0)
for (const L of I.destructure) O.add(L);
else I.name && O.add(I.name);
const N = l.filter((I) => {
const L = I.match(/^const\s+(\w+)\s*=/);
return !(L && O.has(L[1]));
}), B = St(n.lifeCycles || {}, c), T = $t(
n.lifeCycles || {},
c
), de = vt(n.setup, c), x = /* @__PURE__ */ new Set();
f.length > 0 && x.add("ref"), (b.length > 0 || g) && x.add("reactive"), w.length > 0 && x.add("computed"), y.length > 0 && x.add("watch"), $.length > 0 && x.add("inject"), k.length > 0 && x.add("provide");
for (const I of B.usedHooks) x.add(I);
const he = s === "uniapp" ? Array.from(B.usedUniHooks) : [], { imports: ge, uniComponents: ve, componentDeclarations: $e } = jt({
componentMap: e,
components: i.components,
importBlocks: u,
collectImports: t.imports,
platform: s,
vueImports: Array.from(x),
composableImports: C.imports,
globalApiImports: p,
uniHookImports: he,
easycomPackages: t.easycomPackages
}), be = ue(t.urlSchemas), _e = pe(t.blockPlugins);
return {
id: n.id,
version: n.__VERSION__,
name: n.name,
imports: `
` + ge.join(`
`),
props: re(n.props).join(","),
emits: oe(n.emits).join(","),
needsProps: a.has("$props"),
needsEmit: a.has("$emit"),
expose: n.expose && n.expose.length ? `{ ${n.expose.join(", ")} }` : "",
globalApiDeclares: N.join(`
`),
injects: $.join(`
`),
composables: C.statements.join(`
`),
state: g,
refs: f.join(`
`),
reactives: b.join(`
`),
computed: w.join(`
`),
methods: v.join(`
`),
dataSources: h.join(`
`),
watch: y.join(`
`),
provide: k.join(`
`),
createdStatements: T,
setupStatements: de,
lifeCycles: B.statements.join(`
`),
template: i.nodes.join(`
`),
css: n.css || "",
style: le(t.style),
urlSchemas: be.join(`
`),
blockPlugins: _e.join(`
`),
uniComponents: ve,
renderer: s === "uniapp" ? "@vtj/uni-app" : "@vtj/renderer",
rendererImports: ["useProvider", ...m].join(", "),
componentDeclarations: $e.join(`
`)
};
}
const Ot = `
// @ts-nocheck
import { useProvider } from '<%= renderer %>';
<%= imports %>
export default defineComponent({
name: '<%= name %>',
<% if(inject) { %> inject: { <%= inject %>}, <% } %>
<% if(components) { %> components: { <%= components %> }, <% } %>
<% if(directives) { %> directives: { <%= directives %> }, <% } %>
<% if(props) { %> props: { <%= props %> }, <% } %>
<% if(emits) {%> emits: [<%= emits %>], <% } %>
<% if(expose) {%> expose: <%= expose %>, <% } %>
setup(props) {
const provider = useProvider({
id: '<%= id %>',
version: '<%= version %>'
});
const state = reactive({ <%= state %> });
<%= urlSchemas %>
<%= blockPlugins %>
return {
state,
props,
provider
<% if(asyncComponents) { %>, <%= asyncComponents %> <% }%>
<% if(returns) { %>, <%= returns %> <% } %>
};
},
<% if(computed) { %> computed: { <%= computed %> }, <% } %>
<% if(methods) { %> methods: { <%= methods %> }, <% } %>
<% if(watch) { %> watch: { <%= watch %> }, <% } %> <%= lifeCycles %>
});
`, Ct = `
<template>
<%= template %>
</template>
<script lang="<%= scriptLang %>"<% if(scriptSetup) { %> setup<% } %>>
<%= script %>
<\/script>
<style lang="<%= styleLang %>" scoped>
<%= css %>
<%= style %>
</style>
`, xt = `// @ts-nocheck
import { <%= rendererImports %> } from '<%= renderer %>';<%= imports %>
<% if(componentDeclarations) { %><%= componentDeclarations %><% } %>
<% if(props) { %>const __props = defineProps({ <%= props %> });<% } else if(needsProps) { %>const __props = defineProps();<% } %>
<% if(emits) { %>const __emit = defineEmits([<%= emits %>]);<% } else if(needsEmit) { %>const __emit = defineEmits();<% } %>
const __provider = useProvider({ id: '<%= id %>', version: '<%= version %>' });
<%= urlSchemas %>
<%= blockPlugins %>
<%= globalApiDeclares %>
<%= injects %>
<%= composables %>
<%= createdStatements %>
<%= refs %>
<%= reactives %>
<%= computed %>
<%= state %>
<%= methods %>
<%= setupStatements %>
<%= dataSources %>
<%= watch %>
<%= provide %>
<%= lifeCycles %>
<% if(expose) { %>defineExpose(<%= expose %>);<% } %>
`, At = H(Ot), Pt = H(xt), Et = H(Ct);
async function Mt(t, e = /* @__PURE__ */ new Map(), s = [], n = "web", o) {
const r = t, c = typeof r.dsl == "object" && arguments.length === 1 ? r : {
dsl: t,
componentMap: e,
dependencies: s,
platform: n,
formatterDisabled: o
}, {
dsl: a,
componentMap: l = /* @__PURE__ */ new Map(),
dependencies: p = [],
platform: m = "web",
formatterDisabled: i = !1,
ts: u = !0,
scss: f = !1
} = c, b = new Ne(Ie(a), p), g = a.apiMode === "composition";
let w, d, v, h;
if (g) {
const $ = It(b, l, m);
h = Pt($), w = $.template || `
<!--组件模版内容-->
`, d = $.css, v = $.style;
} else {
const $ = Ke(b, l, m);
h = At($), w = $.template || `
<!--组件模版内容-->
`, d = $.css, v = $.style;
}
const y = Et({
template: w,
css: await z(d, i) || `
/* 组件样式内容 */
`,
script: await xe(h, i),
style: await z(v, i),
scriptLang: u ? "ts" : "js",
styleLang: f ? "scss" : "css",
scriptSetup: g
});
return await ee(y, i).catch(($) => ($.content = y, Promise.reject($)));
}
async function Rt(t) {
const e = `
<template>
<div>
<h3>源码模式页面</h3>
<div>文件路径:/.vtj/vue/${t.id}.vue</div>
</div>
</template>
<script lang="ts" setup>
<\/script>
<style scoped lang="scss">
</style>
`;
return await ee(e);
}
export {
E as GLOBAL_API_MAP,
fe as UI_GLOBAL_API_MAPS,
et as UI_PACKAGES,
Tt as VTJ_CODER_VERSION,
st as buildEffectiveApiMap,
Rt as createEmptyPage,
z as cssFormatter,
tt as detectUIPackage,
Mt as generator,
xe as tsFormatter,
ee as vueFormatter
};