@fudanda/create-arcbase 2.20261026.1-beta.1 → 2.20261109.1-beta.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 (79) hide show
  1. package/.runtime/npm/index.json +18 -18
  2. package/.runtime/sdk.json +3 -3
  3. package/LICENSE +21 -21
  4. package/README.md +99 -91
  5. package/cli.mjs +42 -39
  6. package/package.json +10 -5
  7. package/src/assistant.mjs +76 -0
  8. package/src/delivery.mjs +20 -20
  9. package/src/enhance.mjs +103 -104
  10. package/src/evolve.mjs +66 -66
  11. package/src/fields.mjs +73 -73
  12. package/src/goa-contracts.mjs +331 -331
  13. package/src/goa.mjs +202 -202
  14. package/src/history.mjs +16 -16
  15. package/src/layout.mjs +1 -1
  16. package/src/module.mjs +439 -477
  17. package/src/packages.mjs +12 -4
  18. package/src/page-antd.mjs +98 -77
  19. package/src/page-webmcp.mjs +51 -0
  20. package/src/project.mjs +112 -105
  21. package/src/records.mjs +15 -15
  22. package/src/release-vite.mjs +1 -0
  23. package/src/release.mjs +455 -0
  24. package/src/templates.mjs +20 -20
  25. package/src/upgrade.mjs +415 -249
  26. package/templates/module/02-migrations.go.txt +10 -10
  27. package/templates/module/03-service.go.txt +52 -52
  28. package/templates/module/04-module.go.txt +12 -12
  29. package/templates/module/06-queries.ts.txt +15 -15
  30. package/templates/module/08-service_test.go.txt +9 -9
  31. package/templates/module/09-TransferPanel.tsx.txt +16 -0
  32. package/templates/module-runtime-test.go.txt +86 -86
  33. package/templates/module-transfer.go.txt +74 -74
  34. package/templates/project-v2/.agents/skills/arcbase/SKILL.md +32 -0
  35. package/templates/project-v2/.agents/skills/goa-service-designer/SKILL.md +31 -0
  36. package/templates/project-v2/AGENTS.md +38 -0
  37. package/templates/project-v2/DEVELOPMENT.md +115 -84
  38. package/templates/project-v2/README.md +76 -74
  39. package/templates/project-v2/RELEASE.md +88 -0
  40. package/templates/project-v2/TEAM-TRIAL.md +32 -32
  41. package/templates/project-v2/arcbase.release.json +23 -0
  42. package/templates/project-v2/cmd/server/main.go +62 -36
  43. package/templates/project-v2/cmd/server/modules.gen.go +6 -6
  44. package/templates/project-v2/eslint.config.mjs +9 -9
  45. package/templates/project-v2/internal/dashboard/dist/README.txt +1 -1
  46. package/templates/project-v2/internal/dashboard/embed.go +11 -11
  47. package/templates/project-v2/package.json +11 -4
  48. package/templates/project-v2/scripts/application-version.mjs +138 -0
  49. package/templates/project-v2/scripts/assets.mjs +13 -14
  50. package/templates/project-v2/scripts/build-backend.mjs +11 -9
  51. package/templates/project-v2/scripts/build.mjs +12 -0
  52. package/templates/project-v2/scripts/check-generated.mjs +79 -48
  53. package/templates/project-v2/scripts/config.mjs +55 -54
  54. package/templates/project-v2/scripts/dev-watch.mjs +78 -78
  55. package/templates/project-v2/scripts/dev.mjs +50 -49
  56. package/templates/project-v2/scripts/doctor.mjs +94 -94
  57. package/templates/project-v2/scripts/generate-contracts.mjs +88 -88
  58. package/templates/project-v2/scripts/go-build-identity/main.go +210 -0
  59. package/templates/project-v2/scripts/go.mjs +17 -15
  60. package/templates/project-v2/scripts/layout.mjs +10 -10
  61. package/templates/project-v2/scripts/lifecycle.mjs +245 -245
  62. package/templates/project-v2/scripts/openobserve-build.mjs +115 -0
  63. package/templates/project-v2/scripts/project-info.mjs +105 -0
  64. package/templates/project-v2/scripts/release-metadata.mjs +13 -0
  65. package/templates/project-v2/scripts/release-vite.mjs +23 -0
  66. package/templates/project-v2/scripts/release.mjs +3 -0
  67. package/templates/project-v2/scripts/run.mjs +11 -11
  68. package/templates/project-v2/scripts/sdk-integrity.mjs +39 -39
  69. package/templates/project-v2/scripts/setup.mjs +44 -44
  70. package/templates/project-v2/web/admin/index.html +5 -5
  71. package/templates/project-v2/web/admin/package.json +3 -2
  72. package/templates/project-v2/web/admin/src/brand.json +1 -1
  73. package/templates/project-v2/web/admin/src/extensions.gen.ts +6 -6
  74. package/templates/project-v2/web/admin/src/extensions.ts +1 -1
  75. package/templates/project-v2/web/admin/src/main.tsx +20 -14
  76. package/templates/project-v2/web/admin/tsconfig.json +17 -17
  77. package/templates/project-v2/web/admin/vite.config.ts +47 -27
  78. package/src/page.mjs +0 -66
  79. package/templates/module/07-Page.tsx.txt +0 -20
@@ -1,94 +1,94 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { resolve } from 'node:path';
3
- import { fileURLToPath, pathToFileURL } from 'node:url';
4
- import { spawnSync } from 'node:child_process';
5
- import { projectLayout } from './layout.mjs';
6
- import { hostPackageNames, sdkPackageNames, verifySDK } from './sdk-integrity.mjs';
7
-
8
- class DiagnosticError extends Error {
9
- constructor(code, message) { super(message); this.code = code; }
10
- }
11
- function failure(error) {
12
- // Only messages constructed here may enter the report. Tool output, JSON
13
- // parser messages and configuration exceptions can contain credentials.
14
- if (error instanceof DiagnosticError) return { code: error.code, reason: error.message };
15
- if (error?.code === 'ENOENT') return { code: 'FILE_MISSING', reason: '所需文件不存在。' };
16
- if (['EACCES', 'EPERM'].includes(error?.code)) return { code: 'ACCESS_DENIED', reason: '当前用户没有所需文件或目录的访问权限。' };
17
- return { code: 'INVALID_INPUT', reason: '文件格式、项目清单或配置校验失败。' };
18
- }
19
- export async function diagnoseProject(project, { database = false, probe = spawnSync } = {}) {
20
- const root = resolve(project), checks = [];
21
- function record(name, owner, action, next) {
22
- try { action(); checks.push({ name, owner, status: 'passed' }); }
23
- catch (error) { checks.push({ name, owner, status: 'failed', ...failure(error), next }); }
24
- }
25
- let manifest, layout, sdk, pkg;
26
- record('project', '业务项目', () => {
27
- manifest = JSON.parse(readFileSync(resolve(root, 'arcbase.project.json'), 'utf8'));
28
- layout = projectLayout(manifest);
29
- if (!['antd', 'semi'].includes(manifest.ui ?? 'antd')) throw new DiagnosticError('UI_UNSUPPORTED', '项目 UI 必须为 antd 或 semi。');
30
- pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
31
- }, '检查 arcbase.project.json 的 format、UI 和模块清单。');
32
- record('node', '开发环境', () => { if (Number(process.versions.node.split('.')[0]) !== 24) throw new DiagnosticError('NODE_VERSION', `当前 Node.js ${process.versions.node},项目要求 Node.js 24。`); }, '安装项目要求的 Node.js 24,重新执行 npm ci。');
33
- record('go', '开发环境', () => {
34
- const result = probe('go', ['version'], { cwd: root, encoding: 'utf8', windowsHide: true, timeout: 30000 });
35
- const version = /go1\.(\d+)\.(\d+)/.exec(result.stdout ?? '');
36
- if (result.error || result.status !== 0) throw new DiagnosticError('GO_UNAVAILABLE', '无法执行 go version;检查工具链安装和 PATH。');
37
- if (!version || Number(version[1]) < 27 || Number(version[1]) === 27 && Number(version[2]) < 3) throw new DiagnosticError('GO_VERSION', 'Go 版本低于 1.27.3,或版本输出无法识别。');
38
- }, '安装 Go 1.27.3 或项目 go.mod 要求的工具链,确认 go version 可执行。');
39
- if (layout && pkg) {
40
- record('sdk', 'ArcBase 核心维护者', () => {
41
- sdk = JSON.parse(readFileSync(resolve(root, layout.sdkMetadata), 'utf8'));
42
- try { verifySDK(resolve(root, layout.sdk), sdk); }
43
- catch { throw new DiagnosticError('SDK_CONTENT_MISMATCH', 'SDK 文件缺失、摘要不匹配或包含额外文件。'); }
44
- if (manifest.sdk?.version !== sdk.version || manifest.sdk?.sha256 !== sdk.sha256) throw new DiagnosticError('SDK_METADATA_MISMATCH', '项目清单与安装的 SDK 版本或摘要不一致。');
45
- }, '执行匹配版本的 create-arcbase upgrade --project . --check;保留修改过的 SDK 并交由核心维护者处理。');
46
- record('packages', '业务项目', () => {
47
- if (!sdk) throw new DiagnosticError('SDK_REQUIRED', '先解决 SDK 元数据检查失败,再检查 npm 包。');
48
- const declared = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].flatMap(group => Object.keys(pkg[group] ?? {})).filter(name => sdkPackageNames.includes(name));
49
- const names = new Set([...hostPackageNames(manifest.ui ?? 'antd'), ...declared]);
50
- for (const name of names) {
51
- const path = resolve(root, 'node_modules', name, 'package.json');
52
- if (!existsSync(path)) throw new DiagnosticError('PACKAGE_MISSING', `缺少 ${name},请安装项目依赖。`);
53
- const installed = JSON.parse(readFileSync(path, 'utf8'));
54
- const expected = ['dependencies','devDependencies','peerDependencies','optionalDependencies'].map(group=>pkg[group]?.[name]).find(Boolean) ?? manifest.packages?.[name] ?? sdk.version;
55
- if (installed.version !== expected) throw new DiagnosticError('PACKAGE_VERSION_MISMATCH', `${name} 的安装版本与项目声明不一致。`);
56
- }
57
- }, '运行 npm ci;SDK 包使用 package.json 中声明的精确版本;升级后检查客户端与 Go SDK 的契约兼容性。');
58
- let configuration;
59
- try { configuration = await import(pathToFileURL(resolve(root, 'scripts/config.mjs')).href); }
60
- catch (error) { checks.push({ name: 'configuration', owner: '业务项目', status: 'failed', ...failure(error), next: '检查 scripts/config.mjs 和项目清单;不要在问题报告中附上配置文件内容。' }); }
61
- if (configuration) {
62
- record('configuration', '业务项目', () => {
63
- const env = configuration.environment();
64
- try { configuration.urls(env); } catch { throw new DiagnosticError('LISTEN_ADDRESS_INVALID', 'ARCBASE_ADDR 不是有效监听地址。'); }
65
- if (!env.ARCBASE_DATABASE_URL || env.ARCBASE_DATABASE_URL.includes('CHANGE_ME')) throw new DiagnosticError('DATABASE_NOT_CONFIGURED', '数据库连接未配置,或仍使用初始化占位符。');
66
- if (!/^[a-fA-F0-9]{64}$/.test(env.ARCBASE_STORAGE_KEY ?? '')) throw new DiagnosticError('STORAGE_KEY_INVALID', '存储密钥必须为 64 位十六进制字符串。');
67
- }, '检查 configs/.local.env 或显式配置目录中的数据库、端口与存储密钥;运行时环境变量优先。');
68
- if (database) record('database-and-storage', '业务项目 / 运维', () => {
69
- if (!existsSync(configuration.executable)) throw new DiagnosticError('BINARY_MISSING', 'Go 宿主二进制不存在,请先构建项目。');
70
- const result = probe(configuration.executable, ['check'], { cwd: root, env: configuration.environment(), encoding: 'utf8', windowsHide: true, timeout: 30000 });
71
- if (result.error) throw new DiagnosticError(result.error.code === 'ETIMEDOUT' ? 'RUNTIME_CHECK_TIMEOUT' : 'BINARY_UNAVAILABLE', '宿主检查无法完成;检查二进制权限、连接超时和网络。');
72
- if (result.status !== 0) {
73
- const output = `${result.stderr ?? ''}\n${result.stdout ?? ''}`;
74
- if (/connection refused|dial tcp|no such host/i.test(output)) throw new DiagnosticError('DATABASE_UNREACHABLE', '宿主无法连接数据库;检查数据库服务、主机和端口。');
75
- if (/migration|schema.*version|migrate/i.test(output)) throw new DiagnosticError('MIGRATION_REQUIRED', '数据库或模块版本检查失败;按升级流程检查待执行迁移。');
76
- if (/permission denied|access.*denied/i.test(output)) throw new DiagnosticError('RUNTIME_ACCESS_DENIED', '数据库认证或文件目录访问被拒绝。');
77
- throw new DiagnosticError('RUNTIME_CHECK_FAILED', '宿主数据库、存储或模块检查失败;运行 check:database 查看本机详情。');
78
- }
79
- }, '运行 npm run check:database 查看数据库版本、目录权限和模块版本;首次初始化使用 npm run setup,已有实例按升级指南显式迁移。');
80
- }
81
- }
82
- return { project: root, ui: manifest?.ui ?? 'semi', sdkVersion: sdk?.version ?? null, ok: checks.every(check => check.status === 'passed'), checks };
83
- }
84
- if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
85
- const args = process.argv.slice(2);
86
- if (args.some(arg => !['--database', '--json'].includes(arg))) throw new Error('Use npm run doctor [-- --database --json]');
87
- const report = await diagnoseProject(resolve(import.meta.dirname, '..'), { database: args.includes('--database') });
88
- if (args.includes('--json')) console.log(JSON.stringify(report, null, 2));
89
- else {
90
- console.log(`ArcBase ${report.sdkVersion ?? 'unknown'} / ${report.ui}`);
91
- for (const check of report.checks) console.log(`${check.status === 'passed' ? 'PASS' : 'FAIL'} ${check.name} [${check.owner}]${check.reason ? '\n ' + check.code + ': ' + check.reason : ''}${check.next ? '\n ' + check.next : ''}`);
92
- }
93
- if (!report.ok) process.exitCode = 1;
94
- }
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { projectLayout } from './layout.mjs';
6
+ import { hostPackageNames, sdkPackageNames, verifySDK } from './sdk-integrity.mjs';
7
+
8
+ class DiagnosticError extends Error {
9
+ constructor(code, message) { super(message); this.code = code; }
10
+ }
11
+ function failure(error) {
12
+ // Only messages constructed here may enter the report. Tool output, JSON
13
+ // parser messages and configuration exceptions can contain credentials.
14
+ if (error instanceof DiagnosticError) return { code: error.code, reason: error.message };
15
+ if (error?.code === 'ENOENT') return { code: 'FILE_MISSING', reason: '所需文件不存在。' };
16
+ if (['EACCES', 'EPERM'].includes(error?.code)) return { code: 'ACCESS_DENIED', reason: '当前用户没有所需文件或目录的访问权限。' };
17
+ return { code: 'INVALID_INPUT', reason: '文件格式、项目清单或配置校验失败。' };
18
+ }
19
+ export async function diagnoseProject(project, { database = false, probe = spawnSync } = {}) {
20
+ const root = resolve(project), checks = [];
21
+ function record(name, owner, action, next) {
22
+ try { action(); checks.push({ name, owner, status: 'passed' }); }
23
+ catch (error) { checks.push({ name, owner, status: 'failed', ...failure(error), next }); }
24
+ }
25
+ let manifest, layout, sdk, pkg;
26
+ record('project', '业务项目', () => {
27
+ manifest = JSON.parse(readFileSync(resolve(root, 'arcbase.project.json'), 'utf8'));
28
+ layout = projectLayout(manifest);
29
+ if (manifest.ui !== 'antd') throw new DiagnosticError('UI_UNSUPPORTED', '当前分支只支持 Ant Design;Semi 项目请使用归档分支。');
30
+ pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
31
+ }, '检查 arcbase.project.json 的 format、UI 和模块清单。');
32
+ record('node', '开发环境', () => { if (Number(process.versions.node.split('.')[0]) !== 24) throw new DiagnosticError('NODE_VERSION', `当前 Node.js ${process.versions.node},项目要求 Node.js 24。`); }, '安装项目要求的 Node.js 24,重新执行 npm ci。');
33
+ record('go', '开发环境', () => {
34
+ const result = probe('go', ['version'], { cwd: root, encoding: 'utf8', windowsHide: true, timeout: 30000 });
35
+ const version = /go1\.(\d+)\.(\d+)/.exec(result.stdout ?? '');
36
+ if (result.error || result.status !== 0) throw new DiagnosticError('GO_UNAVAILABLE', '无法执行 go version;检查工具链安装和 PATH。');
37
+ if (!version || Number(version[1]) < 27 || Number(version[1]) === 27 && Number(version[2]) < 3) throw new DiagnosticError('GO_VERSION', 'Go 版本低于 1.27.3,或版本输出无法识别。');
38
+ }, '安装 Go 1.27.3 或项目 go.mod 要求的工具链,确认 go version 可执行。');
39
+ if (layout && pkg) {
40
+ record('sdk', 'ArcBase 核心维护者', () => {
41
+ sdk = JSON.parse(readFileSync(resolve(root, layout.sdkMetadata), 'utf8'));
42
+ try { verifySDK(resolve(root, layout.sdk), sdk); }
43
+ catch { throw new DiagnosticError('SDK_CONTENT_MISMATCH', 'SDK 文件缺失、摘要不匹配或包含额外文件。'); }
44
+ if (manifest.sdk?.version !== sdk.version || manifest.sdk?.sha256 !== sdk.sha256) throw new DiagnosticError('SDK_METADATA_MISMATCH', '项目清单与安装的 SDK 版本或摘要不一致。');
45
+ }, '执行匹配版本的 create-arcbase upgrade --project . --check;保留修改过的 SDK 并交由核心维护者处理。');
46
+ record('packages', '业务项目', () => {
47
+ if (!sdk) throw new DiagnosticError('SDK_REQUIRED', '先解决 SDK 元数据检查失败,再检查 npm 包。');
48
+ const declared = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].flatMap(group => Object.keys(pkg[group] ?? {})).filter(name => sdkPackageNames.includes(name));
49
+ const names = new Set([...hostPackageNames(manifest.ui ?? 'antd'), ...declared]);
50
+ for (const name of names) {
51
+ const path = resolve(root, 'node_modules', name, 'package.json');
52
+ if (!existsSync(path)) throw new DiagnosticError('PACKAGE_MISSING', `缺少 ${name},请安装项目依赖。`);
53
+ const installed = JSON.parse(readFileSync(path, 'utf8'));
54
+ const expected = ['dependencies','devDependencies','peerDependencies','optionalDependencies'].map(group=>pkg[group]?.[name]).find(Boolean) ?? manifest.packages?.[name] ?? sdk.version;
55
+ if (installed.version !== expected) throw new DiagnosticError('PACKAGE_VERSION_MISMATCH', `${name} 的安装版本与项目声明不一致。`);
56
+ }
57
+ }, '运行 npm ci;SDK 包使用 package.json 中声明的精确版本;升级后检查客户端与 Go SDK 的契约兼容性。');
58
+ let configuration;
59
+ try { configuration = await import(pathToFileURL(resolve(root, 'scripts/config.mjs')).href); }
60
+ catch (error) { checks.push({ name: 'configuration', owner: '业务项目', status: 'failed', ...failure(error), next: '检查 scripts/config.mjs 和项目清单;不要在问题报告中附上配置文件内容。' }); }
61
+ if (configuration) {
62
+ record('configuration', '业务项目', () => {
63
+ const env = configuration.environment();
64
+ try { configuration.urls(env); } catch { throw new DiagnosticError('LISTEN_ADDRESS_INVALID', 'ARCBASE_ADDR 不是有效监听地址。'); }
65
+ if (!env.ARCBASE_DATABASE_URL || env.ARCBASE_DATABASE_URL.includes('CHANGE_ME')) throw new DiagnosticError('DATABASE_NOT_CONFIGURED', '数据库连接未配置,或仍使用初始化占位符。');
66
+ if (!/^[a-fA-F0-9]{64}$/.test(env.ARCBASE_STORAGE_KEY ?? '')) throw new DiagnosticError('STORAGE_KEY_INVALID', '存储密钥必须为 64 位十六进制字符串。');
67
+ }, '检查 configs/.local.env 或显式配置目录中的数据库、端口与存储密钥;运行时环境变量优先。');
68
+ if (database) record('database-and-storage', '业务项目 / 运维', () => {
69
+ if (!existsSync(configuration.executable)) throw new DiagnosticError('BINARY_MISSING', 'Go 宿主二进制不存在,请先构建项目。');
70
+ const result = probe(configuration.executable, ['check'], { cwd: root, env: configuration.environment(), encoding: 'utf8', windowsHide: true, timeout: 30000 });
71
+ if (result.error) throw new DiagnosticError(result.error.code === 'ETIMEDOUT' ? 'RUNTIME_CHECK_TIMEOUT' : 'BINARY_UNAVAILABLE', '宿主检查无法完成;检查二进制权限、连接超时和网络。');
72
+ if (result.status !== 0) {
73
+ const output = `${result.stderr ?? ''}\n${result.stdout ?? ''}`;
74
+ if (/connection refused|dial tcp|no such host/i.test(output)) throw new DiagnosticError('DATABASE_UNREACHABLE', '宿主无法连接数据库;检查数据库服务、主机和端口。');
75
+ if (/migration|schema.*version|migrate/i.test(output)) throw new DiagnosticError('MIGRATION_REQUIRED', '数据库或模块版本检查失败;按升级流程检查待执行迁移。');
76
+ if (/permission denied|access.*denied/i.test(output)) throw new DiagnosticError('RUNTIME_ACCESS_DENIED', '数据库认证或文件目录访问被拒绝。');
77
+ throw new DiagnosticError('RUNTIME_CHECK_FAILED', '宿主数据库、存储或模块检查失败;运行 check:database 查看本机详情。');
78
+ }
79
+ }, '运行 npm run check:database 查看数据库版本、目录权限和模块版本;首次初始化使用 npm run setup,已有实例按升级指南显式迁移。');
80
+ }
81
+ }
82
+ return { project: root, ui: manifest?.ui ?? null, sdkVersion: sdk?.version ?? null, ok: checks.every(check => check.status === 'passed'), checks };
83
+ }
84
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
85
+ const args = process.argv.slice(2);
86
+ if (args.some(arg => !['--database', '--json'].includes(arg))) throw new Error('Use npm run doctor [-- --database --json]');
87
+ const report = await diagnoseProject(resolve(import.meta.dirname, '..'), { database: args.includes('--database') });
88
+ if (args.includes('--json')) console.log(JSON.stringify(report, null, 2));
89
+ else {
90
+ console.log(`ArcBase ${report.sdkVersion ?? 'unknown'} / ${report.ui}`);
91
+ for (const check of report.checks) console.log(`${check.status === 'passed' ? 'PASS' : 'FAIL'} ${check.name} [${check.owner}]${check.reason ? '\n ' + check.code + ': ' + check.reason : ''}${check.next ? '\n ' + check.next : ''}`);
92
+ }
93
+ if (!report.ok) process.exitCode = 1;
94
+ }
@@ -1,88 +1,88 @@
1
- import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
- import { createRequire } from 'node:module';
3
- import { dirname, isAbsolute, relative, resolve } from 'node:path';
4
- import { renderContracts } from '@fudanda/create-arcbase/goa-contracts';
5
- import { environment, go, layout, manifest, root, run } from './config.mjs';
6
-
7
- const check = process.argv.includes('--check');
8
- const owner = resolve(root, '.arcbase');
9
- owned(owner, root);
10
- mkdirSync(owner, { recursive: true });
11
- const work = mkdtempSync(resolve(owner, 'contracts-stage-'));
12
- const cleanupPath = relative(owner, work);
13
- if (isAbsolute(cleanupPath) || !cleanupPath.startsWith('contracts-stage-') || cleanupPath.includes('..') || cleanupPath.includes('/') || cleanupPath.includes('\\')) throw new Error('Invalid contract staging cleanup path');
14
- const normalize = path => readFileSync(path, 'utf8').replaceAll('\r\n', '\n');
15
- function owned(path, base) {
16
- const rel = relative(base, path);
17
- if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith('../') || rel.startsWith('..\\')) throw new Error('Contract output escaped its owner');
18
- let existing = path;
19
- while (!existsSync(existing)) existing = dirname(existing);
20
- if (lstatSync(existing).isSymbolicLink()) throw new Error('Contract output cannot traverse symbolic links');
21
- const actual = relative(realpathSync(base), realpathSync(existing));
22
- if (isAbsolute(actual) || actual === '..' || actual.startsWith('../') || actual.startsWith('..\\')) throw new Error('Contract output escaped its resolved owner');
23
- return path;
24
- }
25
- function files(folder, base = folder) {
26
- if (!existsSync(folder)) return [];
27
- return readdirSync(folder, { withFileTypes: true }).flatMap(item => {
28
- if (item.isSymbolicLink()) throw new Error('Contract output cannot traverse symbolic links');
29
- const path = resolve(folder, item.name);
30
- return item.isDirectory() ? files(path, base) : [relative(base, path).replaceAll('\\', '/')];
31
- });
32
- }
33
- function equal(actual, expected) {
34
- const names = new Set([...files(actual), ...files(expected)]);
35
- return [...names].every(name => existsSync(resolve(actual, name)) && existsSync(resolve(expected, name)) && normalize(resolve(actual, name)) === normalize(resolve(expected, name)));
36
- }
37
- const prepared = [];
38
- try {
39
- for (const module of manifest.modules) {
40
- const domain = owned(resolve(root, layout.domains, module.id), root);
41
- const output = owned(resolve(work, module.id), work);
42
- mkdirSync(output, { recursive: true });
43
- let mod = readFileSync(resolve(root, layout.goRoot, 'go.mod'), 'utf8');
44
- mod = mod.replace(/^module\s+\S+/m, `module ${manifest.backendModule}/internal/modules/${module.id}`);
45
- // The build utility runs in an isolated module and borrows the selected SDK
46
- // checkout. Neither generation nor its compile opens a business database.
47
- mod = mod.replace(/replace\s+github\.com\/fudanda\/arcbase\/backend\/v2\s+=>[^\r\n]+/, `replace github.com/fudanda/arcbase/backend/v2 => ${JSON.stringify(resolve(root, layout.sdk).replaceAll('\\', '/'))}`);
48
- writeFileSync(resolve(output, 'go.mod'), mod);
49
- if (existsSync(resolve(root, layout.goRoot, 'go.sum'))) cpSync(resolve(root, layout.goRoot, 'go.sum'), resolve(output, 'go.sum'));
50
- const entry = './' + relative(resolve(root, layout.goRoot), resolve(domain, 'cmd/contracts')).replaceAll('\\', '/');
51
- go(['run', entry, '-output', output], { generate: !check });
52
- run('go', ['test', '-p', '1', './gen/...'], { cwd: output, env: { ...environment(), GOWORK: 'off', GOFLAGS: '-mod=mod' } });
53
- const document = JSON.parse(readFileSync(resolve(output, 'gen/http/openapi3.json'), 'utf8'));
54
- const policies = JSON.parse(readFileSync(resolve(output, 'gen/arcbase/policies.json'), 'utf8'));
55
- const generatedTS = resolve(output, 'typescript');
56
- mkdirSync(generatedTS);
57
- for (const [name, source] of Object.entries(renderContracts(document, policies))) writeFileSync(owned(resolve(generatedTS, name), generatedTS), source);
58
- const require = createRequire(resolve(root, 'package.json'));
59
- run(process.execPath, [require.resolve('typescript/lib/tsc.js'), '--noEmit', '--strict', '--module', 'ESNext', '--moduleResolution', 'Bundler', '--target', 'ES2022', '--skipLibCheck', ...files(generatedTS).map(name => resolve(generatedTS, name))]);
60
- prepared.push({ domain, go: resolve(output, 'gen'), ts: generatedTS, targetTS: resolve(root, layout.pages, module.id, 'generated') });
61
- }
62
- if (check) {
63
- for (const entry of prepared) if (!equal(resolve(entry.domain, 'gen'), entry.go) || !equal(entry.targetTS, entry.ts)) throw new Error('Generated Goa contract drift; run npm run generate and review it');
64
- } else {
65
- const published = [];
66
- try {
67
- for (const entry of prepared) for (const [source, target] of [[entry.go, resolve(entry.domain, 'gen')], [entry.ts, entry.targetTS]]) {
68
- owned(target, root);
69
- const backup = resolve(work, `previous-${published.length}`);
70
- mkdirSync(resolve(target, '..'), { recursive: true });
71
- const existed = existsSync(target);
72
- if (existed) renameSync(target, backup);
73
- published.push({ target, backup, existed });
74
- renameSync(source, target);
75
- }
76
- } catch (error) {
77
- for (const entry of published.reverse()) {
78
- owned(entry.target, root);
79
- rmSync(entry.target, { recursive: true, force: true });
80
- if (entry.existed) renameSync(entry.backup, entry.target);
81
- }
82
- throw error;
83
- }
84
- }
85
- console.log(`Goa generated Go, embedded policy and strict TypeScript contracts ${check ? 'match' : 'published'} for ${prepared.length} modules.`);
86
- } finally {
87
- rmSync(work, { recursive: true, force: true });
88
- }
1
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
4
+ import { renderContracts } from '@fudanda/create-arcbase/goa-contracts';
5
+ import { environment, go, layout, manifest, root, run } from './config.mjs';
6
+
7
+ const check = process.argv.includes('--check');
8
+ const owner = resolve(root, '.arcbase');
9
+ owned(owner, root);
10
+ mkdirSync(owner, { recursive: true });
11
+ const work = mkdtempSync(resolve(owner, 'contracts-stage-'));
12
+ const cleanupPath = relative(owner, work);
13
+ if (isAbsolute(cleanupPath) || !cleanupPath.startsWith('contracts-stage-') || cleanupPath.includes('..') || cleanupPath.includes('/') || cleanupPath.includes('\\')) throw new Error('Invalid contract staging cleanup path');
14
+ const normalize = path => readFileSync(path, 'utf8').replaceAll('\r\n', '\n');
15
+ function owned(path, base) {
16
+ const rel = relative(base, path);
17
+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith('../') || rel.startsWith('..\\')) throw new Error('Contract output escaped its owner');
18
+ let existing = path;
19
+ while (!existsSync(existing)) existing = dirname(existing);
20
+ if (lstatSync(existing).isSymbolicLink()) throw new Error('Contract output cannot traverse symbolic links');
21
+ const actual = relative(realpathSync(base), realpathSync(existing));
22
+ if (isAbsolute(actual) || actual === '..' || actual.startsWith('../') || actual.startsWith('..\\')) throw new Error('Contract output escaped its resolved owner');
23
+ return path;
24
+ }
25
+ function files(folder, base = folder) {
26
+ if (!existsSync(folder)) return [];
27
+ return readdirSync(folder, { withFileTypes: true }).flatMap(item => {
28
+ if (item.isSymbolicLink()) throw new Error('Contract output cannot traverse symbolic links');
29
+ const path = resolve(folder, item.name);
30
+ return item.isDirectory() ? files(path, base) : [relative(base, path).replaceAll('\\', '/')];
31
+ });
32
+ }
33
+ function equal(actual, expected) {
34
+ const names = new Set([...files(actual), ...files(expected)]);
35
+ return [...names].every(name => existsSync(resolve(actual, name)) && existsSync(resolve(expected, name)) && normalize(resolve(actual, name)) === normalize(resolve(expected, name)));
36
+ }
37
+ const prepared = [];
38
+ try {
39
+ for (const module of manifest.modules) {
40
+ const domain = owned(resolve(root, layout.domains, module.id), root);
41
+ const output = owned(resolve(work, module.id), work);
42
+ mkdirSync(output, { recursive: true });
43
+ let mod = readFileSync(resolve(root, layout.goRoot, 'go.mod'), 'utf8');
44
+ mod = mod.replace(/^module\s+\S+/m, `module ${manifest.backendModule}/internal/modules/${module.id}`);
45
+ // The build utility runs in an isolated module and borrows the selected SDK
46
+ // checkout. Neither generation nor its compile opens a business database.
47
+ mod = mod.replace(/replace\s+github\.com\/fudanda\/arcbase\/backend\/v2\s+=>[^\r\n]+/, `replace github.com/fudanda/arcbase/backend/v2 => ${JSON.stringify(resolve(root, layout.sdk).replaceAll('\\', '/'))}`);
48
+ writeFileSync(resolve(output, 'go.mod'), mod);
49
+ if (existsSync(resolve(root, layout.goRoot, 'go.sum'))) cpSync(resolve(root, layout.goRoot, 'go.sum'), resolve(output, 'go.sum'));
50
+ const entry = './' + relative(resolve(root, layout.goRoot), resolve(domain, 'cmd/contracts')).replaceAll('\\', '/');
51
+ go(['run', entry, '-output', output], { generate: !check });
52
+ run('go', ['test', '-p', '1', './gen/...'], { cwd: output, env: { ...environment(), GOWORK: 'off', GOFLAGS: '-mod=mod' } });
53
+ const document = JSON.parse(readFileSync(resolve(output, 'gen/http/openapi3.json'), 'utf8'));
54
+ const policies = JSON.parse(readFileSync(resolve(output, 'gen/arcbase/policies.json'), 'utf8'));
55
+ const generatedTS = resolve(output, 'typescript');
56
+ mkdirSync(generatedTS);
57
+ for (const [name, source] of Object.entries(renderContracts(document, policies))) writeFileSync(owned(resolve(generatedTS, name), generatedTS), source);
58
+ const require = createRequire(resolve(root, 'package.json'));
59
+ run(process.execPath, [require.resolve('typescript/lib/tsc.js'), '--noEmit', '--strict', '--module', 'ESNext', '--moduleResolution', 'Bundler', '--target', 'ES2022', '--skipLibCheck', ...files(generatedTS).map(name => resolve(generatedTS, name))]);
60
+ prepared.push({ domain, go: resolve(output, 'gen'), ts: generatedTS, targetTS: resolve(root, layout.pages, module.id, 'generated') });
61
+ }
62
+ if (check) {
63
+ for (const entry of prepared) if (!equal(resolve(entry.domain, 'gen'), entry.go) || !equal(entry.targetTS, entry.ts)) throw new Error('Generated Goa contract drift; run npm run generate and review it');
64
+ } else {
65
+ const published = [];
66
+ try {
67
+ for (const entry of prepared) for (const [source, target] of [[entry.go, resolve(entry.domain, 'gen')], [entry.ts, entry.targetTS]]) {
68
+ owned(target, root);
69
+ const backup = resolve(work, `previous-${published.length}`);
70
+ mkdirSync(resolve(target, '..'), { recursive: true });
71
+ const existed = existsSync(target);
72
+ if (existed) renameSync(target, backup);
73
+ published.push({ target, backup, existed });
74
+ renameSync(source, target);
75
+ }
76
+ } catch (error) {
77
+ for (const entry of published.reverse()) {
78
+ owned(entry.target, root);
79
+ rmSync(entry.target, { recursive: true, force: true });
80
+ if (entry.existed) renameSync(entry.backup, entry.target);
81
+ }
82
+ throw error;
83
+ }
84
+ }
85
+ console.log(`Goa generated Go, embedded policy and strict TypeScript contracts ${check ? 'match' : 'published'} for ${prepared.length} modules.`);
86
+ } finally {
87
+ rmSync(work, { recursive: true, force: true });
88
+ }
@@ -0,0 +1,210 @@
1
+ // Command go-build-identity reads compiled Go string variables without executing a target binary.
2
+ package main
3
+
4
+ import (
5
+ "debug/elf"
6
+ "debug/macho"
7
+ "debug/pe"
8
+ "encoding/binary"
9
+ "encoding/json"
10
+ "errors"
11
+ "fmt"
12
+ "io"
13
+ "os"
14
+ "strings"
15
+ )
16
+
17
+ var names = []string{
18
+ "main.applicationName", "main.applicationVersion", "main.applicationCommit",
19
+ "main.applicationBuildTime", "main.applicationReleaseID",
20
+ "github.com/fudanda/arcbase/backend/v2.Version", "github.com/fudanda/arcbase/backend/v2.Commit",
21
+ "github.com/fudanda/arcbase/backend/v2.BuildTime",
22
+ }
23
+
24
+ type image struct {
25
+ order binary.ByteOrder
26
+ pointer int
27
+ symbols map[string]uint64
28
+ read func(uint64, uint64) ([]byte, error)
29
+ close func() error
30
+ }
31
+
32
+ // Go's string header is a pointer and a length, including zero-filled BSS values.
33
+ func (i *image) stringValue(address uint64) (string, error) {
34
+ header, err := i.read(address, uint64(2*i.pointer))
35
+ if err != nil {
36
+ return "", err
37
+ }
38
+ word := func(bytes []byte) uint64 {
39
+ if i.pointer == 8 {
40
+ return i.order.Uint64(bytes)
41
+ }
42
+ return uint64(i.order.Uint32(bytes))
43
+ }
44
+ data, length := word(header), word(header[i.pointer:])
45
+ if length > 4096 {
46
+ return "", errors.New("compiled identity string exceeds the metadata limit")
47
+ }
48
+ if length == 0 {
49
+ return "", nil
50
+ }
51
+ bytes, err := i.read(data, length)
52
+ return string(bytes), err
53
+ }
54
+
55
+ // readSegment maps a virtual address to file bytes, with bounded zero-fill support.
56
+ func readSegment(file io.ReaderAt, address, length, start, memorySize, offset, fileSize uint64) ([]byte, bool, error) {
57
+ if address < start || length > 8192 || address-start > memorySize || length > memorySize-(address-start) {
58
+ return nil, false, nil
59
+ }
60
+ result := make([]byte, length)
61
+ relative := address - start
62
+ if relative < fileSize {
63
+ size := length
64
+ if size > fileSize-relative {
65
+ size = fileSize - relative
66
+ }
67
+ if relative > uint64(^uint64(0)>>1) || offset > uint64(^uint64(0)>>1)-relative {
68
+ return nil, true, errors.New("invalid binary file offset")
69
+ }
70
+ if _, err := file.ReadAt(result[:size], int64(offset+relative)); err != nil {
71
+ return nil, true, err
72
+ }
73
+ }
74
+ return result, true, nil
75
+ }
76
+
77
+ func openImage(path string) (*image, error) {
78
+ file, err := os.Open(path)
79
+ if err != nil {
80
+ return nil, err
81
+ }
82
+ var magic [4]byte
83
+ if _, err := file.ReadAt(magic[:], 0); err != nil {
84
+ file.Close()
85
+ return nil, err
86
+ }
87
+ i := &image{symbols: map[string]uint64{}, close: file.Close}
88
+ failed := func(err error) (*image, error) { file.Close(); return nil, err }
89
+ switch {
90
+ case magic == [4]byte{0x7f, 'E', 'L', 'F'}:
91
+ value, err := elf.NewFile(file)
92
+ if err != nil {
93
+ return failed(err)
94
+ }
95
+ i.order, i.pointer = value.ByteOrder, 4
96
+ if value.Class == elf.ELFCLASS64 {
97
+ i.pointer = 8
98
+ }
99
+ symbols, err := value.Symbols()
100
+ if err != nil {
101
+ return failed(fmt.Errorf("Go identity symbols are unavailable; retain the symbol table (do not use -s): %w", err))
102
+ }
103
+ for _, symbol := range symbols {
104
+ i.symbols[symbol.Name] = symbol.Value
105
+ }
106
+ i.read = func(address, length uint64) ([]byte, error) {
107
+ for _, program := range value.Progs {
108
+ if program.Type != elf.PT_LOAD {
109
+ continue
110
+ }
111
+ if bytes, found, err := readSegment(file, address, length, program.Vaddr, program.Memsz, program.Off, program.Filesz); found {
112
+ return bytes, err
113
+ }
114
+ }
115
+ return nil, errors.New("identity points outside ELF load segments")
116
+ }
117
+ case magic[0] == 'M' && magic[1] == 'Z':
118
+ value, err := pe.NewFile(file)
119
+ if err != nil {
120
+ return failed(err)
121
+ }
122
+ i.order = binary.LittleEndian
123
+ var base uint64
124
+ switch optional := value.OptionalHeader.(type) {
125
+ case *pe.OptionalHeader64:
126
+ base, i.pointer = optional.ImageBase, 8
127
+ case *pe.OptionalHeader32:
128
+ base, i.pointer = uint64(optional.ImageBase), 4
129
+ default:
130
+ return failed(errors.New("unsupported PE optional header"))
131
+ }
132
+ for _, symbol := range value.Symbols {
133
+ if symbol.SectionNumber > 0 && int(symbol.SectionNumber) <= len(value.Sections) {
134
+ section := value.Sections[symbol.SectionNumber-1]
135
+ i.symbols[symbol.Name] = base + uint64(section.VirtualAddress) + uint64(symbol.Value)
136
+ }
137
+ }
138
+ i.read = func(address, length uint64) ([]byte, error) {
139
+ for _, section := range value.Sections {
140
+ memorySize := max(section.VirtualSize, section.Size)
141
+ if bytes, found, err := readSegment(file, address, length, base+uint64(section.VirtualAddress), uint64(memorySize), uint64(section.Offset), uint64(section.Size)); found {
142
+ return bytes, err
143
+ }
144
+ }
145
+ return nil, errors.New("identity points outside PE sections")
146
+ }
147
+ default:
148
+ value, err := macho.NewFile(file)
149
+ if err != nil {
150
+ return failed(fmt.Errorf("unsupported binary format: %w", err))
151
+ }
152
+ i.order, i.pointer = value.ByteOrder, 4
153
+ if value.Magic == macho.Magic64 {
154
+ i.pointer = 8
155
+ }
156
+ if value.Symtab == nil {
157
+ return failed(errors.New("Go identity symbols are unavailable; retain the symbol table (do not use -s)"))
158
+ }
159
+ for _, symbol := range value.Symtab.Syms {
160
+ i.symbols[strings.TrimPrefix(symbol.Name, "_")] = symbol.Value
161
+ }
162
+ i.read = func(address, length uint64) ([]byte, error) {
163
+ for _, load := range value.Loads {
164
+ if segment, ok := load.(*macho.Segment); ok {
165
+ if bytes, found, err := readSegment(file, address, length, segment.Addr, segment.Memsz, segment.Offset, segment.Filesz); found {
166
+ return bytes, err
167
+ }
168
+ }
169
+ }
170
+ return nil, errors.New("identity points outside Mach-O segments")
171
+ }
172
+ }
173
+ return i, nil
174
+ }
175
+
176
+ func inspect(path string) (map[string]string, error) {
177
+ image, err := openImage(path)
178
+ if err != nil {
179
+ return nil, err
180
+ }
181
+ defer image.close()
182
+ result := map[string]string{}
183
+ for _, name := range names {
184
+ address, ok := image.symbols[name]
185
+ if !ok {
186
+ return nil, fmt.Errorf("required Go identity symbol %s is unavailable; retain symbols (do not use -s)", name)
187
+ }
188
+ result[name], err = image.stringValue(address)
189
+ if err != nil {
190
+ return nil, fmt.Errorf("read %s: %w", name, err)
191
+ }
192
+ }
193
+ return result, nil
194
+ }
195
+
196
+ func main() {
197
+ if len(os.Args) != 2 {
198
+ fmt.Fprintln(os.Stderr, "usage: go-build-identity BINARY")
199
+ os.Exit(1)
200
+ }
201
+ values, err := inspect(os.Args[1])
202
+ if err != nil {
203
+ fmt.Fprintln(os.Stderr, err)
204
+ os.Exit(1)
205
+ }
206
+ if err := json.NewEncoder(os.Stdout).Encode(values); err != nil {
207
+ fmt.Fprintln(os.Stderr, err)
208
+ os.Exit(1)
209
+ }
210
+ }
@@ -1,15 +1,17 @@
1
- import { existsSync, readdirSync } from 'node:fs';
2
- import { relative, resolve } from 'node:path';
3
- import { go, layout, root, run } from './config.mjs';
4
-
5
- const [command = 'serve', ...args] = process.argv.slice(2);
6
- if (command === 'generate') {
7
- const schema = resolve(root, layout.ent, 'schema');
8
- if (existsSync(schema) && readdirSync(schema).some(file => file.endsWith('.go'))) {
9
- go(['run', 'entgo.io/ent/cmd/ent', 'generate', './' + relative(resolve(root, layout.goRoot), schema).replaceAll('\\', '/')], { generate: true });
10
- }
11
- run(process.execPath, ['scripts/generate-contracts.mjs']);
12
- go(['mod', 'tidy'], { generate: true });
13
- go(['fmt', './cmd/...', './internal/...']);
14
- } else if (command === 'test') go(['test', './cmd/...', './internal/...', ...args]);
15
- else go(['run', layout.goEntry, command, ...args]);
1
+ import { existsSync, readdirSync } from 'node:fs';
2
+ import { relative, resolve } from 'node:path';
3
+ import { go, layout, root, run } from './config.mjs';
4
+ import { applicationBuildInfo, applicationGoFlags, readSDKMetadata } from './application-version.mjs';
5
+ import { directGoDependencies } from './project-info.mjs';
6
+
7
+ const [command = 'serve', ...args] = process.argv.slice(2);
8
+ if (command === 'generate') {
9
+ const schema = resolve(root, layout.ent, 'schema');
10
+ if (existsSync(schema) && readdirSync(schema).some(file => file.endsWith('.go'))) {
11
+ go(['run', 'entgo.io/ent/cmd/ent', 'generate', './' + relative(resolve(root, layout.goRoot), schema).replaceAll('\\', '/')], { generate: true });
12
+ }
13
+ run(process.execPath, ['scripts/generate-contracts.mjs']);
14
+ go(['mod', 'tidy'], { generate: true });
15
+ go(['fmt', './cmd/...', './internal/...']);
16
+ } else if (command === 'test') go(['test', './cmd/...', './internal/...', ...args]);
17
+ else go(['run', '-ldflags', applicationGoFlags(applicationBuildInfo(root), readSDKMetadata(root), directGoDependencies(root)), layout.goEntry, command, ...args]);