feat: 收口多品牌与模板构建基础
This commit is contained in:
1 parent
0425a1c672
commit
77224ea51f
317 files changed
+11290
-1158
No files matched your search
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env node
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const packagesRoot = path.join(root, "packages");
|
||||
const generatedRoot = path.join(root, "apps/miniapp-generated");
|
||||
|
||||
function usage() {
|
||||
console.log("Usage: template-compiler --template <package-key> [--out <directory>]");
|
||||
}
|
||||
|
||||
function validateManifest(manifest) {
|
||||
const requiredPages = ["home", "offerings", "detail", "inquiry", "success", "records", "profile"];
|
||||
if (!manifest.packageKey || !manifest.version || !manifest.displayName)
|
||||
throw new Error("template.json requires packageKey, version and displayName");
|
||||
if (manifest.runtimeContract !== "1.0") throw new Error("Only runtimeContract 1.0 is supported");
|
||||
for (const page of requiredPages) {
|
||||
if (typeof manifest.entrypoints?.[page] !== "string")
|
||||
throw new Error(`template.json missing entrypoint: ${page}`);
|
||||
}
|
||||
if (!Array.isArray(manifest.navigation) || !manifest.navigation.length)
|
||||
throw new Error("template.json navigation must not be empty");
|
||||
if (
|
||||
manifest.renderers !== undefined &&
|
||||
(typeof manifest.renderers !== "object" || Array.isArray(manifest.renderers))
|
||||
)
|
||||
throw new Error("template.json renderers must be an object");
|
||||
for (const page of ["home", "offerings", "profile"]) {
|
||||
if (typeof manifest.renderers?.[page] !== "string" || !manifest.renderers[page]) {
|
||||
throw new Error(`template.json requires a dedicated renderer for visual page: ${page}`);
|
||||
}
|
||||
}
|
||||
if (
|
||||
manifest.runtimeOwnedPages !== undefined &&
|
||||
(!Array.isArray(manifest.runtimeOwnedPages) ||
|
||||
manifest.runtimeOwnedPages.some(
|
||||
(page) => !["detail", "inquiry", "success", "records"].includes(page),
|
||||
))
|
||||
)
|
||||
throw new Error("template.json runtimeOwnedPages contains an unsupported page");
|
||||
for (const item of manifest.navigation) {
|
||||
if (!item || typeof item.key !== "string" || typeof item.label !== "string")
|
||||
throw new Error("template.json navigation items require key and label");
|
||||
if (typeof item.page !== "string" || typeof manifest.entrypoints?.[item.page] !== "string")
|
||||
throw new Error(`template.json navigation page is not a declared entrypoint: ${item.key}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateEntrypoints(output, manifest) {
|
||||
for (const [key, relativePath] of Object.entries(manifest.entrypoints || {})) {
|
||||
const pagePath = path.join(output, relativePath);
|
||||
for (const extension of [".js", ".json", ".wxml", ".wxss"]) {
|
||||
if (!fs.existsSync(`${pagePath}${extension}`)) {
|
||||
throw new Error(`Template entrypoint ${key} is missing ${relativePath}${extension}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function validateGeneratedIsolation(output) {
|
||||
const forbidden = [
|
||||
"components/templates",
|
||||
"runtime-tab-bar",
|
||||
"acheng-",
|
||||
"linjing-",
|
||||
"templateKey ===",
|
||||
];
|
||||
const visit = (directory) => {
|
||||
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||
const filePath = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) visit(filePath);
|
||||
else if (/\.(wxml|json|js|wxss)$/.test(entry.name)) {
|
||||
const source = fs.readFileSync(filePath, "utf8");
|
||||
for (const token of forbidden) {
|
||||
if (source.includes(token))
|
||||
throw new Error(`Generated output contains forbidden token ${token}: ${filePath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(path.join(output, "pages"));
|
||||
}
|
||||
|
||||
function copyDirectory(source, target) {
|
||||
fs.mkdirSync(target, { recursive: true });
|
||||
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
|
||||
if (["node_modules", ".turbo", "dist"].includes(entry.name)) continue;
|
||||
const from = path.join(source, entry.name);
|
||||
const to = path.join(target, entry.name);
|
||||
if (entry.isDirectory()) copyDirectory(from, to);
|
||||
else fs.copyFileSync(from, to);
|
||||
}
|
||||
}
|
||||
|
||||
function removeOwnedPaths(rootDirectory, ownedPaths = []) {
|
||||
for (const relativePath of ownedPaths) {
|
||||
fs.rmSync(path.join(rootDirectory, relativePath), { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function removeRuntimeTabBar(output) {
|
||||
const pagesDirectory = path.join(output, "pages");
|
||||
if (!fs.existsSync(pagesDirectory)) return;
|
||||
const visit = (directory) => {
|
||||
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||
const filePath = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) visit(filePath);
|
||||
else if (entry.name.endsWith(".wxml")) {
|
||||
const source = fs.readFileSync(filePath, "utf8");
|
||||
const cleaned = source.replace(/<runtime-tab-bar\b[^>]*\/\s*>/g, "");
|
||||
if (cleaned !== source) fs.writeFileSync(filePath, cleaned);
|
||||
} else if (entry.name.endsWith(".json")) {
|
||||
const json = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
||||
if (json.usingComponents?.["runtime-tab-bar"]) {
|
||||
delete json.usingComponents["runtime-tab-bar"];
|
||||
fs.writeFileSync(filePath, JSON.stringify(json, null, 2) + "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(pagesDirectory);
|
||||
fs.rmSync(path.join(output, "components/runtime-tab-bar"), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function pruneUndeclaredPages(output, manifest) {
|
||||
const appJsonPath = path.join(output, "app.json");
|
||||
const appJson = JSON.parse(fs.readFileSync(appJsonPath, "utf8"));
|
||||
const allowed = new Set([
|
||||
...manifest.navigation.map((item) => manifest.entrypoints[item.page]),
|
||||
...(manifest.runtimeOwnedPages || []).map((page) => manifest.entrypoints[page]),
|
||||
]);
|
||||
for (const page of appJson.pages || []) {
|
||||
if (allowed.has(page)) continue;
|
||||
fs.rmSync(path.join(output, path.dirname(page)), { recursive: true, force: true });
|
||||
}
|
||||
appJson.pages = (appJson.pages || []).filter((page) => allowed.has(page));
|
||||
fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2) + "\n");
|
||||
const appJsPath = path.join(output, "app.js");
|
||||
if (fs.existsSync(appJsPath) && manifest.defaultBrandSlug) {
|
||||
const appJs = fs
|
||||
.readFileSync(appJsPath, "utf8")
|
||||
.replace(
|
||||
/const DEFAULT_BRAND_SLUG = "[^"]*";/,
|
||||
`const DEFAULT_BRAND_SLUG = ${JSON.stringify(manifest.defaultBrandSlug)};`,
|
||||
);
|
||||
fs.writeFileSync(appJsPath, appJs);
|
||||
}
|
||||
}
|
||||
|
||||
function materializeRendererAliases(output, packageDirectory, manifest) {
|
||||
const rendererRoot = path.join(packageDirectory, "miniapp/components/templates");
|
||||
const pagePaths = {
|
||||
home: "pages/index/index",
|
||||
offerings: "pages/services/index",
|
||||
profile: "pages/bookings/index",
|
||||
};
|
||||
for (const page of Object.keys(pagePaths)) {
|
||||
const renderer = manifest.renderers?.[page];
|
||||
const source = path.join(rendererRoot, renderer);
|
||||
if (!fs.existsSync(source)) {
|
||||
throw new Error(`Template renderer source is missing: ${renderer}`);
|
||||
}
|
||||
const aliasDirectory = path.join(output, "components/template-pages", page);
|
||||
fs.mkdirSync(aliasDirectory, { recursive: true });
|
||||
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
|
||||
if (!entry.isFile()) continue;
|
||||
fs.copyFileSync(
|
||||
path.join(source, entry.name),
|
||||
path.join(aliasDirectory, `${page}${path.extname(entry.name)}`),
|
||||
);
|
||||
}
|
||||
const pageDirectory = path.join(output, pagePaths[page]);
|
||||
const jsonPath = `${pageDirectory}.json`;
|
||||
const wxmlPath = `${pageDirectory}.wxml`;
|
||||
const pageJson = JSON.parse(fs.readFileSync(jsonPath, "utf8"));
|
||||
pageJson.usingComponents = pageJson.usingComponents || {};
|
||||
for (const key of Object.keys(pageJson.usingComponents)) {
|
||||
if (/-home$|-offerings$|-profile$/.test(key)) delete pageJson.usingComponents[key];
|
||||
}
|
||||
pageJson.usingComponents[`template-${page}`] = `/components/template-pages/${page}/${page}`;
|
||||
fs.writeFileSync(jsonPath, JSON.stringify(pageJson, null, 2) + "\n");
|
||||
const rendererPattern = new RegExp(`<([a-z0-9-]+)-${page}\\b`, "g");
|
||||
const originalWxml = fs.readFileSync(wxmlPath, "utf8");
|
||||
const wxml =
|
||||
page === "offerings"
|
||||
? `<view class="page"><template-${page} brand="{{brand}}" presentation="{{presentation}}" offerings="{{offerings}}" bind:open="open" bind:more="inquire" /></view>`
|
||||
: originalWxml.replace(rendererPattern, `<template-${page}`);
|
||||
fs.writeFileSync(wxmlPath, wxml);
|
||||
}
|
||||
}
|
||||
|
||||
function freezeRendererConditions(output, manifest) {
|
||||
const rendererByPage = manifest.renderers || {};
|
||||
const pagePaths = {
|
||||
home: "pages/index/index.wxml",
|
||||
offerings: "pages/services/index.wxml",
|
||||
profile: "pages/bookings/index.wxml",
|
||||
};
|
||||
for (const [page, relativePath] of Object.entries(pagePaths)) {
|
||||
const filePath = path.join(output, relativePath);
|
||||
if (!fs.existsSync(filePath)) continue;
|
||||
const selected = rendererByPage[page] || "";
|
||||
const source = fs.readFileSync(filePath, "utf8");
|
||||
const frozen = source.replace(
|
||||
/wx:(if|elif)="\{\{pageRenderer === '([^']+)'\}\}"/g,
|
||||
(_match, branch, renderer) => `wx:${branch}="{{${renderer === selected}}}"`,
|
||||
);
|
||||
const selectedAlias =
|
||||
page === "offerings"
|
||||
? frozen.replace(
|
||||
'<template-offerings wx:if="{{false}}"',
|
||||
'<template-offerings wx:if="{{true}}"',
|
||||
)
|
||||
: frozen;
|
||||
fs.writeFileSync(filePath, selectedAlias);
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const templateIndex = args.indexOf("--template");
|
||||
if (templateIndex < 0 || !args[templateIndex + 1]) return usage();
|
||||
const packageKey = args[templateIndex + 1];
|
||||
const outputIndex = args.indexOf("--out");
|
||||
const output = path.resolve(outputIndex >= 0 ? args[outputIndex + 1] : generatedRoot);
|
||||
const packageDirectory = fs.existsSync(path.join(packagesRoot, packageKey))
|
||||
? path.join(packagesRoot, packageKey)
|
||||
: path.join(packagesRoot, `template-${packageKey}`);
|
||||
const manifestPath = path.join(packageDirectory, "template.json");
|
||||
if (!fs.existsSync(manifestPath)) throw new Error(`Template package not found: ${packageKey}`);
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
||||
if (manifest.packageKey !== packageKey)
|
||||
throw new Error("template.json packageKey does not match requested template");
|
||||
validateManifest(manifest);
|
||||
fs.rmSync(output, { recursive: true, force: true });
|
||||
const shell = path.join(root, "apps/miniapp");
|
||||
if (!fs.existsSync(shell)) throw new Error("Mini Program shell is missing: apps/miniapp");
|
||||
copyDirectory(shell, output);
|
||||
// 迁移期间保留 shell 的模板目录,直到模板包提供对应页面的完整覆盖。
|
||||
// ownedPaths 只记录最终所有权,不在不完整迁移时删除可用 renderer。
|
||||
const source = path.join(packageDirectory, "miniapp");
|
||||
if (!fs.existsSync(source))
|
||||
throw new Error(`Template package has no miniapp directory: ${packageKey}`);
|
||||
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
|
||||
if (entry.name === "app.json") continue;
|
||||
const from = path.join(source, entry.name);
|
||||
const to = path.join(output, entry.name);
|
||||
if (entry.isDirectory()) copyDirectory(from, to);
|
||||
else fs.copyFileSync(from, to);
|
||||
}
|
||||
materializeRendererAliases(output, packageDirectory, manifest);
|
||||
freezeRendererConditions(output, manifest);
|
||||
removeRuntimeTabBar(output);
|
||||
pruneUndeclaredPages(output, manifest);
|
||||
validateEntrypoints(output, manifest);
|
||||
for (const relativePath of manifest.ownedPaths || []) {
|
||||
if (!fs.existsSync(path.join(output, relativePath)))
|
||||
throw new Error(`Template package did not provide owned path: ${relativePath}`);
|
||||
}
|
||||
for (const renderer of Object.values(manifest.renderers || {})) {
|
||||
const rendererPath = path.join(output, "components/templates", renderer, `${renderer}.wxml`);
|
||||
if (!fs.existsSync(rendererPath)) throw new Error(`Template renderer is missing: ${renderer}`);
|
||||
}
|
||||
fs.rmSync(path.join(output, "components/templates"), { recursive: true, force: true });
|
||||
validateGeneratedIsolation(output);
|
||||
const appJsonPath = path.join(output, "app.json");
|
||||
const appJson = JSON.parse(fs.readFileSync(appJsonPath, "utf8"));
|
||||
appJson.window = {
|
||||
...appJson.window,
|
||||
navigationBarTitleText: manifest.displayName,
|
||||
};
|
||||
appJson.tabBar = {
|
||||
color: "#8b8178",
|
||||
selectedColor: "#3b2118",
|
||||
backgroundColor: "#ffffff",
|
||||
borderStyle: "white",
|
||||
list: manifest.navigation.map((item) => ({
|
||||
pagePath: manifest.entrypoints[item.page],
|
||||
text: item.label,
|
||||
...(item.iconPath ? { iconPath: item.iconPath } : {}),
|
||||
...(item.selectedIconPath ? { selectedIconPath: item.selectedIconPath } : {}),
|
||||
})),
|
||||
};
|
||||
fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2) + "\n");
|
||||
fs.writeFileSync(
|
||||
path.join(output, "template.manifest.json"),
|
||||
JSON.stringify(manifest, null, 2) + "\n",
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(output, "template.runtime.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
packageKey: manifest.packageKey,
|
||||
version: manifest.version,
|
||||
runtimeContract: manifest.runtimeContract,
|
||||
entrypoints: manifest.entrypoints,
|
||||
navigation: manifest.navigation,
|
||||
requiredCapabilities: manifest.requiredCapabilities,
|
||||
renderers: manifest.renderers || {},
|
||||
runtimeOwnedPages: manifest.runtimeOwnedPages || [],
|
||||
ownedPaths: manifest.ownedPaths || [],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
);
|
||||
console.log(`Generated ${packageKey}@${manifest.version} -> ${path.relative(root, output)}`);
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in new issue
Block a user