@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.
Files changed (163) hide show
  1. package/README.md +592 -2
  2. package/bin/inbiz-codegen.mjs +7 -0
  3. package/package.json +32 -4
  4. package/scripts/prepare-templates.mjs +35 -0
  5. package/src/backend/init.mjs +170 -0
  6. package/src/config.mjs +150 -0
  7. package/src/favicon.mjs +100 -0
  8. package/src/generate.mjs +935 -0
  9. package/src/generated-output.mjs +107 -0
  10. package/src/index.mjs +346 -0
  11. package/src/menu/build.mjs +252 -0
  12. package/src/menu/check.mjs +163 -0
  13. package/src/menu/command.mjs +179 -0
  14. package/src/migrate-runtime.mjs +106 -0
  15. package/src/platform/client.mjs +167 -0
  16. package/src/platform/command.mjs +386 -0
  17. package/src/platform/pack.mjs +591 -0
  18. package/src/platform/recover.mjs +236 -0
  19. package/src/platform/startup.mjs +343 -0
  20. package/src/platform/state.mjs +116 -0
  21. package/src/platform/update.mjs +157 -0
  22. package/src/platform/zip.mjs +134 -0
  23. package/src/pull.mjs +284 -0
  24. package/src/scaffold/commands.mjs +349 -0
  25. package/src/scaffold/init.mjs +370 -0
  26. package/src/scaffold/template-files.mjs +40 -0
  27. package/src/scaffold/template-source.mjs +235 -0
  28. package/src/scaffold/template-sync.mjs +335 -0
  29. package/src/transform/heaviness.mjs +380 -0
  30. package/src/transform/preview-props.mjs +108 -0
  31. package/src/transform/published-page-links.mjs +61 -0
  32. package/src/transform/published-script.mjs +110 -0
  33. package/src/transform/registry.mjs +781 -0
  34. package/src/transform/schema-to-jsx.mjs +1708 -0
  35. package/src/util/des.mjs +10 -0
  36. package/templates/README.md +34 -0
  37. package/templates/backend/Directory.Build.props +19 -0
  38. package/templates/backend/Directory.Packages.props +49 -0
  39. package/templates/backend/Macrowing.Scaffold.slnx +13 -0
  40. package/templates/backend/host/Macrowing.Start/Init/app.json +8 -0
  41. package/templates/backend/host/Macrowing.Start/Init/menus.json +4 -0
  42. package/templates/backend/host/Macrowing.Start/Initialization/InitializationDefinition.cs +245 -0
  43. package/templates/backend/host/Macrowing.Start/Initialization/InitializationEndpoints.cs +57 -0
  44. package/templates/backend/host/Macrowing.Start/Initialization/InitializationHostedService.cs +63 -0
  45. package/templates/backend/host/Macrowing.Start/Initialization/InitializationOptions.cs +44 -0
  46. package/templates/backend/host/Macrowing.Start/Initialization/InitializationRunner.cs +294 -0
  47. package/templates/backend/host/Macrowing.Start/Initialization/InitializationState.cs +72 -0
  48. package/templates/backend/host/Macrowing.Start/Initialization/MenuFactory.cs +118 -0
  49. package/templates/backend/host/Macrowing.Start/Initialization/PackageBuilder.cs +317 -0
  50. package/templates/backend/host/Macrowing.Start/Initialization/PlatformAppImporter.cs +371 -0
  51. package/templates/backend/host/Macrowing.Start/Macrowing.Start.csproj +26 -0
  52. package/templates/backend/host/Macrowing.Start/Program.cs +33 -0
  53. package/templates/backend/host/Macrowing.Start/StartModule.cs +67 -0
  54. package/templates/backend/host/Macrowing.Start/appsettings.json +38 -0
  55. package/templates/backend/modules/Macrowing.Generated/Application/GeneratedApplicationAutoMapperProfile.cs +42 -0
  56. package/templates/backend/modules/Macrowing.Generated/Domain/Entities/GeneratedEntityBase.cs +72 -0
  57. package/templates/backend/modules/Macrowing.Generated/Domain/GeneratedConsts.cs +50 -0
  58. package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContext.cs +55 -0
  59. package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/GeneratedDbContextModelBuilderExtensions.cs +61 -0
  60. package/templates/backend/modules/Macrowing.Generated/EntityFrameworkCore/IGeneratedDbContext.cs +32 -0
  61. package/templates/backend/modules/Macrowing.Generated/GeneratedModule.cs +89 -0
  62. package/templates/backend/modules/Macrowing.Generated/Macrowing.Generated.csproj +22 -0
  63. package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsClient.cs +95 -0
  64. package/templates/backend/modules/Macrowing.InBiz.SDK/Cms/CmsModels.cs +81 -0
  65. package/templates/backend/modules/Macrowing.InBiz.SDK/Dictionary/DictionaryClient.cs +44 -0
  66. package/templates/backend/modules/Macrowing.InBiz.SDK/InBizSdkModule.cs +16 -0
  67. package/templates/backend/modules/Macrowing.InBiz.SDK/InterfaceEngine/InterfaceEngineClient.cs +50 -0
  68. package/templates/backend/modules/Macrowing.InBiz.SDK/Localization/LocalizationClient.cs +28 -0
  69. package/templates/backend/modules/Macrowing.InBiz.SDK/Macrowing.InBiz.SDK.csproj +16 -0
  70. package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageClient.cs +99 -0
  71. package/templates/backend/modules/Macrowing.InBiz.SDK/Message/MessageModels.cs +63 -0
  72. package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelClient.cs +131 -0
  73. package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelQuery.cs +108 -0
  74. package/templates/backend/modules/Macrowing.InBiz.SDK/Model/ModelWrite.cs +44 -0
  75. package/templates/backend/modules/Macrowing.InBiz.SDK/Permission/PermissionClient.cs +86 -0
  76. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformException.cs +42 -0
  77. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformRegistration.cs +60 -0
  78. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizPlatformTransport.cs +96 -0
  79. package/templates/backend/modules/Macrowing.InBiz.SDK/Platform/InBizRequestContext.cs +27 -0
  80. package/templates/backend/modules/Macrowing.InBiz.SDK/README.md +117 -0
  81. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsClient.cs +35 -0
  82. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Details/WorkFlowDetailsQuery.cs +20 -0
  83. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationRequests.cs +105 -0
  84. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Operations/WorkFlowOperationsClient.cs +53 -0
  85. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/README.md +132 -0
  86. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Tracking/WorkFlowTrackingClient.cs +50 -0
  87. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeClient.cs +78 -0
  88. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Upgrade/WorkFlowUpgradeModels.cs +34 -0
  89. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowContracts.cs +88 -0
  90. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowRegistration.cs +59 -0
  91. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/WorkFlowTransport.cs +163 -0
  92. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchClient.cs +59 -0
  93. package/templates/backend/modules/Macrowing.InBiz.SDK/WorkFlow/Workbench/WorkFlowWorkbenchModels.cs +76 -0
  94. package/templates/backend/modules/Macrowing.OC.SDK/Macrowing.OC.SDK.csproj +20 -0
  95. package/templates/backend/modules/Macrowing.OC.SDK/OcSdkModule.cs +18 -0
  96. package/templates/backend/modules/Macrowing.OC.SDK/Protos/README.md +22 -0
  97. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/Macrowing.InBiz.SDK.Tests.csproj +14 -0
  98. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformContractTests.cs +288 -0
  99. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/PlatformLiveTests.cs +173 -0
  100. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowHttpServer.cs +113 -0
  101. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowLiveTests.cs +269 -0
  102. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowOperationsTests.cs +80 -0
  103. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowQueryTests.cs +163 -0
  104. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowTransportTests.cs +111 -0
  105. package/templates/backend/tests/Macrowing.InBiz.SDK.Tests/WorkFlowUpgradeTests.cs +87 -0
  106. package/templates/frontend/components/README.md +39 -0
  107. package/templates/frontend/components/app-components/README.md +33 -0
  108. package/templates/frontend/components/app-components/common/.gitkeep +0 -0
  109. package/templates/frontend/components/app-components/components/.gitkeep +0 -0
  110. package/templates/frontend/components/app-components/package.json +20 -0
  111. package/templates/frontend/mgt/.umirc.ts +574 -0
  112. package/templates/frontend/mgt/package.json +96 -0
  113. package/templates/frontend/mgt/src/app-extends.ts +9 -0
  114. package/templates/frontend/mgt/src/app.tsx +20 -0
  115. package/templates/frontend/mgt/src/config/app.ts +31 -0
  116. package/templates/frontend/mgt/src/layout/header.tsx +14 -0
  117. package/templates/frontend/mgt/src/layout/index.tsx +11 -0
  118. package/templates/frontend/mgt/src/layout/sidebar.tsx +14 -0
  119. package/templates/frontend/mgt/src/locales.ts +8 -0
  120. package/templates/frontend/mgt/src/pages/.gitkeep +0 -0
  121. package/templates/frontend/mgt/src/root.tsx +12 -0
  122. package/templates/frontend/mgt/src/route-view.tsx +3 -0
  123. package/templates/frontend/mgt/src/runtime.ts +21 -0
  124. package/templates/frontend/mgt/src/styles/app.css +1 -0
  125. package/templates/frontend/mgt/src/styles/layout.less +79 -0
  126. package/templates/frontend/mgt/tsconfig.json +65 -0
  127. package/templates/frontend/mgt/typings.d.ts +57 -0
  128. package/templates/frontend/wap/.umirc.ts +574 -0
  129. package/templates/frontend/wap/package.json +73 -0
  130. package/templates/frontend/wap/src/app-extends.ts +9 -0
  131. package/templates/frontend/wap/src/app.tsx +28 -0
  132. package/templates/frontend/wap/src/config/app.ts +31 -0
  133. package/templates/frontend/wap/src/layout/header.tsx +14 -0
  134. package/templates/frontend/wap/src/layout/index.tsx +18 -0
  135. package/templates/frontend/wap/src/layout/sidebar.tsx +14 -0
  136. package/templates/frontend/wap/src/locales.ts +8 -0
  137. package/templates/frontend/wap/src/pages/.gitkeep +0 -0
  138. package/templates/frontend/wap/src/root.tsx +12 -0
  139. package/templates/frontend/wap/src/route-view.tsx +3 -0
  140. package/templates/frontend/wap/src/runtime.ts +21 -0
  141. package/templates/frontend/wap/src/styles/adaptation.less +190 -0
  142. package/templates/frontend/wap/src/styles/app.css +7 -0
  143. package/templates/frontend/wap/src/styles/global.less +81 -0
  144. package/templates/frontend/wap/src/styles/layout.less +92 -0
  145. package/templates/frontend/wap/tsconfig.json +66 -0
  146. package/templates/frontend/wap/typings.d.ts +24 -0
  147. package/templates/frontend/web/.umirc.ts +574 -0
  148. package/templates/frontend/web/package.json +26 -0
  149. package/templates/frontend/web/src/app-extends.ts +9 -0
  150. package/templates/frontend/web/src/app.tsx +25 -0
  151. package/templates/frontend/web/src/config/app.ts +31 -0
  152. package/templates/frontend/web/src/layout/header.tsx +14 -0
  153. package/templates/frontend/web/src/layout/index.tsx +11 -0
  154. package/templates/frontend/web/src/layout/sidebar.tsx +14 -0
  155. package/templates/frontend/web/src/locales.ts +8 -0
  156. package/templates/frontend/web/src/root.tsx +12 -0
  157. package/templates/frontend/web/src/route-view.tsx +3 -0
  158. package/templates/frontend/web/src/runtime.ts +21 -0
  159. package/templates/frontend/web/src/styles/app.css +104 -0
  160. package/templates/frontend/web/src/styles/layout.less +124 -0
  161. package/templates/frontend/web/tsconfig.json +91 -0
  162. package/templates/frontend/web/typings.d.ts +46 -0
  163. package/templates/package.json +14 -0
@@ -0,0 +1,335 @@
1
+ /**
2
+ * `template status|upgrade|adopt`。
3
+ *
4
+ * 目标:工程能跟着模板升级,但**绝不静默覆盖人手改过的东西**。
5
+ *
6
+ * 三方比较的口径(对每个模板文件):
7
+ * base —— 上次同步时模板里的内容哈希(记录在 .inbiz/template.json)
8
+ * ours —— 工程里当前的内容
9
+ * theirs —— 新版本模板里的内容
10
+ *
11
+ * 判定:
12
+ * ours == base → 本地没动过,直接用新版覆盖
13
+ * ours != base, theirs==base → 本地改过、模板没改,保留本地
14
+ * ours != base, theirs!=base → 冲突:**不覆盖**,写 <file>.template-new 交给人工/AI 合并
15
+ *
16
+ * 边界:模板只拥有结构文件(见 template-files.mjs)。`src/pages/**` 是 generate
17
+ * 的产物,升级一律不碰——它不在模板文件清单里。
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import crypto from 'node:crypto';
23
+ import { CODEGEN_ROOT, TEMPLATES_ROOT, writeIfChanged } from '../config.mjs';
24
+ import { listTemplateFiles } from './template-files.mjs';
25
+ import { resolveTemplatesRoot, TEMPLATES_PACKAGE } from './template-source.mjs';
26
+
27
+ export const MANIFEST_FILE = path.join('.inbiz', 'template.json');
28
+ export const CONFLICT_SUFFIX = '.template-new';
29
+
30
+ export const TEMPLATE_EXIT = { OK: 0, INPUT: 2, PLATFORM: 3, NETWORK: 4 };
31
+
32
+ const SITE_BY_TYPE = { 0: 'web', 1: 'wap', 2: 'mgt' };
33
+ const DEFAULT_PORTS = { 0: 8021, 2: 8022, 1: 8023 };
34
+
35
+ /** 读工程里已有的模板基线;不存在返回 null。 */
36
+ export function readManifest(dir) {
37
+ const file = path.join(dir, MANIFEST_FILE);
38
+ if (!fs.existsSync(file)) return null;
39
+ try {
40
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
41
+ } catch (error) {
42
+ throw Object.assign(new Error(`${file} 不是合法 JSON:${error.message}`), { exitCode: TEMPLATE_EXIT.INPUT });
43
+ }
44
+ }
45
+
46
+ function writeManifest(dir, manifest) {
47
+ return writeIfChanged(path.join(dir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
48
+ }
49
+
50
+ function hashText(text) {
51
+ return `sha256:${crypto.createHash('sha256').update(text, 'utf8').digest('hex')}`;
52
+ }
53
+
54
+ /** 从 .env 读站点类型与端口;读不到就用默认值。 */
55
+ function readProjectEnv(dir) {
56
+ const file = path.join(dir, '.env');
57
+ const env = {};
58
+ if (!fs.existsSync(file)) return env;
59
+ for (const raw of fs.readFileSync(file, 'utf8').split('\n')) {
60
+ const line = raw.trim();
61
+ if (!line || line.startsWith('#')) continue;
62
+ const eq = line.indexOf('=');
63
+ if (eq < 0) continue;
64
+ env[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
65
+ }
66
+ return env;
67
+ }
68
+
69
+ /** 与 init 相同的占位符替换:端口、packages 相对路径。 */
70
+ function render(text, { dir, port }) {
71
+ const packagesRoot = path.join(CODEGEN_ROOT, 'packages');
72
+ const relativePackages = path.relative(dir, packagesRoot).split(path.sep).join('/') || 'packages';
73
+ return text
74
+ .replace(/\.\.\/\.\.\/\.\.\/packages/g, relativePackages)
75
+ .replace(/__INBIZ_DEV_PORT__/g, String(port));
76
+ }
77
+
78
+ /** 把模板目录渲染成 { 相对路径: 最终内容 }。 */
79
+ function renderTemplate(templateDir, options) {
80
+ const out = new Map();
81
+ for (const rel of listTemplateFiles(templateDir)) {
82
+ out.set(rel, render(fs.readFileSync(path.join(templateDir, rel), 'utf8'), options));
83
+ }
84
+ return out;
85
+ }
86
+
87
+ function resolveSite(dir, manifest) {
88
+ if (manifest?.site) return manifest.site;
89
+ const env = readProjectEnv(dir);
90
+ const siteType = Number(env.INBIZ_SITE_TYPE || 0);
91
+ return SITE_BY_TYPE[siteType] || SITE_BY_TYPE[0];
92
+ }
93
+
94
+ function resolvePort(dir, manifest) {
95
+ const env = readProjectEnv(dir);
96
+ return Number(env.INBIZ_DEV_PORT) || DEFAULT_PORTS[manifest?.siteType ?? 0] || DEFAULT_PORTS[0];
97
+ }
98
+
99
+ /** 取模板目录;远程优先,失败回退内置。 */
100
+ async function locateTemplate({ version, offline, registry, site }) {
101
+ const remote = await resolveTemplatesRoot({ version, offline, registry });
102
+ const localRoot = TEMPLATES_ROOT;
103
+ const localVersion = (() => {
104
+ try {
105
+ return JSON.parse(fs.readFileSync(path.join(localRoot, 'package.json'), 'utf8')).version;
106
+ } catch {
107
+ return '0.0.0';
108
+ }
109
+ })();
110
+
111
+ const candidates = [];
112
+ if (remote) {
113
+ candidates.push({
114
+ dir: path.join(remote.root, 'frontend', site),
115
+ version: remote.version,
116
+ source: remote.source,
117
+ });
118
+ }
119
+ candidates.push({
120
+ dir: path.join(localRoot, 'frontend', site),
121
+ version: localVersion,
122
+ source: 'local',
123
+ });
124
+
125
+ const found = candidates.find((item) => fs.existsSync(item.dir));
126
+ if (!found) {
127
+ throw Object.assign(new Error(`找不到站点 ${site} 的模板`), { exitCode: TEMPLATE_EXIT.INPUT });
128
+ }
129
+ return found;
130
+ }
131
+
132
+ /**
133
+ * `template status`:只读,报告每个模板文件相对基线的状态。
134
+ */
135
+ export function runTemplateStatus({ dir = process.cwd(), json = false } = {}) {
136
+ const target = path.resolve(dir);
137
+ const manifest = readManifest(target);
138
+ if (!manifest) {
139
+ const message = `没有模板基线:${path.join(target, MANIFEST_FILE)}。先执行 inbiz-codegen template adopt。`;
140
+ if (json) console.log(JSON.stringify({ ok: false, command: 'template status', errors: [{ code: 'NO_MANIFEST', message }] }, null, 2));
141
+ else console.error(`✗ ${message}`);
142
+ return TEMPLATE_EXIT.INPUT;
143
+ }
144
+
145
+ const rows = [];
146
+ for (const [rel, base] of Object.entries(manifest.files || {})) {
147
+ const file = path.join(target, rel);
148
+ if (!fs.existsSync(file)) {
149
+ rows.push({ file: rel, state: 'deleted' });
150
+ continue;
151
+ }
152
+ const current = hashText(fs.readFileSync(file, 'utf8'));
153
+ rows.push({ file: rel, state: current === base ? 'clean' : 'modified' });
154
+ }
155
+
156
+ const byState = (state) => rows.filter((row) => row.state === state).map((row) => row.file);
157
+ const modified = byState('modified');
158
+ const deleted = byState('deleted');
159
+
160
+ if (json) {
161
+ console.log(JSON.stringify({
162
+ ok: true, command: 'template status', dir: target,
163
+ template: manifest.name, version: manifest.version, site: manifest.site,
164
+ total: rows.length, modified, deleted,
165
+ }, null, 2));
166
+ return TEMPLATE_EXIT.OK;
167
+ }
168
+
169
+ console.log(`模板基线:${manifest.name}@${manifest.version}(站点 ${manifest.site})`);
170
+ console.log(` 文件 ${rows.length} 个:未改动 ${rows.length - modified.length - deleted.length},修改 ${modified.length},删除 ${deleted.length}`);
171
+ if (modified.length) console.log(` 修改:${modified.join(', ')}`);
172
+ if (deleted.length) console.log(` 删除:${deleted.join(', ')}`);
173
+ return TEMPLATE_EXIT.OK;
174
+ }
175
+
176
+ /**
177
+ * `template adopt`:给已有工程补一份基线,不改任何文件。
178
+ */
179
+ export async function runTemplateAdopt({
180
+ dir = process.cwd(), version, offline = false, registry, json = false,
181
+ } = {}) {
182
+ const target = path.resolve(dir);
183
+ const site = resolveSite(target, readManifest(target));
184
+ const template = await locateTemplate({ version, offline, registry, site });
185
+ const rendered = renderTemplate(template.dir, {
186
+ dir: target,
187
+ port: resolvePort(target, null),
188
+ });
189
+
190
+ const files = {};
191
+ const missing = [];
192
+ for (const [rel, text] of rendered) {
193
+ files[rel] = hashText(text);
194
+ if (!fs.existsSync(path.join(target, rel))) missing.push(rel);
195
+ }
196
+
197
+ const siteType = Number(readProjectEnv(target).INBIZ_SITE_TYPE
198
+ ?? Object.keys(SITE_BY_TYPE).find((key) => SITE_BY_TYPE[key] === site)) || 0;
199
+ const manifest = {
200
+ name: TEMPLATES_PACKAGE,
201
+ version: template.version,
202
+ source: template.source,
203
+ site,
204
+ siteType,
205
+ adoptedAt: new Date().toISOString(),
206
+ files,
207
+ };
208
+ writeManifest(target, manifest);
209
+
210
+ if (json) {
211
+ console.log(JSON.stringify({
212
+ ok: true, command: 'template adopt', dir: target,
213
+ version: template.version, source: template.source, site, files: Object.keys(files).length, missing,
214
+ }, null, 2));
215
+ return TEMPLATE_EXIT.OK;
216
+ }
217
+
218
+ console.log(`✓ 已建立模板基线:${TEMPLATES_PACKAGE}@${template.version}(${template.source},站点 ${site})`);
219
+ console.log(` 记录 ${Object.keys(files).length} 个文件${missing.length ? `,工程里缺少 ${missing.length} 个:${missing.join(', ')}` : ''}`);
220
+ return TEMPLATE_EXIT.OK;
221
+ }
222
+
223
+ /**
224
+ * `template upgrade`:升级到指定版本(缺省 latest)。
225
+ * 冲突不覆盖,落 `<file>.template-new` 交给人工或 AI 合并。
226
+ */
227
+ export async function runTemplateUpgrade({
228
+ dir = process.cwd(), to, offline = false, registry, force = false, json = false,
229
+ } = {}) {
230
+ const target = path.resolve(dir);
231
+ const manifest = readManifest(target);
232
+ if (!manifest) {
233
+ const message = `没有模板基线:${path.join(target, MANIFEST_FILE)}。先执行 inbiz-codegen template adopt。`;
234
+ if (json) console.log(JSON.stringify({ ok: false, command: 'template upgrade', errors: [{ code: 'NO_MANIFEST', message }] }, null, 2));
235
+ else console.error(`✗ ${message}`);
236
+ return TEMPLATE_EXIT.INPUT;
237
+ }
238
+
239
+ const site = resolveSite(target, manifest);
240
+ const template = await locateTemplate({ version: to, offline, registry, site });
241
+ if (template.version === manifest.version && !force) {
242
+ const message = `已是最新:${TEMPLATES_PACKAGE}@${template.version}`;
243
+ if (json) console.log(JSON.stringify({ ok: true, command: 'template upgrade', upToDate: true, version: template.version }, null, 2));
244
+ else console.log(`✓ ${message}`);
245
+ return TEMPLATE_EXIT.OK;
246
+ }
247
+
248
+ const rendered = renderTemplate(template.dir, {
249
+ dir: target,
250
+ port: resolvePort(target, manifest),
251
+ });
252
+
253
+ const updated = [];
254
+ const added = [];
255
+ const kept = [];
256
+ const unchanged = [];
257
+ const conflicts = [];
258
+ const base = manifest.files || {};
259
+
260
+ for (const [rel, theirs] of rendered) {
261
+ const file = path.join(target, rel);
262
+ const theirsHash = hashText(theirs);
263
+ const baseHash = base[rel];
264
+ const exists = fs.existsSync(file);
265
+
266
+ if (!exists) {
267
+ writeIfChanged(file, theirs);
268
+ added.push(rel);
269
+ continue;
270
+ }
271
+
272
+ const ours = fs.readFileSync(file, 'utf8');
273
+ const oursHash = hashText(ours);
274
+
275
+ if (oursHash === baseHash) {
276
+ if (theirsHash !== baseHash) {
277
+ writeIfChanged(file, theirs);
278
+ updated.push(rel);
279
+ } else {
280
+ // 本地没动、模板也没动
281
+ unchanged.push(rel);
282
+ }
283
+ continue;
284
+ }
285
+
286
+ // 本地改过
287
+ if (theirsHash === baseHash) {
288
+ kept.push(rel);
289
+ continue;
290
+ }
291
+
292
+ // 两边都改:不覆盖,写出新版本供合并
293
+ writeIfChanged(`${file}${CONFLICT_SUFFIX}`, theirs);
294
+ conflicts.push(rel);
295
+ }
296
+
297
+ const removed = Object.keys(base).filter((rel) => !rendered.has(rel));
298
+
299
+ // 基线推进到新版本:所有模板文件都以新模板为准,冲突文件仍会显示为 modified
300
+ const files = {};
301
+ for (const [rel, text] of rendered) files[rel] = hashText(text);
302
+ writeManifest(target, {
303
+ ...manifest,
304
+ version: template.version,
305
+ source: template.source,
306
+ site,
307
+ files,
308
+ upgradedAt: new Date().toISOString(),
309
+ });
310
+
311
+ if (json) {
312
+ console.log(JSON.stringify({
313
+ ok: true, command: 'template upgrade',
314
+ from: manifest.version, to: template.version, source: template.source,
315
+ updated, added, kept, unchanged, conflicts, removed,
316
+ next: conflicts.length
317
+ ? [`逐个合并:<file> 与 <file>${CONFLICT_SUFFIX}`, `合并后删除所有 *${CONFLICT_SUFFIX}`]
318
+ : [],
319
+ }, null, 2));
320
+ return TEMPLATE_EXIT.OK;
321
+ }
322
+
323
+ console.log(`✓ 模板 ${manifest.version} → ${template.version}(${template.source})`);
324
+ console.log(` 更新 ${updated.length},新增 ${added.length},未变化 ${unchanged.length},保留本地修改 ${kept.length},冲突 ${conflicts.length},模板已移除 ${removed.length}`);
325
+ if (updated.length) console.log(` 更新:${updated.join(', ')}`);
326
+ if (added.length) console.log(` 新增:${added.join(', ')}`);
327
+ if (kept.length) console.log(` 保留:${kept.join(', ')}`);
328
+ if (removed.length) console.log(` 模板已移除(未自动删除):${removed.join(', ')}`);
329
+ if (conflicts.length) {
330
+ console.log(' 冲突(未覆盖,已写出新版本):');
331
+ for (const rel of conflicts) console.log(` ${rel} ↔ ${rel}${CONFLICT_SUFFIX}`);
332
+ console.log(` 合并后删除所有 *${CONFLICT_SUFFIX} 文件。`);
333
+ }
334
+ return TEMPLATE_EXIT.OK;
335
+ }