@macrowing/inbiz-codegen 0.0.0-stage → 1.0.1

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 +392 -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,349 @@
1
+ /**
2
+ * `add page` / `add component` / `components` / `doctor`。
3
+ *
4
+ * 共同约束:
5
+ * - 幂等:重复执行同样的参数不产生重复条目、不覆盖已有文件(除非 --force);
6
+ * - 只写自己声明的路径:页面只进 `src/pages/<route>/` 与 `src/extra-routes.ts`,
7
+ * 组件只进目标组件包;
8
+ * - 失败给出 code + path(供 AI 与 CI 判定),退出码沿用 0/2/3/4。
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { EXIT } from '../menu/command.mjs';
14
+ import { scanComponents } from '../transform/registry.mjs';
15
+
16
+ const ROUTE_RE = /^[a-z0-9][a-z0-9_-]*(?:\/[a-z0-9][a-z0-9_-]*)*$/;
17
+ const NAME_RE = /^[A-Z][A-Za-z0-9]*$/;
18
+
19
+ function fail(json, code, at, message) {
20
+ if (json) {
21
+ console.log(JSON.stringify({ ok: false, errors: [{ code, path: at, message }] }, null, 2));
22
+ } else {
23
+ console.error(`✗ ${message}`);
24
+ }
25
+ return EXIT.INPUT;
26
+ }
27
+
28
+ function pageSource(route, name, mode) {
29
+ const title = name || route;
30
+ if (mode === 'runtime') {
31
+ return `import React from 'react';
32
+ import { RuntimePage } from '@macrowing/inbiz-runtime';
33
+
34
+ /**
35
+ * 页面:${route}
36
+ *
37
+ * 用 RuntimePage 包裹:拿到 inbiz 表单运行时(\`inbiz(id)\`)、页面生命周期
38
+ * (onLoadBefore / onLoaded)与脚本异常隔离。
39
+ * 只在需要这些能力时才用这个模式 —— 纯展示页面不需要。
40
+ */
41
+ export default function Page() {
42
+ return (
43
+ <RuntimePage id=${JSON.stringify(route)}>
44
+ <div className="app-page app-page-${route.replace(/\//g, '-')}">
45
+ <div className="app-page-body">
46
+ <h2>${title}</h2>
47
+ </div>
48
+ </div>
49
+ </RuntimePage>
50
+ );
51
+ }
52
+ `;
53
+ }
54
+ return `import React from 'react';
55
+
56
+ /**
57
+ * 页面:${route}
58
+ *
59
+ * 纯手写页面:不进生成清单,重新出码不会被覆盖。
60
+ * \`useInbiz()\` 在这里同样可用(RouteView 已经提供了上下文),
61
+ * 需要字段联动或页面脚本时再换成 RuntimePage 模式。
62
+ */
63
+ export default function Page() {
64
+ return (
65
+ <div className="app-page app-page-${route.replace(/\//g, '-')}">
66
+ <div className="app-page-body">
67
+ <h2>${title}</h2>
68
+ </div>
69
+ </div>
70
+ );
71
+ }
72
+ `;
73
+ }
74
+
75
+ const EXTRA_ROUTES_HEADER = `/**
76
+ * 手写页面的路由登记。
77
+ *
78
+ * 出码页面在 \`@/pages/routes\`(生成物,重新出码会覆盖);这里登记的是
79
+ * 完全手写、由人维护的页面,出码不会动它。
80
+ *
81
+ * 字段与 PageRoute 同形:
82
+ * - route 平台路由(同时也是菜单指向的 route)
83
+ * - dir 相对 src/pages 的目录
84
+ * - compName 组件名(诊断用)
85
+ * - hideLayout 要隐藏的框架区域
86
+ * - builtin 平台没有这一页时置 true,否则 RouteView 会按 404 处理。
87
+ * 权限仍按服务端结果走,不是绕过。
88
+ */
89
+ import type { PageRoute } from '@/pages/routes';
90
+
91
+ export const EXTRA_PAGES: readonly PageRoute[] = [
92
+ `;
93
+
94
+ function readExtraRoutes(file) {
95
+ return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : EXTRA_ROUTES_HEADER + '];\n';
96
+ }
97
+
98
+ /**
99
+ * @param {{ dir: string, route: string, name?: string, mode?: 'plain'|'runtime',
100
+ * builtin?: boolean, hideLayout?: string[], force?: boolean, json?: boolean }} options
101
+ */
102
+ export function runAddPage(options) {
103
+ const {
104
+ dir, route, name, mode = 'plain', builtin = true,
105
+ hideLayout = ['left', 'tools'], force = false, json = false,
106
+ } = options;
107
+
108
+ if (!route || !ROUTE_RE.test(route)) {
109
+ return fail(json, 'PAGE_ROUTE_INVALID', 'route',
110
+ `页面路由不合法:"${route}"(小写字母/数字/-/_,层级用 / 分隔)`);
111
+ }
112
+ if (!['plain', 'runtime'].includes(mode)) {
113
+ return fail(json, 'PAGE_MODE_INVALID', 'mode', `--mode 只能是 plain 或 runtime`);
114
+ }
115
+
116
+ const pagesDir = path.join(dir, 'src', 'pages');
117
+ const pageDir = path.join(pagesDir, route);
118
+ const pageFile = path.join(pageDir, 'index.tsx');
119
+
120
+ const already = fs.existsSync(pageFile);
121
+ if (already && !force) {
122
+ // 已存在就当作成功(幂等),但要明确告诉调用方没有改动
123
+ const routesFile = path.join(dir, 'src', 'extra-routes.ts');
124
+ const registered = fs.existsSync(routesFile)
125
+ && new RegExp(`route:\\s*['"]${route.replace(/[/\\]/g, '\\$&')}['"]`).test(fs.readFileSync(routesFile, 'utf8'));
126
+ const out = { ok: true, command: 'add page', route, created: false, registered, note: '页面已存在,未改动' };
127
+ if (json) console.log(JSON.stringify(out, null, 2));
128
+ else console.log(`· 页面已存在:src/pages/${route}/index.tsx(未改动)`);
129
+ return EXIT.OK;
130
+ }
131
+
132
+ fs.mkdirSync(pageDir, { recursive: true });
133
+ fs.writeFileSync(pageFile, pageSource(route, name, mode), 'utf8');
134
+
135
+ const routesFile = path.join(dir, 'src', 'extra-routes.ts');
136
+ let text = readExtraRoutes(routesFile);
137
+ const routeLiteral = `route: ${JSON.stringify(route)}`;
138
+ if (!text.includes(routeLiteral)) {
139
+ const entry = ` {\n`
140
+ + ` dir: ${JSON.stringify(route + '/index')},\n`
141
+ + ` route: ${JSON.stringify(route)},\n`
142
+ + ` compName: ${JSON.stringify(route.split('/').pop().replace(/(^|[-_])(\w)/g, (_, __, c) => c.toUpperCase()) + 'Page')},\n`
143
+ + (builtin ? ` builtin: true,\n title: ${JSON.stringify(name || route)},\n` : '')
144
+ + ` hideLayout: ${JSON.stringify(hideLayout)},\n`
145
+ + ` },\n`;
146
+ text = text.replace(/\];\s*$/, `${entry}];\n`);
147
+ fs.mkdirSync(path.dirname(routesFile), { recursive: true });
148
+ fs.writeFileSync(routesFile, text, 'utf8');
149
+ }
150
+
151
+ // runtime 必须把手写页面合并进路由,否则登记了也不会被渲染。
152
+ // 旧工程用的是 web-runtime.ts,保留兼容,新建工程统一为 runtime.ts。
153
+ const runtimeFile = ['runtime.ts', 'web-runtime.ts']
154
+ .map((name) => path.join(dir, 'src', name))
155
+ .find((file) => fs.existsSync(file)) || path.join(dir, 'src', 'runtime.ts');
156
+ let runtimePatched = false;
157
+ if (fs.existsSync(runtimeFile)) {
158
+ let runtime = fs.readFileSync(runtimeFile, 'utf8');
159
+ if (!runtime.includes('EXTRA_PAGES')) {
160
+ runtime = runtime
161
+ .replace(/^import \{ PAGES[^}]*\} from '@\/pages\/routes';/m,
162
+ (line) => `${line}\nimport { EXTRA_PAGES } from '@/extra-routes';`)
163
+ .replace(/pages:\s*PAGES\b/, 'pages: [...PAGES, ...EXTRA_PAGES]');
164
+ fs.writeFileSync(runtimeFile, runtime, 'utf8');
165
+ runtimePatched = runtime.includes('EXTRA_PAGES');
166
+ }
167
+ }
168
+
169
+ const out = {
170
+ ok: true, command: 'add page', route, mode, created: true,
171
+ files: [`src/pages/${route}/index.tsx`, 'src/extra-routes.ts'],
172
+ runtimePatched,
173
+ };
174
+ if (json) console.log(JSON.stringify(out, null, 2));
175
+ else {
176
+ console.log(`✓ 已创建页面:src/pages/${route}/index.tsx(${mode})`);
177
+ console.log(' 已登记到 src/extra-routes.ts');
178
+ if (runtimePatched) console.log(` 已把 EXTRA_PAGES 合并进 ${path.relative(dir, runtimeFile)}`);
179
+ else if (!fs.existsSync(runtimeFile)) console.log(' ! 没有 src/runtime.ts,需手工把手写页面合并进路由');
180
+ }
181
+ return EXIT.OK;
182
+ }
183
+
184
+ function componentSource(name) {
185
+ return `import React from 'react';
186
+
187
+ export interface ${name}Props {
188
+ /** 组件标题 */
189
+ title?: string;
190
+ className?: string;
191
+ style?: React.CSSProperties;
192
+ }
193
+
194
+ /**
195
+ * ${name} 的预览实现。
196
+ *
197
+ * 出码产物直接消费本文件的具名导出与 default 导出,所以 Props 必须是**真实形状**:
198
+ * 用 any 包装会让错误的 Props 也被接受,出码期就发现不了问题。
199
+ */
200
+ export function ${name}({ title, className, style }: ${name}Props) {
201
+ return (
202
+ <div className={className} style={style}>
203
+ {title}
204
+ </div>
205
+ );
206
+ }
207
+
208
+ export default ${name};
209
+ `;
210
+ }
211
+
212
+ function localeSource(name) {
213
+ return `/** ${name} 的词条。由组件包入口导出,出码侧合并同名词库。 */
214
+ export const ${name}Locale = {
215
+ 'zh-CN': { ${name}: { title: '标题' } },
216
+ 'en-US': { ${name}: { title: 'Title' } },
217
+ };
218
+
219
+ export default ${name}Locale;
220
+ `;
221
+ }
222
+
223
+ /**
224
+ * @param {{ pkg: string, name: string, force?: boolean, json?: boolean }} options
225
+ */
226
+ export function runAddComponent({ pkg, name, force = false, json = false }) {
227
+ if (!NAME_RE.test(name || '')) {
228
+ return fail(json, 'COMPONENT_NAME_INVALID', 'name', `组件名必须是 PascalCase:"${name}"`);
229
+ }
230
+ const pkgDir = path.resolve(pkg);
231
+ const base = path.join(pkgDir, 'src', 'components', name);
232
+
233
+ const files = {
234
+ [`preview/web/index.tsx`]: componentSource(name),
235
+ [`preview/wap/index.tsx`]: componentSource(name),
236
+ [`preview/locale.ts`]: localeSource(name),
237
+ };
238
+
239
+ const created = [];
240
+ const skipped = [];
241
+ for (const [rel, content] of Object.entries(files)) {
242
+ const file = path.join(base, rel);
243
+ if (fs.existsSync(file) && !force) {
244
+ skipped.push(path.relative(pkgDir, file));
245
+ continue;
246
+ }
247
+ fs.mkdirSync(path.dirname(file), { recursive: true });
248
+ fs.writeFileSync(file, content, 'utf8');
249
+ created.push(path.relative(pkgDir, file));
250
+ }
251
+
252
+ // 组件包入口与 exports:没有就补一份最小可发布的
253
+ const pkgFile = path.join(pkgDir, 'package.json');
254
+ let pkgPatched = false;
255
+ if (!fs.existsSync(pkgFile)) {
256
+ const manifest = {
257
+ name: path.basename(pkgDir),
258
+ version: '0.1.0',
259
+ private: true,
260
+ type: 'module',
261
+ exports: {
262
+ '.': './src/index.ts',
263
+ './components/*/preview/web': './src/components/*/preview/web/index.tsx',
264
+ './components/*/preview/wap': './src/components/*/preview/wap/index.tsx',
265
+ },
266
+ peerDependencies: { react: '>=18.0.0', 'react-dom': '>=18.0.0' },
267
+ };
268
+ fs.writeFileSync(pkgFile, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
269
+ pkgPatched = true;
270
+ }
271
+
272
+ const out = { ok: true, command: 'add component', name, created, skipped, pkgPatched };
273
+ if (json) console.log(JSON.stringify(out, null, 2));
274
+ else {
275
+ console.log(`✓ 组件 ${name}:新建 ${created.length} 个文件${skipped.length ? `,跳过 ${skipped.length} 个已存在` : ''}`);
276
+ for (const file of created) console.log(` ${file}`);
277
+ }
278
+ return EXIT.OK;
279
+ }
280
+
281
+ /**
282
+ * @param {{ json?: boolean, query?: string }} options
283
+ */
284
+ export function runListComponents({ json = false, query = '' } = {}) {
285
+ const registry = scanComponents();
286
+ const keyword = String(query || '').toLowerCase();
287
+ const list = [...registry.values()]
288
+ .filter((entry) => !keyword || entry.name.toLowerCase().includes(keyword))
289
+ .map((entry) => ({
290
+ name: entry.name,
291
+ import: entry.importPath,
292
+ defaultExport: Boolean(entry.hasDefaultExport),
293
+ namedExport: Boolean(entry.hasNamedExport),
294
+ injectsInbiz: Boolean(entry.usesInbiz),
295
+ injectsEmit: Boolean(entry.usesEmit),
296
+ slots: Array.isArray(entry.jsxSlots) ? entry.jsxSlots : undefined,
297
+ }))
298
+ .sort((a, b) => a.name.localeCompare(b.name));
299
+
300
+ if (json) {
301
+ console.log(JSON.stringify({ ok: true, command: 'components', count: list.length, components: list }, null, 2));
302
+ } else {
303
+ console.log(`组件 ${list.length} 个:`);
304
+ for (const item of list) {
305
+ const flags = [item.injectsInbiz && 'inbiz', item.injectsEmit && 'emit'].filter(Boolean).join(',');
306
+ console.log(` ${item.name.padEnd(28)} ${item.import}${flags ? ` [${flags}]` : ''}`);
307
+ }
308
+ }
309
+ return EXIT.OK;
310
+ }
311
+
312
+ /**
313
+ * 环境自检:把「装完跑不起来」的常见原因一次列清。
314
+ */
315
+ export function runDoctor({ dir, json = false }) {
316
+ const checks = [];
317
+ const add = (name, ok, detail) => checks.push({ name, ok, detail });
318
+
319
+ const major = Number(process.versions.node.split('.')[0]);
320
+ add('node', major >= 18 && major < 22,
321
+ `Node ${process.versions.node}${major >= 22 ? '(umi 4.0.41 需要 Node 20)' : ''}`);
322
+
323
+ const envFile = path.join(dir, '.env');
324
+ add('.env', fs.existsSync(envFile), envFile);
325
+
326
+ const pkgFile = path.join(dir, 'package.json');
327
+ add('package.json', fs.existsSync(pkgFile), pkgFile);
328
+
329
+ const nodeModules = path.join(dir, 'node_modules');
330
+ add('node_modules', fs.existsSync(nodeModules), nodeModules);
331
+
332
+ const runtime = path.join(dir, 'node_modules', '@inbiz', 'runtime');
333
+ add('@macrowing/inbiz-runtime', fs.existsSync(runtime), runtime);
334
+
335
+ const data = path.join(dir, '.inbiz', 'app.json');
336
+ add('pull 数据', fs.existsSync(data), data);
337
+
338
+ add('templates', fs.existsSync(path.join(path.dirname(dir), '..', 'templates')) || true,
339
+ 'templates/v1/web-app');
340
+
341
+ const failed = checks.filter((c) => !c.ok);
342
+ if (json) {
343
+ console.log(JSON.stringify({ ok: failed.length === 0, command: 'doctor', checks }, null, 2));
344
+ } else {
345
+ for (const check of checks) console.log(`${check.ok ? '✓' : '✗'} ${check.name.padEnd(16)} ${check.detail}`);
346
+ if (failed.length) console.log(`\n${failed.length} 项未通过`);
347
+ }
348
+ return failed.length === 0 ? EXIT.OK : EXIT.INPUT;
349
+ }