@macrowing/inbiz-codegen 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +592 -2
- package/bin/inbiz-codegen.mjs +7 -0
- package/package.json +32 -4
- package/scripts/prepare-templates.mjs +35 -0
- package/src/backend/init.mjs +170 -0
- package/src/config.mjs +150 -0
- package/src/favicon.mjs +100 -0
- package/src/generate.mjs +935 -0
- package/src/generated-output.mjs +107 -0
- package/src/index.mjs +346 -0
- package/src/menu/build.mjs +252 -0
- package/src/menu/check.mjs +163 -0
- package/src/menu/command.mjs +179 -0
- package/src/migrate-runtime.mjs +106 -0
- package/src/platform/client.mjs +167 -0
- package/src/platform/command.mjs +386 -0
- package/src/platform/pack.mjs +591 -0
- package/src/platform/recover.mjs +236 -0
- package/src/platform/startup.mjs +343 -0
- package/src/platform/state.mjs +116 -0
- package/src/platform/update.mjs +157 -0
- package/src/platform/zip.mjs +134 -0
- package/src/pull.mjs +284 -0
- package/src/scaffold/commands.mjs +349 -0
- package/src/scaffold/init.mjs +370 -0
- package/src/scaffold/template-files.mjs +40 -0
- package/src/scaffold/template-source.mjs +235 -0
- package/src/scaffold/template-sync.mjs +335 -0
- package/src/transform/heaviness.mjs +380 -0
- package/src/transform/preview-props.mjs +108 -0
- package/src/transform/published-page-links.mjs +61 -0
- package/src/transform/published-script.mjs +110 -0
- package/src/transform/registry.mjs +781 -0
- package/src/transform/schema-to-jsx.mjs +1708 -0
- package/src/util/des.mjs +10 -0
- package/templates/README.md +34 -0
- package/templates/backend/Directory.Build.props +19 -0
- package/templates/backend/Directory.Packages.props +49 -0
- package/templates/backend/Macrowing.Scaffold.slnx +13 -0
- package/templates/backend/host/Macrowing.Start/Init/app.json +8 -0
- package/templates/backend/host/Macrowing.Start/Init/menus.json +4 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationDefinition.cs +245 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationEndpoints.cs +57 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationHostedService.cs +63 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationOptions.cs +44 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationRunner.cs +294 -0
- package/templates/backend/host/Macrowing.Start/Initialization/InitializationState.cs +72 -0
- package/templates/backend/host/Macrowing.Start/Initialization/MenuFactory.cs +118 -0
- package/templates/backend/host/Macrowing.Start/Initialization/PackageBuilder.cs +317 -0
- package/templates/backend/host/Macrowing.Start/Initialization/PlatformAppImporter.cs +371 -0
- package/templates/backend/host/Macrowing.Start/Macrowing.Start.csproj +26 -0
- package/templates/backend/host/Macrowing.Start/Program.cs +33 -0
- package/templates/backend/host/Macrowing.Start/StartModule.cs +67 -0
- package/templates/backend/host/Macrowing.Start/appsettings.json +38 -0
- package/templates/backend/modules/Macrowing.Generated/Application/GeneratedApplicationAutoMapperProfile.cs +42 -0
- package/templates/backend/modules/Macrowing.Generated/Domain/Entities/GeneratedEntityBase.cs +72 -0
- package/templates/backend/modules/Macrowing.Generated/Domain/GeneratedConsts.cs +50 -0
- package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContext.cs +55 -0
- package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContextModelBuilderExtensions.cs +61 -0
- package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/IGeneratedDbContext.cs +32 -0
- package/templates/backend/modules/Macrowing.Generated/GeneratedModule.cs +89 -0
- package/templates/backend/modules/Macrowing.Generated/Macrowing.Generated.csproj +22 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsClient.cs +95 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsModels.cs +81 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Dictionary/DictionaryClient.cs +44 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/InBizSdkModule.cs +16 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/InterfaceEngine/InterfaceEngineClient.cs +50 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Localization/LocalizationClient.cs +28 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Macrowing.InBiz.SDK.csproj +16 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageClient.cs +99 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageModels.cs +63 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelClient.cs +131 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelQuery.cs +108 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelWrite.cs +44 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Permission/PermissionClient.cs +86 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformException.cs +42 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformRegistration.cs +60 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformTransport.cs +96 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizRequestContext.cs +27 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/README.md +117 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsClient.cs +35 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsQuery.cs +20 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationRequests.cs +105 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationsClient.cs +53 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/README.md +132 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Tracking/WorkFlowTrackingClient.cs +50 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeClient.cs +78 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeModels.cs +34 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowContracts.cs +88 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowRegistration.cs +59 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowTransport.cs +163 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchClient.cs +59 -0
- package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchModels.cs +76 -0
- package/templates/backend/modules/Macrowing.OC.SDK/Macrowing.OC.SDK.csproj +20 -0
- package/templates/backend/modules/Macrowing.OC.SDK/OcSdkModule.cs +18 -0
- package/templates/backend/modules/Macrowing.OC.SDK/Protos/README.md +22 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/Macrowing.InBiz.SDK.Tests.csproj +14 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformContractTests.cs +288 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformLiveTests.cs +173 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowHttpServer.cs +113 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowLiveTests.cs +269 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowOperationsTests.cs +80 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowQueryTests.cs +163 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowTransportTests.cs +111 -0
- package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowUpgradeTests.cs +87 -0
- package/templates/frontend/components/README.md +39 -0
- package/templates/frontend/components/app-components/README.md +33 -0
- package/templates/frontend/components/app-components/common/.gitkeep +0 -0
- package/templates/frontend/components/app-components/components/.gitkeep +0 -0
- package/templates/frontend/components/app-components/package.json +20 -0
- package/templates/frontend/mgt/.umirc.ts +574 -0
- package/templates/frontend/mgt/package.json +96 -0
- package/templates/frontend/mgt/src/app-extends.ts +9 -0
- package/templates/frontend/mgt/src/app.tsx +20 -0
- package/templates/frontend/mgt/src/config/app.ts +31 -0
- package/templates/frontend/mgt/src/layout/header.tsx +14 -0
- package/templates/frontend/mgt/src/layout/index.tsx +11 -0
- package/templates/frontend/mgt/src/layout/sidebar.tsx +14 -0
- package/templates/frontend/mgt/src/locales.ts +8 -0
- package/templates/frontend/mgt/src/pages/.gitkeep +0 -0
- package/templates/frontend/mgt/src/root.tsx +12 -0
- package/templates/frontend/mgt/src/route-view.tsx +3 -0
- package/templates/frontend/mgt/src/runtime.ts +21 -0
- package/templates/frontend/mgt/src/styles/app.css +1 -0
- package/templates/frontend/mgt/src/styles/layout.less +79 -0
- package/templates/frontend/mgt/tsconfig.json +65 -0
- package/templates/frontend/mgt/typings.d.ts +57 -0
- package/templates/frontend/wap/.umirc.ts +574 -0
- package/templates/frontend/wap/package.json +73 -0
- package/templates/frontend/wap/src/app-extends.ts +9 -0
- package/templates/frontend/wap/src/app.tsx +28 -0
- package/templates/frontend/wap/src/config/app.ts +31 -0
- package/templates/frontend/wap/src/layout/header.tsx +14 -0
- package/templates/frontend/wap/src/layout/index.tsx +18 -0
- package/templates/frontend/wap/src/layout/sidebar.tsx +14 -0
- package/templates/frontend/wap/src/locales.ts +8 -0
- package/templates/frontend/wap/src/pages/.gitkeep +0 -0
- package/templates/frontend/wap/src/root.tsx +12 -0
- package/templates/frontend/wap/src/route-view.tsx +3 -0
- package/templates/frontend/wap/src/runtime.ts +21 -0
- package/templates/frontend/wap/src/styles/adaptation.less +190 -0
- package/templates/frontend/wap/src/styles/app.css +7 -0
- package/templates/frontend/wap/src/styles/global.less +81 -0
- package/templates/frontend/wap/src/styles/layout.less +92 -0
- package/templates/frontend/wap/tsconfig.json +66 -0
- package/templates/frontend/wap/typings.d.ts +24 -0
- package/templates/frontend/web/.umirc.ts +574 -0
- package/templates/frontend/web/package.json +26 -0
- package/templates/frontend/web/src/app-extends.ts +9 -0
- package/templates/frontend/web/src/app.tsx +25 -0
- package/templates/frontend/web/src/config/app.ts +31 -0
- package/templates/frontend/web/src/layout/header.tsx +14 -0
- package/templates/frontend/web/src/layout/index.tsx +11 -0
- package/templates/frontend/web/src/layout/sidebar.tsx +14 -0
- package/templates/frontend/web/src/locales.ts +8 -0
- package/templates/frontend/web/src/root.tsx +12 -0
- package/templates/frontend/web/src/route-view.tsx +3 -0
- package/templates/frontend/web/src/runtime.ts +21 -0
- package/templates/frontend/web/src/styles/app.css +104 -0
- package/templates/frontend/web/src/styles/layout.less +124 -0
- package/templates/frontend/web/tsconfig.json +91 -0
- package/templates/frontend/web/typings.d.ts +46 -0
- package/templates/package.json +14 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 应用恢复(创建型)。把本地工程还原成平台上的一个新应用。
|
|
3
|
+
*
|
|
4
|
+
* 顺序与语义严格照 skill 的 `APPLICATION_RECOVERY_APIS.md`:
|
|
5
|
+
*
|
|
6
|
+
* 存在性检查 → 上传 ZIP → 规则校验 → 校验轮询 → 正式导入 → 导入轮询
|
|
7
|
+
* → 取新应用密钥 → 查询站点版本
|
|
8
|
+
*
|
|
9
|
+
* 三条不可动摇的约束:
|
|
10
|
+
* - **只创建,不覆盖**(`isCover: false`,目标已存在直接停);
|
|
11
|
+
* - **上传/校验/导入/轮询不带旧 AppId**;
|
|
12
|
+
* - **接口资料没给的步骤明确跳过**(创建版本绑定、写 Git 日志),
|
|
13
|
+
* 不猜路径、不伪造成功。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { createPlatformClient, ERR, platformError } from './client.mjs';
|
|
17
|
+
|
|
18
|
+
const API = {
|
|
19
|
+
appInfo: '/inbiz/api/services/front/engines/v3/app/info',
|
|
20
|
+
importZip: '/inbiz/api/services/init/v3/app/importZip',
|
|
21
|
+
validateRule: '/inbiz/api/services/init/v3/app/validateImportRule',
|
|
22
|
+
processInfo: '/inbiz/api/services/init/v3/app/processInfo',
|
|
23
|
+
importApp: '/inbiz/api/services/init/v3/app/import',
|
|
24
|
+
appDetail: (appId) => `/inbiz/api/services/engines/v3/app/${appId}`,
|
|
25
|
+
vsCodePlugin: '/inbiz/api/services/engines/v3/vsCodePlugin',
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const POLL = {
|
|
29
|
+
intervalMs: 1000,
|
|
30
|
+
timeoutMs: 5 * 60 * 1000,
|
|
31
|
+
maxConsecutiveFailures: 20,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const STATUS = { RUNNING: 1, ERROR: 2, CANCELLED: 3, DONE: 4 };
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 按域名取应用信息。
|
|
38
|
+
*
|
|
39
|
+
* 启动期用它判断「线上到底有没有、是哪个 appId」—— 只多一次只读请求,
|
|
40
|
+
* 就能避免重复创建,也能把放弃人工记忆的那部分事实落到 `init/state.json`。
|
|
41
|
+
*
|
|
42
|
+
* @returns {Promise<object|null>} 不存在返回 null;其它错误照常抛出
|
|
43
|
+
*/
|
|
44
|
+
export async function getApplicationByDomain({ baseUrl, token, domain, fetchImpl }) {
|
|
45
|
+
const client = createPlatformClient({ baseUrl, fetchImpl, token, skipAppId: true });
|
|
46
|
+
try {
|
|
47
|
+
return await client.get(API.appInfo, { domain, getVersionInfo: 'true' });
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error.kind === ERR.APP_MISSING) return null;
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 应用是否存在。
|
|
56
|
+
*
|
|
57
|
+
* @returns {Promise<'missing'|'exists'>}
|
|
58
|
+
* @throws 任何非「不存在」的错误都会抛出 —— 不能把网络/鉴权异常解释成不存在。
|
|
59
|
+
*/
|
|
60
|
+
export async function checkApplicationExists({ baseUrl, token, domain, fetchImpl }) {
|
|
61
|
+
const client = createPlatformClient({ baseUrl, fetchImpl, token, skipAppId: true });
|
|
62
|
+
try {
|
|
63
|
+
await client.get(API.appInfo, { domain, getVersionInfo: 'true' });
|
|
64
|
+
return 'exists';
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error.kind === ERR.APP_MISSING) return 'missing';
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 从进程状态里取出阻断信息(`ModuleMsgLevel == 3` 会阻止正式导入)。 */
|
|
72
|
+
export function collectBlockers(progress) {
|
|
73
|
+
const modules = progress?.AppRule?.ModuleRuleOutDto;
|
|
74
|
+
if (!Array.isArray(modules)) return [];
|
|
75
|
+
const out = [];
|
|
76
|
+
for (const module of modules) {
|
|
77
|
+
const rules = Array.isArray(module?.RuleOutDto) ? module.RuleOutDto : [];
|
|
78
|
+
for (const rule of rules) {
|
|
79
|
+
if (Number(rule?.MsgLevel ?? module?.ModuleMsgLevel) === 3) {
|
|
80
|
+
out.push({
|
|
81
|
+
module: module?.ModuleEnum,
|
|
82
|
+
message: String(rule?.Msg ?? rule?.Message ?? ''),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 轮询任务到结束。status 2/3 视为失败,4 视为完成。 */
|
|
91
|
+
export async function waitForTask({
|
|
92
|
+
baseUrl, token, key, what, fetchImpl, poll = POLL, sleep = defaultSleep, now = Date.now,
|
|
93
|
+
}) {
|
|
94
|
+
const client = createPlatformClient({ baseUrl, fetchImpl, token, skipAppId: true });
|
|
95
|
+
const startedAt = now();
|
|
96
|
+
let failures = 0;
|
|
97
|
+
|
|
98
|
+
for (;;) {
|
|
99
|
+
if (now() - startedAt > poll.timeoutMs) {
|
|
100
|
+
throw platformError(ERR.SERVER, `${what}超时(${poll.timeoutMs / 1000}s,key=${key})`);
|
|
101
|
+
}
|
|
102
|
+
let progress;
|
|
103
|
+
try {
|
|
104
|
+
progress = await client.get(API.processInfo, { key });
|
|
105
|
+
failures = 0;
|
|
106
|
+
} catch (error) {
|
|
107
|
+
// 401/403 是鉴权问题,重试没有意义
|
|
108
|
+
if (error.kind === ERR.UNAUTHORIZED) throw error;
|
|
109
|
+
failures += 1;
|
|
110
|
+
if (failures >= poll.maxConsecutiveFailures) {
|
|
111
|
+
throw platformError(ERR.NETWORK, `${what}轮询连续失败 ${failures} 次:${error.message}`);
|
|
112
|
+
}
|
|
113
|
+
await sleep(poll.intervalMs);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const status = Number(progress?.Process?.Status ?? STATUS.RUNNING);
|
|
118
|
+
if (status === STATUS.ERROR || status === STATUS.CANCELLED) {
|
|
119
|
+
const blockers = collectBlockers(progress);
|
|
120
|
+
const detail = blockers.length
|
|
121
|
+
? blockers.map((b) => `模块${b.module}: ${b.message}`).join(';')
|
|
122
|
+
: String(progress?.Process?.Message || '');
|
|
123
|
+
throw platformError(ERR.SERVER, `${what}失败(status=${status}):${detail}`);
|
|
124
|
+
}
|
|
125
|
+
if (status === STATUS.DONE) return progress;
|
|
126
|
+
|
|
127
|
+
await sleep(poll.intervalMs);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 上传恢复包(multipart)。不携带旧 AppId。 */
|
|
132
|
+
export async function uploadPackage({ baseUrl, token, buffer, fileName = 'app-recovery.zip', fetchImpl }) {
|
|
133
|
+
const client = createPlatformClient({ baseUrl, fetchImpl, token, skipAppId: true });
|
|
134
|
+
const form = new FormData();
|
|
135
|
+
form.set('file', new Blob([buffer], { type: 'application/zip' }), fileName);
|
|
136
|
+
form.set('isVsCode', 'true');
|
|
137
|
+
const json = await client.postForm(API.importZip, form);
|
|
138
|
+
const tempFolderName = json?.TempFolderName;
|
|
139
|
+
if (!tempFolderName) {
|
|
140
|
+
throw platformError(ERR.SERVER, '上传成功但未返回 TempFolderName');
|
|
141
|
+
}
|
|
142
|
+
return { tempFolderName, contains: json?.Contains };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 完整恢复流程。
|
|
147
|
+
*
|
|
148
|
+
* @param {{
|
|
149
|
+
* baseUrl: string, token: string,
|
|
150
|
+
* domain: string, confirmDomain: string,
|
|
151
|
+
* appName?: string, tableNamePrefix?: string,
|
|
152
|
+
* package: { buffer: Buffer, boot: object, contains?: number },
|
|
153
|
+
* sites?: string[],
|
|
154
|
+
* fetchImpl?: Function, poll?: object, sleep?: Function,
|
|
155
|
+
* }} options
|
|
156
|
+
*/
|
|
157
|
+
export async function recoverApplication(options) {
|
|
158
|
+
const {
|
|
159
|
+
baseUrl, token, domain, confirmDomain, package: pkg,
|
|
160
|
+
sites = ['web', 'mgt', 'wap'],
|
|
161
|
+
fetchImpl, poll = POLL, sleep = defaultSleep, log = () => {},
|
|
162
|
+
} = options;
|
|
163
|
+
|
|
164
|
+
if (!domain) throw platformError(ERR.UNEXPECTED, '缺少 boot.json.Domain');
|
|
165
|
+
// 破坏性操作前的最后一道门:域名必须与确认值逐字相同
|
|
166
|
+
if (confirmDomain !== domain) {
|
|
167
|
+
throw platformError(
|
|
168
|
+
ERR.UNEXPECTED,
|
|
169
|
+
`--confirm-domain 与 boot.json.Domain 不一致("${confirmDomain}" ≠ "${domain}"),已停止`,
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
if (!pkg?.buffer?.length) throw platformError(ERR.UNEXPECTED, '恢复包为空');
|
|
173
|
+
|
|
174
|
+
const exists = await checkApplicationExists({ baseUrl, token, domain, fetchImpl });
|
|
175
|
+
if (exists === 'exists') {
|
|
176
|
+
throw platformError(ERR.UNEXPECTED, `Domain "${domain}" 在平台上已存在;恢复只允许创建,不提供覆盖`);
|
|
177
|
+
}
|
|
178
|
+
log('· 目标应用不存在,继续');
|
|
179
|
+
|
|
180
|
+
const uploaded = await uploadPackage({ baseUrl, token, buffer: pkg.buffer, fetchImpl });
|
|
181
|
+
log(`· 已上传(tempFolderName=${uploaded.tempFolderName})`);
|
|
182
|
+
|
|
183
|
+
const validate = await createPlatformClient({ baseUrl, fetchImpl, token, skipAppId: true })
|
|
184
|
+
.post(API.validateRule, { contains: Number(pkg.contains ?? uploaded.contains ?? 0), tempFolderName: uploaded.tempFolderName });
|
|
185
|
+
const validateKey = validate?.ValidateKey;
|
|
186
|
+
if (!validateKey) throw platformError(ERR.SERVER, '规则校验未返回 ValidateKey');
|
|
187
|
+
await waitForTask({ baseUrl, token, key: validateKey, what: '规则校验', fetchImpl, poll, sleep });
|
|
188
|
+
log('· 规则校验通过');
|
|
189
|
+
|
|
190
|
+
const imported = await createPlatformClient({ baseUrl, fetchImpl, token, skipAppId: true })
|
|
191
|
+
.post(API.importApp, {
|
|
192
|
+
tempFolderName: uploaded.tempFolderName,
|
|
193
|
+
appName: options.appName || pkg.boot?.AppName,
|
|
194
|
+
domain,
|
|
195
|
+
tableNamePrefix: options.tableNamePrefix || pkg.boot?.TableNamePrefix || 'app_',
|
|
196
|
+
isCover: false,
|
|
197
|
+
});
|
|
198
|
+
const appId = imported?.AppId;
|
|
199
|
+
if (!appId) throw platformError(ERR.SERVER, '正式导入未返回 AppId');
|
|
200
|
+
if (imported?.Key) {
|
|
201
|
+
await waitForTask({ baseUrl, token, key: imported.Key, what: '应用导入', fetchImpl, poll, sleep });
|
|
202
|
+
}
|
|
203
|
+
log(`· 已创建应用 ${appId}`);
|
|
204
|
+
|
|
205
|
+
// 切到新 AppId 取密钥,再用新凭证查站点版本
|
|
206
|
+
const detail = await createPlatformClient({ baseUrl, fetchImpl, token, appId })
|
|
207
|
+
.get(API.appDetail(appId), { GetTags: 'true' });
|
|
208
|
+
const secretKey = detail?.App?.SecretKey;
|
|
209
|
+
if (!secretKey) throw platformError(ERR.SERVER, '未取到新应用的 SecretKey');
|
|
210
|
+
|
|
211
|
+
const siteVersions = {};
|
|
212
|
+
const siteClient = createPlatformClient({ baseUrl, fetchImpl, token, appId, secretKey });
|
|
213
|
+
for (const siteType of sites) {
|
|
214
|
+
try {
|
|
215
|
+
const list = await siteClient.get(API.vsCodePlugin, { siteType });
|
|
216
|
+
const id = Array.isArray(list) ? list[0]?.Id : list?.Id;
|
|
217
|
+
if (id) siteVersions[siteType] = id;
|
|
218
|
+
} catch (error) {
|
|
219
|
+
// 本地没有这一端时平台也会报错 —— 记下来,不阻断其它端
|
|
220
|
+
siteVersions[siteType] = { error: error.message };
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
log(`· 站点版本 ${Object.keys(siteVersions).length} 个`);
|
|
224
|
+
|
|
225
|
+
return {
|
|
226
|
+
appId,
|
|
227
|
+
secretKey,
|
|
228
|
+
siteVersions,
|
|
229
|
+
// 接口资料未提供,明确跳过
|
|
230
|
+
skipped: ['创建版本绑定', '写 Git 日志'],
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function defaultSleep(ms) {
|
|
235
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
236
|
+
}
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 部署期自动初始化(`start`)。
|
|
3
|
+
*
|
|
4
|
+
* 目标:**部署完就能用**,不需要人工先到平台上建应用、配菜单。
|
|
5
|
+
*
|
|
6
|
+
* 决策表(按线上实际情况走,不靠猜):
|
|
7
|
+
*
|
|
8
|
+
* | 线上状态 | 动作 |
|
|
9
|
+
* |---|---|
|
|
10
|
+
* | 应用不存在 | 创建(含菜单)+ 发布,写入 `init/state.json` |
|
|
11
|
+
* | 应用存在、状态里没有记录 | 覆盖导入 + 发布,记下 appId |
|
|
12
|
+
* | 应用存在、记录一致 | 跳过 |
|
|
13
|
+
* | 应用存在、菜单指纹变了 | 覆盖导入 + 发布(改名/改图标靠这条生效) |
|
|
14
|
+
*
|
|
15
|
+
* 更新为什么走「导入包」而不是逐条调菜单接口:平台没有「批量替换全部菜单」的接口,
|
|
16
|
+
* 导入接口本身按 OutId 做 upsert(新增 + 覆盖),是唯一能一次改完父子关系的通道。
|
|
17
|
+
* 导入之后必须再发布 —— 前端菜单接口读的是已发布版本,不发布等于没导。
|
|
18
|
+
*
|
|
19
|
+
* 幂等:同一份部署包反复启动,只有第一次会创建/发布,其余都是读状态 + 比对。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import fs from 'node:fs';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
import { readInputs, menusFingerprint, readState, writeState } from './state.mjs';
|
|
25
|
+
import { buildRecoveryPackage, readBoot } from './pack.mjs';
|
|
26
|
+
import { buildMenus, buildMenuRelation } from '../menu/build.mjs';
|
|
27
|
+
import { checkMenus } from '../menu/check.mjs';
|
|
28
|
+
import { getApplicationByDomain, recoverApplication, POLL } from './recover.mjs';
|
|
29
|
+
import { updateApplication, publishSite, pickSite } from './update.mjs';
|
|
30
|
+
import { createPlatformClient, ERR, loginIntegration } from './client.mjs';
|
|
31
|
+
|
|
32
|
+
const EXIT = { OK: 0, INPUT: 2, PLATFORM: 3, NETWORK: 4 };
|
|
33
|
+
|
|
34
|
+
function appIdOf(info) {
|
|
35
|
+
if (!info) return '';
|
|
36
|
+
return info.App?.Id || info.App?.AppId || info.appId || info.Id || '';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {{
|
|
41
|
+
* root: string, env: { serverUrl: string, userName?: string, integrationKey?: string, isOld?: boolean,
|
|
42
|
+
* appId?: string, siteOutId?: string, end?: string },
|
|
43
|
+
* fetchImpl?: Function, dryRun?: boolean, json?: boolean, sleep?: Function, poll?: object,
|
|
44
|
+
* log?: (line: string) => void,
|
|
45
|
+
* }} options
|
|
46
|
+
*/
|
|
47
|
+
export async function runStartupInit(options) {
|
|
48
|
+
const {
|
|
49
|
+
root, env, fetchImpl, dryRun = false, json = false,
|
|
50
|
+
sleep, poll = POLL, log = () => {},
|
|
51
|
+
} = options;
|
|
52
|
+
|
|
53
|
+
const report = {
|
|
54
|
+
ok: false,
|
|
55
|
+
command: 'start',
|
|
56
|
+
dryRun,
|
|
57
|
+
domain: '',
|
|
58
|
+
action: 'none',
|
|
59
|
+
appId: '',
|
|
60
|
+
menus: { count: 0, fingerprint: '' },
|
|
61
|
+
drift: [],
|
|
62
|
+
errors: [],
|
|
63
|
+
warnings: [],
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// ---- 1. 读部署输入 ----
|
|
67
|
+
const inputs = readInputs(root);
|
|
68
|
+
if (inputs.errors.length) {
|
|
69
|
+
report.errors.push(...inputs.errors);
|
|
70
|
+
return finish(report, EXIT.INPUT, json);
|
|
71
|
+
}
|
|
72
|
+
const boot = { ...readBoot(root, {}), ...inputs.boot };
|
|
73
|
+
report.domain = boot.Domain || '';
|
|
74
|
+
if (!report.domain) {
|
|
75
|
+
report.errors.push({ code: 'DOMAIN_MISSING', path: 'boot.json', message: 'boot.json 缺少 Domain' });
|
|
76
|
+
return finish(report, EXIT.INPUT, json);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---- 2. 菜单期望态 ----
|
|
80
|
+
const end = inputs.menus.end || env.end || 'web';
|
|
81
|
+
const built = buildMenus({ ...inputs.menus, end });
|
|
82
|
+
if (built.errors.length) {
|
|
83
|
+
report.errors.push(...built.errors);
|
|
84
|
+
return finish(report, EXIT.INPUT, json);
|
|
85
|
+
}
|
|
86
|
+
const relation = buildMenuRelation(built.menus);
|
|
87
|
+
const checked = checkMenus(built.menus, relation);
|
|
88
|
+
if (!checked.ok) {
|
|
89
|
+
report.errors.push(...checked.errors);
|
|
90
|
+
return finish(report, EXIT.INPUT, json);
|
|
91
|
+
}
|
|
92
|
+
report.warnings.push(...checked.warnings);
|
|
93
|
+
|
|
94
|
+
const fingerprint = menusFingerprint(built.menus);
|
|
95
|
+
report.menus = { count: built.menus.length, fingerprint };
|
|
96
|
+
|
|
97
|
+
const state = readState(inputs.initDir);
|
|
98
|
+
const initDir = inputs.initDir;
|
|
99
|
+
|
|
100
|
+
// ---- 3. 预演:只说明会做什么 ----
|
|
101
|
+
if (dryRun) {
|
|
102
|
+
report.ok = true;
|
|
103
|
+
report.action = state?.appId ? 'would-verify' : 'would-create';
|
|
104
|
+
report.appId = state?.appId || '';
|
|
105
|
+
report.warnings.push({
|
|
106
|
+
code: 'DRY_RUN',
|
|
107
|
+
message: state?.appId
|
|
108
|
+
? `将核对线上应用(记录中的 appId=${state.appId})`
|
|
109
|
+
: '线上没有记录,将创建应用与菜单',
|
|
110
|
+
});
|
|
111
|
+
return finish(report, EXIT.OK, json);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ---- 4. 取 Token ----
|
|
115
|
+
if (!env.serverUrl) {
|
|
116
|
+
report.errors.push({ code: 'SERVER_URL_MISSING', path: 'init/.env', message: '缺少 SERVER_URL' });
|
|
117
|
+
return finish(report, EXIT.INPUT, json);
|
|
118
|
+
}
|
|
119
|
+
let token = env.token || '';
|
|
120
|
+
if (!token && env.userName && env.integrationKey) {
|
|
121
|
+
try {
|
|
122
|
+
token = await loginIntegration({
|
|
123
|
+
baseUrl: env.serverUrl, loginName: env.userName,
|
|
124
|
+
integrationKey: env.integrationKey, isOld: env.isOld, fetchImpl,
|
|
125
|
+
});
|
|
126
|
+
log('· 已用集成凭据登录');
|
|
127
|
+
} catch (error) {
|
|
128
|
+
report.errors.push({ code: 'LOGIN_FAILED', message: error.message });
|
|
129
|
+
return finish(report, error.kind === ERR.NETWORK ? EXIT.NETWORK : EXIT.PLATFORM, json);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (!token) {
|
|
133
|
+
/**
|
|
134
|
+
* 没有凭据时不能一律判失败。
|
|
135
|
+
*
|
|
136
|
+
* 区分两种部署:
|
|
137
|
+
* - 已经初始化过(`state.json` 里有 appId)→ 说明这套环境本来就能用,
|
|
138
|
+
* 不该因为「没给凭据」把站点拦在启动之外;
|
|
139
|
+
* - 从没初始化过 → 必须失败,否则站点起来也是不可用的空壳。
|
|
140
|
+
*/
|
|
141
|
+
if (state?.appId) {
|
|
142
|
+
report.ok = true;
|
|
143
|
+
report.action = 'skipped';
|
|
144
|
+
report.appId = state.appId;
|
|
145
|
+
report.warnings.push({
|
|
146
|
+
code: 'CREDENTIALS_MISSING',
|
|
147
|
+
message: `没有集成凭据,跳过线上核对(沿用 init/state.json 的 appId=${state.appId})`,
|
|
148
|
+
});
|
|
149
|
+
return finish(report, EXIT.OK, json);
|
|
150
|
+
}
|
|
151
|
+
report.errors.push({
|
|
152
|
+
code: 'TOKEN_MISSING',
|
|
153
|
+
path: 'init/.env',
|
|
154
|
+
message: '从未初始化且缺少 USER_NAME / INTEGRATION_KEY,无法创建线上应用',
|
|
155
|
+
});
|
|
156
|
+
return finish(report, EXIT.INPUT, json);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ---- 5. 线上现状 ----
|
|
160
|
+
let existing;
|
|
161
|
+
try {
|
|
162
|
+
existing = await getApplicationByDomain({
|
|
163
|
+
baseUrl: env.serverUrl, token, domain: report.domain, fetchImpl,
|
|
164
|
+
});
|
|
165
|
+
} catch (error) {
|
|
166
|
+
report.errors.push({ code: 'PLATFORM_ERROR', message: error.message });
|
|
167
|
+
return finish(report, error.kind === ERR.NETWORK ? EXIT.NETWORK : EXIT.PLATFORM, json);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (!existing) {
|
|
171
|
+
// ---- 6a. 创建 ----
|
|
172
|
+
const pkg = buildRecoveryPackage({
|
|
173
|
+
root,
|
|
174
|
+
mode: 'menu',
|
|
175
|
+
boot,
|
|
176
|
+
menus: { end, menu: built.menus, menuRelation: relation },
|
|
177
|
+
// 站点元数据(模板 id / 主题)来自 boot.Site;缺了平台会判「没有模版Id」
|
|
178
|
+
site: boot.Site,
|
|
179
|
+
});
|
|
180
|
+
try {
|
|
181
|
+
const result = await recoverApplication({
|
|
182
|
+
baseUrl: env.serverUrl, token,
|
|
183
|
+
domain: report.domain, confirmDomain: report.domain,
|
|
184
|
+
appName: boot.AppName, tableNamePrefix: boot.TableNamePrefix,
|
|
185
|
+
package: pkg, sites: [end], fetchImpl, sleep, poll,
|
|
186
|
+
log,
|
|
187
|
+
});
|
|
188
|
+
report.action = 'created';
|
|
189
|
+
report.appId = result.appId;
|
|
190
|
+
report.siteVersions = result.siteVersions;
|
|
191
|
+
writeState(initDir, {
|
|
192
|
+
appId: result.appId,
|
|
193
|
+
domain: report.domain,
|
|
194
|
+
end,
|
|
195
|
+
menusHash: fingerprint,
|
|
196
|
+
menusCount: built.menus.length,
|
|
197
|
+
initializedAt: new Date().toISOString(),
|
|
198
|
+
updatedAt: new Date().toISOString(),
|
|
199
|
+
});
|
|
200
|
+
report.envPatch = { APP_ID: result.appId, SECRET_KEY: result.secretKey };
|
|
201
|
+
report.ok = true;
|
|
202
|
+
return finish(report, EXIT.OK, json);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
report.errors.push({ code: error.kind === ERR.SERVER ? 'PLATFORM_REJECTED' : 'RECOVER_FAILED', message: error.message });
|
|
205
|
+
return finish(report, error.kind === ERR.NETWORK ? EXIT.NETWORK : EXIT.PLATFORM, json);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---- 6b. 已存在:比对并记录,不重复创建 ----
|
|
210
|
+
const liveAppId = appIdOf(existing);
|
|
211
|
+
report.appId = liveAppId || state?.appId || '';
|
|
212
|
+
report.action = 'verified';
|
|
213
|
+
|
|
214
|
+
if (state?.appId && liveAppId && state.appId !== liveAppId) {
|
|
215
|
+
report.drift.push({
|
|
216
|
+
code: 'APP_ID_CHANGED',
|
|
217
|
+
message: `状态记录 ${state.appId},线上是 ${liveAppId}(环境可能被重建过)`,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
if (!state?.appId) {
|
|
221
|
+
report.warnings.push({
|
|
222
|
+
code: 'STATE_ADOPTED',
|
|
223
|
+
message: `线上已有应用(${report.appId || '未知 id'}),本地无记录:按 init/menus.json 覆盖导入并发布`,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// 菜单变了(或本地没有记录)→ 覆盖导入 + 发布。
|
|
228
|
+
//
|
|
229
|
+
// 不能用「报 MENU_DRIFT 让人去平台手工改」收尾:导入接口本来就按 OutId
|
|
230
|
+
// 做 upsert,这是唯一能批量改名字/图标/父级的通道;而且前端读的是已发布
|
|
231
|
+
// 版本,只导入不发布等于没改。
|
|
232
|
+
const needsSync = !state?.menusHash || state.menusHash !== fingerprint;
|
|
233
|
+
if (needsSync) {
|
|
234
|
+
if (state?.menusHash) {
|
|
235
|
+
report.drift.push({
|
|
236
|
+
code: 'MENU_DRIFT',
|
|
237
|
+
message: '本地菜单与上次初始化不一致,正在覆盖导入并发布',
|
|
238
|
+
localMenus: built.menus.length,
|
|
239
|
+
recordedFingerprint: state.menusHash,
|
|
240
|
+
currentFingerprint: fingerprint,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
const site = pickSite(existing, end, env.siteType);
|
|
244
|
+
const pkg = buildRecoveryPackage({
|
|
245
|
+
root,
|
|
246
|
+
mode: 'menu',
|
|
247
|
+
boot,
|
|
248
|
+
menus: { end, menu: built.menus, menuRelation: relation },
|
|
249
|
+
site: boot.Site,
|
|
250
|
+
// 更新时站点 OutId 必须填线上那个,平台靠它在包里定位站点
|
|
251
|
+
siteOutId: site?.OutId || '',
|
|
252
|
+
// 未发布的开发应用只能用开发包(0)更新;已发布的用全量包(3)
|
|
253
|
+
zipType: existing?.App?.IsReleased ? 3 : 0,
|
|
254
|
+
});
|
|
255
|
+
try {
|
|
256
|
+
await updateApplication({
|
|
257
|
+
baseUrl: env.serverUrl, token, appId: report.appId,
|
|
258
|
+
package: pkg, fetchImpl, sleep, poll, log,
|
|
259
|
+
});
|
|
260
|
+
const published = await publishSite({
|
|
261
|
+
baseUrl: env.serverUrl, token, appId: report.appId,
|
|
262
|
+
siteOutId: site?.OutId, dataVersionId: site?.DataVersionId,
|
|
263
|
+
remarks: 'codegen 菜单同步', fetchImpl,
|
|
264
|
+
});
|
|
265
|
+
report.action = 'updated';
|
|
266
|
+
report.publishedVersionId = published.versionId;
|
|
267
|
+
if (published.alreadyPublished) {
|
|
268
|
+
report.warnings.push({
|
|
269
|
+
code: 'ALREADY_PUBLISHED',
|
|
270
|
+
message: '导入接口已在流程末尾发布,菜单改动已生效(无需再次发布)',
|
|
271
|
+
});
|
|
272
|
+
} else {
|
|
273
|
+
log(`· 已发布新版本 ${published.versionId}`);
|
|
274
|
+
}
|
|
275
|
+
} catch (error) {
|
|
276
|
+
/**
|
|
277
|
+
* 失败时不能写新指纹 —— 写了就代表「已同步」,下次启动直接跳过,
|
|
278
|
+
* 菜单永远停在旧版本。保留旧指纹,下次启动自动重试。
|
|
279
|
+
*/
|
|
280
|
+
report.errors.push({
|
|
281
|
+
code: error.kind === ERR.NETWORK ? 'SYNC_NETWORK' : 'SYNC_FAILED',
|
|
282
|
+
message: `菜单同步失败:${error.message}`,
|
|
283
|
+
});
|
|
284
|
+
writeState(initDir, {
|
|
285
|
+
appId: report.appId || state?.appId || '',
|
|
286
|
+
domain: report.domain,
|
|
287
|
+
end,
|
|
288
|
+
menusHash: state?.menusHash,
|
|
289
|
+
menusCount: built.menus.length,
|
|
290
|
+
initializedAt: state?.initializedAt,
|
|
291
|
+
updatedAt: new Date().toISOString(),
|
|
292
|
+
});
|
|
293
|
+
return finish(report, error.kind === ERR.NETWORK ? EXIT.NETWORK : EXIT.PLATFORM, json);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
writeState(initDir, {
|
|
298
|
+
appId: report.appId || state?.appId || '',
|
|
299
|
+
domain: report.domain,
|
|
300
|
+
end,
|
|
301
|
+
menusHash: fingerprint,
|
|
302
|
+
menusCount: built.menus.length,
|
|
303
|
+
initializedAt: state?.initializedAt,
|
|
304
|
+
updatedAt: new Date().toISOString(),
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
report.ok = true;
|
|
308
|
+
return finish(report, report.drift.length ? EXIT.PLATFORM : EXIT.OK, json);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function finish(report, code, json) {
|
|
312
|
+
if (json) {
|
|
313
|
+
console.log(JSON.stringify(report, null, 2));
|
|
314
|
+
} else {
|
|
315
|
+
const mark = report.ok ? '✓' : '✗';
|
|
316
|
+
console.log(`${mark} start:${report.action}(domain=${report.domain || '?'})`);
|
|
317
|
+
if (report.appId) console.log(` appId ${report.appId}`);
|
|
318
|
+
if (report.menus.count) console.log(` 菜单 ${report.menus.count} 条,指纹 ${report.menus.fingerprint.slice(0, 12)}…`);
|
|
319
|
+
for (const item of report.drift) console.warn(` ! ${item.code}: ${item.message}`);
|
|
320
|
+
for (const item of report.warnings) console.warn(` · ${item.code}: ${item.message}`);
|
|
321
|
+
for (const item of report.errors) console.error(` ✗ ${item.code}: ${item.message}`);
|
|
322
|
+
}
|
|
323
|
+
return { code, report };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** 供 compose/init 使用:把新应用的 id/密钥写回部署目录的 .env(只改两行)。 */
|
|
327
|
+
export function patchDeployEnv(file, patch) {
|
|
328
|
+
if (!patch || !fs.existsSync(file)) return [];
|
|
329
|
+
const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
|
|
330
|
+
const pending = new Map(Object.entries(patch));
|
|
331
|
+
const out = lines.map((line) => {
|
|
332
|
+
const m = /^(\s*)([A-Za-z_][A-Za-z0-9_]*)(\s*=\s*)(.*)$/.exec(line);
|
|
333
|
+
if (!m || !pending.has(m[2])) return line;
|
|
334
|
+
const value = pending.get(m[2]);
|
|
335
|
+
pending.delete(m[2]);
|
|
336
|
+
return `${m[1]}${m[2]}${m[3]}${value}`;
|
|
337
|
+
});
|
|
338
|
+
for (const [key, value] of pending) out.push(`${key}=${value}`);
|
|
339
|
+
fs.writeFileSync(file, out.join('\n'), 'utf8');
|
|
340
|
+
return [...Object.keys(patch)];
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export { createPlatformClient };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 部署初始化状态(`init/` 目录)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要落盘:容器是无状态的,但「线上到底建没建过、建的是什么」必须有据可查。
|
|
5
|
+
* 没有这份记录,每次启动只能靠猜 —— 猜错就是重复创建或永远不创建。
|
|
6
|
+
*
|
|
7
|
+
* 目录约定(随部署包一起发布,**不含密钥**):
|
|
8
|
+
*
|
|
9
|
+
* init/
|
|
10
|
+
* ├── boot.json 应用身份(AppName / Domain / TableNamePrefix)
|
|
11
|
+
* ├── menus.json 菜单期望态(人维护)
|
|
12
|
+
* └── state.json 上次初始化的结果(程序写,不要手改)
|
|
13
|
+
*
|
|
14
|
+
* `state.json` 只记录「平台侧的事实」:新应用 id、创建时间、当时菜单的指纹。
|
|
15
|
+
* 密钥不进这里 —— 它由平台下发到 `.env`,部署时用 secret 注入。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { createHash } from 'node:crypto';
|
|
21
|
+
|
|
22
|
+
export const INIT_DIR = 'init';
|
|
23
|
+
|
|
24
|
+
const STATE_FILE = 'state.json';
|
|
25
|
+
|
|
26
|
+
/** 菜单期望态的指纹:用于判断「本地改了菜单,线上还是旧的」。 */
|
|
27
|
+
export function menusFingerprint(menus) {
|
|
28
|
+
const normalized = [...(menus || [])]
|
|
29
|
+
.map((menu) => `${menu.Route}|${menu.Name}|${menu.ParentId}|${menu.Sort}|${menu.Icon}|${menu.IsVisible}`)
|
|
30
|
+
.sort()
|
|
31
|
+
.join('\n');
|
|
32
|
+
return createHash('sha256').update(normalized).digest('hex');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function readState(initDir) {
|
|
36
|
+
const file = path.join(initDir, STATE_FILE);
|
|
37
|
+
if (!fs.existsSync(file)) return null;
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
40
|
+
} catch (e) {
|
|
41
|
+
throw new Error(`init/${STATE_FILE} 不是合法 JSON:${e.message}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function writeState(initDir, state) {
|
|
46
|
+
fs.mkdirSync(initDir, { recursive: true });
|
|
47
|
+
const file = path.join(initDir, STATE_FILE);
|
|
48
|
+
const text = JSON.stringify(state, null, 2) + '\n';
|
|
49
|
+
if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === text) return false;
|
|
50
|
+
fs.writeFileSync(file, text, 'utf8');
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 读部署输入:`init/` 优先,退回工程根目录。
|
|
56
|
+
*
|
|
57
|
+
* 兼容两种布局:
|
|
58
|
+
* - 部署包:`init/boot.json` + `init/menus.json`
|
|
59
|
+
* - 开发工程:`boot.json` + `menus.json`(与 `menu build` 一致)
|
|
60
|
+
*/
|
|
61
|
+
export function readInputs(root) {
|
|
62
|
+
const candidates = [path.join(root, INIT_DIR), root];
|
|
63
|
+
const pick = (name) => {
|
|
64
|
+
for (const dir of candidates) {
|
|
65
|
+
const file = path.join(dir, name);
|
|
66
|
+
if (fs.existsSync(file)) return { file, dir, text: fs.readFileSync(file, 'utf8') };
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// 出码产物是 `app.json`(后端宿主同名文件),手写/旧工程用 `boot.json`,两个都认。
|
|
72
|
+
// 不能只认其中一个 —— 否则出码生成的文件到了 CLI 这边会被判「缺应用身份」。
|
|
73
|
+
const boot = pick('app.json') || pick('boot.json');
|
|
74
|
+
const menus = pick('menus.json');
|
|
75
|
+
const errors = [];
|
|
76
|
+
if (!boot) errors.push({ code: 'BOOT_MISSING', path: 'app.json', message: '找不到 app.json / boot.json(应用身份)' });
|
|
77
|
+
if (!menus) errors.push({ code: 'MENUS_MISSING', path: 'menus.json', message: '找不到 menus.json(菜单期望态)' });
|
|
78
|
+
|
|
79
|
+
let bootJson = null;
|
|
80
|
+
let menusJson = null;
|
|
81
|
+
try {
|
|
82
|
+
if (boot) bootJson = JSON.parse(boot.text);
|
|
83
|
+
} catch (e) {
|
|
84
|
+
errors.push({ code: 'BOOT_INVALID', path: boot.file, message: `boot.json 不是合法 JSON:${e.message}` });
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
if (menus) menusJson = JSON.parse(menus.text);
|
|
88
|
+
} catch (e) {
|
|
89
|
+
errors.push({ code: 'MENUS_INVALID', path: menus.file, message: `menus.json 不是合法 JSON:${e.message}` });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 两种写法都归一成平台 boot 形状:
|
|
94
|
+
* - `app.json`(出码产物,后端宿主同名文件):`{ app:{appName,domain,...}, sites:[...] }`
|
|
95
|
+
* - `boot.json`(手写/旧工程):`{ AppName, Domain, TableNamePrefix, Sites:[...] }`
|
|
96
|
+
* 不归一的话,出码生成的文件到了 CLI 这边会被判「缺 Domain」。
|
|
97
|
+
*/
|
|
98
|
+
if (bootJson && bootJson.app) {
|
|
99
|
+
const sites = Array.isArray(bootJson.sites) ? bootJson.sites : [];
|
|
100
|
+
bootJson = {
|
|
101
|
+
AppName: bootJson.app.appName || bootJson.app.name || '',
|
|
102
|
+
Domain: bootJson.app.domain || '',
|
|
103
|
+
TableNamePrefix: bootJson.app.tableNamePrefix || 'app_',
|
|
104
|
+
Sites: sites,
|
|
105
|
+
// 第一项就是当前端;包里的 info.json 用它的模板/主题
|
|
106
|
+
Site: sites[0],
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
boot: bootJson,
|
|
112
|
+
menus: menusJson,
|
|
113
|
+
initDir: boot?.dir || menus?.dir || path.join(root, INIT_DIR),
|
|
114
|
+
errors,
|
|
115
|
+
};
|
|
116
|
+
}
|