@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,935 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { WEB_DIR, CODEGEN_ROOT, writeIfChanged } from './config.mjs';
4
+ import { createGeneratedOutput } from './generated-output.mjs';
5
+ import { emitFavicon } from './favicon.mjs';
6
+ import { scanComponents, CUSTOM_ROOTS } from './transform/registry.mjs';
7
+ import { createTransformer, parseStyleText } from './transform/schema-to-jsx.mjs';
8
+ import { compilePublishedPageLinks, pageUrlImport } from './transform/published-page-links.mjs';
9
+ import { collectPageFieldRefs, compilePublishedScript } from './transform/published-script.mjs';
10
+ import { emitBackendInit } from './backend/init.mjs';
11
+
12
+ /**
13
+ * 生成:把 .inbiz/app.json 里的 schema 翻译成一份普通的 React 工程源码。
14
+ *
15
+ * 产物是**可维护的业务代码**,不带 generated 后缀、不带自动生成声明:
16
+ * src/layout/ 应用框架(顶栏 / 侧边栏 / 内容区)
17
+ * src/pages/<route>/ 页面,按平台的路由分组
18
+ * src/styles/app.css 应用级扩展样式
19
+ * src/app-extends.ts 应用级扩展脚本
20
+ * src/locales.ts 定制组件语言包(各组件包词库的聚合入口)
21
+ */
22
+
23
+ /**
24
+ * 平台布局区域的固定枚举。
25
+ *
26
+ * 顺序固定 = 产物里 hideLayout 数组的书写顺序。同一份数据每次出码都得到
27
+ * 同样的字面量,diff 才只有「真正变了的那几页」。
28
+ */
29
+ const LAYOUT_REGIONS = ['top', 'left', 'right', 'bottom', 'tools', 'content'];
30
+
31
+ /** 布局区域 → 文件名与导出名 */
32
+ const SECTION_FILE = {
33
+ top: { file: 'header', comp: 'Header' },
34
+ left: { file: 'sidebar', comp: 'Sidebar' },
35
+ right: { file: 'aside', comp: 'Aside' },
36
+ bottom: { file: 'footer', comp: 'Footer' },
37
+ tools: { file: 'tools', comp: 'Tools' },
38
+ };
39
+
40
+ function pascal(s) {
41
+ return String(s || '')
42
+ .split(/[^A-Za-z0-9]+/)
43
+ .filter(Boolean)
44
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
45
+ .join('');
46
+ }
47
+
48
+ function indent(text, level) {
49
+ const pad = ' '.repeat(level);
50
+ return text
51
+ .split('\n')
52
+ .map((l) => (l.trim() ? pad + l : l))
53
+ .join('\n');
54
+ }
55
+
56
+ /**
57
+ * 平台占位符替换。
58
+ *
59
+ * `/inbiz/static/{AppId}/...` 这类地址里的 {AppId} 在平台上由运行时替换,
60
+ * 出码后没有那一步,会变成 /inbiz/static/undefined/... 导致静态资源 404。
61
+ */
62
+ export function applyPlaceholders(value, appId) {
63
+ if (!value || !appId) return value;
64
+ const json = JSON.stringify(value);
65
+ if (!json.includes('{AppId}')) return value;
66
+ return JSON.parse(json.split('{AppId}').join(appId));
67
+ }
68
+
69
+ /**
70
+ * 把指向平台站点的**页面链接**改成本地路由。
71
+ *
72
+ * schema 里的 `url: '/inbiz/web/iso'`、`menu[].LinkUrl: '/inbiz/web/ecm#/index'`
73
+ * 是平台内部跳转;出码产物是独立应用,点这些链接会跳到平台站点(表现就是
74
+ * 「点一下就跳去登录」)。
75
+ *
76
+ * 只改页面链接,不动资源路径 —— 这两类在 schema 里长得一样,都是
77
+ * `/inbiz/web/...`,早先按前缀一把替换把搜索结果模板改成了 `/`:
78
+ * `tabsConfig[].filepath: '/inbiz/web/template_search/file.jsx'`
79
+ * `template.content: '/inbiz/web/template/file.jsx'`
80
+ * 它们是服务端下发的 `.jsx` 渲染模板,不是链接;改成 `/` 之后搜索页拿到的是
81
+ * 站点根路径,模板加载不出来。
82
+ *
83
+ * 判别规则(不枚举字段名、不枚举页面):
84
+ * 1. 路径去掉 hash / query 之后**带文件扩展名**的是资源,不碰;
85
+ * 2. 其余是页面链接:有 hash 路由的保留路由(`#/index`),
86
+ * 没有的落到站点根 `/`。
87
+ */
88
+ const PLATFORM_LINK = /^\/inbiz\/(?:web|wap)(\/[^?#]*)?(?:[?#][\s\S]*)?$/;
89
+ /** 资源/模板文件:`file.jsx`、`iconfont.js`、`report.pdf` */
90
+ const RESOURCE_EXT = /\.[a-z0-9]{1,8}$/i;
91
+
92
+ export function rewritePlatformLink(text) {
93
+ const match = PLATFORM_LINK.exec(text);
94
+ if (!match) return text;
95
+ const path = match[1] || '';
96
+ if (RESOURCE_EXT.test(path)) return text;
97
+ const hashAt = text.indexOf('#');
98
+ // 平台站点里的 hash 就是应用内路由,出码产物用 hash history,原样保留。
99
+ if (hashAt >= 0 && text.slice(hashAt).length > 1) return text.slice(hashAt);
100
+ return '/';
101
+ }
102
+
103
+ export function normalizeLinks(value) {
104
+ if (!value) return value;
105
+ const json = JSON.stringify(value);
106
+ if (!json.includes('/inbiz/web/') && !json.includes('/inbiz/wap/')) return value;
107
+ return JSON.parse(json.replace(/"((?:\\.|[^"\\])*)"/g, (whole, body) => {
108
+ if (!body.includes('/inbiz/')) return whole;
109
+ let decoded;
110
+ try {
111
+ decoded = JSON.parse('"' + body + '"');
112
+ } catch {
113
+ return whole;
114
+ }
115
+ const next = rewritePlatformLink(decoded);
116
+ return next === decoded ? whole : JSON.stringify(next);
117
+ }));
118
+ }
119
+
120
+ /**
121
+ * 页面根容器的 className / style。
122
+ *
123
+ * 平台渲染页面的入口是 `ParserCore`(designer/packages/base/render/core/index.tsx:220):
124
+ * 它把 `content.form` 整个铺在最外层的 Form 上,`form.style` 决定页面的
125
+ * 背景图、背景色、内边距、阴影;`form.className` 追加在容器类名后面。
126
+ *
127
+ * 出码原先只取 `detail.CssContent` 生成 index.css,`content.form` 整块被丢掉,
128
+ * 于是 46 个配了背景/内边距的页面一进产物就是白板 —— 首页那张整屏背景图、
129
+ * 各列表页的 #f6f7f7 底色和 15px 内边距全都不见了,区块位置自然对不上。
130
+ */
131
+ export function pageRootProps(form) {
132
+ const raw = form?.style;
133
+ // 平台这份数据目前 46/46 都是对象;但 schema 编辑器里 style 也可能是
134
+ // `padding: 15px; background: #fff` 这样的文本,直接 JSON.stringify 进
135
+ // style={} 会让 React 拿到字符串报 "style prop expects an object"
136
+ const style = typeof raw === 'string' ? parseStyleText(raw) : raw;
137
+ const className = form?.className;
138
+ return {
139
+ // 空对象不进 JSX:`style={{}}` 会让产物多一堆噪音,也掩盖「这里压根没配」
140
+ style: style && typeof style === 'object' && !Array.isArray(style) && Object.keys(style).length
141
+ ? style
142
+ : null,
143
+ className: typeof className === 'string' ? className : '',
144
+ };
145
+ }
146
+
147
+ /** 单个布局区域 → src/layout/<file>.tsx */
148
+ export function emitSection(sectionName, section, registry, messages, { runtimeTranslations = true, dataSourceContracts, extractPageConfig = true } = {}) {
149
+ const tr = createTransformer({
150
+ registry, messages, runtimeTranslations, dataSourceContracts, bindLayoutFieldEvents: true, extractPageConfig,
151
+ });
152
+ const body = tr.renderSchema(section.schema);
153
+ const meta = SECTION_FILE[sectionName] || {
154
+ file: sectionName.toLowerCase(),
155
+ comp: pascal(sectionName),
156
+ };
157
+
158
+ // 大型对象/数组参数和页面同一条规则提取到同目录的 `<file>-config.ts`:
159
+ // 布局区域的组件配置(菜单 configList、图标表等)动辄几百行,留在 TSX
160
+ // 里会把真正的结构埋掉,也没法和页面一样单独演进。
161
+ const config = tr.renderPageConfig();
162
+ const configImport = config ? `import * as pageConfig from './${meta.file}-config';\n` : '';
163
+ const imports = tr.importBlock();
164
+ const lazy = tr.lazyBlock();
165
+ // Side regions already have a flex item in WebLayout; this node carries only the region content.
166
+ const isSide = sectionName === 'left' || sectionName === 'right';
167
+ const { style: formStyle, className: formClassName } = pageRootProps(section.form);
168
+ const className = [`app-${meta.file}${isSide ? '-content' : ''}`, formClassName].filter(Boolean).join(' ');
169
+ const classAttr = formClassName ? `className={${JSON.stringify(className)}}` : `className="${className}"`;
170
+ const inbizHook = tr.needsInbiz ? ' const inbiz = useInbiz();\n' : '';
171
+
172
+ const code = `import React from 'react';
173
+ ${configImport}${imports ? imports + '\n' : ''}${lazy ? '\n' + lazy + '\n' : ''}
174
+ /** 应用框架的「${sectionName}」区域。 */
175
+ export function ${meta.comp}() {
176
+ ${inbizHook} return (
177
+ <div ${classAttr}${formStyle ? ` style={${JSON.stringify(formStyle)}}` : ''}>
178
+ ${indent(body, 6)}
179
+ </div>
180
+ );
181
+ }
182
+
183
+ export default ${meta.comp};
184
+ `;
185
+ return { ...meta, section: sectionName, code, config, warnings: tr.warnings, lazy: tr.lazyComponents };
186
+ }
187
+
188
+ /**
189
+ * 路由名归一化:`#/system-index`、`/system-index`、`system-index?x=1` 都是 `system-index`。
190
+ *
191
+ * 和 @macrowing/inbiz-runtime 的 normalizePageRoute 同一口径。生成期也要归一化,
192
+ * 因为 PageLayoutInfo 的 key 和页面清单的 route 来自两个接口,写法不一定一致。
193
+ */
194
+ function normalizeRouteName(route) {
195
+ return (
196
+ String(route || '')
197
+ .replace(/^#/, '')
198
+ .replace(/^\//, '')
199
+ .split('?')[0]
200
+ .split('/')
201
+ .filter(Boolean)
202
+ .pop() || 'index'
203
+ );
204
+ }
205
+
206
+ /** PageLayoutInfo / MenuLayoutInfo 的值是 JSON 数组字符串(也可能已经是数组)。 */
207
+ function parseHiddenRegions(value) {
208
+ if (!value) return [];
209
+ if (Array.isArray(value)) return value.map(String);
210
+ try {
211
+ const parsed = JSON.parse(value);
212
+ return Array.isArray(parsed) ? parsed.map(String) : [];
213
+ } catch {
214
+ // 配置坏了就当作「这一页没有额外规则」,不要因为一条脏数据让全站布局瘫掉
215
+ return [];
216
+ }
217
+ }
218
+
219
+ /**
220
+ * 某一页要隐藏的区域 = 全站默认 ∪ 本页配置。
221
+ *
222
+ * 平台 useChangeLayout 的语义就是这两者取并集(`x-display` 为真 或 本页列到了
223
+ * 该区域)。区别在于**合并的时机**:这里在生成期就算完,产物里只剩一个数组,
224
+ * 运行时不需要再认识 LayoutInfo / PageLayoutInfo 这两份平台原始数据。
225
+ */
226
+ function composeHidden(defaultHidden, extra) {
227
+ const merged = new Set([...defaultHidden, ...extra]);
228
+ const known = LAYOUT_REGIONS.filter((r) => merged.has(r));
229
+ // 平台将来新增、这里还不认识的区域:保留并排在末尾,宁可多隐藏也不漏
230
+ const unknown = [...merged].filter((r) => !LAYOUT_REGIONS.includes(r)).sort();
231
+ return [...known, ...unknown];
232
+ }
233
+
234
+ /** 两个区域数组内容是否一致(用来决定要不要写 hideLayoutInPage) */
235
+ function sameRegions(a, b) {
236
+ return a.length === b.length && a.every((r, i) => r === b[i]);
237
+ }
238
+
239
+ /**
240
+ * 平台内置页目录:产品自带、但不在应用页面清单里的页面 schema 副本。
241
+ *
242
+ * 每个子目录 = 一个页面:
243
+ * page.json 路由、标题、schema 文件名(见下)
244
+ * schema.json 平台页面 schema,**逐字复制**,不手工改写
245
+ */
246
+ const BUILTIN_PAGES_ROOT = path.join(CODEGEN_ROOT, 'scaffolds/frontend/components/edoc2/pages');
247
+
248
+ /**
249
+ * 平台内置页 → 与 app.json 同构的页面对象。
250
+ *
251
+ * 为什么要这条通道:`pull` 拉的是**当前应用**的页面清单(app.json 的 pages),
252
+ * 而 docflow-preview / docflow-detail 这类页面是产品(docInformationPortal
253
+ * 标准 web)自带的,服务端 pageAllPerm 对它们只回 notfound —— 平台自己也不是
254
+ * 靠菜单路由进入,而是按页面 id 打开(`window.ecmPlugins.config.docflowPreviewURL`
255
+ * → `loadPage`)。只把路由塞进 routes.ts,页面仍然会因为「服务端说没有这一页」
256
+ * 而落进 404 分支,所以必须让产物自己知道这些页面是「本地有的」。
257
+ *
258
+ * 这里不猜页面长什么样:组件、属性、容器全部来自平台 schema 原文,交给
259
+ * 普通页面的产出管线(emitPage)翻译。这与「凭空造一个空页面糊弄路由」
260
+ * 是两件事 —— 后者会把真实的 DocFlow 编辑器换成一块空白。
261
+ *
262
+ * 仍然是扫描目录而不是写死两个名字:平台再加内置页时,放一个目录即可。
263
+ */
264
+ export function scanBuiltinPages(root = BUILTIN_PAGES_ROOT) {
265
+ if (!fs.existsSync(root)) return [];
266
+ const pages = [];
267
+ for (const entry of fs.readdirSync(root, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
268
+ if (!entry.isDirectory()) continue;
269
+ const dir = path.join(root, entry.name);
270
+ const manifestFile = path.join(dir, 'page.json');
271
+ if (!fs.existsSync(manifestFile)) continue;
272
+ const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
273
+ const schemaFile = path.join(dir, manifest.schema || 'schema.json');
274
+ // 缺 schema 不能静默跳过:跳过的结果就是「路由补了、页面是空的」,
275
+ // 这正是这类内置页最初出问题的方式。
276
+ if (!manifest.route) throw new Error(`[builtin-page:${entry.name}] page.json 缺少 route`);
277
+ if (!fs.existsSync(schemaFile)) throw new Error(`[builtin-page:${entry.name}] 缺少 ${path.basename(schemaFile)}`);
278
+ pages.push({
279
+ route: manifest.route,
280
+ name: manifest.name || manifest.route,
281
+ builtin: true,
282
+ // emitPage 读的是 detail.Component 里的 content({ form, schema }),
283
+ // 平台页面 schema 文件本身就是这个形状,直接沿用。
284
+ detail: { Route: manifest.route, Component: fs.readFileSync(schemaFile, 'utf8') },
285
+ });
286
+ }
287
+ return pages;
288
+ }
289
+
290
+ /**
291
+ * 页面清单 + 平台布局显隐 → 路由表条目。
292
+ *
293
+ * 抽成独立函数是为了让「出码」和「离线补产物」走同一段逻辑:两份实现
294
+ * 各写一遍,迟早会在「页面态用 PageLayoutInfo 还是 MenuLayoutInfo」
295
+ * 这种细节上分叉。
296
+ */
297
+ export function buildPageRoutes(pageIndex, layoutInfo = {}, pageLayoutInfo = {}, menuLayoutInfo = {}) {
298
+ // 调用方可能把「没拉到」传成 null(默认参数只兜 undefined),这里统一兜一次:
299
+ // 少一份配置最多是少隐藏一个区域,不该让整个出码失败。
300
+ layoutInfo = layoutInfo || {};
301
+ pageLayoutInfo = pageLayoutInfo || {};
302
+ menuLayoutInfo = menuLayoutInfo || {};
303
+ const defaultHidden = LAYOUT_REGIONS.filter((r) => !!(layoutInfo[r]?.form?.['x-display']));
304
+ const routes = pageIndex.map((page) => {
305
+ // 每页的框架显隐:全站默认 ∪ 本页配置,在生成期就合并成字面量。
306
+ // 菜单态与页面态分开算,只有真的不一样才多写一个 hideLayoutInPage,
307
+ // 免得 108 条路由里出现一堆「两个相同数组」的噪音。
308
+ const name = normalizeRouteName(page.route);
309
+ const menuHidden = composeHidden(defaultHidden, parseHiddenRegions(menuLayoutInfo[name]));
310
+ const pageHidden = composeHidden(defaultHidden, parseHiddenRegions(pageLayoutInfo[name]));
311
+ return {
312
+ dir: page.dir,
313
+ route: page.route,
314
+ compName: page.compName,
315
+ // 内置页必须把身份写进路由表:运行时靠它决定「服务端说没有这一页时,
316
+ // 还要不要去本地找」。普通页面不写,保持「服务端为准」的严格语义。
317
+ ...(page.builtin ? { builtin: true, title: page.title } : {}),
318
+ hideLayout: menuHidden,
319
+ ...(sameRegions(pageHidden, menuHidden) ? {} : { hideLayoutInPage: pageHidden }),
320
+ };
321
+ });
322
+ return { defaultHidden, pageIndex: routes };
323
+ }
324
+
325
+ /**
326
+ * 页面清单 + 框架显隐 → src/pages/routes.ts。
327
+ *
328
+ * 这里就是「路由表」本体:每条路由自带 hideLayout,布局组件按当前匹配到的
329
+ * 页面记录读取。不再产出 layout-info.ts 那种「运行时读配置」的产物。
330
+ */
331
+ export function renderPageRoutes(pageIndex, defaultHidden) {
332
+ const list = pageIndex
333
+ .map((page) => {
334
+ const lines = [
335
+ ` "dir": ${JSON.stringify(page.dir)},`,
336
+ ` "route": ${JSON.stringify(page.route)},`,
337
+ ` "compName": ${JSON.stringify(page.compName)},`,
338
+ ...(page.builtin
339
+ ? [` "builtin": true,`, ` "title": ${JSON.stringify(page.title || page.route)},`]
340
+ : []),
341
+ ` "hideLayout": ${JSON.stringify(page.hideLayout)}`,
342
+ ];
343
+ if (page.hideLayoutInPage) {
344
+ lines[lines.length - 1] += ',';
345
+ lines.push(` "hideLayoutInPage": ${JSON.stringify(page.hideLayoutInPage)}`);
346
+ }
347
+ return [' {', ...lines, ' }'].join('\n');
348
+ })
349
+ .join(',\n');
350
+
351
+ const defaultText = defaultHidden.length ? defaultHidden.join('、') : '(无)';
352
+
353
+ return `/**
354
+ * 页面清单:路由 → 组件 + 框架区域显隐。
355
+ *
356
+ * 这是**路由表本身**。每条路由自带 hideLayout,布局组件按当前匹配到的页面
357
+ * 记录读取,不再有 layout-info 那种全局配置表。
358
+ *
359
+ * hideLayout 已经把平台的全站默认折算进来了 —— LayoutInfo 里 form['x-display']
360
+ * 为真的区域(当前是 ${defaultText})会并进每一页的数组,所以运行时只管
361
+ * includes,不做任何合并,也不需要认识平台的原始数据结构。
362
+ *
363
+ * hideLayoutInPage 只在「页面态」(page/xxx)与「菜单态」隐藏的区域不同时出现;
364
+ * 字段不存在就说明两者一致,直接用 hideLayout。
365
+ */
366
+ import type { LayoutRegion } from '@macrowing/inbiz-runtime/web';
367
+ export type { LayoutRegion } from '@macrowing/inbiz-runtime/web';
368
+
369
+ export interface PageRoute {
370
+ dir: string;
371
+ route: string;
372
+ compName: string;
373
+ /**
374
+ * 平台内置页:产品自带、不在应用页面清单里。
375
+ *
376
+ * 服务端的 pageAllPerm 对它只回 notfound(页面不归这个应用所有),
377
+ * 但页面代码在本地产物里,所以路由要回落到本地,而不是 404。
378
+ */
379
+ builtin?: boolean;
380
+ /** 内置页标题:服务端不给 PageName,文档标题用这个 */
381
+ title?: string;
382
+ /** 菜单态要隐藏的区域(含全站默认) */
383
+ hideLayout: readonly LayoutRegion[];
384
+ /** 页面态要隐藏的区域;与菜单态相同时不出现 */
385
+ hideLayoutInPage?: readonly LayoutRegion[];
386
+ }
387
+
388
+ /** 全站默认显隐:没有出码 / 不在清单里的路由按它处理 */
389
+ export const DEFAULT_HIDE_LAYOUT: readonly LayoutRegion[] = ${JSON.stringify(defaultHidden)};
390
+
391
+ export const PAGES: readonly PageRoute[] = [
392
+ ${list}
393
+ ];
394
+
395
+ const BY_ROUTE = new Map<string, PageRoute>(PAGES.map((page) => [page.route, page]));
396
+
397
+ /** 扁平路由 → 页面记录(入参请先归一化)。 */
398
+ export function findPageRoute(route: string): PageRoute | undefined {
399
+ return BY_ROUTE.get(route);
400
+ }
401
+ `;
402
+ }
403
+
404
+ /** 框架总装 → src/layout/index.tsx */
405
+ export function emitLayout(sections) {
406
+ const slots = ['top', 'left', 'right', 'bottom']
407
+ .map((name) => sections.find((s) => s.section === name))
408
+ .filter(Boolean);
409
+ const imports = slots
410
+ .map((s) => `import { ${s.comp} } from './${s.file}';`)
411
+ .join('\n');
412
+ const props = slots.map((s) => ` ${s.section}={${s.comp}}`).join('');
413
+ return `import React from 'react';
414
+ import { WebLayout } from '@macrowing/inbiz-runtime/web';
415
+ import { DEFAULT_HIDE_LAYOUT, findPageRoute } from '@/pages/routes';
416
+ ${imports ? `${imports}\n` : ''}
417
+ export function Layout({ children }: { children?: React.ReactNode }) {
418
+ return <WebLayout${props} defaultHidden={DEFAULT_HIDE_LAYOUT} findPageRoute={findPageRoute}>{children}</WebLayout>;
419
+ }
420
+
421
+ export default Layout;
422
+ `;
423
+ }
424
+
425
+ /** 页面路由 → 目录路径:`file-maneger/file-list` → `file-maneger/file-list` */
426
+ function routeDir(route) {
427
+ const segs = String(route || 'index')
428
+ .split('/')
429
+ .map((s) => s.replace(/[^\w-]/g, '').toLowerCase())
430
+ .filter(Boolean);
431
+ return segs.length ? segs.join('/') : 'index';
432
+ }
433
+
434
+ /**
435
+ * 页面脚本 → 「哪些控件必须留在表单里」。
436
+ *
437
+ * 平台脚本全靠名字操作控件(`inbiz('name').display = 'hidden'`、
438
+ * `.required = true`、`.value`、`.loadData()`),这些语句落的都是 Formily
439
+ * 字段状态。出码产物只有对**确实需要字段**的控件才生成 FieldScope,
440
+ * 所以这里先把脚本里点过名的控件收集出来,交给生成器:
441
+ *
442
+ * 1. `inbiz('x')` 字面量 → 点名的控件;
443
+ * 2. `getValue() / validate() / setValues() / reset() / getFields()` →
444
+ * 整表读写,说明这个页面的表单项都是「数据」,不能按纯展示渲染。
445
+ *
446
+ * 动态名字(`inbiz(key)`)推不出来,但取值来源在调用处通常是字面量
447
+ * (`versionTypeChange(value, "majorLetterType", …)`),第 2 条兜住这种。
448
+ */
449
+ function scriptFieldRefs(scripts) {
450
+ const text = String(scripts || '');
451
+ const scriptNames = new Set();
452
+ for (const match of text.matchAll(/inbiz\(\s*['"]([^'"]+)['"]\s*\)/g)) {
453
+ scriptNames.add(match[1]);
454
+ }
455
+ // 名字经常是通过变量传进来的:`versionTypeChange(value, "majorLetterType", …)`
456
+ // 里没有 `inbiz('…')` 的形状,但 `inbiz(letterTypeId).display = 'hidden'` 同样
457
+ // 落在字段状态上。所以把所有**字符串字面量**都当作「可能被点名的控件」。
458
+ // 宁可多留几个字段(多一次 createField),也不能让脚本的显隐/必填/校验落空。
459
+ for (const match of text.matchAll(/(['"])((?:\\.|(?!\1)[^\\\n])*)\1/g)) {
460
+ if (match[2]) scriptNames.add(match[2]);
461
+ }
462
+ const readsValues = /\b(getValue|validate|setValues|getFields|reset)\s*\(/.test(text);
463
+ return { scriptNames, readsValues };
464
+ }
465
+
466
+ const PAGE_EVENTS = [
467
+ ['OnLoadBefore', 'onLoadBefore', 'before'],
468
+ ['OnLoaded', 'onLoaded', 'loaded'],
469
+ ];
470
+
471
+ const PAGE_EVENTS_HEADER = '// @ts-nocheck -- Preserve the platform JavaScript body and its dynamic bindings.\n';
472
+ const PAGE_EXTENDS_MODULE = './page-extends';
473
+ const PAGE_CONFIG_MODULE = './page-config';
474
+ const LEGACY_PAGE_EVENTS_MODULE = './events';
475
+
476
+ /**
477
+ * 找出脚本里「隐式创建全局」的标识符。
478
+ *
479
+ * 平台把这些脚本当普通函数体执行(非严格模式),`foo = () => {}` 这种
480
+ * 未声明的赋值会静默创建 window.foo,随后表格里拼出来的
481
+ * `onclick="foo(row)"` 才找得到它。产物是 ES 模块(严格模式),
482
+ * 同样的写法直接抛 `foo is not defined`。
483
+ *
484
+ * 所以要做的不是改脚本,而是把平台那层语义补回来:函数顶部声明,
485
+ * 执行完挂到 window 上,内联事件处理器照旧按全局名调用。
486
+ */
487
+ // Keep the old emitter only for recognizing pristine events.js during migration.
488
+ function legacyImplicitGlobals(script) {
489
+ const text = String(script || '');
490
+ // 已在本脚本内声明过的名字不算隐式全局
491
+ const declared = new Set();
492
+ for (const m of text.matchAll(/\b(?:let|const|var|function|class)\s+([A-Za-z_$][\w$]*)/g)) {
493
+ declared.add(m[1]);
494
+ }
495
+
496
+ const found = new Set();
497
+ // 语句起始位置的「标识符 = 」,排除属性赋值(a.b =)与比较(a == b)
498
+ for (const m of text.matchAll(/(?:^|[\n;{}])\s*([A-Za-z_$][\w$]*)\s*=(?![=>])/g)) {
499
+ const name = m[1];
500
+ if (declared.has(name)) continue;
501
+ found.add(name);
502
+ }
503
+ return [...found];
504
+ }
505
+
506
+ function emitLegacyEventFunction(name, script) {
507
+ const globals = legacyImplicitGlobals(script);
508
+ // 顶部声明 + 末尾挂到 window:平台脚本的执行结果对全局可见,产物里要显式还原
509
+ const decl = globals.length ? ` let ${globals.join(', ')};\n` : '';
510
+ const expose = globals.length
511
+ ? `\n // 平台在非严格模式下执行脚本,这些赋值的本意就是创建全局(内联 onclick 会用到)\n${globals
512
+ .map((g) => ` window.${g} = ${g};`)
513
+ .join('\n')}\n`
514
+ : '';
515
+ return `export function ${name}(inbiz) {\n${decl}${indent(script || '', 1)}\n${expose}}\n`;
516
+ }
517
+
518
+ function emitEventFunction(name, script) {
519
+ const { body, globalsParam } = compilePublishedScript(script);
520
+ return `export function ${name}(inbiz: IInbiz${globalsParam ? `, ${globalsParam}` : ''}) {\n${indent(body, 1)}\n}\n`;
521
+ }
522
+
523
+ /** 页面 → src/pages/<route>/index.tsx */
524
+ export function emitPage(page, registry, messages, appId, {
525
+ runtimeTranslations = true, dataSourceContracts, publishedPages, pageFieldRefs, extractPageConfig = true,
526
+ } = {}) {
527
+ const detail = page.detail || {};
528
+ let schema = null;
529
+ let pageForm = null;
530
+ const schemaErrors = [];
531
+ try {
532
+ const comp = typeof detail.Component === 'string' ? JSON.parse(detail.Component) : detail.Component;
533
+ schema = applyPlaceholders(comp?.content?.schema || comp?.content || null, appId);
534
+ schema = normalizeLinks(schema);
535
+ // 页面级 form:背景图/背景色/内边距都在这里,和 schema 同级(见 pageRootProps)
536
+ pageForm = applyPlaceholders(comp?.content?.form || null, appId);
537
+ } catch (e) {
538
+ /**
539
+ * schema 解析失败 = 这个页面会变成空白页。早先这里只把 schema 置空,
540
+ * 错误文本直接丢掉,上层只剩一句「未找到页面 schema」—— 出码时最该
541
+ * 定位的一类故障,恰恰是唯一不给原因的。把原始错误带上。
542
+ */
543
+ schema = null;
544
+ schemaErrors.push(`页面 schema 解析失败:${e?.message || e}`);
545
+ }
546
+
547
+ const transformerOptions = {
548
+ registry,
549
+ messages,
550
+ runtimeTranslations,
551
+ dataSourceContracts,
552
+ ...scriptFieldRefs(`${detail.OnLoadBefore || ''}\n${detail.OnLoaded || ''}`),
553
+ };
554
+ for (const name of pageFieldRefs ?? []) transformerOptions.scriptNames.add(name);
555
+ const tr = createTransformer({ ...transformerOptions, extractPageConfig });
556
+ const body = schema ? tr.renderSchema(schema) : '';
557
+ const config = tr.renderPageConfig();
558
+ const dir = routeDir(page.route);
559
+ const compName = pascal(dir) + 'Page';
560
+
561
+ const pageCss = (detail.CssContent || '').trim();
562
+ const cssImport = pageCss ? `import './index.css';\n` : '';
563
+
564
+ const root = pageRootProps(pageForm);
565
+ const pageRoute = detail.Route || page.route;
566
+ const platformId = pageRoute.replace(/^\/?page\//, '');
567
+ const legacyRootClass = ['app-page', `app-page-${dir.replace(/\//g, '-')}`, root.className].filter(Boolean).join(' ');
568
+ const rootClass = [legacyRootClass, `pageContainer_${platformId}`].join(' ');
569
+ // 平台把 form.style 内联在页面容器上,这里保持同样的形态:
570
+ // 背景图是按路径拼出来的,放进 CSS 类里反而多一层「谁是数据源」的歧义
571
+ const rootStyle = root.style ? ` style={${JSON.stringify(root.style)}}` : '';
572
+
573
+ const activeEvents = PAGE_EVENTS.filter(([key]) => detail[key]?.trim());
574
+ const scripts = activeEvents.map(([key, name]) => [name, detail[key], compilePublishedPageLinks(detail[key], publishedPages)]);
575
+ const urlImport = scripts.some(([, original, compiled]) => original !== compiled) ? pageUrlImport : '';
576
+ const eventImport = activeEvents.length
577
+ ? `import { ${activeEvents.map(([, name]) => name).join(', ')} } from '${PAGE_EXTENDS_MODULE}';\n`
578
+ : '';
579
+ const pageId = JSON.stringify(pageRoute);
580
+ const eventProps = activeEvents.map(([, name, prop]) => ` ${prop}={${name}}`).join('');
581
+ const pageElement = ` return (
582
+ <RuntimePage id=${pageId}${eventProps}>
583
+ <PageContent />
584
+ </RuntimePage>
585
+ );`;
586
+ const renderPage = (eventsImport, element, classAttribute = `{${JSON.stringify(rootClass)}}`, transformer = tr, content = body, legacy = false) => {
587
+ const imports = transformer.importBlock(['RuntimePage']);
588
+ const configImport = transformer === tr && config ? `import * as pageConfig from '${PAGE_CONFIG_MODULE}';\n` : '';
589
+ const lazy = transformer.lazyBlock();
590
+ const inbizHook = transformer.needsInbiz ? ' const inbiz = useInbiz();\n' : '';
591
+ // Preserve the inner form's layout boundary without nesting native forms in modals.
592
+ const children = content ? indent(content, 6)
593
+ : `${legacy ? ' ' : ' '}{/* 该页面暂无可渲染内容 */}`;
594
+ const pageContent = legacy ? children : ` <div className="app-page-body">\n${children}\n </div>`;
595
+ return `import React from 'react';
596
+ ${eventsImport}${configImport}${cssImport}${imports ? imports + '\n' : ''}${lazy ? '\n' + lazy + '\n' : ''}
597
+ /** 页面:${page.route} */
598
+ function PageContent() {
599
+ ${inbizHook} return (
600
+ <div className=${classAttribute}${rootStyle}>
601
+ ${pageContent}
602
+ </div>
603
+ );
604
+ }
605
+
606
+ export function ${compName}() {
607
+ ${element}
608
+ }
609
+
610
+ export default ${compName};
611
+ `;
612
+ };
613
+ const code = renderPage(eventImport, pageElement);
614
+ return {
615
+ dir,
616
+ compName,
617
+ // 平台真实路由是**扁平的**:`detail.Route`(如 system-index、file-delay)。
618
+ // 目录里的 `分组/页面` 只是设计器里的层级,不参与 URL。
619
+ // 菜单跳转走 `history.push(routerPrefix + menu.Route)`,与之一致。
620
+ route: pageRoute,
621
+ code,
622
+ config,
623
+ events: activeEvents.length
624
+ ? `${PAGE_EVENTS_HEADER}${urlImport}import type { IInbiz } from '@macrowing/inbiz-runtime';\n\n`
625
+ + scripts.map(([name, , script]) => emitEventFunction(name, script)).join('\n')
626
+ : '',
627
+ get legacyTsCode() {
628
+ const legacyImport = eventImport.replace(PAGE_EXTENDS_MODULE, LEGACY_PAGE_EVENTS_MODULE);
629
+ if (!config) return eventImport ? code.replace(eventImport, legacyImport) : code;
630
+ const inline = createTransformer(transformerOptions);
631
+ return renderPage(legacyImport, pageElement, undefined, inline, inline.renderSchema(schema));
632
+ },
633
+ get legacyCode() {
634
+ const legacy = createTransformer({
635
+ ...transformerOptions,
636
+ runtimeTranslations: false,
637
+ registry: new Map(Array.from(registry, ([name, entry]) => [name, { ...entry, widgetSlots: undefined }])),
638
+ });
639
+ const legacyBody = schema ? legacy.renderSchema(schema) : '';
640
+ return renderPage("import { onLoadBefore, onLoaded } from './events';\n",
641
+ ` return <RuntimePage id=${pageId} before={onLoadBefore} loaded={onLoaded}><PageContent /></RuntimePage>;`,
642
+ JSON.stringify(legacyRootClass), legacy, legacyBody, true);
643
+ },
644
+ legacyEvents: PAGE_EVENTS.map(([key, name]) => emitLegacyEventFunction(name, detail[key])).join('\n'),
645
+ css: pageCss,
646
+ warnings: [...schemaErrors, ...tr.warnings],
647
+ hasSchema: !!schema,
648
+ lazy: tr.lazyComponents,
649
+ };
650
+ }
651
+
652
+ /** Migrate exact old output, or output verified by the migration caller. */
653
+ export function writePageSource(dir, out, { migrateOnly = false, dryRun = false, verifiedPage } = {}) {
654
+ const pageFile = path.join(dir, 'index.tsx');
655
+ const legacyJsFile = path.join(dir, `${LEGACY_PAGE_EVENTS_MODULE}.js`);
656
+ const legacyTsFile = path.join(dir, `${LEGACY_PAGE_EVENTS_MODULE}.ts`);
657
+ const extendsFile = path.join(dir, `${PAGE_EXTENDS_MODULE}.ts`);
658
+ const read = (file) => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : undefined;
659
+ const normalize = (text) => text?.replace(/\r\n/g, '\n');
660
+ const jsScript = read(legacyJsFile);
661
+ const tsScript = read(legacyTsFile);
662
+ const extensions = read(extendsFile);
663
+ const hasLegacyScript = jsScript !== undefined || tsScript !== undefined;
664
+ if (jsScript !== undefined && normalize(jsScript) !== normalize(out.legacyEvents)) return path.basename(legacyJsFile);
665
+ if (tsScript !== undefined && normalize(tsScript) !== normalize(out.events)) return path.basename(legacyTsFile);
666
+ if (extensions !== undefined && normalize(extensions) !== normalize(out.events)) return path.basename(extendsFile);
667
+ const current = normalize(read(pageFile));
668
+ if ((current !== undefined || migrateOnly || hasLegacyScript) &&
669
+ ![out.code, out.legacyTsCode, out.legacyCode, verifiedPage].some(code => code !== undefined && current === normalize(code))) {
670
+ return 'index.tsx';
671
+ }
672
+ if (!dryRun) {
673
+ if (out.events) writeIfChanged(extendsFile, out.events);
674
+ writeIfChanged(pageFile, out.code);
675
+ if (jsScript !== undefined) fs.unlinkSync(legacyJsFile);
676
+ if (tsScript !== undefined) fs.unlinkSync(legacyTsFile);
677
+ }
678
+ }
679
+ /** 定制组件语言包 → src/locales.ts(应用根目录,不塞进业务代码目录) */
680
+ export function emitCustomLocales(genRoot, roots = CUSTOM_ROOTS, codegenRoot = CODEGEN_ROOT, write = writeIfChanged) {
681
+ // 定制组件可能来自多个插件工程(iso-web 的 iso-custom、edoc2-frontend 的 ECM 插件),
682
+ // 所以按 registry 里的 CUSTOM_ROOTS 逐个扫描,import 前缀用各自包的别名。
683
+ // 写死一个根时,后接入的插件包词条会整批退化成 key(界面显示 i18n-xxxx)。
684
+ const entries = [];
685
+ const shared = [];
686
+ for (const root of roots) {
687
+ const componentsRoot = path.resolve(codegenRoot, root.rel);
688
+ if (!fs.existsSync(componentsRoot)) continue;
689
+
690
+ const walk = (dir) => {
691
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
692
+ const full = path.join(dir, e.name);
693
+ if (e.isDirectory()) {
694
+ walk(full);
695
+ continue;
696
+ }
697
+ if (e.name !== 'locale.ts' && e.name !== 'locale.tsx') continue;
698
+ const rel = full.slice(componentsRoot.length + 1).split(path.sep).join('/');
699
+ if (!/\/preview\/locale\.tsx?$/.test(rel)) continue;
700
+ const compName = rel.split('/').slice(0, -2).pop();
701
+ entries.push({ compName, importPath: root.importPrefix + '/' + rel.replace(/\.tsx?$/, '') });
702
+ }
703
+ };
704
+ walk(componentsRoot);
705
+
706
+ // Plugin packages can also ship standalone basic widgets alongside components/.
707
+ // Read their runtime catalogs from the same package, not from designer or runtime.
708
+ const packageRoot = path.dirname(componentsRoot);
709
+ const packageImport = path.posix.dirname(root.importPrefix);
710
+ if (fs.existsSync(path.join(packageRoot, 'locales.ts'))) {
711
+ shared.push(`${packageImport}/locales`);
712
+ }
713
+ const basicRoot = path.join(packageRoot, 'basic');
714
+ for (const grouping of ['', 'SyncComponents']) {
715
+ const dir = path.join(basicRoot, grouping);
716
+ if (!fs.existsSync(dir)) continue;
717
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
718
+ if (!entry.isDirectory() || /^SyncDesignerComponents$/i.test(entry.name)) continue;
719
+ const relative = ['basic', grouping, entry.name, 'locale'].filter(Boolean).join('/');
720
+ if (['.ts', '.tsx'].some(ext => fs.existsSync(path.join(packageRoot, relative + ext)))) {
721
+ entries.push({ compName: entry.name, importPath: `${packageImport}/${relative}` });
722
+ }
723
+ }
724
+ }
725
+ }
726
+ const catalogs = [
727
+ ...shared.map(importPath => ({ importPath })),
728
+ ...entries,
729
+ ];
730
+ const imports = catalogs.map(({ importPath }, i) => `import * as catalog${i} from ${JSON.stringify(importPath)};`).join('\n');
731
+ const manifest = catalogs.map(({ compName }, i) => ` [${JSON.stringify(compName) ?? 'undefined'}, catalog${i}],`).join('\n');
732
+ const code = `// Generated preview locale resources. Translations are owned by the component packages.
733
+ import type { PreviewCatalog } from '@macrowing/inbiz-runtime';
734
+ ${imports ? `${imports}\n` : ''}
735
+ export const customLocales: readonly PreviewCatalog[] = [
736
+ ${manifest ? `${manifest}\n` : ''}];
737
+ `;
738
+ write(path.join(genRoot, 'locales.ts'), code);
739
+ return { count: entries.length + shared.length };
740
+ }
741
+
742
+ /** 应用级扩展样式与脚本 */
743
+ export function renderAppExtends(extend, publishedPages) {
744
+ const keys = ['OnLoadBefore', 'OnLoaded'];
745
+ const scripts = keys.map((key) => compilePublishedPageLinks(extend?.[key] || '', publishedPages));
746
+ const urlImport = scripts.some((script, i) => script !== (extend?.[keys[i]] || '')) ? pageUrlImport : '';
747
+ return '// @ts-nocheck\n' + urlImport + keys.map((key, i) => {
748
+ const fnName = key === 'OnLoaded' ? 'onLoaded' : 'onLoadBefore';
749
+ const { body, globalsParam } = compilePublishedScript(scripts[i]);
750
+ return `export function ${fnName}(${globalsParam}) {\n const inbiz = window.inbizGlobal;\n${indent(body, 1)}\n}\n`;
751
+ }).join('\n');
752
+ }
753
+
754
+ function emitAppExtends(extend, genRoot, publishedPages, write) {
755
+ const css = (extend?.CssContent || '').trim();
756
+ write(path.join(genRoot, 'styles/app.css'), css ? css + '\n' : '/* 应用级自定义样式 */\n');
757
+
758
+ write(path.join(genRoot, 'app-extends.ts'), renderAppExtends(extend, publishedPages));
759
+ }
760
+
761
+ export async function generate({ webDir = WEB_DIR, dataDir = path.join(webDir, '.inbiz'), baselineDir } = {}) {
762
+ const genRoot = path.join(webDir, 'src');
763
+ const output = createGeneratedOutput(webDir);
764
+ const retire = new Map();
765
+ const legacy = new Map();
766
+ const relative = (file) => path.relative(webDir, file).split(path.sep).join('/');
767
+ const dataFile = path.join(dataDir, 'app.json');
768
+ if (!fs.existsSync(dataFile)) {
769
+ throw new Error('缺少 ' + dataFile + ',请先执行 inbiz-codegen pull');
770
+ }
771
+ const data = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
772
+ emitFavicon(data, genRoot, output.add, retire);
773
+ const pageFieldRefs = collectPageFieldRefs([
774
+ ...Object.values(data.extend ?? {}).filter(value => typeof value === 'string'),
775
+ ...(data.pages ?? []).flatMap(({ detail }) => PAGE_EVENTS.map(([key]) => detail?.[key])),
776
+ ]);
777
+ const publishedPages = {
778
+ domain: data.app?.Domain,
779
+ routes: new Set((data.pages || []).map((page) => page.detail?.Route || page.route)),
780
+ menuRoutes: new Set((data.menu || []).map((menu) => menu.Route)),
781
+ };
782
+ const contractsFile = path.join(dataDir, 'data-source-contracts.json');
783
+ const dataSourceContracts = fs.existsSync(contractsFile)
784
+ ? JSON.parse(fs.readFileSync(contractsFile, 'utf8'))
785
+ : undefined;
786
+
787
+ console.log('→ 扫描组件库 …');
788
+ const registry = scanComponents();
789
+ console.log(` ✓ 识别 ${registry.size} 个组件`);
790
+
791
+ const messages = data.language?.messages || {};
792
+ const layout = data.layout || {};
793
+ const layoutDir = path.join(genRoot, 'layout');
794
+
795
+ // 框架区域显隐:平台给的是三份原始数据 ——
796
+ // LayoutInfo 每个区域的 form['x-display'],为 true 表示全站隐藏;
797
+ // PageLayoutInfo 页面态(page/xxx)下,某路由额外要隐藏的区域;
798
+ // MenuLayoutInfo 菜单态(普通菜单路由)下,某路由额外要隐藏的区域。
799
+ // 这里**不把它们搬进产物**(那是「运行时读配置」),而是当场折算成
800
+ // 「每一页一个 hideLayout 数组」,随路由表一起写进 src/pages/routes.ts。
801
+ const rawLayoutFile = path.join(dataDir, 'layout.raw.json');
802
+ let layoutInfo = {};
803
+ let pageLayoutInfo = {};
804
+ let menuLayoutInfo = {};
805
+ if (fs.existsSync(rawLayoutFile)) {
806
+ const raw = JSON.parse(fs.readFileSync(rawLayoutFile, 'utf8'));
807
+ try {
808
+ layoutInfo = JSON.parse(raw.LayoutInfo || '{}');
809
+ } catch {
810
+ layoutInfo = {};
811
+ }
812
+ pageLayoutInfo = raw.PageLayoutInfo || {};
813
+ menuLayoutInfo = raw.MenuLayoutInfo || {};
814
+ }
815
+ // 旧产物清理:layout-info.ts 曾经把上面三份原始数据整个搬进运行时。
816
+ // 生成器只写不删的话,改完规则它还会留在产物里,用户看到的就是
817
+ // 「明明都出码了,怎么还有个配置文件」—— 显式删除才叫真的消灭它。
818
+ const legacyLayoutInfo = path.join(layoutDir, 'layout-info.ts');
819
+ if (fs.existsSync(legacyLayoutInfo)) retire.set(relative(legacyLayoutInfo), undefined);
820
+
821
+ /** 被按需加载的组件汇总:标识符 → { pages, reasons } */
822
+ const lazyReport = new Map();
823
+ const noteLazy = (out, where) => {
824
+ for (const [name, info] of out.lazy || []) {
825
+ const item = lazyReport.get(name) || { path: info.path, reasons: info.reasons, where: [] };
826
+ if (!item.where.includes(where)) item.where.push(where);
827
+ lazyReport.set(name, item);
828
+ }
829
+ };
830
+
831
+ const sections = [];
832
+ const allWarnings = [];
833
+ for (const key of Object.keys(layout)) {
834
+ const section = layout[key];
835
+ if (!section?.schema || !Object.keys(section.schema.properties || {}).length) continue;
836
+ const fixed = { ...section, schema: normalizeLinks(applyPlaceholders(section.schema, data.app?.Id)) };
837
+ const out = emitSection(key, fixed, registry, messages, { dataSourceContracts });
838
+ output.add(path.join(layoutDir, `${out.file}.tsx`), out.code);
839
+ if (out.config) output.add(path.join(layoutDir, `${out.file}-config.ts`), out.config);
840
+ sections.push(out);
841
+ allWarnings.push(...out.warnings.map((w) => `[${key}] ${w}`));
842
+ noteLazy(out, `layout/${key}`);
843
+ }
844
+ console.log(` ✓ 框架:${sections.map((s) => s.section).join(', ')}`);
845
+
846
+ output.add(path.join(layoutDir, 'index.tsx'), emitLayout(sections));
847
+
848
+ // 页面
849
+ const pagesDir = path.join(genRoot, 'pages');
850
+ // 内置页(平台产品自带、不在应用页面清单里的页面)与 app.json 的页面
851
+ // 走同一条产出管线:它们本来就是同一种东西 —— 一份页面 schema。
852
+ // 同名时以应用页面为准:应用里出现过同名页面,说明它已被定制,
853
+ // 再用产品副本覆盖会把客户的定制顶掉。
854
+ const appPageRoutes = new Set((data.pages || []).map((p) => p.detail?.Route || p.route));
855
+ const builtinPages = scanBuiltinPages().filter((p) => {
856
+ if (!appPageRoutes.has(p.route)) return true;
857
+ allWarnings.push(`[page:${p.route}] 应用页面清单里已有同名页面,忽略内置页副本`);
858
+ return false;
859
+ });
860
+ if (builtinPages.length) console.log(` · 内置页:${builtinPages.map((p) => p.route).join(', ')}`);
861
+
862
+ const pageIndex = [];
863
+ for (const page of [...(data.pages || []), ...builtinPages]) {
864
+ const out = emitPage(page, registry, messages, data.app?.Id, { dataSourceContracts, publishedPages, pageFieldRefs });
865
+ const { dir, compName, route, css, warnings, hasSchema } = out;
866
+ const pageDir = path.join(pagesDir, dir);
867
+ output.add(path.join(pageDir, 'index.tsx'), out.code);
868
+ legacy.set(relative(path.join(pageDir, 'index.tsx')), () => [out.legacyTsCode, out.legacyCode]);
869
+ if (out.events) output.add(path.join(pageDir, `${PAGE_EXTENDS_MODULE}.ts`), out.events);
870
+ if (out.config) output.add(path.join(pageDir, `${PAGE_CONFIG_MODULE}.ts`), out.config);
871
+ if (css) output.add(path.join(pageDir, 'index.css'), css);
872
+ retire.set(relative(path.join(pageDir, `${LEGACY_PAGE_EVENTS_MODULE}.js`)), out.legacyEvents);
873
+ retire.set(relative(path.join(pageDir, `${LEGACY_PAGE_EVENTS_MODULE}.ts`)), out.events);
874
+ pageIndex.push({
875
+ dir,
876
+ route,
877
+ compName,
878
+ ...(page.builtin ? { builtin: true, title: page.name } : {}),
879
+ });
880
+ if (!hasSchema) allWarnings.push(`[page:${page.route}] 未找到页面 schema`);
881
+ allWarnings.push(...warnings.map((w) => `[page:${page.route}] ${w}`));
882
+ noteLazy(out, page.route);
883
+ }
884
+ console.log(` ✓ 页面:${pageIndex.length} 个`);
885
+
886
+ if (lazyReport.size) {
887
+ console.log(` ✓ 按需加载:${lazyReport.size} 个重型组件`);
888
+ for (const [name, info] of lazyReport) {
889
+ const pages = info.where.length > 3
890
+ ? `${info.where.slice(0, 3).join(', ')} 等 ${info.where.length} 处`
891
+ : info.where.join(', ');
892
+ console.log(` ${name} ← ${info.reasons.join(';')}`);
893
+ console.log(` 用于 ${pages}`);
894
+ }
895
+ } else {
896
+ console.log(' · 无重型组件,全部静态导入');
897
+ }
898
+
899
+ // 路由表 = 页面清单 + 每页的框架显隐。全站默认在这里折算进每条路由,
900
+ // 产物只剩「页面 → 隐藏区域数组」这种业务可读的字面量。
901
+ const routes = buildPageRoutes(pageIndex, layoutInfo, pageLayoutInfo, menuLayoutInfo);
902
+ output.add(path.join(pagesDir, 'routes.ts'), renderPageRoutes(routes.pageIndex, routes.defaultHidden));
903
+
904
+ const locales = emitCustomLocales(genRoot, CUSTOM_ROOTS, CODEGEN_ROOT, output.add);
905
+ if (locales) console.log(` ✓ 定制组件语言包 ${locales.count} 个`);
906
+
907
+ emitAppExtends(data.extend || {}, genRoot, publishedPages, output.add);
908
+ output.commit({ retire, legacy, baselineDir });
909
+ console.log(' ✓ 应用级样式与脚本');
910
+
911
+ /**
912
+ * 后端初始化文件(Macrowing.Start/Init)。
913
+ *
914
+ * 与前端出码同源:都来自这次 pull 的数据,避免两边各维护一份菜单。
915
+ * 后端启动时把它打包导入平台 —— 全新环境创建、已有环境按 OutId 更新。
916
+ */
917
+ const endNames = { 0: 'web', 1: 'wap', 2: 'mgt' };
918
+ // A detached Web generation must not overwrite the shared backend scaffold.
919
+ const backendInit = path.resolve(webDir) === WEB_DIR && emitBackendInit({
920
+ codegenRoot: CODEGEN_ROOT,
921
+ snapshot: data,
922
+ end: endNames[Number(data.site?.SiteType ?? 0)] || 'web',
923
+ siteType: Number(data.site?.SiteType ?? 0),
924
+ });
925
+ if (backendInit?.written) {
926
+ console.log(` ✓ 后端初始化文件:${backendInit.menus} 条菜单 → ${backendInit.menusFile}`);
927
+ if (backendInit.warning) allWarnings.push(`[backend-init] ${backendInit.warning}`);
928
+ }
929
+
930
+ if (allWarnings.length) {
931
+ console.log('\n需要人工确认:');
932
+ for (const w of [...new Set(allWarnings)]) console.log(' ! ' + w);
933
+ }
934
+ console.log('\n生成完成。');
935
+ }