Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47a24e0d53 | ||
|
|
c78deafee3 | ||
|
|
3330b536dc | ||
|
|
07629a4596 | ||
|
|
5c6ad02f46 |
No files matched your search
@@ -2523,6 +2523,231 @@
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CONDITIONAL_RENDER_REVIEW",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"target": "linjing-editorial.profile.profileDetails",
|
||||
"line": 213,
|
||||
"message": "条件显示需验证全部分支与空数据入口。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "本次改动保持既有条件分支,不新增业务条件;仅补充固定 SVG 图标和样式,空态仍由上层条件控制,缺失记录提供后台编辑入口。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CONDITIONAL_RENDER_REVIEW",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"target": "linjing-editorial.profile.profileDetails",
|
||||
"line": 224,
|
||||
"message": "条件显示需验证全部分支与空数据入口。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "本次改动保持既有条件分支,不新增业务条件;仅补充固定 SVG 图标和样式,空态仍由上层条件控制,缺失记录提供后台编辑入口。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "DYNAMIC_TARGET_REVIEW",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"line": 236,
|
||||
"message": "动态目标需用真实 manifest 和实际记录验证分支。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "动态目标使用实际 trust 记录类型和 formTargets 页面入口;manifest 已声明页面与信任类型,真实 manifest 测试覆盖。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "UNSCOPED_RENDER_VALUE",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"binding": "trust.title",
|
||||
"line": 242,
|
||||
"message": "展示变量没有可证明的编辑区域。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "trust title/summary/content 由 manifest trustContentTypes 声明,当前记录通过 data-editor-record-id 绑定实际 id;编辑链路与集成测试覆盖。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CONDITIONAL_RENDER_REVIEW",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"line": 243,
|
||||
"message": "条件显示需验证全部分支与空数据入口。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "本次改动保持既有条件分支,不新增业务条件;仅补充固定 SVG 图标和样式,空态仍由上层条件控制,缺失记录提供后台编辑入口。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "UNSCOPED_RENDER_VALUE",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"binding": "trust.summary",
|
||||
"line": 243,
|
||||
"message": "展示变量没有可证明的编辑区域。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "trust title/summary/content 由 manifest trustContentTypes 声明,当前记录通过 data-editor-record-id 绑定实际 id;编辑链路与集成测试覆盖。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "UNSCOPED_RENDER_VALUE",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"binding": "trust.content",
|
||||
"line": 244,
|
||||
"message": "展示变量没有可证明的编辑区域。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "trust title/summary/content 由 manifest trustContentTypes 声明,当前记录通过 data-editor-record-id 绑定实际 id;编辑链路与集成测试覆盖。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CONDITIONAL_RENDER_REVIEW",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"target": "linjing-editorial.offerings.cases",
|
||||
"line": 283,
|
||||
"message": "条件显示需验证全部分支与空数据入口。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "本次改动保持既有条件分支,不新增业务条件;仅补充固定 SVG 图标和样式,空态仍由上层条件控制,缺失记录提供后台编辑入口。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "UNRESOLVED_RENDER_VALUE",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"target": "linjing-editorial.offerings.cases",
|
||||
"page": "offerings",
|
||||
"expression": "inquiryPluginState(workspace).disabledHint",
|
||||
"line": 289,
|
||||
"message": "需要核对循环项或间接映射,不能视为已覆盖。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "inquiryPluginState 仅消费 capabilityRegistry 声明的通用咨询能力状态;enabled/disabled 分支固定展示,无行业分支。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CONDITIONAL_RENDER_REVIEW",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"target": "linjing-editorial.detail.detailCopy",
|
||||
"line": 343,
|
||||
"message": "条件显示需验证全部分支与空数据入口。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "本次改动保持既有条件分支,不新增业务条件;仅补充固定 SVG 图标和样式,空态仍由上层条件控制,缺失记录提供后台编辑入口。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CONDITIONAL_RENDER_REVIEW",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"target": "linjing-editorial.detail.detailCopy",
|
||||
"line": 360,
|
||||
"message": "条件显示需验证全部分支与空数据入口。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "本次改动保持既有条件分支,不新增业务条件;仅补充固定 SVG 图标和样式,空态仍由上层条件控制,缺失记录提供后台编辑入口。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "CONDITIONAL_RENDER_REVIEW",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"target": "linjing-editorial.detail.action",
|
||||
"line": 380,
|
||||
"message": "条件显示需验证全部分支与空数据入口。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "本次改动保持既有条件分支,不新增业务条件;仅补充固定 SVG 图标和样式,空态仍由上层条件控制,缺失记录提供后台编辑入口。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "UNRESOLVED_RENDER_VALUE",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"target": "linjing-editorial.detail.action",
|
||||
"page": "detail",
|
||||
"expression": "inquiryPluginState(workspace).disabledHint",
|
||||
"line": 385,
|
||||
"message": "需要核对循环项或间接映射,不能视为已覆盖。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "inquiryPluginState 仅消费 capabilityRegistry 声明的通用咨询能力状态;enabled/disabled 分支固定展示,无行业分支。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": "DYNAMIC_TARGET_REVIEW",
|
||||
"severity": "review",
|
||||
"file": "packages/template-linjing-editorial/taro/index.tsx",
|
||||
"line": 404,
|
||||
"message": "动态目标需用真实 manifest 和实际记录验证分支。",
|
||||
"template": "linjing-editorial",
|
||||
"reviewStatus": "source-reviewed",
|
||||
"decision": "动态目标使用实际 trust 记录类型和 formTargets 页面入口;manifest 已声明页面与信任类型,真实 manifest 测试覆盖。",
|
||||
"evidence": [
|
||||
"packages/config/src/capability-contracts.ts",
|
||||
"packages/template-linjing-editorial/template.json",
|
||||
"apps/api/test/http.integration.test.js"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
NODE_ENV=production
|
||||
POSTGRES_USER=personal_brand
|
||||
POSTGRES_PASSWORD=replace-with-a-long-database-password
|
||||
POSTGRES_DB=personal_brand
|
||||
POSTGRES_PORT=5432
|
||||
|
||||
DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public
|
||||
SESSION_SECRET=replace-with-at-least-32-random-characters
|
||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
|
||||
SEED_MODE=seed
|
||||
|
||||
API_PORT=3001
|
||||
API_PREFIX=
|
||||
|
||||
LOCAL_MEDIA_ROOT=/home/ubuntu/persional-brand/media
|
||||
LOCAL_MEDIA_BASE_URL=/media
|
||||
OBJECT_STORAGE_ENDPOINT=
|
||||
OBJECT_STORAGE_PUBLIC_URL=
|
||||
OBJECT_STORAGE_BUCKET=
|
||||
OBJECT_STORAGE_ACCESS_KEY=
|
||||
OBJECT_STORAGE_SECRET_KEY=
|
||||
OBJECT_STORAGE_REGION=us-east-1
|
||||
|
||||
WECHAT_APP_ID=
|
||||
WECHAT_APP_SECRET=
|
||||
+2
-2
@@ -6,8 +6,9 @@ packages/config/dist/
|
||||
.next/
|
||||
coverage/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.env.production
|
||||
!.env.production.example
|
||||
*.log
|
||||
.DS_Store
|
||||
apps/miniapp/miniprogram_npm/
|
||||
@@ -24,5 +25,4 @@ media/
|
||||
**/.swc/
|
||||
.codex-tasks/
|
||||
docker-compose.override.yml
|
||||
docker-compose.prod.yml
|
||||
.env.production
|
||||
@@ -48,6 +48,11 @@
|
||||
0 10px 30px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
:where(.component-template-preview__canvas) {
|
||||
--taro-button-height: 11.7333333cqw;
|
||||
--taro-button-compact-height: 6.1333333cqw;
|
||||
}
|
||||
|
||||
.component-template-preview__canvas,
|
||||
.component-template-preview__canvas * {
|
||||
box-sizing: border-box;
|
||||
@@ -59,8 +64,12 @@
|
||||
}
|
||||
|
||||
:where(.component-template-preview__canvas) button {
|
||||
display: block;
|
||||
width: -webkit-fill-available;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-height: var(--taro-button-height);
|
||||
appearance: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
@@ -68,8 +77,7 @@
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 4.8cqw;
|
||||
line-height: 2.55555556;
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
|
||||
@@ -71,8 +71,8 @@ export function WorkspacePage() {
|
||||
const { query, runtimeQuery, templateCatalog, forms, templatePreview } = useWorkspaceQueries();
|
||||
const previewIndustryKey =
|
||||
previewIndustry ??
|
||||
query.data?.installations[0]?.templateKey ??
|
||||
query.data?.brand.templateKey ??
|
||||
query.data?.installations[0]?.templateKey ??
|
||||
templateCatalog.data?.industries[0]?.key;
|
||||
const previewVisualKey =
|
||||
previewVisual ??
|
||||
|
||||
@@ -7,6 +7,7 @@ export default defineConfig({
|
||||
css: { postcss: { plugins: [templatePreviewCss()] } },
|
||||
base: process.env.VITE_APP_BASE_PATH ?? "/",
|
||||
resolve: {
|
||||
dedupe: ["react", "react-dom"],
|
||||
alias: {
|
||||
"@tarojs/components": `${process.cwd()}/src/features/brand/taro-web-components.jsx`,
|
||||
"@tarojs/taro": `${process.cwd()}/src/features/brand/taro-web-runtime.jsx`,
|
||||
|
||||
@@ -32,12 +32,12 @@
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"fastify": "^5.11.3",
|
||||
"prisma": "^6.2.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.5",
|
||||
"prisma": "^6.2.1",
|
||||
"tsx": "^4.19.2"
|
||||
}
|
||||
}
|
||||
@@ -3,3 +3,4 @@ TEMPLATE_KEY=acheng-campus-food
|
||||
BRAND_SLUG=default-brand
|
||||
API_BASE_URL=http://localhost:3001
|
||||
PREVIEW_PORT=3002
|
||||
WEAPP_APP_ID=touristappid
|
||||
+1
-1
@@ -31,7 +31,7 @@ TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5
|
||||
TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp
|
||||
```
|
||||
|
||||
输出 `apps/taro/dist/<templateKey>/h5` 和 `weapp`。微信开发者工具导入对应 weapp 目录;正式登录需在项目配置里设置与 API 相匹配的 AppID,配置请求合法域名。默认 touristappid 仅用于浏览,不含密钥。
|
||||
输出 `apps/taro/dist/<templateKey>/h5` 和 `weapp`。微信开发者工具导入对应 weapp 目录;构建时通过 `API_BASE_URL` 设置 API 地址,通过 `WEAPP_APP_ID` 或 `TARO_APP_ID` 设置小程序 AppID,并在微信公众平台配置请求合法域名。默认 touristappid 仅用于浏览,不含密钥。
|
||||
|
||||
页面结构和样式以 React 原型为参考,当前原生小程序用于校对字段、结构化来源、认证与提交行为。模板实现位于各 package 的 `taro/`;公共请求、表单、记录和状态位于此目录。新模板须提供 manifest、Taro 实现和验收用例,不新增全局 seed。
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ const templates = fs
|
||||
const key = process.env.TEMPLATE_KEY || templates[0];
|
||||
if (!key) throw new Error("No Taro template package found");
|
||||
if (!templates.includes(key)) throw new Error(`Unsupported Taro template: ${key}`);
|
||||
process.env.TARO_APP_ID ||= process.env.WEAPP_APP_ID;
|
||||
const template = path.join(root, "packages", `template-${key}`);
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(template, "template.json"), "utf8")) as {
|
||||
packageKey: string;
|
||||
@@ -60,14 +61,6 @@ export default defineConfig({
|
||||
to: `dist/template-preview/h5/assets/${templateKey}`,
|
||||
}))
|
||||
: []),
|
||||
...(process.env.TARO_ENV === "weapp"
|
||||
? [
|
||||
{
|
||||
from: path.resolve(__dirname, "../project.config.json"),
|
||||
to: `dist/${key}/weapp/project.config.json`,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(!previewAllTemplates
|
||||
? [
|
||||
{
|
||||
@@ -78,7 +71,13 @@ export default defineConfig({
|
||||
: []),
|
||||
],
|
||||
},
|
||||
mini: {},
|
||||
mini: {
|
||||
postcss: {
|
||||
htmltransform: {
|
||||
enable: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
h5: {
|
||||
publicPath: process.env.PREVIEW_PUBLIC_PATH || "/",
|
||||
router: { mode: "hash" },
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
page {
|
||||
background: #fafaf9;
|
||||
--taro-button-height: 88px;
|
||||
--taro-button-compact-height: 46px;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
@@ -13,6 +15,13 @@ button {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-height: var(--taro-button-height);
|
||||
text-align: center;
|
||||
appearance: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
|
||||
@@ -47,7 +47,7 @@ export async function loadWorkspace() {
|
||||
const data = await request<RuntimeWorkspace>("/public/workspace");
|
||||
const editorPreview = isEditorPreview();
|
||||
if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布");
|
||||
return {
|
||||
return resolveMediaUrls({
|
||||
...data,
|
||||
brand: data.brand ?? {},
|
||||
templateData: data.templateData ?? {},
|
||||
@@ -58,7 +58,21 @@ export async function loadWorkspace() {
|
||||
capabilities: data.capabilities ?? [],
|
||||
theme: data.theme ?? { colors: {} },
|
||||
plugins: data.plugins ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
function resolveMediaUrls(workspace: RuntimeWorkspace): RuntimeWorkspace {
|
||||
const resolve = (value: unknown): unknown => {
|
||||
if (typeof value === "string") {
|
||||
return value.startsWith("/media/") ? `${API_BASE_URL.replace(/\/$/, "")}${value}` : value;
|
||||
}
|
||||
if (Array.isArray(value)) return value.map(resolve);
|
||||
if (value && typeof value === "object") {
|
||||
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolve(item)]));
|
||||
}
|
||||
return value;
|
||||
};
|
||||
return resolve(workspace) as RuntimeWorkspace;
|
||||
}
|
||||
export async function ensureSession() {
|
||||
if (hasSession()) return;
|
||||
|
||||
@@ -25,7 +25,19 @@ for (const key of templateKeys)
|
||||
for (const page of config.pages)
|
||||
for (const ext of ["js", "wxml", "json"])
|
||||
assert.ok(fs.existsSync(path.join(base, "weapp", `${page}.${ext}`)), `${page}.${ext}`);
|
||||
assert.ok(fs.readFileSync(path.join(base, "h5/index.html"), "utf8").includes('type="module"'));
|
||||
if (fs.existsSync(path.join(base, "h5/index.html")))
|
||||
assert.ok(
|
||||
fs.readFileSync(path.join(base, "h5/index.html"), "utf8").includes('type="module"'),
|
||||
);
|
||||
assert.ok(fs.existsSync(path.join(base, "weapp/project.config.json")));
|
||||
assert.ok(fs.readFileSync(path.join(base, "weapp/common.wxss"), "utf8").length > 1000);
|
||||
const weappStyles = fs.readFileSync(path.join(base, "weapp/common.wxss"), "utf8");
|
||||
const appStyles = fs.readFileSync(path.join(base, "weapp/app-origin.wxss"), "utf8");
|
||||
assert.ok(weappStyles.length > 1000);
|
||||
assert.match(appStyles, /(^|})button\{/);
|
||||
assert.match(appStyles, /--taro-button-height:\s*88rpx/);
|
||||
assert.match(
|
||||
appStyles,
|
||||
/display:flex;align-items:center;justify-content:center;width:100%;min-height:var\(--taro-button-height\)/,
|
||||
);
|
||||
assert.doesNotMatch(appStyles, /(^|})\.h5-button\{/);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
const path = require("node:path");
|
||||
const root = process.env.DEPLOY_ROOT;
|
||||
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
|
||||
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: "personal-brand-api",
|
||||
cwd: path.join(root, "current/apps/api"),
|
||||
script: "dist/main.js",
|
||||
interpreter: process.execPath,
|
||||
node_args: ["--env-file=" + path.join(root, "shared/.env.production")],
|
||||
env: { NODE_ENV: "production" },
|
||||
autorestart: true,
|
||||
restart_delay: 2000,
|
||||
max_restarts: 10,
|
||||
time: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,353 @@
|
||||
import { createWriteStream } from "node:fs";
|
||||
import {
|
||||
copyFile,
|
||||
cp,
|
||||
mkdir,
|
||||
open,
|
||||
readFile,
|
||||
readlink,
|
||||
readdir,
|
||||
rename,
|
||||
rm,
|
||||
symlink,
|
||||
unlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { checkPackage } from "../scripts/deploy/check-package.mjs";
|
||||
|
||||
const root = process.env.DEPLOY_ROOT;
|
||||
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
|
||||
const source = path.resolve(process.argv[2] ?? ".");
|
||||
const environmentFile = path.join(root, "shared/.env.production");
|
||||
process.loadEnvFile(environmentFile);
|
||||
const current = path.join(root, "current");
|
||||
const postgresContainer = process.env.POSTGRES_CONTAINER;
|
||||
if (!postgresContainer || !/^[a-zA-Z0-9_.-]+$/.test(postgresContainer)) {
|
||||
throw new Error("POSTGRES_CONTAINER is required for the database backup");
|
||||
}
|
||||
if (Number(process.versions.node.split(".")[0]) !== 24) throw new Error("Node.js 24 is required");
|
||||
if (
|
||||
process.env.NODE_ENV !== "production" ||
|
||||
!process.env.DATABASE_URL ||
|
||||
!process.env.SESSION_SECRET ||
|
||||
process.env.SESSION_SECRET.length < 32 ||
|
||||
!process.env.DEFAULT_BRAND_ID ||
|
||||
!process.env.LOCAL_MEDIA_ROOT
|
||||
) {
|
||||
throw new Error("Production environment is missing required values");
|
||||
}
|
||||
if (!path.isAbsolute(process.env.LOCAL_MEDIA_ROOT))
|
||||
throw new Error("LOCAL_MEDIA_ROOT must be absolute");
|
||||
if (process.env.API_PREFIX) throw new Error("API_PREFIX must be empty when Traefik strips /api");
|
||||
const databaseUrl = new URL(process.env.DATABASE_URL);
|
||||
const privateDatabaseHost = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/.test(
|
||||
databaseUrl.hostname,
|
||||
);
|
||||
if (
|
||||
!["127.0.0.1", "localhost"].includes(databaseUrl.hostname) &&
|
||||
!(privateDatabaseHost && process.env.ALLOW_PRIVATE_DATABASE_HOST === "true")
|
||||
) {
|
||||
throw new Error(
|
||||
"DATABASE_URL must use loopback or explicitly approved private Docker networking",
|
||||
);
|
||||
}
|
||||
const traefikDirectory = process.env.TRAEFIK_DYNAMIC_DIR ?? "/home/ubuntu/traefik/dynamic";
|
||||
const traefikGateway = process.env.TRAEFIK_DOCKER_GATEWAY ?? "172.21.0.1";
|
||||
const traefikHost = process.env.TRAEFIK_HOST ?? "wechat.app.que01.top";
|
||||
if (!/^[a-zA-Z0-9.-]+$/.test(traefikHost) || !/^[a-zA-Z0-9.:-]+$/.test(traefikGateway)) {
|
||||
throw new Error("Invalid Traefik host or gateway setting");
|
||||
}
|
||||
const routeFile = path.join(traefikDirectory, "personal-brand-managed.yml");
|
||||
const adminServiceName = "personal-brand-admin-static.service";
|
||||
const adminServiceDirectory = path.join(
|
||||
process.env.XDG_CONFIG_HOME ?? path.join(process.env.HOME ?? "/home/ubuntu", ".config"),
|
||||
"systemd/user",
|
||||
);
|
||||
const adminServiceFile = path.join(adminServiceDirectory, adminServiceName);
|
||||
|
||||
function run(command, args, cwd = root) {
|
||||
const result = spawnSync(command, args, { cwd, stdio: "inherit", env: process.env });
|
||||
if (result.status !== 0) throw new Error(command + " failed with exit " + result.status);
|
||||
}
|
||||
|
||||
async function installAdminService(release) {
|
||||
const stopped = spawnSync("systemctl", ["--user", "stop", adminServiceName], {
|
||||
stdio: "ignore",
|
||||
env: process.env,
|
||||
});
|
||||
if (stopped.status !== 0 && stopped.status !== 5) {
|
||||
throw new Error("Could not stop the previous Admin systemd unit");
|
||||
}
|
||||
await mkdir(adminServiceDirectory, { recursive: true });
|
||||
await writeFile(
|
||||
adminServiceFile,
|
||||
`[Unit]\nDescription=Personal Brand Admin static server\nAfter=network-online.target\n\n[Service]\nType=simple\nWorkingDirectory=${release}\nEnvironment=NODE_ENV=production\nEnvironment=ADMIN_STATIC_PORT=${process.env.ADMIN_STATIC_PORT ?? "3010"}\nEnvironment=ADMIN_STATIC_ROOT=${release}/apps/admin/dist\nExecStart=${process.execPath} ${release}/deploy/static-server.mjs\nRestart=always\nRestartSec=2\n\n[Install]\nWantedBy=default.target\n`,
|
||||
{ mode: 0o644 },
|
||||
);
|
||||
run("systemctl", ["--user", "daemon-reload"]);
|
||||
run("systemctl", ["--user", "enable", "--now", adminServiceName]);
|
||||
run("systemctl", ["--user", "restart", adminServiceName]);
|
||||
}
|
||||
|
||||
function verifyTraefikAdmin() {
|
||||
const result = spawnSync(
|
||||
"docker",
|
||||
[
|
||||
"exec",
|
||||
"traefik",
|
||||
"wget",
|
||||
"-qO",
|
||||
"/dev/null",
|
||||
"-T",
|
||||
"5",
|
||||
`http://${traefikGateway}:${process.env.ADMIN_STATIC_PORT ?? "3010"}/admin/`,
|
||||
],
|
||||
{ stdio: "inherit", env: process.env },
|
||||
);
|
||||
if (result.status !== 0) throw new Error("Traefik cannot reach Admin static service");
|
||||
}
|
||||
|
||||
async function switchCurrent(target) {
|
||||
const temporary = current + ".next-" + process.pid;
|
||||
await symlink(target, temporary);
|
||||
await rename(temporary, current);
|
||||
}
|
||||
|
||||
async function backupDatabase(destination) {
|
||||
const temporary = destination + ".tmp";
|
||||
const child = spawn(
|
||||
"docker",
|
||||
[
|
||||
"exec",
|
||||
postgresContainer,
|
||||
"sh",
|
||||
"-c",
|
||||
'exec pg_dump -Fc -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
||||
],
|
||||
{ stdio: ["ignore", "pipe", "inherit"] },
|
||||
);
|
||||
const output = createWriteStream(temporary, { flags: "wx", mode: 0o600 });
|
||||
child.stdout.pipe(output);
|
||||
await Promise.all([
|
||||
new Promise((resolve, reject) => {
|
||||
child.on("error", reject);
|
||||
child.on("exit", (code) =>
|
||||
code === 0 ? resolve() : reject(new Error("Database backup failed")),
|
||||
);
|
||||
}),
|
||||
new Promise((resolve, reject) => {
|
||||
output.on("finish", resolve);
|
||||
output.on("error", reject);
|
||||
}),
|
||||
]);
|
||||
await rename(temporary, destination);
|
||||
}
|
||||
|
||||
async function copyMissingFiles(sourceDirectory, destinationDirectory) {
|
||||
await mkdir(destinationDirectory, { recursive: true });
|
||||
for (const entry of await readdir(sourceDirectory, { withFileTypes: true })) {
|
||||
if (!entry.isFile()) throw new Error("Unexpected seed media entry: " + entry.name);
|
||||
try {
|
||||
await copyFile(
|
||||
path.join(sourceDirectory, entry.name),
|
||||
path.join(destinationDirectory, entry.name),
|
||||
1,
|
||||
);
|
||||
} catch (error) {
|
||||
if (error.code !== "EEXIST") throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function writeTraefikRoute() {
|
||||
await mkdir(traefikDirectory, { recursive: true });
|
||||
const existing = await readFile(routeFile, "utf8").catch((error) => {
|
||||
if (error.code === "ENOENT") return undefined;
|
||||
throw error;
|
||||
});
|
||||
if (existing && !existing.includes("managed-by-personal-brand-deploy")) {
|
||||
throw new Error("Refusing to overwrite an unmanaged Traefik route file");
|
||||
}
|
||||
const hostRule = "Host(`" + traefikHost + "`)";
|
||||
const configuration = [
|
||||
"# managed-by-personal-brand-deploy",
|
||||
"http:",
|
||||
" routers:",
|
||||
" personal-brand-managed-admin:",
|
||||
" rule: " + JSON.stringify(hostRule + " && !PathPrefix(`/api`) && !PathPrefix(`/media`)"),
|
||||
" entryPoints:",
|
||||
" - websecure",
|
||||
" service: personal-brand-managed-admin",
|
||||
" priority: 1000",
|
||||
" tls:",
|
||||
" certResolver: le",
|
||||
" personal-brand-managed-api:",
|
||||
" rule: " + JSON.stringify(hostRule + " && PathPrefix(`/api`)"),
|
||||
" entryPoints:",
|
||||
" - websecure",
|
||||
" middlewares:",
|
||||
" - personal-brand-managed-strip-api",
|
||||
" service: personal-brand-managed-api",
|
||||
" priority: 1000",
|
||||
" tls:",
|
||||
" certResolver: le",
|
||||
" personal-brand-managed-media:",
|
||||
" rule: " + JSON.stringify(hostRule + " && PathPrefix(`/media`)"),
|
||||
" entryPoints:",
|
||||
" - websecure",
|
||||
" service: personal-brand-managed-api",
|
||||
" priority: 1000",
|
||||
" tls:",
|
||||
" certResolver: le",
|
||||
" middlewares:",
|
||||
" personal-brand-managed-strip-api:",
|
||||
" stripPrefix:",
|
||||
" prefixes:",
|
||||
" - /api",
|
||||
" services:",
|
||||
" personal-brand-managed-admin:",
|
||||
" loadBalancer:",
|
||||
" servers:",
|
||||
" - url: http://" + traefikGateway + ":3010",
|
||||
" personal-brand-managed-api:",
|
||||
" loadBalancer:",
|
||||
" servers:",
|
||||
" - url: http://" + traefikGateway + ":" + (process.env.API_PORT ?? "3001"),
|
||||
"",
|
||||
].join("\n");
|
||||
const temporary = routeFile + ".tmp-" + process.pid;
|
||||
await writeFile(temporary, configuration, { mode: 0o644 });
|
||||
await rename(temporary, routeFile);
|
||||
}
|
||||
|
||||
async function waitForPublicRelease(release) {
|
||||
const verifier = path.join(release, "scripts/deploy/verify-public-release.mjs");
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
const result = spawnSync(process.execPath, [verifier, release], {
|
||||
cwd: release,
|
||||
encoding: "utf8",
|
||||
env: process.env,
|
||||
timeout: 45000,
|
||||
});
|
||||
if (result.status === 0) {
|
||||
process.stdout.write(result.stdout);
|
||||
return;
|
||||
}
|
||||
if (attempt === 3) {
|
||||
process.stderr.write(result.stderr ?? "");
|
||||
process.stdout.write(result.stdout ?? "");
|
||||
throw new Error("Public release verification failed");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForHealth() {
|
||||
const url = "http://127.0.0.1:" + (process.env.API_PORT ?? "3001") + "/health";
|
||||
for (let attempt = 0; attempt < 20; attempt++) {
|
||||
try {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(2000) });
|
||||
const body = await response.json();
|
||||
if (response.ok && body.status === "ok") return;
|
||||
} catch {}
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
throw new Error("API health check failed");
|
||||
}
|
||||
|
||||
await mkdir(path.join(root, "shared/backups"), { recursive: true });
|
||||
await mkdir(path.join(root, "releases"), { recursive: true });
|
||||
const lockPath = path.join(root, "shared/deploy.lock");
|
||||
const lock = await open(lockPath, "wx", 0o600);
|
||||
await lock.writeFile(String(process.pid));
|
||||
let previous;
|
||||
let switched = false;
|
||||
let routeUpdated = false;
|
||||
let previousRoute;
|
||||
try {
|
||||
const manifest = await checkPackage(source);
|
||||
if (manifest.nodeMajor !== 24 || manifest.packageManager !== "pnpm@9.15.0") {
|
||||
throw new Error("Unsupported release toolchain");
|
||||
}
|
||||
const pnpmVersion = spawnSync("pnpm", ["--version"], { encoding: "utf8" });
|
||||
if (pnpmVersion.status !== 0 || pnpmVersion.stdout.trim() !== "9.15.0") {
|
||||
throw new Error("pnpm 9.15.0 is required");
|
||||
}
|
||||
previous = await readlink(current).catch((error) => {
|
||||
if (error.code === "ENOENT") {
|
||||
throw new Error(
|
||||
"Initialize DEPLOY_ROOT/current with the working deployment before the first managed release",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
if (!previous) throw new Error("DEPLOY_ROOT/current must point to the working deployment");
|
||||
previousRoute = await readFile(routeFile).catch((error) => {
|
||||
if (error.code === "ENOENT") return undefined;
|
||||
throw error;
|
||||
});
|
||||
const release = path.join(root, "releases", manifest.version);
|
||||
await mkdir(release, { recursive: false });
|
||||
await cp(source, release, { recursive: true });
|
||||
run(
|
||||
"pnpm",
|
||||
[
|
||||
"--filter",
|
||||
"@personal-brand/api...",
|
||||
"install",
|
||||
"--prod",
|
||||
"--frozen-lockfile",
|
||||
"--prefer-offline",
|
||||
"--ignore-scripts",
|
||||
],
|
||||
release,
|
||||
);
|
||||
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], release);
|
||||
await backupDatabase(path.join(root, "shared/backups", manifest.version + ".dump"));
|
||||
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "migrate", "deploy"], release);
|
||||
const seedDirectory = path.join(process.env.LOCAL_MEDIA_ROOT, "seed");
|
||||
await copyMissingFiles(path.join(release, "seed-media"), seedDirectory);
|
||||
await switchCurrent(release);
|
||||
switched = true;
|
||||
run("pm2", ["startOrRestart", path.join(release, "deploy/ecosystem.config.cjs"), "--update-env"]);
|
||||
await installAdminService(release);
|
||||
await waitForHealth();
|
||||
const staticResponse = await fetch(
|
||||
"http://127.0.0.1:" + (process.env.ADMIN_STATIC_PORT ?? "3010") + "/admin/",
|
||||
{ signal: AbortSignal.timeout(5000) },
|
||||
);
|
||||
if (!staticResponse.ok) throw new Error("Admin static health check failed");
|
||||
verifyTraefikAdmin();
|
||||
await writeTraefikRoute();
|
||||
routeUpdated = true;
|
||||
if (!process.env.PUBLIC_BASE_URL)
|
||||
throw new Error("PUBLIC_BASE_URL is required for cutover verification");
|
||||
await waitForPublicRelease(release);
|
||||
await writeFile(path.join(root, "shared/previous-release"), previous + "\n");
|
||||
run("pm2", ["save"]);
|
||||
console.log("release installed: " + manifest.version);
|
||||
} catch (error) {
|
||||
if (routeUpdated) {
|
||||
if (previousRoute) await writeFile(routeFile, previousRoute);
|
||||
else await rm(routeFile, { force: true });
|
||||
}
|
||||
if (switched) {
|
||||
await switchCurrent(previous);
|
||||
await installAdminService(previous);
|
||||
run("pm2", [
|
||||
"startOrRestart",
|
||||
path.join(source, "deploy/ecosystem.config.cjs"),
|
||||
"--update-env",
|
||||
]);
|
||||
await waitForHealth();
|
||||
console.error(
|
||||
"application and route rollback completed; database migrations were not reversed",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
await lock.close();
|
||||
await unlink(lockPath);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const contentTypes = new Map([
|
||||
[".css", "text/css; charset=utf-8"],
|
||||
[".gif", "image/gif"],
|
||||
[".html", "text/html; charset=utf-8"],
|
||||
[".ico", "image/x-icon"],
|
||||
[".jpeg", "image/jpeg"],
|
||||
[".jpg", "image/jpeg"],
|
||||
[".js", "text/javascript; charset=utf-8"],
|
||||
[".json", "application/json; charset=utf-8"],
|
||||
[".map", "application/json; charset=utf-8"],
|
||||
[".png", "image/png"],
|
||||
[".svg", "image/svg+xml"],
|
||||
[".webmanifest", "application/manifest+json"],
|
||||
[".webp", "image/webp"],
|
||||
[".woff", "font/woff"],
|
||||
[".woff2", "font/woff2"],
|
||||
]);
|
||||
|
||||
function setSecurityHeaders(response) {
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
|
||||
response.setHeader("X-Frame-Options", "SAMEORIGIN");
|
||||
}
|
||||
|
||||
function sendError(response, status, message) {
|
||||
response.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
|
||||
response.end(message);
|
||||
}
|
||||
|
||||
function resolveInside(root, relativePath) {
|
||||
const target = path.resolve(root, relativePath);
|
||||
const relative = path.relative(root, target);
|
||||
if (relative === ".." || relative.startsWith(".." + path.sep) || path.isAbsolute(relative)) {
|
||||
return null;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
function routeFor(pathname, adminRoot) {
|
||||
if (pathname === "/") return { redirect: "/admin/" };
|
||||
if (pathname === "/admin") return { redirect: "/admin/" };
|
||||
if (pathname === "/template-preview") return { redirect: "/template-preview/" };
|
||||
if (pathname === "/favicon.ico") return { root: adminRoot, relativePath: "favicon.ico" };
|
||||
if (pathname.startsWith("/admin/")) {
|
||||
return { root: adminRoot, relativePath: pathname.slice("/admin/".length), spa: true };
|
||||
}
|
||||
if (pathname.startsWith("/template-preview/")) {
|
||||
return {
|
||||
root: path.join(adminRoot, "template-preview"),
|
||||
relativePath: pathname.slice("/template-preview/".length),
|
||||
spa: true,
|
||||
};
|
||||
}
|
||||
if (pathname.startsWith("/assets/")) {
|
||||
return { root: adminRoot, relativePath: pathname.slice(1) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function createStaticServer({ adminRoot }) {
|
||||
const root = path.resolve(adminRoot);
|
||||
|
||||
return createServer(async (request, response) => {
|
||||
setSecurityHeaders(response);
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
response.setHeader("Allow", "GET, HEAD");
|
||||
sendError(response, 405, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
|
||||
let pathname;
|
||||
try {
|
||||
pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
||||
} catch {
|
||||
sendError(response, 400, "Bad Request");
|
||||
return;
|
||||
}
|
||||
const route = routeFor(pathname, root);
|
||||
if (!route) {
|
||||
sendError(response, 404, "Not Found");
|
||||
return;
|
||||
}
|
||||
if (route.redirect) {
|
||||
response.writeHead(308, { location: route.redirect });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
|
||||
let relativePath;
|
||||
try {
|
||||
relativePath = decodeURIComponent(route.relativePath);
|
||||
} catch {
|
||||
sendError(response, 400, "Bad Request");
|
||||
return;
|
||||
}
|
||||
const target = resolveInside(route.root, relativePath || "index.html");
|
||||
if (!target) {
|
||||
sendError(response, 404, "Not Found");
|
||||
return;
|
||||
}
|
||||
|
||||
let filePath = target;
|
||||
let fileInfo;
|
||||
try {
|
||||
fileInfo = await stat(filePath);
|
||||
if (fileInfo.isDirectory()) {
|
||||
filePath = path.join(filePath, "index.html");
|
||||
fileInfo = await stat(filePath);
|
||||
}
|
||||
if (!fileInfo.isFile()) throw new Error("Not a regular file");
|
||||
} catch {
|
||||
const wantsHtml = request.headers.accept?.includes("text/html");
|
||||
if (!route.spa || !wantsHtml || path.extname(relativePath)) {
|
||||
sendError(response, 404, "Not Found");
|
||||
return;
|
||||
}
|
||||
filePath = path.join(route.root, "index.html");
|
||||
try {
|
||||
fileInfo = await stat(filePath);
|
||||
} catch {
|
||||
sendError(response, 404, "Not Found");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const etag =
|
||||
'"' + fileInfo.size.toString(16) + "-" + Math.trunc(fileInfo.mtimeMs).toString(16) + '"';
|
||||
response.setHeader("ETag", etag);
|
||||
if (request.headers["if-none-match"] === etag) {
|
||||
response.writeHead(304);
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const extension = path.extname(filePath).toLowerCase();
|
||||
response.setHeader("Content-Type", contentTypes.get(extension) ?? "application/octet-stream");
|
||||
response.setHeader("Content-Length", fileInfo.size);
|
||||
response.setHeader(
|
||||
"Cache-Control",
|
||||
extension === ".html"
|
||||
? "no-cache"
|
||||
: /(?:^|[.-])[a-zA-Z0-9_-]{8,}(?:[.-])/.test(path.basename(filePath))
|
||||
? "public, max-age=31536000, immutable"
|
||||
: "public, max-age=300",
|
||||
);
|
||||
response.writeHead(200);
|
||||
if (request.method === "HEAD") {
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const stream = createReadStream(filePath);
|
||||
stream.on("error", () => {
|
||||
if (!response.headersSent) sendError(response, 500, "Internal Server Error");
|
||||
else response.destroy();
|
||||
});
|
||||
stream.pipe(response);
|
||||
});
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const port = Number(process.env.ADMIN_STATIC_PORT ?? 3010);
|
||||
const adminRoot = process.env.ADMIN_STATIC_ROOT ?? path.resolve("apps/admin/dist");
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error("ADMIN_STATIC_PORT must be between 1 and 65535");
|
||||
}
|
||||
const server = createStaticServer({ adminRoot });
|
||||
server.listen(port, "0.0.0.0");
|
||||
server.on("error", (error) => {
|
||||
console.error("admin static server failed", error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
for (const signal of ["SIGINT", "SIGTERM"]) {
|
||||
process.on(signal, () => server.close(() => process.exit(0)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { createStaticServer } from "./static-server.mjs";
|
||||
|
||||
test("static server serves the admin, template preview, and root public assets", async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-static-"));
|
||||
const adminRoot = path.join(directory, "dist");
|
||||
await mkdir(path.join(adminRoot, "assets", "owner"), { recursive: true });
|
||||
await mkdir(path.join(adminRoot, "template-preview"), { recursive: true });
|
||||
await writeFile(path.join(adminRoot, "index.html"), "admin entry");
|
||||
await writeFile(path.join(adminRoot, "template-preview", "index.html"), "preview entry");
|
||||
await writeFile(path.join(adminRoot, "assets", "app-12345678.js"), "console.log('ok')");
|
||||
await writeFile(path.join(adminRoot, "assets", "owner", "portrait.jpg"), "portrait");
|
||||
|
||||
const server = createStaticServer({ adminRoot });
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
const baseUrl = "http://127.0.0.1:" + address.port;
|
||||
try {
|
||||
const admin = await fetch(baseUrl + "/admin/");
|
||||
assert.equal(admin.status, 200);
|
||||
assert.match(admin.headers.get("content-type"), /text\/html/);
|
||||
assert.equal(await admin.text(), "admin entry");
|
||||
|
||||
const adminRoute = await fetch(baseUrl + "/admin/brand", {
|
||||
headers: { accept: "text/html" },
|
||||
});
|
||||
assert.equal(await adminRoute.text(), "admin entry");
|
||||
|
||||
const preview = await fetch(baseUrl + "/template-preview/");
|
||||
assert.equal(await preview.text(), "preview entry");
|
||||
|
||||
const script = await fetch(baseUrl + "/admin/assets/app-12345678.js");
|
||||
assert.match(script.headers.get("content-type"), /javascript/);
|
||||
assert.match(script.headers.get("cache-control"), /immutable/);
|
||||
|
||||
const image = await fetch(baseUrl + "/assets/owner/portrait.jpg");
|
||||
assert.equal(image.headers.get("content-type"), "image/jpeg");
|
||||
assert.equal(await image.text(), "portrait");
|
||||
|
||||
const missingAsset = await fetch(baseUrl + "/admin/assets/missing.js");
|
||||
assert.equal(missingAsset.status, 404);
|
||||
assert.match(missingAsset.headers.get("content-type"), /text\/plain/);
|
||||
|
||||
const traversal = await fetch(baseUrl + "/admin/%2e%2e/%2e%2e/etc/passwd");
|
||||
assert.equal(traversal.status, 404);
|
||||
|
||||
const unsupportedMethod = await fetch(baseUrl + "/admin/", { method: "POST" });
|
||||
assert.equal(unsupportedMethod.status, 405);
|
||||
} finally {
|
||||
await new Promise((resolve, reject) =>
|
||||
server.close((error) => (error ? reject(error) : resolve())),
|
||||
);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
http:
|
||||
routers:
|
||||
personal-brand-admin-vps:
|
||||
rule: "Host(`wechat.app.que01.top`) && !PathPrefix(`/api`) && !PathPrefix(`/media`)"
|
||||
entryPoints:
|
||||
- websecure
|
||||
service: personal-brand-admin-vps
|
||||
priority: 1000
|
||||
tls:
|
||||
certResolver: le
|
||||
personal-brand-api-vps:
|
||||
rule: "Host(`wechat.app.que01.top`) && PathPrefix(`/api`)"
|
||||
entryPoints:
|
||||
- websecure
|
||||
middlewares:
|
||||
- personal-brand-api-strip-vps
|
||||
service: personal-brand-api-vps
|
||||
priority: 1000
|
||||
tls:
|
||||
certResolver: le
|
||||
personal-brand-media-vps:
|
||||
rule: "Host(`wechat.app.que01.top`) && PathPrefix(`/media`)"
|
||||
entryPoints:
|
||||
- websecure
|
||||
service: personal-brand-api-vps
|
||||
priority: 1000
|
||||
tls:
|
||||
certResolver: le
|
||||
middlewares:
|
||||
personal-brand-api-strip-vps:
|
||||
stripPrefix:
|
||||
prefixes:
|
||||
- /api
|
||||
services:
|
||||
personal-brand-admin-vps:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: http://172.21.0.1:3010
|
||||
personal-brand-api-vps:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: http://172.21.0.1:3001
|
||||
@@ -0,0 +1,29 @@
|
||||
name: personal-brand
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:?POSTGRES_USER is required}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
|
||||
POSTGRES_DB: ${POSTGRES_DB:?POSTGRES_DB is required}
|
||||
ports:
|
||||
- "127.0.0.1:${POSTGRES_PORT:-5432}:5432"
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 5s
|
||||
networks:
|
||||
- database
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
|
||||
networks:
|
||||
database:
|
||||
driver: bridge
|
||||
+24
-5
@@ -4,6 +4,26 @@
|
||||
|
||||
API 默认监听 `http://localhost:3001`,管理后台默认监听 `http://localhost:3000`。后台开发服务器会把 `/api` 请求代理到 API,并移除 `/api` 前缀,因此本地不需要额外配置跨域。
|
||||
|
||||
## 生产架构
|
||||
|
||||
生产环境只使用 Docker Compose 运行 PostgreSQL;API 和 Admin 运行在 VPS 宿主机上。API 由 Node.js 24 + PM2 运行在 `3001`,Admin 静态服务由 user-level `systemd` 运行在 `3010`,Traefik file provider 负责路由。Traefik 所在 Docker 网段必须允许访问宿主机 `3010`,但不需要向公网开放该端口。用户媒体目录位于发布目录之外,发布时只补充缺失的种子图片,不覆盖上传文件。
|
||||
|
||||
每次发布先创建 PostgreSQL `pg_dump` 备份,再执行 Prisma migration 和公网健康检查;检查失败时恢复应用版本和 Traefik 路由。数据库 migration 不自动回滚,必须使用备份恢复或人工处理。
|
||||
|
||||
`docker-compose.prod.yml` 只负责 PostgreSQL,不再定义 API、Admin 或业务镜像。Gitea 用于保存源码、发布包和 SHA-256 校验文件;生产机只安装经过校验的发布包,不在 VPS 上临时拉取源码并构建。
|
||||
|
||||
日常发布只执行一条命令:
|
||||
|
||||
```bash
|
||||
pnpm deploy:release
|
||||
```
|
||||
|
||||
命令会自动构建 Admin 和 API、生成带 manifest 的发布包、生成 SHA-256、上传到 `DEPLOY_TARGET`(默认 `oracle_arm`)、在 VPS 校验并安装、备份数据库、执行 migration、切换服务和 Traefik,最后检查 Admin、模板预览、API 和媒体。需要更换目标或域名时通过环境变量配置:
|
||||
|
||||
```bash
|
||||
DEPLOY_TARGET=oracle_arm PUBLIC_BASE_URL=https://wechat.app.que01.top pnpm deploy:release
|
||||
```
|
||||
|
||||
## Nginx 反向代理
|
||||
|
||||
生产环境建议使用同源路径:
|
||||
@@ -56,15 +76,14 @@ SEED_ADMIN_PASSWORD=<first-boot-admin-password>
|
||||
|
||||
`DATABASE_URL` 使用最小权限数据库账号。`SESSION_SECRET` 不能复用示例值或开发值。媒体上传使用 S3 兼容对象存储和预签名直传,生产环境必须配置独立的 `OBJECT_STORAGE_PUBLIC_URL`、最小权限访问密钥和专用 bucket。微信相关变量只在启用对应能力时配置,同样不能提交真实凭据。
|
||||
|
||||
### 2. 构建与迁移
|
||||
### 2. 构建发布包
|
||||
|
||||
```bash
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build:admin:preview
|
||||
pnpm --filter @personal-brand/api db:migrate:deploy
|
||||
pnpm deploy:package
|
||||
```
|
||||
|
||||
`apps/admin/dist` 是部署产物,包含 Admin 静态站点和已构建的模板预览应用。生产 API 使用 `pnpm --filter @personal-brand/api start` 启动,由进程管理器负责重启与日志。
|
||||
`apps/admin/dist` 是部署产物,包含 Admin 静态站点和已构建的模板预览应用。生产 API 使用 PM2 启动,配置位于发布包的 `deploy/ecosystem.config.cjs`。
|
||||
|
||||
部署产物中的模板预览入口是 `apps/admin/dist/template-preview/index.html`,资源位于同级 `assets`、`css`、`js` 目录,线上必须保留 `/template-preview/` 前缀。
|
||||
|
||||
@@ -74,7 +93,7 @@ pnpm --filter @personal-brand/api db:migrate:deploy
|
||||
pnpm deploy:package
|
||||
```
|
||||
|
||||
脚本会先执行数据库迁移,再生成 `dist/release`,其中 `admin/` 是静态站点,`api/` 是编译后的 API 产物,`manifest.json` 记录关键入口的大小和 SHA-256。发布进程需要保留 API 的 `node_modules` 或在目标机器重新执行 `pnpm install --prod --frozen-lockfile`。
|
||||
脚本生成带完整文件清单和 SHA-256 的版本目录及归档,归档旁边会生成 `.sha256` 文件。上传到 VPS 后由 `deploy/install-release.mjs` 复用 pnpm store 安装依赖、备份数据库、执行迁移、切换 PM2、systemd 和 Traefik 路由,并运行公网验证。切流前必须通过 Traefik 容器访问 Admin 上游的检查。
|
||||
|
||||
首次部署可以执行一次 `pnpm db:seed` 创建管理员与演示品牌。已有生产环境禁止重复执行种子命令;模板示例内容只能由管理员在后台对指定品牌显式导入,不能把示例数据扩展到全局种子。
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
## 模板与配置包
|
||||
|
||||
- 执行 pnpm template:doctor 并遵循 [模板完成度规则](template-completion-rules.md),诊断未解决项和未验证项不能视为完成;
|
||||
|
||||
- 模板声明必须真正驱动安装和升级,不能只增加类型而保留 Controller 硬编码;
|
||||
- 每个页面上的品牌事实、信任资料、业务详情和可编辑文案都必须来自 Runtime 数据,并在同一页面声明对应 Admin editor binding;`pnpm validate:templates` 的逐页 renderer / editor 契约测试通过后才能判定模板完成;
|
||||
- 每种模板信任内容必须声明实际展示页面,逐页测试要同时验证“声明的类型有 renderer 消费”和“renderer 使用的类型已声明”;
|
||||
@@ -34,6 +33,23 @@
|
||||
- 回滚必须明确是恢复配置基线还是删除新增数据,并在接口文案和测试中保持一致;
|
||||
- 模板新增能力不得侵入个人品牌核心模型。
|
||||
|
||||
## Taro 模板双端验收
|
||||
|
||||
- 构建任意 Taro 模板小程序时使用真实发布参数,并保留命令证据:
|
||||
`TEMPLATE_KEY=<template-key> API_BASE_URL=<production-api> WEAPP_APP_ID=<appid> pnpm --filter @personal-brand/taro build:weapp`;
|
||||
- 小程序和 H5 必须分别构建并归档到 `apps/taro/dist/<templateKey>/weapp` 与 `apps/taro/dist/<templateKey>/h5`;产物契约测试通过;
|
||||
- 产物检查必须覆盖:`project.config.json` 的 AppID、请求内嵌的 `API_BASE_URL`、`/media/` 相对地址补全结果、`common.wxss` 中的按钮规则;
|
||||
- 涉及 `Button`、`Input`、`Textarea`、`Picker` 等原生控件时,源码和产物都要核对;禁止只依据 H5 预览判定小程序样式;
|
||||
- 按页面角色检查视觉点,不按模板名称写专用清单,并记录截图或说明未改动原因:
|
||||
- 首页:媒体加载、横向间距、标签换行、整卡点击;
|
||||
- 列表页:卡片宽度、媒体高度、空态和点击目标;
|
||||
- 详情页:主行动按钮全宽、默认高度 88rpx、文字垂直居中,安全区不被遮挡,底部说明不被遮盖;
|
||||
- 个人页:紧凑行动按钮高度由模板令牌定义、文字垂直居中、拨号/复制可点;
|
||||
- 表单页:提交按钮全宽、88rpx 高、文字垂直居中,错误和重试可见;
|
||||
- 微信真机:request/media 域名、登录、拨号、复制、滚动和底部安全区;
|
||||
- 模板自定义尺寸必须通过共享 CSS 变量声明,不把 `46rpx`、`88rpx` 这类值散落在多个模板里;
|
||||
- 产物级断言只能证明配置和规则存在,不能替代真实数据驱动的页面截图;最终视觉证据必须来自微信开发者工具或真机。
|
||||
|
||||
## 后台 UI
|
||||
|
||||
- 覆盖 loading、empty、error、retry、success 和 mutation failure 状态;
|
||||
|
||||
@@ -67,3 +67,20 @@ templateFields 按各自 page 分组;预览同步 templateData。列表审计
|
||||
Runtime 合并标准品牌列和模板 config 时,标准列是共享品牌事实的权威值。同名旧 config 不得覆盖标准列;标准列主动清空为 null 时,旧 slogan、phone、wechat、studioAddress 等别名也不能恢复旧内容。回归须注入冲突值及清空值,验证草稿和公开投影一致,不依赖清洗数据库掩盖优先级错误。
|
||||
|
||||
画布点选测试必须点击实际区域内部的叶子内容,并验证目标和记录 ID;侧栏定位通过不能代替画布可点击。应避开圆角透明角落,不能用强制点击或 dispatchEvent 掩盖真实命中问题。
|
||||
|
||||
## Taro 小程序视觉一致性
|
||||
|
||||
Taro 小程序构建默认会把 CSS 中的 HTML 标签选择器重写为 `.h5-<tag>`,但 React `<Button />` 渲染的是微信原生 `<button>`,不会自动获得 `.h5-button`。本项目关闭小程序 `htmltransform`,保证 `button` 选择器直接命中微信原生 `<button>`;新增共享组件样式时不得再依赖 `.h5-<tag>`。
|
||||
|
||||
共享 reset 必须让微信 `<button>` 与 Taro H5 的 `taro-button-core` 一致:默认 flex、全宽、`min-height:var(--taro-button-height)`、文字居中,并重置 `appearance`、间距、边框和背景。局部按钮通过 `--taro-button-height` 或结构化 class 调整;模板样式不得复制基础尺寸,也不得重新声明整套居中规则。
|
||||
|
||||
## Taro 双端验收清单
|
||||
|
||||
小程序视觉回归按页面角色和原生控件执行,不按模板名写专用清单。平台新增或修改原生控件时,先更新共享 reset、令牌和产物契约测试,再让所有模板自动受益。每个模板变更至少记录一次:
|
||||
|
||||
1. 使用生产参数构建 `weapp` 和 `h5`,保留命令、产物路径和 `project.config.json` 中的 AppID。
|
||||
2. 产物断言:`API_BASE_URL`、`/media/` 补全、`button` 选择器未被改写为 `.h5-button`、共享 reset 存在。
|
||||
3. 页面证据:首页媒体、列表卡片、详情主行动按钮、个人页紧凑行动按钮、表单提交按钮、错误与空态。
|
||||
4. 原生控件必查:显示类型、宽度、高度令牌、文字垂直居中、点击命中、安全区和底部遮挡。
|
||||
5. 真机必查:request/media 合法域名、登录、拨号、复制、滚动、字体缩放和 iPhone 底部安全区。
|
||||
6. 修复方式先查共享 reset、令牌和 Taro 运行时,再改模板局部样式;同类问题必须补产物契约测试或视觉清单项,不允许只改单个模板的单个按钮。
|
||||
@@ -29,8 +29,10 @@
|
||||
"preview:templates": "pnpm --filter @personal-brand/taro dev:preview",
|
||||
"deploy:verify": "node scripts/deploy/verify-release.mjs",
|
||||
"deploy:package": "node scripts/deploy/package-release.mjs",
|
||||
"deploy:release": "node scripts/deploy/publish-release.mjs",
|
||||
"deploy:images": "node scripts/deploy/export-images.mjs",
|
||||
"test:deploy-verify": "node --test scripts/deploy/verify-release.test.mjs",
|
||||
"test:deploy": "node --test scripts/deploy/*.test.mjs deploy/*.test.mjs",
|
||||
"build:admin:preview": "PREVIEW_ALL_TEMPLATES=true API_BASE_URL=/api PREVIEW_PUBLIC_PATH=/template-preview/ pnpm --filter @personal-brand/taro build:preview && node scripts/package-template-preview.cjs && VITE_APP_BASE_PATH=/admin/ VITE_API_BASE_URL=/api pnpm --filter @personal-brand/admin build",
|
||||
"build:taro:food": "pnpm --filter @personal-brand/taro build:h5 && pnpm --filter @personal-brand/taro build:weapp",
|
||||
"build:taro:linjing": "TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5 && TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp",
|
||||
|
||||
@@ -130,6 +130,9 @@
|
||||
.food-home .actions button,
|
||||
.food-home .actions .home-action {
|
||||
flex: 0 0 calc(50% - 7px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: calc(50% - 7px);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
@@ -670,6 +673,10 @@
|
||||
gap: 16px;
|
||||
}
|
||||
.food-profile .contact-actions button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: var(--taro-button-height);
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
border-radius: 24px;
|
||||
|
||||
@@ -375,31 +375,36 @@ export function compileTemplate(options) {
|
||||
const output = prepareOutput(
|
||||
options.out || path.join(workspaceRoot, "dist/miniapp", params.brandSlug),
|
||||
);
|
||||
const writer = createLayerWriter(output);
|
||||
writer.copy(runtimeRoot, "runtime", RUNTIME_EXCLUDES);
|
||||
for (const capability of capabilities) {
|
||||
try {
|
||||
const writer = createLayerWriter(output);
|
||||
writer.copy(runtimeRoot, "runtime", RUNTIME_EXCLUDES);
|
||||
for (const capability of capabilities) {
|
||||
writer.copy(
|
||||
path.join(capability.directory, "miniapp"),
|
||||
`capability:${capability.key}`,
|
||||
LAYER_EXCLUDES,
|
||||
);
|
||||
for (const page of capability.manifest.pages) {
|
||||
if (!fs.existsSync(path.join(output, page + ".js")))
|
||||
fail(`capability ${capability.key} declares ${page} but does not provide it`);
|
||||
}
|
||||
}
|
||||
for (const prefix of manifest.overrides || [])
|
||||
writer.release(prefix, `template:${manifest.packageKey}`);
|
||||
writer.copy(
|
||||
path.join(capability.directory, "miniapp"),
|
||||
`capability:${capability.key}`,
|
||||
path.join(templateDirectory, "miniapp"),
|
||||
`template:${manifest.packageKey}`,
|
||||
LAYER_EXCLUDES,
|
||||
);
|
||||
for (const page of capability.manifest.pages) {
|
||||
if (!fs.existsSync(path.join(output, page + ".js")))
|
||||
fail(`capability ${capability.key} declares ${page} but does not provide it`);
|
||||
}
|
||||
const appJson = buildAppJson(manifest, templateDirectory, capabilities);
|
||||
writeGeneratedFiles(output, manifest, params, appJson, capabilities);
|
||||
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 };
|
||||
} catch (error) {
|
||||
fs.rmSync(output, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
for (const prefix of manifest.overrides || [])
|
||||
writer.release(prefix, `template:${manifest.packageKey}`);
|
||||
writer.copy(
|
||||
path.join(templateDirectory, "miniapp"),
|
||||
`template:${manifest.packageKey}`,
|
||||
LAYER_EXCLUDES,
|
||||
);
|
||||
const appJson = buildAppJson(manifest, templateDirectory, capabilities);
|
||||
writeGeneratedFiles(output, manifest, params, appJson, capabilities);
|
||||
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 };
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
|
||||
@@ -203,6 +203,7 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
data-editor-target="linjing-editorial.profile.records"
|
||||
onClick={() => navigate("records")}
|
||||
>
|
||||
<View className="entry-icon" />
|
||||
<View className="entry-copy">
|
||||
<Text>{p.recordsTitle || "我的咨询记录"}</Text>
|
||||
<Text>{p.recordsSubtitle}</Text>
|
||||
@@ -211,7 +212,7 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
</View>
|
||||
{rows(config.coverage).length > 0 && (
|
||||
<View className="info-card" data-editor-target="linjing-editorial.profile.coverage">
|
||||
<View className="card-title">{p.coverageTitle}</View>
|
||||
<View className="card-title coverage-title">{p.coverageTitle}</View>
|
||||
{rows(config.coverage).map((item, index) => (
|
||||
<View className="note" key={index}>
|
||||
<Text className="note-title">{item.title}</Text>
|
||||
@@ -222,7 +223,7 @@ function Profile({ workspace }: { workspace: RuntimeWorkspace }) {
|
||||
)}
|
||||
{Array.isArray(config.warranty) && config.warranty.length > 0 && (
|
||||
<View className="info-card" data-editor-target="linjing-editorial.profile.warranty">
|
||||
<View className="card-title">{p.warrantyTitle}</View>
|
||||
<View className="card-title warranty-title">{p.warrantyTitle}</View>
|
||||
{config.warranty.map((item, index) => (
|
||||
<View className="warranty" key={index}>
|
||||
<Text className="dot">•</Text>
|
||||
|
||||
@@ -344,6 +344,7 @@
|
||||
}
|
||||
.editorial-profile .contact-action button {
|
||||
display: flex;
|
||||
width: auto;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
@@ -388,6 +389,10 @@
|
||||
height: 66px;
|
||||
border-radius: 12px;
|
||||
background: rgba(138, 104, 70, 0.1);
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238a6846' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4 6h5a3 3 0 0 1 3 3v9a2.5 2.5 0 0 0-2.5-2.5H4z'/%3E%3Cpath d='M20 6h-5a3 3 0 0 0-3 3v9a2.5 2.5 0 0 1 2.5-2.5H20z'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
background-size: 34px;
|
||||
color: #8a6846;
|
||||
}
|
||||
.editorial-profile .entry-copy {
|
||||
@@ -427,6 +432,29 @@
|
||||
.editorial-profile .card-title t-icon {
|
||||
color: #8a6846;
|
||||
}
|
||||
.editorial-profile .coverage-title,
|
||||
.editorial-profile .warranty-title {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.editorial-profile .coverage-title::before,
|
||||
.editorial-profile .warranty-title::before {
|
||||
display: block;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
content: "";
|
||||
background-color: #8a6846;
|
||||
mask-position: center;
|
||||
mask-repeat: no-repeat;
|
||||
mask-size: contain;
|
||||
}
|
||||
.editorial-profile .coverage-title::before {
|
||||
mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 21s7-5.2 7-11a7 7 0 0 0-14 0c0 5.8 7 11 7 11z'/%3E%3Ccircle cx='12' cy='10' r='2.4'/%3E%3C/svg%3E");
|
||||
-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 21s7-5.2 7-11a7 7 0 0 0-14 0c0 5.8 7 11 7 11z'/%3E%3Ccircle cx='12' cy='10' r='2.4'/%3E%3C/svg%3E");
|
||||
}
|
||||
.editorial-profile .warranty-title::before {
|
||||
mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 21c5-2 7-5.4 7-10V6l-7-3-7 3v5c0 4.6 2 8 7 10z'/%3E%3Cpath d='M9.2 12l2 2 3.6-3.8'/%3E%3C/svg%3E");
|
||||
-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 21c5-2 7-5.4 7-10V6l-7-3-7 3v5c0 4.6 2 8 7 10z'/%3E%3Cpath d='M9.2 12l2 2 3.6-3.8'/%3E%3C/svg%3E");
|
||||
}
|
||||
.editorial-profile .note {
|
||||
margin-top: 18px;
|
||||
padding: 20px;
|
||||
@@ -647,6 +675,7 @@
|
||||
margin: 30px 0;
|
||||
}
|
||||
.editorial-detail .chips text {
|
||||
display: inline-block;
|
||||
border: 1px solid #c9b7a0;
|
||||
color: #8a6846;
|
||||
padding: 10px 18px;
|
||||
@@ -657,7 +686,10 @@
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 1;
|
||||
box-sizing: border-box;
|
||||
padding: 22px 32px;
|
||||
padding-bottom: calc(22px + env(safe-area-inset-bottom));
|
||||
background: #f7f5f1;
|
||||
}
|
||||
.editorial-detail .bar button {
|
||||
|
||||
Generated
+3
-3
@@ -114,6 +114,9 @@ importers:
|
||||
fastify:
|
||||
specifier: ^5.11.3
|
||||
version: 5.11.3
|
||||
prisma:
|
||||
specifier: ^6.2.1
|
||||
version: 6.19.3(typescript@5.9.3)
|
||||
reflect-metadata:
|
||||
specifier: ^0.2.2
|
||||
version: 0.2.2
|
||||
@@ -124,9 +127,6 @@ importers:
|
||||
'@types/node':
|
||||
specifier: ^22.10.5
|
||||
version: 22.20.3
|
||||
prisma:
|
||||
specifier: ^6.2.1
|
||||
version: 6.19.3(typescript@5.9.3)
|
||||
tsx:
|
||||
specifier: ^4.19.2
|
||||
version: 4.23.13
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
async function listFiles(directory, prefix = "") {
|
||||
const files = [];
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const relative = path.posix.join(prefix, entry.name);
|
||||
if (entry.isDirectory())
|
||||
files.push(...(await listFiles(path.join(directory, entry.name), relative)));
|
||||
else if (entry.isFile()) files.push(relative);
|
||||
else throw new Error("Unsupported file: " + relative);
|
||||
}
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
export async function checkPackage(directory) {
|
||||
const manifest = JSON.parse(await readFile(path.join(directory, "manifest.json"), "utf8"));
|
||||
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,100}$/.test(manifest.version))
|
||||
throw new Error("Invalid release version");
|
||||
const actual = await listFiles(directory);
|
||||
const expected = manifest.files
|
||||
.map((file) => file.path)
|
||||
.concat("manifest.json")
|
||||
.sort();
|
||||
if (JSON.stringify(actual) !== JSON.stringify(expected))
|
||||
throw new Error("Release file list mismatch");
|
||||
for (const file of manifest.files) {
|
||||
if (file.path.startsWith("/") || file.path.split("/").includes(".."))
|
||||
throw new Error("Unsafe release path");
|
||||
const content = await readFile(path.join(directory, file.path));
|
||||
const digest = createHash("sha256").update(content).digest("hex");
|
||||
if (content.byteLength !== file.bytes || digest !== file.sha256)
|
||||
throw new Error("Release checksum mismatch: " + file.path);
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const manifest = await checkPackage(path.resolve(process.argv[2] ?? "."));
|
||||
console.log("release verified: " + manifest.version + " (" + manifest.files.length + " files)");
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { checkPackage } from "./check-package.mjs";
|
||||
|
||||
async function createPackage() {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-release-"));
|
||||
await mkdir(path.join(directory, "apps"), { recursive: true });
|
||||
const content = Buffer.from("release fixture");
|
||||
await writeFile(path.join(directory, "apps/api.js"), content);
|
||||
await writeFile(
|
||||
path.join(directory, "manifest.json"),
|
||||
JSON.stringify({
|
||||
version: "fixture-1",
|
||||
files: [
|
||||
{
|
||||
path: "apps/api.js",
|
||||
bytes: content.byteLength,
|
||||
sha256: createHash("sha256").update(content).digest("hex"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
return directory;
|
||||
}
|
||||
|
||||
test("release package checker accepts a matching file manifest", async () => {
|
||||
const directory = await createPackage();
|
||||
try {
|
||||
const manifest = await checkPackage(directory);
|
||||
assert.equal(manifest.version, "fixture-1");
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("release package checker rejects modified package files", async () => {
|
||||
const directory = await createPackage();
|
||||
try {
|
||||
await writeFile(path.join(directory, "apps/api.js"), "modified");
|
||||
await assert.rejects(checkPackage(directory), /checksum mismatch/);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("release package checker rejects files missing from the manifest", async () => {
|
||||
const directory = await createPackage();
|
||||
try {
|
||||
await writeFile(path.join(directory, "extra.txt"), "not in manifest");
|
||||
await assert.rejects(checkPackage(directory), /file list mismatch/);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,50 +1,150 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { checkPackage } from "./check-package.mjs";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../..");
|
||||
const source = path.join(root, "apps/admin/dist");
|
||||
const output = path.join(root, "dist/release");
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
||||
const timestamp = new Date().toISOString().replace(/\D/g, "").slice(0, 14);
|
||||
const git = spawnSync("git", ["rev-parse", "--short=12", "HEAD"], { cwd: root, encoding: "utf8" });
|
||||
if (git.status !== 0) throw new Error("Cannot determine source revision");
|
||||
const revision = git.stdout.trim();
|
||||
const version = process.env.RELEASE_VERSION ?? timestamp + "-" + revision;
|
||||
const output = path.join(root, "dist/releases", version);
|
||||
const archive = path.join(root, "dist/releases", "personal-brand-" + version + ".tar.gz");
|
||||
|
||||
function run(command, args, environment = {}) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: root,
|
||||
stdio: "inherit",
|
||||
env: { ...process.env, ...environment },
|
||||
});
|
||||
function run(command, args) {
|
||||
const result = spawnSync(command, args, { cwd: root, stdio: "inherit" });
|
||||
if (result.status !== 0) process.exit(result.status ?? 1);
|
||||
}
|
||||
|
||||
const requiredFiles = ["index.html", "template-preview/index.html"];
|
||||
const manifest = { createdAt: new Date().toISOString(), files: [] };
|
||||
|
||||
for (const file of requiredFiles) {
|
||||
await readFile(path.join(source, file));
|
||||
async function listFiles(directory, prefix = "") {
|
||||
const files = [];
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const relative = path.posix.join(prefix, entry.name);
|
||||
if (entry.isDirectory())
|
||||
files.push(...(await listFiles(path.join(directory, entry.name), relative)));
|
||||
else if (entry.isFile()) files.push(relative);
|
||||
else throw new Error("Unsupported release file: " + relative);
|
||||
}
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
run("pnpm", ["--filter", "@personal-brand/api", "db:migrate:deploy"]);
|
||||
async function verifyStaticEntry(dist, entry, prefix) {
|
||||
const html = await readFile(path.join(dist, entry), "utf8");
|
||||
for (const match of html.matchAll(/(?:src|href)=["']([^"']+)["']/g)) {
|
||||
const reference = match[1];
|
||||
if (!/\.(?:js|css)(?:[?#]|$)/.test(reference)) continue;
|
||||
const url = new URL(reference, "https://release.invalid" + prefix);
|
||||
if (url.origin !== "https://release.invalid" || !url.pathname.startsWith(prefix)) {
|
||||
throw new Error("Invalid static base path in " + entry + ": " + reference);
|
||||
}
|
||||
const relative = decodeURIComponent(url.pathname.slice(prefix.length));
|
||||
const base = entry === "index.html" ? dist : path.join(dist, "template-preview");
|
||||
await readFile(path.join(base, relative));
|
||||
}
|
||||
}
|
||||
|
||||
await rm(output, { recursive: true, force: true });
|
||||
await mkdir(path.join(output, "api"), { recursive: true });
|
||||
await cp(source, path.join(output, "admin"), { recursive: true });
|
||||
await cp(path.join(root, "apps/api/dist"), path.join(output, "api"), { recursive: true });
|
||||
async function copyWorkspace(workspace) {
|
||||
const source = path.join(root, workspace);
|
||||
const target = path.join(output, workspace);
|
||||
await mkdir(target, { recursive: true });
|
||||
await cp(path.join(source, "package.json"), path.join(target, "package.json"));
|
||||
await cp(path.join(source, "src"), path.join(target, "src"), { recursive: true });
|
||||
await cp(path.join(source, "dist"), path.join(target, "dist"), { recursive: true });
|
||||
await cp(path.join(source, "tsconfig.json"), path.join(target, "tsconfig.json"));
|
||||
if (workspace === "apps/api") {
|
||||
await cp(path.join(source, "prisma/schema.prisma"), path.join(target, "prisma/schema.prisma"));
|
||||
await cp(path.join(source, "prisma/migrations"), path.join(target, "prisma/migrations"), {
|
||||
recursive: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const relativePath of [
|
||||
"api/main.js",
|
||||
"admin/index.html",
|
||||
"admin/template-preview/index.html",
|
||||
]) {
|
||||
const file = path.join(output, relativePath);
|
||||
const content = await readFile(file);
|
||||
manifest.files.push({
|
||||
path: relativePath,
|
||||
bytes: content.byteLength,
|
||||
sha256: createHash("sha256").update(content).digest("hex"),
|
||||
async function main() {
|
||||
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,100}$/.test(version))
|
||||
throw new Error("Invalid release version");
|
||||
const adminDist = path.join(root, "apps/admin/dist");
|
||||
await verifyStaticEntry(adminDist, "index.html", "/admin/");
|
||||
await verifyStaticEntry(adminDist, "template-preview/index.html", "/template-preview/");
|
||||
await mkdir(path.dirname(output), { recursive: true });
|
||||
await mkdir(output, { recursive: false });
|
||||
for (const file of [
|
||||
"package.json",
|
||||
"pnpm-lock.yaml",
|
||||
"pnpm-workspace.yaml",
|
||||
"tsconfig.base.json",
|
||||
]) {
|
||||
await cp(path.join(root, file), path.join(output, file));
|
||||
}
|
||||
for (const workspace of [
|
||||
"apps/api",
|
||||
"packages/config",
|
||||
"packages/types",
|
||||
"packages/validation",
|
||||
]) {
|
||||
await copyWorkspace(workspace);
|
||||
}
|
||||
await cp(adminDist, path.join(output, "apps/admin/dist"), { recursive: true });
|
||||
await cp(path.join(root, "apps/api/prisma/assets"), path.join(output, "seed-media"), {
|
||||
recursive: true,
|
||||
});
|
||||
await cp(path.join(root, "deploy"), path.join(output, "deploy"), { recursive: true });
|
||||
for (const file of ["check-package.mjs", "verify-public-release.mjs"]) {
|
||||
await mkdir(path.join(output, "scripts/deploy"), { recursive: true });
|
||||
await cp(path.join(root, "scripts/deploy", file), path.join(output, "scripts/deploy", file));
|
||||
}
|
||||
const validationPath = path.join(output, "packages/validation/package.json");
|
||||
const validation = JSON.parse(await readFile(validationPath, "utf8"));
|
||||
validation.exports["."].import = "./dist/index.js";
|
||||
validation.exports["."].types = "./dist/index.d.ts";
|
||||
await writeFile(validationPath, JSON.stringify(validation, null, 2) + "\n");
|
||||
const schemaPath = path.join(output, "apps/api/prisma/schema.prisma");
|
||||
const schema = await readFile(schemaPath, "utf8");
|
||||
await writeFile(
|
||||
schemaPath,
|
||||
schema.replace(/binaryTargets\s*=\s*\[[^\]]*\]/, 'binaryTargets = ["native"]'),
|
||||
);
|
||||
const status = spawnSync("git", ["status", "--porcelain"], { cwd: root, encoding: "utf8" });
|
||||
if (status.status !== 0) throw new Error("Cannot determine working tree state");
|
||||
const manifest = {
|
||||
version,
|
||||
revision,
|
||||
dirty: Boolean(status.stdout.trim()),
|
||||
createdAt: new Date().toISOString(),
|
||||
nodeMajor: 24,
|
||||
packageManager: "pnpm@9.15.0",
|
||||
files: [],
|
||||
};
|
||||
for (const file of await listFiles(output)) {
|
||||
if (/(?:^|\/)\.env(?:\.|$)/.test(file) && !file.endsWith(".example")) {
|
||||
throw new Error("Refusing to package environment file: " + file);
|
||||
}
|
||||
const content = await readFile(path.join(output, file));
|
||||
manifest.files.push({
|
||||
path: file,
|
||||
bytes: content.byteLength,
|
||||
sha256: createHash("sha256").update(content).digest("hex"),
|
||||
});
|
||||
}
|
||||
await writeFile(path.join(output, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
||||
await checkPackage(output);
|
||||
run("tar", ["-czf", archive, "-C", output, "."]);
|
||||
const checksum = createHash("sha256")
|
||||
.update(await readFile(archive))
|
||||
.digest("hex");
|
||||
await writeFile(archive + ".sha256", checksum + " " + path.basename(archive) + "\n");
|
||||
console.log("release: " + version);
|
||||
console.log("files: " + manifest.files.length);
|
||||
console.log("archive: " + path.relative(root, archive));
|
||||
console.log("checksum: " + path.relative(root, archive + ".sha256"));
|
||||
}
|
||||
|
||||
await writeFile(path.join(output, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
|
||||
console.log(
|
||||
`release package: ${path.relative(root, output)} (${manifest.files.length} checked files)`,
|
||||
);
|
||||
run("pnpm", ["build:admin:preview"]);
|
||||
run("pnpm", ["--filter", "@personal-brand/config", "build"]);
|
||||
run("pnpm", ["--filter", "@personal-brand/types", "build"]);
|
||||
run("pnpm", ["--filter", "@personal-brand/validation", "build"]);
|
||||
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"]);
|
||||
run("pnpm", ["--filter", "@personal-brand/api", "build"]);
|
||||
await main();
|
||||
@@ -0,0 +1,83 @@
|
||||
import { access } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
|
||||
const target = process.env.DEPLOY_TARGET ?? "oracle_arm";
|
||||
const remoteRoot = process.env.DEPLOY_ROOT ?? "/home/ubuntu/persional-brand";
|
||||
const publicBaseUrl = process.env.PUBLIC_BASE_URL ?? "https://wechat.app.que01.top";
|
||||
const timestamp = new Date().toISOString().replace(/\D/g, "").slice(0, 14);
|
||||
const git = spawnSync("git", ["rev-parse", "--short=12", "HEAD"], {
|
||||
cwd: root,
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (git.status !== 0) throw new Error("Cannot determine source revision");
|
||||
const version = process.env.RELEASE_VERSION ?? timestamp + "-" + git.stdout.trim();
|
||||
const releasePrefix = "personal-brand-" + version;
|
||||
const archiveName = releasePrefix + ".tar.gz";
|
||||
const archive = path.join(root, "dist/releases", archiveName);
|
||||
|
||||
function run(command, args, options = {}) {
|
||||
const stdio = options.input === undefined ? "inherit" : ["pipe", "inherit", "inherit"];
|
||||
const result = spawnSync(command, args, { cwd: root, stdio, ...options });
|
||||
if (result.status !== 0) throw new Error(command + " failed with exit " + result.status);
|
||||
}
|
||||
|
||||
if (!/^[a-zA-Z0-9_.@:-]+$/.test(target)) throw new Error("Invalid deployment SSH target");
|
||||
if (!/^\/[a-zA-Z0-9_./-]+$/.test(remoteRoot)) throw new Error("Invalid deployment root");
|
||||
const publicUrl = new URL(publicBaseUrl);
|
||||
if (publicUrl.protocol !== "https:") throw new Error("PUBLIC_BASE_URL must use HTTPS");
|
||||
|
||||
const packageResult = spawnSync("pnpm", ["deploy:package"], {
|
||||
cwd: root,
|
||||
stdio: "inherit",
|
||||
env: { ...process.env, RELEASE_VERSION: version },
|
||||
});
|
||||
if (packageResult.status !== 0) process.exit(packageResult.status ?? 1);
|
||||
|
||||
await access(archive);
|
||||
await access(archive + ".sha256");
|
||||
run("scp", [archive, archive + ".sha256", target + ":/tmp/"]);
|
||||
|
||||
const remoteScript = [
|
||||
"set -eu",
|
||||
'export NVM_DIR="$HOME/.nvm"',
|
||||
'. "$NVM_DIR/nvm.sh"',
|
||||
'release="/tmp/' + releasePrefix + '"',
|
||||
'rm -rf "$release"',
|
||||
'mkdir -p "$release"',
|
||||
"cd /tmp",
|
||||
'sha256sum -c "' + releasePrefix + '.tar.gz.sha256"',
|
||||
'tar -xzf "' + archiveName + '" -C "$release"',
|
||||
"pnpm_bin=$(find \"$HOME/.cache/pnpm/dlx\" -path '*/pnpm@9.15.0/node_modules/pnpm/bin/pnpm.cjs' -print -quit)",
|
||||
'test -n "$pnpm_bin"',
|
||||
"mkdir -p /tmp/pnpm-9.15-bin",
|
||||
'ln -sf "$pnpm_bin" /tmp/pnpm-9.15-bin/pnpm',
|
||||
"export PATH=/tmp/pnpm-9.15-bin:$PATH",
|
||||
'export DEPLOY_ROOT="' + remoteRoot + '"',
|
||||
'export PUBLIC_BASE_URL="' + publicBaseUrl + '"',
|
||||
"export TRAEFIK_DYNAMIC_DIR=/home/ubuntu/traefik/dynamic",
|
||||
'cd "$release"',
|
||||
"node deploy/install-release.mjs .",
|
||||
].join("; ");
|
||||
|
||||
run("ssh", [target, "bash -s"], { input: remoteScript + "\n" });
|
||||
|
||||
const checks = ["/admin/", "/template-preview/", "/api/health", "/media/seed/food-package-02.jpg"];
|
||||
for (const route of checks) {
|
||||
run("curl", [
|
||||
"--fail",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--max-time",
|
||||
"10",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
route + " %{http_code}\\n",
|
||||
publicBaseUrl + route,
|
||||
]);
|
||||
}
|
||||
|
||||
console.log("release published: " + version);
|
||||
@@ -0,0 +1,98 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
const baseUrl = (process.env.PUBLIC_BASE_URL ?? "https://wechat.app.que01.top").replace(/\/+$/, "");
|
||||
const root = path.resolve(process.argv[2] ?? ".");
|
||||
const contentTypes = new Map([
|
||||
[".avif", "image/avif"],
|
||||
[".css", "text/css"],
|
||||
[".gif", "image/gif"],
|
||||
[".ico", "image/"],
|
||||
[".jpeg", "image/jpeg"],
|
||||
[".jpg", "image/jpeg"],
|
||||
[".js", "javascript"],
|
||||
[".json", "application/json"],
|
||||
[".png", "image/png"],
|
||||
[".svg", "image/svg+xml"],
|
||||
[".webp", "image/webp"],
|
||||
[".woff", "font/woff"],
|
||||
[".woff2", "font/woff2"],
|
||||
]);
|
||||
|
||||
async function checkResource(url, expectedType, label) {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(10000) });
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
assert.equal(response.status, 200, label + " returned " + response.status);
|
||||
assert.ok(contentType.includes(expectedType), label + " has content type " + contentType);
|
||||
await response.body?.cancel();
|
||||
}
|
||||
|
||||
async function checkHtmlAssets(relativeEntry, localPath, publicPath) {
|
||||
const html = await readFile(localPath, "utf8");
|
||||
const checks = [];
|
||||
for (const match of html.matchAll(/(?:src|href)=["']([^"']+)["']/g)) {
|
||||
const asset = match[1];
|
||||
if (!/\.(?:js|css)(?:[?#]|$)/.test(asset)) continue;
|
||||
const url = new URL(asset, baseUrl + publicPath);
|
||||
const expectedType = /\.css(?:[?#]|$)/.test(url.pathname) ? "text/css" : "javascript";
|
||||
checks.push(checkResource(url, expectedType, relativeEntry + " -> " + asset));
|
||||
}
|
||||
await Promise.all(checks);
|
||||
}
|
||||
|
||||
async function listFiles(directory, prefix = "") {
|
||||
const files = [];
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const relative = path.posix.join(prefix, entry.name);
|
||||
if (entry.isDirectory())
|
||||
files.push(...(await listFiles(path.join(directory, entry.name), relative)));
|
||||
else if (entry.isFile()) files.push(relative);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const apiHealthResponse = await fetch(baseUrl + "/api/health", {
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
assert.equal(apiHealthResponse.status, 200, "public API health check failed");
|
||||
assert.match(apiHealthResponse.headers.get("content-type") ?? "", /application\/json/);
|
||||
assert.equal((await apiHealthResponse.json()).status, "ok");
|
||||
|
||||
for (const [entry, localFile, publicPath] of [
|
||||
["admin", path.join(root, "apps/admin/dist/index.html"), "/admin/"],
|
||||
[
|
||||
"template preview",
|
||||
path.join(root, "apps/admin/dist/template-preview/index.html"),
|
||||
"/template-preview/",
|
||||
],
|
||||
]) {
|
||||
await checkResource(baseUrl + publicPath, "text/html", entry);
|
||||
await checkHtmlAssets(entry, localFile, publicPath);
|
||||
}
|
||||
|
||||
const assetRoot = path.join(root, "apps/admin/dist/assets");
|
||||
await Promise.all(
|
||||
(await listFiles(assetRoot)).map(async (asset) => {
|
||||
const extension = path.extname(asset).toLowerCase();
|
||||
const expectedType = contentTypes.get(extension);
|
||||
if (!expectedType) return;
|
||||
await checkResource(
|
||||
baseUrl + "/assets/" + asset.split("/").map(encodeURIComponent).join("/"),
|
||||
expectedType,
|
||||
"static asset " + asset,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
(await readdir(path.join(root, "seed-media"))).map((entry) =>
|
||||
checkResource(
|
||||
baseUrl + "/media/seed/" + encodeURIComponent(entry),
|
||||
"image/jpeg",
|
||||
"seed media " + entry,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
console.log("public release verified: admin, preview, assets, and seed media");
|
||||
Reference in new issue
Block a user