feat: 补齐模板编译扩展性门禁与演练模板

- 新增第二行业演练模板 drill-consultant,验证新增行业无需修改编译器和运行���
- 补充 override 冲突与显式覆盖测试,产物校验覆盖 wxss
- 修复 --template-dir 模板被误判引用其他模板组件的问题
- 修复运行时排除规则误删 TDesign 深层 src 目录,增加 miniprogram_npm 完整性回归
- 模板目录校验统一复用 template-contract,新增 template:check 并接入 pnpm check
- tabBar 配色归属模板包,清理编译器过期排除项和旧 fixture
- ADR 0015 明确对 0005/0008/0009 的替换范围

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
que01andClaude Opus 5.5 committed 2026-09-27 06:55:56 +08:00
1 parent e2e2340bfe
commit a97cc860cf
31 files changed
+418 -158

No files matched your search

@@ -4,5 +4,11 @@
"navigationBarTitleText": "阿成校园餐",
"navigationBarBackgroundColor": "#FFF8F0",
"navigationBarTextStyle": "black"
},
"tabBar": {
"color": "#8b8178",
"selectedColor": "#3b2118",
"backgroundColor": "#ffffff",
"borderStyle": "white"
}
}
+14 -22
View File
@@ -29,18 +29,9 @@ const RUNTIME_EXCLUDES = new Set([
"app.json",
"project.config.json",
"runtime-config.js",
"assets",
"pages/booking",
"utils/templates.js",
"components/templates",
"components/runtime-tab-bar",
"pages/index",
"pages/services",
"pages/bookings",
"pages/stall-service",
]);
const LAYER_EXCLUDES = new Set(["node_modules", ".turbo", "dist", ".gitkeep", "app.json"]);
const PAGE_EXTENSIONS = [".js", ".json", ".wxml"];
const PAGE_EXTENSIONS = [".js", ".json", ".wxml", ".wxss"];
class CompileError extends Error {}
@@ -56,15 +47,12 @@ function toPosix(relativePath) {
return relativePath.split(path.sep).join("/");
}
/** exclude 中的条目是相对层根目录的路径,只匹配该路径本身,不匹配深层同名目录(如 TDesign 的 common/src)。 */
function listFiles(directory, exclude, base = directory) {
const files = [];
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const entryPath = toPosix(path.relative(base, path.join(directory, entry.name)));
if (
exclude.has(entry.name) ||
[...exclude].some((value) => entryPath === value || entryPath.startsWith(value + "/"))
)
continue;
if (exclude.has(entryPath)) continue;
if (entry.name === ".gitkeep") continue;
const filePath = path.join(directory, entry.name);
if (entry.isDirectory()) files.push(...listFiles(filePath, exclude, base));
@@ -202,6 +190,7 @@ function buildAppJson(manifest, templateDirectory, capabilities) {
for (const [key, page] of Object.entries(manifest.entrypoints)) {
if (!pages.includes(page)) fail(`entrypoints.${key} (${page}) is not provided by any layer`);
}
// 颜色属于模板视觉,由模板的 miniapp/app.json 提供;这里只兜底中性色。
const tabBarStyle = templateApp.tabBar || {};
return {
...runtimeApp,
@@ -212,8 +201,8 @@ function buildAppJson(manifest, templateDirectory, capabilities) {
...(templateApp.window || {}),
},
tabBar: {
color: tabBarStyle.color || "#8b8178",
selectedColor: tabBarStyle.selectedColor || "#3b2118",
color: tabBarStyle.color || "#7a7a7a",
selectedColor: tabBarStyle.selectedColor || "#1a1a1a",
backgroundColor: tabBarStyle.backgroundColor || "#ffffff",
borderStyle: tabBarStyle.borderStyle || "white",
list: manifest.navigation.map((item) => ({
@@ -276,12 +265,15 @@ function writeGeneratedFiles(output, manifest, params, appJson, capabilities) {
);
}
function otherTemplateComponentNames(currentDirectory) {
// 按 packageKey 识别当前模板,--template-dir 指向 packages/ 之外的副本时同样成立。
function otherTemplateComponentNames(currentPackageKey) {
const names = new Set();
for (const entry of fs.readdirSync(packagesRoot, { withFileTypes: true })) {
if (!entry.isDirectory() || !entry.name.startsWith("template-")) continue;
const directory = path.join(packagesRoot, entry.name);
if (path.resolve(directory) === path.resolve(currentDirectory)) continue;
const manifestPath = path.join(directory, "template.json");
if (!fs.existsSync(manifestPath) || readJson(manifestPath).packageKey === currentPackageKey)
continue;
const componentRoot = path.join(directory, "miniapp/components/templates");
if (!fs.existsSync(componentRoot)) continue;
for (const component of fs.readdirSync(componentRoot)) names.add(component);
@@ -306,7 +298,7 @@ function resolveRequire(output, fromFile, reference) {
}
/** 校验产物可以被微信开发者工具直接打开:页面、组件、require、图标和模板隔离。 */
function validateOutput(output, appJson, templateDirectory) {
function validateOutput(output, appJson, packageKey) {
const errors = [];
const warnings = [];
for (const page of appJson.pages) {
@@ -322,7 +314,7 @@ function validateOutput(output, appJson, templateDirectory) {
}
}
const hasNpm = fs.existsSync(path.join(output, "miniprogram_npm"));
const forbiddenComponents = otherTemplateComponentNames(templateDirectory);
const forbiddenComponents = otherTemplateComponentNames(packageKey);
const sourceFiles = listFiles(output, new Set(["miniprogram_npm"])).filter((file) =>
/\.(js|json|wxml)$/.test(file),
);
@@ -393,7 +385,7 @@ export function compileTemplate(options) {
);
const appJson = buildAppJson(manifest, templateDirectory, capabilities);
writeGeneratedFiles(output, manifest, params, appJson, capabilities);
const { errors, warnings } = validateOutput(output, appJson, templateDirectory);
const { errors, warnings } = validateOutput(output, appJson, manifest.packageKey);
if (errors.length) fail(`Generated mini program is invalid:\n ${errors.join("\n ")}`);
return { output, manifest, params, warnings };
}
+81 -4
View File
@@ -45,6 +45,14 @@ test("compiler generates an isolated Acheng runtime manifest", () => {
assert.equal(fs.existsSync(path.join(output, "pages/stall-service/index.wxml")), true);
assert.equal(fs.existsSync(path.join(output, "pages/booking/index.wxml")), true);
assert.equal(fs.existsSync(path.join(output, "assets/tab/booking.png")), true);
// 运行时的 npm 构建产物必须完整复制,不能被按名称排除的 src/test/dist 误伤。
const runtimeNpm = path.join(workspaceRoot, "apps/miniapp/miniprogram_npm");
if (fs.existsSync(runtimeNpm)) {
for (const file of fs.readdirSync(runtimeNpm, { recursive: true })) {
if (fs.statSync(path.join(runtimeNpm, file)).isFile())
assert.equal(fs.existsSync(path.join(output, "miniprogram_npm", file)), true, file);
}
}
});
test("compiler generates the Linjing navigation contract", () => {
@@ -108,13 +116,82 @@ test("compiler rejects production builds without deployment parameters", () => {
);
});
test("compiler rejects unknown capabilities before copying layers", () => {
const templateDirectory = fs.mkdtempSync(
path.join(os.tmpdir(), "personal-brand-template-package-"),
test("a second-industry template compiles without compiler or runtime changes", () => {
const output = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-"));
execFileSync(
process.execPath,
[
compiler,
"--template-dir",
path.join(packageRoot, "test/fixtures/template-drill-consultant"),
"--out",
output,
],
{ cwd: workspaceRoot, stdio: "inherit" },
);
fs.cpSync(path.join(workspaceRoot, "packages/template-linjing-editorial"), templateDirectory, {
const app = JSON.parse(fs.readFileSync(path.join(output, "app.json"), "utf8"));
assertPageBundle(output, app);
assert.equal(app.pages[0], "pages/index/index");
for (const page of ["pages/offering/detail", "pages/inquiry/index", "pages/records/index"])
assert.equal(app.pages.includes(page), true, page);
assert.deepEqual(
app.tabBar.list.map((item) => item.pagePath),
["pages/index/index", "pages/services/index", "pages/profile/index"],
);
assert.equal(fs.existsSync(path.join(output, "pages/booking")), false);
assert.deepEqual(fs.readdirSync(path.join(output, "components/templates")), ["drill-card"]);
assert.match(fs.readFileSync(path.join(output, "runtime-config.js"), "utf8"), /drill-consultant/);
});
function copyTemplate(key) {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-package-"));
fs.cpSync(path.join(workspaceRoot, `packages/template-${key}`), directory, { recursive: true });
return directory;
}
test("compiler rejects template files that shadow runtime files without overrides", () => {
const templateDirectory = copyTemplate("linjing-editorial");
fs.cpSync(
path.join(workspaceRoot, "apps/miniapp/pages/records"),
path.join(templateDirectory, "miniapp/pages/records"),
{ recursive: true },
);
const output = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-"));
assert.throws(
() =>
execFileSync(
process.execPath,
[compiler, "--template-dir", templateDirectory, "--out", output],
{ cwd: workspaceRoot, stdio: "pipe" },
),
/conflicts with runtime at pages\/records\/index\.(js|json|wxml|wxss); declare it in overrides/,
);
});
test("compiler lets a template replace a runtime page declared in overrides", () => {
const templateDirectory = copyTemplate("linjing-editorial");
const pageDirectory = path.join(templateDirectory, "miniapp/pages/records");
fs.cpSync(path.join(workspaceRoot, "apps/miniapp/pages/records"), pageDirectory, {
recursive: true,
});
fs.appendFileSync(path.join(pageDirectory, "index.wxml"), "<!-- template override -->\n");
const manifestPath = path.join(templateDirectory, "template.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
manifest.overrides = [...(manifest.overrides || []), "pages/records"];
fs.writeFileSync(manifestPath, JSON.stringify(manifest));
const output = fs.mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-"));
execFileSync(process.execPath, [compiler, "--template-dir", templateDirectory, "--out", output], {
cwd: workspaceRoot,
stdio: "pipe",
});
assert.match(
fs.readFileSync(path.join(output, "pages/records/index.wxml"), "utf8"),
/template override/,
);
});
test("compiler rejects unknown capabilities before copying layers", () => {
const templateDirectory = copyTemplate("linjing-editorial");
const manifestPath = path.join(templateDirectory, "template.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
manifest.requiredCapabilities.push("missing");
@@ -0,0 +1,5 @@
# 第二行业演练模板
编译器扩展性的回归门禁。它是一个最小的咨询师模板:只包含模板包自己的页面和组件,数据访问、详情、咨询、记录等页面全部来自运行时。
`packages/template-compiler/test/cli.test.mjs` 会编译它。如果为了让它通过而必须修改编译器或 `apps/miniapp`,说明新增行业仍然需要改平台代码,应先修正平台边界。
@@ -0,0 +1,13 @@
Component({
properties: {
itemId: { type: String, value: "" },
title: { type: String, value: "" },
desc: { type: String, value: "" },
meta: { type: String, value: "" },
},
methods: {
open() {
if (this.data.itemId) this.triggerEvent("open", { id: this.data.itemId });
},
},
});
@@ -0,0 +1,5 @@
<view class="drill-card" bindtap="open">
<view class="drill-card__title">{{title}}</view>
<view wx:if="{{desc}}" class="drill-card__desc">{{desc}}</view>
<view wx:if="{{meta}}" class="drill-card__meta">{{meta}}</view>
</view>
@@ -0,0 +1,18 @@
.drill-card {
margin: 24rpx 32rpx;
padding: 32rpx;
border-radius: 16rpx;
background: #ffffff;
}
.drill-card__title {
font-size: 32rpx;
font-weight: 600;
}
.drill-card__desc,
.drill-card__meta {
margin-top: 12rpx;
font-size: 26rpx;
color: #666666;
}
@@ -0,0 +1,23 @@
const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace");
Page({
data: { brand: {}, offerings: [], error: "" },
onLoad() {
loadWorkspaceWithFallback()
.then((workspace) => {
const brand = workspace.brand || {};
this.setData({ brand, offerings: (workspace.offerings || []).slice(0, 3) });
wx.setNavigationBarTitle({ title: brand.name || "个人品牌" });
})
.catch((error) => this.setData({ error: error.message }));
},
open(event) {
wx.navigateTo({ url: "/pages/offering/detail?id=" + event.detail.id });
},
goServices() {
wx.switchTab({ url: "/pages/services/index" });
},
inquire() {
wx.navigateTo({ url: "/pages/inquiry/index" });
},
});
@@ -0,0 +1,6 @@
{
"usingComponents": {
"drill-card": "/components/templates/drill-card/drill-card",
"brand-button": "/components/ui/brand-button/brand-button"
}
}
@@ -0,0 +1,22 @@
<view class="page">
<view wx:if="{{error}}" class="runtime-error">{{error}}</view>
<block wx:else>
<view class="drill-hero">
<view class="drill-hero__name">{{brand.name}}</view>
<view class="drill-hero__tagline">{{brand.tagline || brand.description}}</view>
</view>
<drill-card
wx:for="{{offerings}}"
wx:key="id"
item-id="{{item.id}}"
title="{{item.name}}"
desc="{{item.desc}}"
meta="{{item.priceRange}}"
bind:open="open"
/>
<view class="drill-actions">
<view class="drill-link" bindtap="goServices">查看全部服务</view>
<brand-button bindtap="inquire">预约咨询</brand-button>
</view>
</block>
</view>
@@ -0,0 +1,24 @@
.drill-hero {
padding: 64rpx 32rpx 32rpx;
}
.drill-hero__name {
font-size: 44rpx;
font-weight: 700;
}
.drill-hero__tagline {
margin-top: 16rpx;
font-size: 28rpx;
color: #666666;
}
.drill-actions {
padding: 32rpx;
}
.drill-link {
margin-bottom: 24rpx;
font-size: 28rpx;
text-align: center;
}
@@ -0,0 +1,16 @@
const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace");
Page({
data: { brand: {}, error: "" },
onLoad() {
loadWorkspaceWithFallback()
.then((workspace) => this.setData({ brand: workspace.brand || {} }))
.catch((error) => this.setData({ error: error.message }));
},
openRecords() {
wx.navigateTo({ url: "/pages/records/index" });
},
inquire() {
wx.navigateTo({ url: "/pages/inquiry/index" });
},
});
@@ -0,0 +1,7 @@
{
"navigationBarTitleText": "关于我",
"usingComponents": {
"drill-card": "/components/templates/drill-card/drill-card",
"brand-button": "/components/ui/brand-button/brand-button"
}
}
@@ -0,0 +1,10 @@
<view class="page">
<view wx:if="{{error}}" class="runtime-error">{{error}}</view>
<block wx:else>
<drill-card title="{{brand.name}}" desc="{{brand.description}}" />
<view class="drill-actions">
<view class="drill-link" bindtap="openRecords">我的咨询记录</view>
<brand-button bindtap="inquire">预约咨询</brand-button>
</view>
</block>
</view>
@@ -0,0 +1,9 @@
.drill-actions {
padding: 32rpx;
}
.drill-link {
margin-bottom: 24rpx;
font-size: 28rpx;
text-align: center;
}
@@ -0,0 +1,13 @@
const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace");
Page({
data: { offerings: [], error: "" },
onLoad() {
loadWorkspaceWithFallback()
.then((workspace) => this.setData({ offerings: workspace.offerings || [] }))
.catch((error) => this.setData({ error: error.message }));
},
open(event) {
wx.navigateTo({ url: "/pages/offering/detail?id=" + event.detail.id });
},
});
@@ -0,0 +1,7 @@
{
"navigationBarTitleText": "服务",
"usingComponents": {
"drill-card": "/components/templates/drill-card/drill-card",
"brand-empty": "/components/ui/brand-empty/brand-empty"
}
}
@@ -0,0 +1,13 @@
<view class="page">
<view wx:if="{{error}}" class="runtime-error">{{error}}</view>
<brand-empty wx:elif="{{!offerings.length}}" description="暂未发布服务" />
<drill-card
wx:for="{{offerings}}"
wx:key="id"
item-id="{{item.id}}"
title="{{item.name}}"
desc="{{item.desc}}"
meta="{{item.priceRange}}"
bind:open="open"
/>
</view>
@@ -0,0 +1,3 @@
.page {
padding-bottom: 32rpx;
}
@@ -0,0 +1,58 @@
{
"packageKey": "drill-consultant",
"version": "0.1.0",
"displayName": "咨询师演练模板",
"defaultBrandSlug": "drill-consultant",
"runtimeContract": "1.0",
"supportedIndustryTemplates": ["consulting"],
"entrypoints": {
"home": "pages/index/index",
"offerings": "pages/services/index",
"detail": "pages/offering/detail",
"inquiry": "pages/inquiry/index",
"success": "pages/inquiry-success/index",
"records": "pages/records/index",
"profile": "pages/profile/index"
},
"navigation": [
{ "key": "home", "label": "首页", "page": "home" },
{ "key": "offerings", "label": "服务", "page": "offerings" },
{ "key": "profile", "label": "关于我", "page": "profile" }
],
"requiredCapabilities": ["offerings", "inquiry"],
"pages": ["pages/index/index", "pages/services/index", "pages/profile/index"],
"dataSlots": [
{
"key": "brand.identity",
"source": "brand",
"required": true,
"description": "顾问姓名、定位和联系方式"
},
{
"key": "offering.list",
"source": "offering",
"required": true,
"description": "咨询服务项目"
}
],
"assetSlots": [],
"admin": {
"sections": [
{
"key": "identity",
"title": "顾问介绍",
"description": "客户在首页看到的姓名和定位",
"target": "brand",
"fields": [
{
"key": "name",
"binding": "brand.name",
"label": "姓名",
"input": "text",
"required": true
}
]
}
]
}
}
+3 -1
View File
@@ -8,6 +8,8 @@
2. 在 manifest 中声明 `entrypoints`、`pages`、`navigation`、`requiredCapabilities`、数据槽位、媒体槽位和面向管理员的 `admin.sections`。
3. 将模板自己的页面、组件、tab 图标和 `miniapp/app.json` 放入模板包。页面必须提供 `.js`、`.json`、`.wxml`、`.wxss` 四个文件。
4. 如果需要替换运行时或能力包页面,必须在 `overrides` 中声明目录;未声明的同路径文件会被 compiler 拒绝。
5. 执行 `pnpm generate:template-catalog --write`、`pnpm validate:templates` 和 `pnpm test:template-compiler`。
5. 执行 `pnpm generate:template-catalog --write` 和 `pnpm template:check`。
最小可编译模板可参考 `packages/template-compiler/test/fixtures/template-drill-consultant`。
使用 `pnpm template:dev <key> --brand <slug>` 生成微信开发者工具项目。生产构建还必须提供 `--appid` 和 HTTPS `--api`。模板在构建时选择,运行时不会下载或解释模板代码。
@@ -0,0 +1,8 @@
{
"tabBar": {
"color": "#8b8178",
"selectedColor": "#3b2118",
"backgroundColor": "#ffffff",
"borderStyle": "white"
}
}