@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,106 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { createHash } from 'node:crypto';
6
+ import { WEB_DIR, DATA_DIR, writeIfChanged } from './config.mjs';
7
+ import { emitPage, emitSection, writePageSource } from './generate.mjs';
8
+ import { scanComponents } from './transform/registry.mjs';
9
+
10
+ // Compare the prior compiler output before migrating. User-edited files are
11
+ // reported and left untouched, never overwritten by a wholesale regeneration.
12
+ const sourceDir = path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/i, '$1'));
13
+ const moduleUrl = (file) => pathToFileURL(path.join(sourceDir, file)).href;
14
+ const dataUrl = (text) => 'data:text/javascript;base64,' + Buffer.from(text).toString('base64');
15
+ let transformer = fs.readFileSync(path.join(sourceDir, 'transform/schema-to-jsx.mjs'), 'utf8').replace(/\r\n/g, '\n');
16
+ transformer = transformer.replace(
17
+ / \/\/ Keep field behavior,[\s\S]*?(?= \/\/ 重型组件套)/,
18
+ '',
19
+ ).replace(
20
+ "const display = node['x-display'];",
21
+ "const display = node['x-display']; if (display !== undefined && display !== 'visible' && !node['x-reactions']) return [pad + '{/* hidden */}'];",
22
+ ).replace('&& !compName)', ')');
23
+ transformer = transformer.replaceAll("'./registry.mjs'", JSON.stringify(moduleUrl('transform/registry.mjs')))
24
+ .replaceAll("'./heaviness.mjs'", JSON.stringify(moduleUrl('transform/heaviness.mjs')));
25
+ let generator = fs.readFileSync(path.join(sourceDir, 'generate.mjs'), 'utf8').replace(/\r\n/g, '\n');
26
+ generator = generator
27
+ .replaceAll("'./config.mjs'", JSON.stringify(moduleUrl('config.mjs')))
28
+ .replaceAll("'./generated-output.mjs'", JSON.stringify(moduleUrl('generated-output.mjs')))
29
+ .replaceAll("'./transform/published-page-links.mjs'", JSON.stringify(moduleUrl('transform/published-page-links.mjs')))
30
+ .replaceAll("'./transform/registry.mjs'", JSON.stringify(moduleUrl('transform/registry.mjs')))
31
+ .replaceAll("'./transform/schema-to-jsx.mjs'", JSON.stringify(dataUrl(transformer)));
32
+ const previous = await import(dataUrl(generator));
33
+ const ts = createRequire(path.join(WEB_DIR, 'package.json'))('typescript');
34
+ function tokens(code) {
35
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.JSX, code);
36
+ const result = [];
37
+ while (scanner.scan() !== ts.SyntaxKind.EndOfFileToken) result.push(scanner.getTokenText());
38
+ return JSON.stringify(result);
39
+ }
40
+ const data = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'app.json'), 'utf8'));
41
+ const registry = scanComponents();
42
+ const messages = data.language?.messages || {};
43
+ const conflicts = [];
44
+ const manifestFile = path.join(DATA_DIR, 'runtime-migration.json');
45
+ const manifest = fs.existsSync(manifestFile) ? JSON.parse(fs.readFileSync(manifestFile, 'utf8')) : {};
46
+ const digest = (code) => createHash('sha256').update(tokens(code)).digest('hex');
47
+ let updated = 0;
48
+ function migrate(file, oldCode, newCode, write = () => writeIfChanged(file, newCode), intermediateCodes = []) {
49
+ if (!fs.existsSync(file)) return;
50
+ const current = fs.readFileSync(file, 'utf8');
51
+ if (tokens(current) !== tokens(oldCode) && tokens(current) !== tokens(newCode)
52
+ && !intermediateCodes.some((code) => tokens(current) === tokens(code))
53
+ && manifest[path.relative(WEB_DIR, file)] !== digest(current)) {
54
+ if (process.argv.includes('--diff') && conflicts.length < 3) {
55
+ const a = JSON.parse(tokens(current)), b = JSON.parse(tokens(oldCode));
56
+ const at = a.findIndex((v, i) => v !== b[i]);
57
+ console.log(file, { at, current: a.slice(Math.max(0, at - 5), at + 12), expected: b.slice(Math.max(0, at - 5), at + 12) });
58
+ }
59
+ conflicts.push(path.relative(WEB_DIR, file));
60
+ return;
61
+ }
62
+ if (process.argv.includes('--write')) write();
63
+ if (process.argv.includes('--record') || process.argv.includes('--write')) {
64
+ manifest[path.relative(WEB_DIR, file)] = digest(process.argv.includes('--write') ? newCode : current);
65
+ }
66
+ updated++;
67
+ }
68
+ for (const page of data.pages) {
69
+ // Only normal generation writes page-config.ts through the output manifest.
70
+ const options = { extractPageConfig: false };
71
+ const old = previous.emitPage(page, registry, messages, data.app?.Id, options);
72
+ const next = emitPage(page, registry, messages, data.app?.Id, options);
73
+ const dir = path.join(WEB_DIR, 'src/pages', next.dir);
74
+ const file = path.join(dir, 'index.tsx');
75
+ if (!fs.existsSync(file)) continue;
76
+ const verifiedPage = fs.readFileSync(file, 'utf8');
77
+ const conflict = writePageSource(dir, next, { dryRun: true, verifiedPage });
78
+ if (conflict) {
79
+ conflicts.push(path.relative(WEB_DIR, path.join(dir, conflict)));
80
+ continue;
81
+ }
82
+ const priorCode = old.legacyCode
83
+ .replace("import { RuntimePage } from '@macrowing/inbiz-runtime';\n", '')
84
+ .replace("import { onLoadBefore, onLoaded } from './events';\n", '')
85
+ .replace(/export function \w+\(\) \{\n return <RuntimePage[^\n]*<\/RuntimePage>;\n\}\n\n/, '')
86
+ .replace('function PageContent() {', `export function ${old.compName}() {`);
87
+ migrate(path.join(dir, 'index.tsx'), priorCode, next.code,
88
+ () => {
89
+ const conflict = writePageSource(dir, next, { verifiedPage });
90
+ if (conflict) throw new Error(`Migration conflict: ${path.join(dir, conflict)}`);
91
+ }, [next.legacyCode, next.legacyTsCode]);
92
+ }
93
+ // Layout normalization is performed by generate(), so compare using the same
94
+ // substitutions, without changing any business configuration.
95
+ for (const [key, section] of Object.entries(data.layout || {})) {
96
+ if (!Object.keys(section?.schema?.properties || {}).length) continue;
97
+ const fixed = JSON.parse(JSON.stringify(section).replaceAll('{AppId}', data.app?.Id)
98
+ .replace(/"\/inbiz\/(web|wap)\/[^"]*"/g, '"/"'));
99
+ const old = previous.emitSection(key, fixed, registry, messages);
100
+ const next = emitSection(key, fixed, registry, messages);
101
+ migrate(path.join(WEB_DIR, 'src/layout', next.file + '.tsx'), old.code, next.code);
102
+ }
103
+ console.log(JSON.stringify({ updated, conflicts }, null, 2));
104
+ if (process.argv.includes('--record') || process.argv.includes('--write')) {
105
+ writeIfChanged(manifestFile, JSON.stringify(manifest, null, 2) + '\n');
106
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * InBiz 平台客户端(鉴权 + 请求 + 错误分类)。
3
+ *
4
+ * 接口契约来自 `inbiz-app-builder-skill` 的
5
+ * `references/platform/APPLICATION_RECOVERY_APIS.md`,这里只做实现,不改语义。
6
+ *
7
+ * 三条必须守住的规则(写错就会误判成「应用不存在」并重复创建):
8
+ *
9
+ * 1. **只有 404,或结构化业务错误「应用不存在或已删除」**,才算不存在;
10
+ * 普通 500、鉴权失败、网络错误一律终止 —— 不能拿异常反推不存在。
11
+ * 2. 上传 / 校验 / 正式导入 / 进度查询**不带旧 AppId**(`skipAppId`)。
12
+ * 带上旧 AppId 会让平台把新应用挂到旧应用下。
13
+ * 3. `fetch` 可注入。默认用全局 `fetch`,测试里传假实现 ——
14
+ * 恢复流程一旦只能在真环境验证,就没人敢改它了。
15
+ */
16
+
17
+ export const ERR = {
18
+ APP_MISSING: 'APP_MISSING',
19
+ UNAUTHORIZED: 'UNAUTHORIZED',
20
+ SERVER: 'SERVER',
21
+ NETWORK: 'NETWORK',
22
+ UNEXPECTED: 'UNEXPECTED',
23
+ };
24
+
25
+ /** 业务错误码:应用不存在。必须三个条件同时成立才认。 */
26
+ const APP_MISSING_CODE = 'coreErr:000002';
27
+
28
+ function isAppMissingBody(json) {
29
+ const error = json?.Error;
30
+ if (!error || typeof error !== 'object') return false;
31
+ const data = error.Data && typeof error.Data === 'object' ? error.Data : {};
32
+ return error.Code === APP_MISSING_CODE
33
+ && data.errorMsg === '应用'
34
+ && typeof error.Message === 'string'
35
+ && error.Message.includes('不存在');
36
+ }
37
+
38
+ export function platformError(kind, message, extra = {}) {
39
+ const error = new Error(message);
40
+ error.kind = kind;
41
+ Object.assign(error, extra);
42
+ return error;
43
+ }
44
+
45
+ /**
46
+ * @param {{
47
+ * baseUrl: string,
48
+ * fetchImpl?: Function,
49
+ * token?: string,
50
+ * secretKey?: string,
51
+ * appId?: string,
52
+ * skipAppId?: boolean,
53
+ * }} options
54
+ */
55
+ export function createPlatformClient(options) {
56
+ const {
57
+ baseUrl,
58
+ fetchImpl = globalThis.fetch,
59
+ token = '',
60
+ secretKey = '',
61
+ appId = '',
62
+ skipAppId = false,
63
+ } = options;
64
+ if (!baseUrl) throw new Error('缺少平台地址');
65
+ if (typeof fetchImpl !== 'function') throw new Error('当前 Node 没有可用的 fetch');
66
+
67
+ const base = baseUrl.replace(/\/+$/, '');
68
+
69
+ function headers(extra = {}) {
70
+ return {
71
+ Accept: 'application/json',
72
+ ...(token ? { token } : {}),
73
+ ...(secretKey ? { SecretKey: secretKey } : {}),
74
+ // skipAppId 的语义是「不携带应用维度」,不是「带一个空值」
75
+ ...(!skipAppId && appId ? { appId } : {}),
76
+ ...extra,
77
+ };
78
+ }
79
+
80
+ async function parse(res, method, url) {
81
+ const text = await res.text();
82
+ let json = null;
83
+ try {
84
+ json = text ? JSON.parse(text) : null;
85
+ } catch {
86
+ json = null;
87
+ }
88
+
89
+ if (res.status === 401 || res.status === 403) {
90
+ throw platformError(ERR.UNAUTHORIZED, `${method} ${url} → HTTP ${res.status},Token 失效或无权访问`, {
91
+ status: res.status,
92
+ });
93
+ }
94
+ if (res.status === 404) {
95
+ throw platformError(ERR.APP_MISSING, `${method} ${url} → HTTP 404`, { status: 404 });
96
+ }
97
+ if (isAppMissingBody(json)) {
98
+ throw platformError(ERR.APP_MISSING, `${method} ${url} → 平台表示应用不存在或已删除`, { status: res.status });
99
+ }
100
+ if (res.status >= 400) {
101
+ throw platformError(ERR.SERVER, `${method} ${url} → HTTP ${res.status}: ${text.slice(0, 300)}`, {
102
+ status: res.status,
103
+ });
104
+ }
105
+ return json;
106
+ }
107
+
108
+ async function request(method, url, { body, contentType, query } = {}) {
109
+ const target = new URL(base + url);
110
+ if (query) {
111
+ for (const [key, value] of Object.entries(query)) {
112
+ if (value !== undefined && value !== null) target.searchParams.set(key, String(value));
113
+ }
114
+ }
115
+ let res;
116
+ try {
117
+ res = await fetchImpl(target.toString(), {
118
+ method,
119
+ headers: headers(contentType ? { 'Content-Type': contentType } : {}),
120
+ body,
121
+ });
122
+ } catch (e) {
123
+ throw platformError(ERR.NETWORK, `${method} ${url} → 网络错误:${e?.message || e}`, { cause: e });
124
+ }
125
+ return parse(res, method, target.pathname + target.search);
126
+ }
127
+
128
+ return {
129
+ baseUrl: base,
130
+ get: (url, query) => request('GET', url, { query }),
131
+ post: (url, body) => request('POST', url, {
132
+ body: JSON.stringify(body ?? {}),
133
+ contentType: 'application/json',
134
+ }),
135
+ postForm: (url, form) => request('POST', url, { body: form }),
136
+ withSession(patch) {
137
+ return createPlatformClient({ ...options, ...patch });
138
+ },
139
+ };
140
+ }
141
+
142
+ /**
143
+ * 集成登录(服务账号)。返回 token。
144
+ *
145
+ * Core 与旧平台路径不同;`isOld` 由 .env 的 `IS_OLD` 决定,默认走 Core。
146
+ */
147
+ export async function loginIntegration({ baseUrl, loginName, integrationKey, ipAddress = '127.0.0.1', isOld = false, fetchImpl }) {
148
+ const path = isOld
149
+ ? '/api/services/Org/UserLoginIntegrationByUserLoginName'
150
+ : '/inbiz/auth/api/AuthCore/UserLoginIntegrationByUserLoginName';
151
+ const client = createPlatformClient({ baseUrl, fetchImpl, skipAppId: true });
152
+ const json = await client.post(path, {
153
+ LoginName: loginName,
154
+ IPAddress: ipAddress,
155
+ IntegrationKey: integrationKey,
156
+ });
157
+ const token = json?.Token || json?.token || json?.Result?.Token;
158
+ if (!token) throw platformError(ERR.UNAUTHORIZED, '集成登录未返回 Token,请检查账号与 IntegrationKey');
159
+ return token;
160
+ }
161
+
162
+ /** Token 有效性。401/403 由 client 统一抛 UNAUTHORIZED。 */
163
+ export async function checkToken({ baseUrl, token, isOld = false, fetchImpl }) {
164
+ const path = isOld ? '/api/services/Org/CheckUserTokenValidity' : '/inbiz/auth/api/AuthCore/CheckUserTokenValidity';
165
+ const client = createPlatformClient({ baseUrl, fetchImpl, token, skipAppId: true });
166
+ return isOld ? client.get(path) : client.post(path, {});
167
+ }
@@ -0,0 +1,386 @@
1
+ /**
2
+ * `platform auth status` / `platform app recover`。
3
+ *
4
+ * 配置来自工程根目录的 `.env`。字段名沿用平台扩展的约定
5
+ * (SERVER_URL / APP_ID / SECRET_KEY / USER_NAME / INTEGRATION_KEY / IS_OLD),
6
+ * 同时兼容本仓库既有的 `INBIZ_*` 写法,避免两套工程各写一份。
7
+ *
8
+ * 恢复成功后**只改 `.env` 的 APP_ID 与 SECRET_KEY**,其余行与注释原样保留 ——
9
+ * 配置里往往还有代理前缀、端口这些人工维护的内容。
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { EXIT } from '../menu/command.mjs';
16
+ import { readEnv } from '../config.mjs';
17
+ import { ERR } from './client.mjs';
18
+ import { buildRecoveryPackage } from './pack.mjs';
19
+ import { recoverApplication } from './recover.mjs';
20
+ import { buildMenus, buildMenuRelation } from '../menu/build.mjs';
21
+ import { readSpec } from '../menu/command.mjs';
22
+
23
+ const CREDENTIALS = path.join(os.homedir(), '.inbiz', 'credentials');
24
+
25
+ /** 端名归一:0/1/2 与 web/wap/mgt 互认,其它值按 web 处理。 */
26
+ export function normalizeEnd(value) {
27
+ const text = String(value ?? '').trim().toLowerCase();
28
+ if (text === '0' || text === 'web') return 'web';
29
+ if (text === '1' || text === 'wap') return 'wap';
30
+ if (text === '2' || text === 'mgt') return 'mgt';
31
+ return 'web';
32
+ }
33
+
34
+ export function readPlatformEnv(dir) {
35
+ const env = readEnv(path.join(dir, '.env'));
36
+ return {
37
+ serverUrl: env.SERVER_URL || env.INBIZ_URL || '',
38
+ appId: env.APP_ID || env.INBIZ_APP_ID || '',
39
+ secretKey: env.SECRET_KEY || '',
40
+ userName: env.USER_NAME || env.INBIZ_PREVIEW_ACCOUNT || '',
41
+ integrationKey: env.INTEGRATION_KEY || '',
42
+ // 预签发 token(CI / 临时验证)。有它就跳过集成登录,优先级高于账号+密钥。
43
+ token: env.TOKEN || env.INBIZ_TOKEN || '',
44
+ isOld: String(env.IS_OLD || '').toLowerCase() === 'true',
45
+ /**
46
+ * 端:`INBIZ_SITE_TYPE` 写的是平台的数字(0/1/2),但出码侧一律用端名。
47
+ * 直接透传会把 `1` 当成端名,包就打到错误的端上(`/wap` 变成 `/1`)。
48
+ */
49
+ siteType: normalizeEnd(env.INBIZ_SITE_TYPE || env.INBIZ_END || 'web'),
50
+ };
51
+ }
52
+
53
+ export function readCredentials() {
54
+ try {
55
+ return JSON.parse(fs.readFileSync(CREDENTIALS, 'utf8'));
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ export function writeCredentials(payload) {
62
+ fs.mkdirSync(path.dirname(CREDENTIALS), { recursive: true });
63
+ fs.writeFileSync(CREDENTIALS, JSON.stringify(payload, null, 2), 'utf8');
64
+ }
65
+
66
+ /**
67
+ * 只替换指定的键,保留文件其余内容与注释。
68
+ * 键不存在时追加到末尾。
69
+ */
70
+ export function updateEnvFile(file, patch) {
71
+ const exists = fs.existsSync(file);
72
+ const lines = exists ? fs.readFileSync(file, 'utf8').split(/\r?\n/) : [];
73
+ const pending = new Map(Object.entries(patch));
74
+ const out = lines.map((line) => {
75
+ const match = /^(\s*)([A-Za-z_][A-Za-z0-9_]*)(\s*=\s*)(.*)$/.exec(line);
76
+ if (!match) return line;
77
+ const [, indent, key, eq] = match;
78
+ if (!pending.has(key)) return line;
79
+ const value = pending.get(key);
80
+ pending.delete(key);
81
+ return `${indent}${key}${eq}${value}`;
82
+ });
83
+ for (const [key, value] of pending) out.push(`${key}=${value}`);
84
+ fs.writeFileSync(file, out.join('\n'), 'utf8');
85
+ return [...Object.keys(patch)];
86
+ }
87
+
88
+ /**
89
+ * 集成登录并把 Token 缓存到 `~/.inbiz/credentials`。
90
+ *
91
+ * 与 `pull` 的 Cookie 登录是两套凭据,这里**不复用**:
92
+ * `pull` 用账号密码换 Cookie(浏览器等价),这里用 IntegrationKey 换 Token
93
+ * (服务间调用)。混在一起会互相覆盖,出问题时也分不清是哪条链路失效。
94
+ */
95
+ export async function runPlatformAuthLogin({ dir, ipAddress, json = false }) {
96
+ const env = readPlatformEnv(dir);
97
+ const fail = (code, message) => {
98
+ if (json) console.log(JSON.stringify({ ok: false, command: 'platform auth login', errors: [{ code, path: '.env', message }] }, null, 2));
99
+ else console.error(`✗ ${message}`);
100
+ return EXIT.INPUT;
101
+ };
102
+
103
+ if (!env.serverUrl) return fail('ENV_SERVER_URL_MISSING', '缺少 SERVER_URL(或 INBIZ_URL)');
104
+ if (!env.userName) return fail('ENV_USER_MISSING', '缺少 USER_NAME');
105
+ if (!env.integrationKey) return fail('ENV_INTEGRATION_KEY_MISSING', '缺少 INTEGRATION_KEY(集成登录密钥)');
106
+
107
+ try {
108
+ const token = await loginIntegration({
109
+ baseUrl: env.serverUrl,
110
+ loginName: env.userName,
111
+ integrationKey: env.integrationKey,
112
+ ipAddress: ipAddress || '127.0.0.1',
113
+ isOld: env.isOld,
114
+ });
115
+ writeCredentials({ serverUrl: env.serverUrl, token, updatedAt: new Date().toISOString() });
116
+ const out = { ok: true, command: 'platform auth login', serverUrl: env.serverUrl, credentials: CREDENTIALS };
117
+ if (json) console.log(JSON.stringify(out, null, 2));
118
+ else {
119
+ console.log(`✓ 已登录 ${env.serverUrl}`);
120
+ console.log(` Token 已缓存到 ${CREDENTIALS}`);
121
+ }
122
+ return EXIT.OK;
123
+ } catch (error) {
124
+ const code = error.kind === ERR.NETWORK ? 'NETWORK' : error.kind === ERR.UNAUTHORIZED ? 'LOGIN_REJECTED' : 'UNEXPECTED';
125
+ if (json) console.log(JSON.stringify({ ok: false, command: 'platform auth login', errors: [{ code, message: error.message }] }, null, 2));
126
+ else console.error(`✗ [${code}] ${error.message}`);
127
+ return error.kind === ERR.NETWORK ? EXIT.NETWORK : EXIT.PLATFORM;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * 部署期自动初始化入口(`start`)。
133
+ *
134
+ * 把「读部署输入 → 判断线上现状 → 创建或比对 → 落状态」封装成一条命令,
135
+ * 由容器启动期调用。成功后把新的 APP_ID / SECRET_KEY 写回 `.env`。
136
+ */
137
+ export async function runDeployStart({ dir, initDir, json = false, dryRun = false }) {
138
+ const root = path.resolve(dir);
139
+ const env = readPlatformEnv(root);
140
+ const { runStartupInit, patchDeployEnv } = await import('./startup.mjs');
141
+
142
+ const result = await runStartupInit({
143
+ root,
144
+ env: { ...env, end: env.siteType || 'web' },
145
+ dryRun,
146
+ json,
147
+ log: json ? () => {} : (line) => console.log(line),
148
+ });
149
+
150
+ // 只在真正创建成功后回写凭据;失败或跳过时不碰 .env
151
+ if (!dryRun && result.report?.envPatch) {
152
+ const envFile = path.join(root, '.env');
153
+ const updated = patchDeployEnv(envFile, result.report.envPatch);
154
+ if (updated.length && !json) console.log(` .env 已更新:${updated.join(', ')}`);
155
+ if (initDir) {
156
+ // init 目录也可能有一份 .env(部署包),一并更新
157
+ const initEnv = path.join(path.resolve(initDir), '.env');
158
+ if (fs.existsSync(initEnv)) patchDeployEnv(initEnv, result.report.envPatch);
159
+ }
160
+ }
161
+ return result.code;
162
+ }
163
+
164
+ export async function runPlatformAuthStatus({ dir, json = false }) {
165
+ const env = readPlatformEnv(dir);
166
+ const cached = readCredentials();
167
+ const result = {
168
+ ok: Boolean(env.serverUrl),
169
+ command: 'platform auth status',
170
+ serverUrl: env.serverUrl || null,
171
+ appId: env.appId || null,
172
+ hasSecretKey: Boolean(env.secretKey),
173
+ hasIntegrationKey: Boolean(env.integrationKey),
174
+ token: cached?.serverUrl === env.serverUrl && cached?.token
175
+ ? { present: true, updatedAt: cached.updatedAt || null }
176
+ : { present: false },
177
+ errors: [],
178
+ };
179
+ if (!env.serverUrl) {
180
+ result.errors.push({ code: 'ENV_SERVER_URL_MISSING', path: '.env', message: '缺少 SERVER_URL(或 INBIZ_URL)' });
181
+ result.ok = false;
182
+ }
183
+ if (json) {
184
+ console.log(JSON.stringify(result, null, 2));
185
+ } else {
186
+ console.log(`${result.ok ? '✓' : '✗'} ${result.serverUrl || '(未配置 SERVER_URL)'}`);
187
+ console.log(` 应用: ${result.appId || '(未配置 APP_ID)'}`);
188
+ console.log(` SecretKey: ${result.hasSecretKey ? '已配置' : '未配置'}`);
189
+ console.log(` Token: ${result.token.present ? `已缓存(${result.token.updatedAt})` : '未缓存'}`);
190
+ for (const error of result.errors) console.error(` ✗ ${error.code}: ${error.message}`);
191
+ }
192
+ return result.ok ? EXIT.OK : EXIT.INPUT;
193
+ }
194
+
195
+ /**
196
+ * 准备恢复包。
197
+ *
198
+ * 出码口径:优先用 `menus.json` 生成「应用 + 菜单」最小包;
199
+ * 工程里已有低码源(`standard/`)时按 full 模式整包恢复。
200
+ */
201
+ export function preparePackage({ dir, appName, tablePrefix }) {
202
+ /**
203
+ * 判定与 `buildRecoveryPackage` 的 `auto` 保持一致:
204
+ * 有 `menus.json` 就走菜单包;否则才看是否真有低码源。
205
+ * 不能只看 `standard/` —— `menu build` 自己会写 `standard/<end>/`。
206
+ */
207
+ const hasSpec = fs.existsSync(path.join(dir, 'menus.json'));
208
+ const hasLowCode = fs.existsSync(path.join(dir, 'standard', 'common'))
209
+ || fs.existsSync(path.join(dir, 'custom'));
210
+ const bootOverride = {
211
+ ...(appName ? { AppName: appName } : {}),
212
+ ...(tablePrefix ? { TableNamePrefix: tablePrefix } : {}),
213
+ };
214
+
215
+ if (hasSpec || !hasLowCode) {
216
+ const spec = readSpec(dir);
217
+ const { menus, errors } = buildMenus(spec);
218
+ if (errors.length) {
219
+ throw Object.assign(new Error(`menus.json 校验失败:${errors.map((e) => e.message).join(';')}`), {
220
+ exitCode: EXIT.INPUT,
221
+ errors,
222
+ });
223
+ }
224
+ return buildRecoveryPackage({
225
+ root: dir,
226
+ mode: 'menu',
227
+ boot: bootOverride,
228
+ menus: { end: spec.end || 'web', menu: menus, menuRelation: buildMenuRelation(menus) },
229
+ });
230
+ }
231
+ return buildRecoveryPackage({ root: dir, mode: 'full', boot: bootOverride });
232
+ }
233
+
234
+ export async function runPlatformAppRecover({
235
+ dir, confirmDomain, appName, tablePrefix, keepArchive, json = false, dryRun = false,
236
+ }) {
237
+ const env = readPlatformEnv(dir);
238
+ const fail = (code, message) => {
239
+ if (json) console.log(JSON.stringify({ ok: false, command: 'platform app recover', errors: [{ code, path: '.env', message }] }, null, 2));
240
+ else console.error(`✗ ${message}`);
241
+ return EXIT.INPUT;
242
+ };
243
+
244
+ if (!env.serverUrl) return fail('ENV_SERVER_URL_MISSING', '缺少 SERVER_URL(或 INBIZ_URL)');
245
+
246
+ let pkg;
247
+ try {
248
+ pkg = preparePackage({ dir, appName, tablePrefix });
249
+ } catch (error) {
250
+ if (json) {
251
+ console.log(JSON.stringify({
252
+ ok: false,
253
+ command: 'platform app recover',
254
+ errors: error.errors || [{ code: 'PACKAGE_INVALID', path: 'menus.json', message: error.message }],
255
+ }, null, 2));
256
+ } else {
257
+ console.error(`✗ ${error.message}`);
258
+ }
259
+ return error.exitCode || EXIT.INPUT;
260
+ }
261
+
262
+ const domain = pkg.boot?.Domain || '';
263
+ if (!confirmDomain || confirmDomain !== domain) {
264
+ return fail('CONFIRM_DOMAIN_MISMATCH', `--confirm-domain 必须等于 boot.json.Domain(当前 "${domain}")`);
265
+ }
266
+
267
+ if (dryRun) {
268
+ const summary = {
269
+ ok: true,
270
+ command: 'platform app recover',
271
+ dryRun: true,
272
+ mode: pkg.mode,
273
+ domain,
274
+ appName: pkg.boot.AppName,
275
+ tableNamePrefix: pkg.boot.TableNamePrefix,
276
+ zipType: pkg.boot.ZipType,
277
+ contains: pkg.contains,
278
+ entries: pkg.entries,
279
+ note: '仅预览:未连接平台、未写入 .env',
280
+ };
281
+ if (json) console.log(JSON.stringify(summary, null, 2));
282
+ else {
283
+ console.log(`(dry-run)将创建应用 ${pkg.boot.AppName} / domain=${domain}`);
284
+ console.log(` 模式 ${pkg.mode},ZipType=${pkg.boot.ZipType},Contains=${pkg.contains},${pkg.entries.length} 个文件`);
285
+ for (const name of pkg.entries.slice(0, 12)) console.log(` ${name}`);
286
+ if (pkg.entries.length > 12) console.log(` … 共 ${pkg.entries.length} 个`);
287
+ }
288
+ if (keepArchive) {
289
+ const archive = path.join(dir, 'scratch', `${domain}-recovery.zip`);
290
+ fs.mkdirSync(path.dirname(archive), { recursive: true });
291
+ fs.writeFileSync(archive, pkg.buffer);
292
+ console.log(` 恢复包已保留:${archive}`);
293
+ }
294
+ return EXIT.OK;
295
+ }
296
+
297
+ /**
298
+ * 取 Token:先看缓存,没有就用集成凭据现场登录。
299
+ *
300
+ * 自动登录这一步是**部署期必需**的:容器里没有 `~/.inbiz/credentials`,
301
+ * 指望人工先登录一次再启动是不现实的。凭据从环境变量/`.env` 注入。
302
+ */
303
+ let token = (() => {
304
+ const cached = readCredentials();
305
+ return cached?.serverUrl === env.serverUrl ? cached.token : '';
306
+ })();
307
+
308
+ if (!token && env.userName && env.integrationKey) {
309
+ try {
310
+ token = await loginIntegration({
311
+ baseUrl: env.serverUrl,
312
+ loginName: env.userName,
313
+ integrationKey: env.integrationKey,
314
+ isOld: env.isOld,
315
+ });
316
+ writeCredentials({ serverUrl: env.serverUrl, token, updatedAt: new Date().toISOString() });
317
+ if (!json) console.log('· 已用集成凭据登录');
318
+ } catch (error) {
319
+ return fail('LOGIN_FAILED', `集成登录失败:${error.message}`);
320
+ }
321
+ }
322
+
323
+ if (!token) {
324
+ return fail('TOKEN_MISSING',
325
+ '没有可用 Token 且缺少 USER_NAME / INTEGRATION_KEY:部署时请把这两个值注入环境变量');
326
+ }
327
+
328
+ try {
329
+ const result = await recoverApplication({
330
+ baseUrl: env.serverUrl,
331
+ token,
332
+ domain,
333
+ confirmDomain,
334
+ appName: pkg.boot.AppName,
335
+ tableNamePrefix: pkg.boot.TableNamePrefix,
336
+ package: pkg,
337
+ log: json ? () => {} : (line) => console.log(line),
338
+ });
339
+
340
+ const updated = updateEnvFile(path.join(dir, '.env'), {
341
+ APP_ID: result.appId,
342
+ SECRET_KEY: result.secretKey,
343
+ });
344
+
345
+ if (keepArchive) {
346
+ const archive = path.join(dir, 'scratch', `${domain}-recovery.zip`);
347
+ fs.mkdirSync(path.dirname(archive), { recursive: true });
348
+ fs.writeFileSync(archive, pkg.buffer);
349
+ }
350
+
351
+ const out = {
352
+ ok: true,
353
+ command: 'platform app recover',
354
+ appId: result.appId,
355
+ secretKey: result.secretKey,
356
+ siteVersions: result.siteVersions,
357
+ updatedEnv: updated,
358
+ skipped: result.skipped,
359
+ };
360
+ if (json) console.log(JSON.stringify(out, null, 2));
361
+ else {
362
+ console.log(`✓ 已创建应用 ${result.appId}`);
363
+ console.log(` .env 已更新:${updated.join(', ')}`);
364
+ console.log(` 站点版本:${JSON.stringify(result.siteVersions)}`);
365
+ console.log(` 跳过(接口资料未提供):${result.skipped.join('、')}`);
366
+ }
367
+ return EXIT.OK;
368
+ } catch (error) {
369
+ const codeByKind = {
370
+ [ERR.UNAUTHORIZED]: 'TOKEN_INVALID',
371
+ [ERR.NETWORK]: 'NETWORK',
372
+ [ERR.APP_MISSING]: 'APP_MISSING',
373
+ [ERR.SERVER]: 'PLATFORM_REJECTED',
374
+ };
375
+ const code = codeByKind[error.kind] || 'UNEXPECTED';
376
+ if (json) {
377
+ console.log(JSON.stringify({ ok: false, command: 'platform app recover', errors: [{ code, message: error.message }] }, null, 2));
378
+ } else {
379
+ console.error(`✗ [${code}] ${error.message}`);
380
+ }
381
+ if (error.kind === ERR.UNAUTHORIZED) return EXIT.PLATFORM;
382
+ if (error.kind === ERR.NETWORK) return EXIT.NETWORK;
383
+ if (error.kind === ERR.SERVER) return EXIT.PLATFORM;
384
+ return EXIT.INPUT;
385
+ }
386
+ }