@fudanda/create-arcbase 2.20261024.1-beta.2 → 2.20261107.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 +58 -53
  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 -11
  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,48 +1,79 @@
1
- import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
2
- import { isAbsolute, relative, resolve } from 'node:path';
3
- import { tmpdir } from 'node:os';
4
- import { spawnSync } from 'node:child_process';
5
- import { layout, manifest, root } from './config.mjs';
6
-
7
- const temporaryRoot = resolve(tmpdir());
8
- const work = mkdtempSync(resolve(temporaryRoot, 'arcbase-generated-check-'));
9
- const normalized = path => readFileSync(path, 'utf8').replaceAll('\r\n', '\n');
10
- const generatedRoots = [layout.ent, ...manifest.modules.flatMap(module => [`${layout.domains}/${module.id}/gen`,`${layout.pages}/${module.id}/generated`])];
11
- function sources(directory, base = directory) {
12
- if (!existsSync(directory)) return [];
13
- return readdirSync(directory, { withFileTypes: true }).flatMap(item => {
14
- const path = resolve(directory, item.name);
15
- if (item.isSymbolicLink()) throw new Error('Generated sources must not use symbolic links');
16
- return item.isDirectory() ? sources(path, base) : [relative(base, path).replaceAll('\\', '/')];
17
- });
18
- }
19
- try {
20
- if (!existsSync(resolve(root, 'node_modules'))) throw new Error('Run npm ci before checking generated code');
21
- cpSync(root, work, { recursive: true, filter: source => {
22
- const path = relative(root, source).replaceAll('\\', '/');
23
- if (/^(node_modules|build|var|backups|\.git)(\/|$)|^\.arcbase\/(npm|runtime|upgrades|module-plans)(\/|$)|^web\/admin\/public(\/|$)|^internal\/dashboard\/dist(\/|$)/.test(path)) return false;
24
- if (/(^|\/)\.env(?:\.|$)|^configs\/\.[^/]*\.env$|\.(db|dump|log|exe)$/.test(path)) return false;
25
- if (lstatSync(source).isSymbolicLink()) throw new Error('Project source must not traverse symbolic links');
26
- return true;
27
- } });
28
- mkdirSync(resolve(work, layout.dashboard), { recursive: true });
29
- writeFileSync(resolve(work, layout.dashboard, 'README.txt'), 'Isolated generated-code check.\n');
30
- symlinkSync(resolve(root, 'node_modules'), resolve(work, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');
31
- const result = spawnSync(process.execPath, ['scripts/go.mjs', 'generate'], { cwd: work, env: { ...process.env, GOWORK: 'off' }, encoding: 'utf8', windowsHide: true });
32
- if (result.error) throw result.error;
33
- if (result.status !== 0) throw new Error('Generated-code check could not run in its isolated copy; run npm run generate to inspect the generator error');
34
- const paths = new Set(['go.mod', 'go.sum']);
35
- for (const directory of generatedRoots) for (const name of [...sources(resolve(root, directory)), ...sources(resolve(work, directory))]) paths.add(`${directory}/${name}`);
36
- const drift = [...paths].filter(path => !existsSync(resolve(root, path)) || !existsSync(resolve(work, path)) || normalized(resolve(root, path)) !== normalized(resolve(work, path)));
37
- if (drift.length) throw new Error(`Generated-code drift: ${drift.join(', ')}. Run npm run generate and review the changes.`);
38
- console.log('Ent, Goa Go/TypeScript/policy and Go dependency manifests match explicit generation; project source was not rewritten.');
39
- } catch (error) {
40
- console.error(error.message);
41
- process.exitCode = 1;
42
- } finally {
43
- const owned = relative(temporaryRoot, work);
44
- if (isAbsolute(owned) || owned.startsWith('..') || !owned.startsWith('arcbase-generated-check-')) {
45
- console.error('Invalid generated-check cleanup target');
46
- process.exitCode = 1;
47
- } else rmSync(work, { recursive: true, force: true });
48
- }
1
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
2
+ import { isAbsolute, relative, resolve } from 'node:path';
3
+ import { tmpdir } from 'node:os';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { layout, manifest, root } from './config.mjs';
6
+
7
+ const temporaryRoot = resolve(tmpdir());
8
+ const work = mkdtempSync(resolve(temporaryRoot, 'arcbase-generated-check-'));
9
+ const normalized = path => readFileSync(path, 'utf8').replaceAll('\r\n', '\n');
10
+ const generatedRoots = [layout.ent, ...manifest.modules.flatMap(module => [`${layout.domains}/${module.id}/gen`,`${layout.pages}/${module.id}/generated`])];
11
+ function sources(directory, base = directory) {
12
+ if (!existsSync(directory)) return [];
13
+ return readdirSync(directory, { withFileTypes: true }).flatMap(item => {
14
+ const path = resolve(directory, item.name);
15
+ if (item.isSymbolicLink()) throw new Error('Generated sources must not use symbolic links');
16
+ return item.isDirectory() ? sources(path, base) : [relative(base, path).replaceAll('\\', '/')];
17
+ });
18
+ }
19
+ function diagnosticText(value) {
20
+ for (const [key, secret] of Object.entries(process.env)) {
21
+ if (/PASSWORD|SECRET|TOKEN|(?:^|_)KEY$/.test(key) && secret && secret.length >= 8) value = value.replaceAll(secret, '[redacted]');
22
+ }
23
+ return value
24
+ .replace(/\b((?:postgres(?:ql)?|https?):\/\/)[^\s/@:]+:[^\s/@]+@/gi, '$1[redacted]@')
25
+ .replace(/(ARCBASE_[A-Z_]*(?:PASSWORD|SECRET|TOKEN|KEY)\s*=)[^\r\n]*/g, '$1[redacted]')
26
+ .replace(/("(?:password|csrfToken|accessToken|clientSecret|storageKey)"\s*:\s*")[^"]*/gi, '$1[redacted]')
27
+ .replace(/((?:Authorization|Cookie|Set-Cookie):\s*)[^\r\n]*/gi, '$1[redacted]');
28
+ }
29
+ function describeDifference(path) {
30
+ const lines = base => existsSync(resolve(base, path)) ? normalized(resolve(base, path)).split('\n') : [];
31
+ const before = lines(root), after = lines(work);
32
+ let line = 0;
33
+ while (line < Math.max(before.length, after.length) && before[line] === after[line]) line++;
34
+ let column = 0;
35
+ while (column < Math.min(before[line]?.length ?? 0, after[line]?.length ?? 0) && before[line][column] === after[line][column]) column++;
36
+ console.error(`First generated difference: ${path}:${line + 1} (column ${column + 1})`);
37
+ for (const [label, values] of [['source', before], ['regenerated', after]]) {
38
+ for (let index = Math.max(0, line - 1); index <= Math.min(line + 1, Math.max(before.length, after.length) - 1); index++) {
39
+ const value = diagnosticText(values[index] ?? '<missing>');
40
+ const start = index === line ? Math.max(0, column - 80) : 0;
41
+ const excerpt = (start ? '…' : '') + value.slice(start, start + 240) + (value.length > start + 240 ? '…' : '');
42
+ console.error(`${label} ${index + 1}: ${JSON.stringify(excerpt)}`);
43
+ }
44
+ }
45
+ }
46
+ try {
47
+ if (!existsSync(resolve(root, 'node_modules'))) throw new Error('Run npm ci before checking generated code');
48
+ cpSync(root, work, { recursive: true, filter: source => {
49
+ const path = relative(root, source).replaceAll('\\', '/');
50
+ if (/^(node_modules|build|var|backups|\.git)(\/|$)|^\.arcbase\/(npm|runtime|upgrades|module-plans)(\/|$)|^web\/admin\/public(\/|$)|^internal\/dashboard\/dist(\/|$)/.test(path)) return false;
51
+ if (/(^|\/)\.env(?:\.|$)|^configs\/\.[^/]*\.env$|\.(db|dump|log|exe)$/.test(path)) return false;
52
+ if (lstatSync(source).isSymbolicLink()) throw new Error('Project source must not traverse symbolic links');
53
+ return true;
54
+ } });
55
+ mkdirSync(resolve(work, layout.dashboard), { recursive: true });
56
+ writeFileSync(resolve(work, layout.dashboard, 'README.txt'), 'Isolated generated-code check.\n');
57
+ symlinkSync(resolve(root, 'node_modules'), resolve(work, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');
58
+ const result = spawnSync(process.execPath, ['scripts/go.mjs', 'generate'], { cwd: work, env: { ...process.env, GOWORK: 'off' }, encoding: 'utf8', windowsHide: true });
59
+ if (result.error) throw result.error;
60
+ if (result.status !== 0) throw new Error('Generated-code check could not run in its isolated copy; run npm run generate to inspect the generator error');
61
+ const paths = new Set(['go.mod', 'go.sum']);
62
+ for (const directory of generatedRoots) for (const name of [...sources(resolve(root, directory)), ...sources(resolve(work, directory))]) paths.add(`${directory}/${name}`);
63
+ const drift = [...paths].filter(path => !existsSync(resolve(root, path)) || !existsSync(resolve(work, path)) || normalized(resolve(root, path)) !== normalized(resolve(work, path)));
64
+ if (drift.length) {
65
+ const generated = drift.find(path => /\.(?:go|tsx?)$/.test(path) && generatedRoots.some(directory => path.startsWith(directory + '/')));
66
+ if (generated) describeDifference(generated);
67
+ throw new Error(`Generated-code drift: ${drift.join(', ')}. Run npm run generate and review the changes.`);
68
+ }
69
+ console.log('Ent, Goa Go/TypeScript/policy and Go dependency manifests match explicit generation; project source was not rewritten.');
70
+ } catch (error) {
71
+ console.error(error.message);
72
+ process.exitCode = 1;
73
+ } finally {
74
+ const owned = relative(temporaryRoot, work);
75
+ if (isAbsolute(owned) || owned.startsWith('..') || !owned.startsWith('arcbase-generated-check-')) {
76
+ console.error('Invalid generated-check cleanup target');
77
+ process.exitCode = 1;
78
+ } else rmSync(work, { recursive: true, force: true });
79
+ }
@@ -1,54 +1,55 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
- import { createRequire } from 'node:module';
3
- import { dirname, resolve } from 'node:path';
4
- import { spawnSync } from 'node:child_process';
5
- import { parseEnv } from 'node:util';
6
- import { projectLayout } from './layout.mjs';
7
-
8
- export const root = resolve(import.meta.dirname, '..');
9
- export const require = createRequire(resolve(root, 'package.json'));
10
- export const manifest = JSON.parse(readFileSync(resolve(root, 'arcbase.project.json'), 'utf8'));
11
- export const layout = projectLayout(manifest);
12
- const profile = process.env.APP_ENV || 'local';
13
- if (!/^[a-zA-Z0-9_-]+$/.test(profile)) throw new Error('APP_ENV is invalid');
14
- const profiles = resolve(root, 'configs');
15
- const hasProfiles = existsSync(resolve(profiles, '.env')) || existsSync(resolve(profiles, `.${profile}.env`));
16
- const configFolder = resolve(root, process.env.ARCBASE_CONFIG_DIR || (!hasProfiles && existsSync(resolve(root, '.env')) ? '.' : 'configs'));
17
- export const envFile = resolve(configFolder, `.${profile}.env`);
18
- export const executable = resolve(root, layout.binary + (process.platform === 'win32' ? '.exe' : ''));
19
- /** @returns {Record<string, string | undefined>} */
20
- export function environment() {
21
- const files = {};
22
- for (const path of [resolve(configFolder, '.env'), envFile]) {
23
- if (existsSync(path)) Object.assign(files, parseEnv(readFileSync(path, 'utf8')));
24
- }
25
- return { ...files, ...process.env, ARCBASE_CONFIG_DIR: configFolder };
26
- }
27
- export function urls(env = environment()) {
28
- let address = env.ARCBASE_ADDR || ':8000';
29
- if (address.startsWith(':')) address = '127.0.0.1' + address;
30
- const explicitPort = address.match(/:([0-9]+)$/)?.[1];
31
- const url = new URL('http://' + address);
32
- if (!explicitPort || Number(explicitPort) < 1 || Number(explicitPort) > 65535 || url.username || url.password || url.pathname !== '/' || url.search || url.hash) throw new Error('ARCBASE_ADDR must be HOST:PORT');
33
- if (url.hostname === '0.0.0.0' || url.hostname === '[::]') url.hostname = '127.0.0.1';
34
- return { api: url.origin, login: url.origin + '/dash/login', development: `http://127.0.0.1:${manifest.developmentPort ?? 5373}/dash/` };
35
- }
36
- export function run(command, args, options = {}) {
37
- const result = spawnSync(command, args, { cwd: root, env: environment(), stdio: 'inherit', windowsHide: true, ...options });
38
- if (result.error) throw result.error;
39
- if (result.status !== 0 && !options.allowFailure) throw new Error(`${command === process.execPath ? 'npm' : command} failed (${result.status ?? 'signal'})`);
40
- return result;
41
- }
42
- export function npm(args) {
43
- if (!process.env.npm_execpath) throw new Error('Use the npm scripts for this command');
44
- return run(process.execPath, [process.env.npm_execpath, ...args]);
45
- }
46
- export function go(args, { generate = false } = {}) {
47
- const boundary = resolve(root, 'node_modules/go.mod');
48
- if (existsSync(dirname(boundary)) && !existsSync(boundary)) writeFileSync(boundary, 'module example.org/arcbase-npm-dependencies\n\ngo 1.27.3\n');
49
- const env = environment();
50
- return run('go', args, { cwd: resolve(root, layout.goRoot), env: { ...env, GOWORK: 'off', GOFLAGS: `${env.GOFLAGS ?? ''} -mod=${generate ? 'mod' : 'readonly'}`.trim() } });
51
- }
52
- export function prepareDirectories(env = environment()) {
53
- if (env.ARCBASE_FILE_STAGING_PATH) mkdirSync(resolve(root, env.ARCBASE_FILE_STAGING_PATH), { recursive: true });
54
- }
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { parseEnv } from 'node:util';
6
+ import { projectLayout } from './layout.mjs';
7
+
8
+ export const root = resolve(import.meta.dirname, '..');
9
+ export const require = createRequire(resolve(root, 'package.json'));
10
+ export const manifest = JSON.parse(readFileSync(resolve(root, 'arcbase.project.json'), 'utf8'));
11
+ export const layout = projectLayout(manifest);
12
+ const profile = process.env.APP_ENV || 'local';
13
+ if (!/^[a-zA-Z0-9_-]+$/.test(profile)) throw new Error('APP_ENV is invalid');
14
+ const profiles = resolve(root, 'configs');
15
+ const hasProfiles = existsSync(resolve(profiles, '.env')) || existsSync(resolve(profiles, `.${profile}.env`));
16
+ const configFolder = resolve(root, process.env.ARCBASE_CONFIG_DIR || (!hasProfiles && existsSync(resolve(root, '.env')) ? '.' : 'configs'));
17
+ export const envFile = resolve(configFolder, `.${profile}.env`);
18
+ export const executable = resolve(root, layout.binary + (process.platform === 'win32' ? '.exe' : ''));
19
+ /** @returns {Record<string, string | undefined>} */
20
+ export function environment() {
21
+ const files = {};
22
+ for (const path of [resolve(configFolder, '.env'), envFile]) {
23
+ if (existsSync(path)) Object.assign(files, parseEnv(readFileSync(path, 'utf8')));
24
+ }
25
+ return { ...files, ...process.env, ARCBASE_CONFIG_DIR: configFolder };
26
+ }
27
+ export function urls(env = environment()) {
28
+ let address = env.ARCBASE_ADDR || ':8000';
29
+ if (address.startsWith(':')) address = '127.0.0.1' + address;
30
+ const explicitPort = address.match(/:([0-9]+)$/)?.[1];
31
+ const url = new URL('http://' + address);
32
+ if (!explicitPort || Number(explicitPort) < 1 || Number(explicitPort) > 65535 || url.username || url.password || url.pathname !== '/' || url.search || url.hash) throw new Error('ARCBASE_ADDR must be HOST:PORT');
33
+ if (url.hostname === '0.0.0.0' || url.hostname === '[::]') url.hostname = '127.0.0.1';
34
+ return { api: url.origin, login: url.origin + '/dash/login', development: `http://127.0.0.1:${manifest.developmentPort ?? 5373}/dash/` };
35
+ }
36
+ export function run(command, args, options = {}) {
37
+ const result = spawnSync(command, args, { cwd: root, env: environment(), stdio: 'inherit', windowsHide: true, ...options });
38
+ if (result.error) throw result.error;
39
+ if (result.status !== 0 && !options.allowFailure) throw new Error(`${command === process.execPath ? 'npm' : command} failed (${result.status ?? 'signal'})`);
40
+ return result;
41
+ }
42
+ export function npm(args) {
43
+ if (!process.env.npm_execpath) throw new Error('Use the npm scripts for this command');
44
+ const launcher = process.env.npm_execpath;
45
+ return /\.[cm]?js$/i.test(launcher) ? run(process.execPath, [launcher, ...args]) : run(launcher, args);
46
+ }
47
+ export function go(args, { generate = false, target = {} } = {}) {
48
+ const boundary = resolve(root, 'node_modules/go.mod');
49
+ if (existsSync(dirname(boundary)) && !existsSync(boundary)) writeFileSync(boundary, 'module example.org/arcbase-npm-dependencies\n\ngo 1.27.3\n');
50
+ const env = environment();
51
+ return run('go', args, { cwd: resolve(root, layout.goRoot), env: { ...env, GOWORK: 'off', GOFLAGS: `${env.GOFLAGS ?? ''} -mod=${generate ? 'mod' : 'readonly'}`.trim(), ...target } });
52
+ }
53
+ export function prepareDirectories(env = environment()) {
54
+ if (env.ARCBASE_FILE_STAGING_PATH) mkdirSync(resolve(root, env.ARCBASE_FILE_STAGING_PATH), { recursive: true });
55
+ }
@@ -1,78 +1,78 @@
1
- import { existsSync, readdirSync, statSync } from 'node:fs';
2
- import { resolve } from 'node:path';
3
-
4
- export function goSourceSnapshot(root, layout) {
5
- const files = new Map();
6
- const inspect = path => {
7
- if (!existsSync(path)) return;
8
- const info = statSync(path);
9
- files.set(path, `${info.mtimeMs}:${info.size}`);
10
- };
11
- const walk = path => {
12
- if (!existsSync(path)) return;
13
- for (const item of readdirSync(path, { withFileTypes: true })) {
14
- if (item.isSymbolicLink()) continue;
15
- const child = resolve(path, item.name);
16
- if (item.isDirectory() && item.name !== 'dist') walk(child);
17
- else if (item.isFile() && item.name.endsWith('.go')) inspect(child);
18
- }
19
- };
20
- for (const path of ['cmd', 'internal']) walk(resolve(root, layout.goRoot, path));
21
- for (const path of ['go.mod', 'go.sum']) inspect(resolve(root, layout.goRoot, path));
22
- return JSON.stringify([...files].sort(([a], [b]) => a.localeCompare(b)));
23
- }
24
-
25
- export async function superviseDevelopment({ snapshot, build, reload, cleanup, stopped, api, frontend, interval = 400, log = console.log }) {
26
- const controller = new AbortController(), listeners = new Map();
27
- let closing = false, replacing = false, exitCode = 0;
28
- const finish = code => { closing = true; exitCode = code; controller.abort(); };
29
- const signal = () => finish(0);
30
- const observe = (child, kind) => {
31
- const exited = code => {
32
- if (kind === 'api' && replacing) return;
33
- finish(closing || stopped() ? 0 : code || 1);
34
- };
35
- listeners.set(child, exited);
36
- child.once('exit', exited);
37
- if (child.exitCode !== null || child.signalCode != null) exited(child.exitCode);
38
- };
39
- const pause = () => new Promise(done => {
40
- const complete = () => { clearTimeout(timer); controller.signal.removeEventListener('abort', complete); done(); };
41
- const timer = setTimeout(complete, interval);
42
- controller.signal.addEventListener('abort', complete, { once: true });
43
- if (closing) complete();
44
- });
45
- process.once('SIGINT', signal);
46
- process.once('SIGTERM', signal);
47
- observe(api, 'api'); observe(frontend, 'frontend');
48
- try {
49
- let revision = snapshot();
50
- while (!closing) {
51
- await pause();
52
- if (closing) break;
53
- const next = snapshot();
54
- if (revision === next) continue;
55
- revision = next;
56
- let candidate;
57
- try { candidate = await build(controller.signal); }
58
- catch (error) { if (!closing) log(`Go build failed; existing API remains available. ${error.message}`); continue; }
59
- if (closing) break;
60
- replacing = true;
61
- try {
62
- const replacement = await reload(candidate, api.pid);
63
- if (!replacement) { finish(0); break; }
64
- api.removeListener('exit', listeners.get(api)); listeners.delete(api);
65
- api = replacement.api;
66
- replacing = false;
67
- observe(api, 'api');
68
- log(replacement.error ? 'New API failed readiness; restored the preceding binary.' : 'Go API reloaded; Vite, configuration and business data preserved.');
69
- } finally { replacing = false; }
70
- }
71
- } finally {
72
- controller.abort();
73
- process.removeListener('SIGINT', signal); process.removeListener('SIGTERM', signal);
74
- for (const [child, listener] of listeners) child.removeListener('exit', listener);
75
- await cleanup();
76
- }
77
- return exitCode;
78
- }
1
+ import { existsSync, readdirSync, statSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+
4
+ export function goSourceSnapshot(root, layout) {
5
+ const files = new Map();
6
+ const inspect = path => {
7
+ if (!existsSync(path)) return;
8
+ const info = statSync(path);
9
+ files.set(path, `${info.mtimeMs}:${info.size}`);
10
+ };
11
+ const walk = path => {
12
+ if (!existsSync(path)) return;
13
+ for (const item of readdirSync(path, { withFileTypes: true })) {
14
+ if (item.isSymbolicLink()) continue;
15
+ const child = resolve(path, item.name);
16
+ if (item.isDirectory() && item.name !== 'dist') walk(child);
17
+ else if (item.isFile() && item.name.endsWith('.go')) inspect(child);
18
+ }
19
+ };
20
+ for (const path of ['cmd', 'internal']) walk(resolve(root, layout.goRoot, path));
21
+ for (const path of ['go.mod', 'go.sum']) inspect(resolve(root, layout.goRoot, path));
22
+ return JSON.stringify([...files].sort(([a], [b]) => a.localeCompare(b)));
23
+ }
24
+
25
+ export async function superviseDevelopment({ snapshot, build, reload, cleanup, stopped, api, frontend, interval = 400, log = console.log }) {
26
+ const controller = new AbortController(), listeners = new Map();
27
+ let closing = false, replacing = false, exitCode = 0;
28
+ const finish = code => { closing = true; exitCode = code; controller.abort(); };
29
+ const signal = () => finish(0);
30
+ const observe = (child, kind) => {
31
+ const exited = code => {
32
+ if (kind === 'api' && replacing) return;
33
+ finish(closing || stopped() ? 0 : code || 1);
34
+ };
35
+ listeners.set(child, exited);
36
+ child.once('exit', exited);
37
+ if (child.exitCode !== null || child.signalCode != null) exited(child.exitCode);
38
+ };
39
+ const pause = () => new Promise(done => {
40
+ const complete = () => { clearTimeout(timer); controller.signal.removeEventListener('abort', complete); done(); };
41
+ const timer = setTimeout(complete, interval);
42
+ controller.signal.addEventListener('abort', complete, { once: true });
43
+ if (closing) complete();
44
+ });
45
+ process.once('SIGINT', signal);
46
+ process.once('SIGTERM', signal);
47
+ observe(api, 'api'); observe(frontend, 'frontend');
48
+ try {
49
+ let revision = snapshot();
50
+ while (!closing) {
51
+ await pause();
52
+ if (closing) break;
53
+ const next = snapshot();
54
+ if (revision === next) continue;
55
+ revision = next;
56
+ let candidate;
57
+ try { candidate = await build(controller.signal); }
58
+ catch (error) { if (!closing) log(`Go build failed; existing API remains available. ${error.message}`); continue; }
59
+ if (closing) break;
60
+ replacing = true;
61
+ try {
62
+ const replacement = await reload(candidate, api.pid);
63
+ if (!replacement) { finish(0); break; }
64
+ api.removeListener('exit', listeners.get(api)); listeners.delete(api);
65
+ api = replacement.api;
66
+ replacing = false;
67
+ observe(api, 'api');
68
+ log(replacement.error ? 'New API failed readiness; restored the preceding binary.' : 'Go API reloaded; Vite, configuration and business data preserved.');
69
+ } finally { replacing = false; }
70
+ }
71
+ } finally {
72
+ controller.abort();
73
+ process.removeListener('SIGINT', signal); process.removeListener('SIGTERM', signal);
74
+ for (const [child, listener] of listeners) child.removeListener('exit', listener);
75
+ await cleanup();
76
+ }
77
+ return exitCode;
78
+ }
@@ -1,49 +1,50 @@
1
- import { dirname, resolve } from 'node:path';
2
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, unlinkSync } from 'node:fs';
3
- import { spawn } from 'node:child_process';
4
- import { environment, layout, npm, require, root } from './config.mjs';
5
- import { control, current, launch, reloadAPI, stop, stopping } from './lifecycle.mjs';
6
- import { goSourceSnapshot, superviseDevelopment } from './dev-watch.mjs';
7
- try {
8
- if (current().length) throw new Error('Stop this project before entering development mode');
9
- npm(['run', 'build:server']);
10
- const vite = resolve(dirname(require.resolve('vite/package.json')), 'bin/vite.js');
11
- const [api, frontend] = await control(() => launch({ vite }));
12
- const directory = resolve(root, '.arcbase/runtime/dev');
13
- mkdirSync(directory, { recursive: true });
14
- const sdk = JSON.parse(readFileSync(resolve(root, layout.sdkMetadata), 'utf8'));
15
- const prefix = 'github.com/fudanda/arcbase/backend/v2';
16
- const flags = `-X ${prefix}.Version=${sdk.version} -X ${prefix}.Commit=${sdk.commit}`;
17
- const binaries = new Set();
18
- const prune = keep => {
19
- if (realpathSync(directory).toLowerCase() !== directory.toLowerCase()) throw new Error('Development output must not traverse a symbolic link');
20
- for (const path of binaries) {
21
- if (keep && (process.platform === 'win32' ? path.toLowerCase() === keep.toLowerCase() : path === keep)) continue;
22
- if (dirname(path) !== directory || !lstatSync(path, { throwIfNoEntry: false })?.isFile()) { binaries.delete(path); continue; }
23
- if (existsSync(path)) unlinkSync(path);
24
- binaries.delete(path);
25
- }
26
- };
27
- let generation = 0;
28
- process.exitCode = await superviseDevelopment({
29
- api, frontend, snapshot: () => goSourceSnapshot(root, layout), stopped: stopping,
30
- build: signal => new Promise((done, reject) => {
31
- const candidate = resolve(directory, `arcbase-${process.pid}-${++generation}${process.platform === 'win32' ? '.exe' : ''}`);
32
- binaries.add(candidate);
33
- const env = environment();
34
- const child = spawn('go', ['build', '-trimpath', '-ldflags', flags, '-o', candidate, layout.goEntry], {
35
- cwd: resolve(root, layout.goRoot), env: { ...env, GOWORK: 'off', GOFLAGS: `${env.GOFLAGS ?? ''} -mod=readonly`.trim() },
36
- windowsHide: true, stdio: 'inherit', signal,
37
- });
38
- child.once('error', reject);
39
- child.once('exit', code => code === 0 ? done(candidate) : reject(new Error('Fix the compile error; schema changes require npm run generate.')));
40
- }),
41
- reload: (candidate, pid) => control(async () => {
42
- if (stopping()) return null;
43
- const result = await reloadAPI(candidate, pid);
44
- if (result) prune(current().find(record => record.kind === 'api')?.identity.executable);
45
- return result;
46
- }, { wait: 35000, command: 'reload' }),
47
- cleanup: async () => { await control(stop, { wait: 35000, command: 'cleanup' }); prune(); },
48
- });
49
- } catch (error) { console.error(error.message); process.exitCode = 1; }
1
+ import { dirname, resolve } from 'node:path';
2
+ import { existsSync, lstatSync, mkdirSync, realpathSync, unlinkSync } from 'node:fs';
3
+ import { spawn } from 'node:child_process';
4
+ import { environment, layout, npm, require, root } from './config.mjs';
5
+ import { control, current, launch, reloadAPI, stop, stopping } from './lifecycle.mjs';
6
+ import { goSourceSnapshot, superviseDevelopment } from './dev-watch.mjs';
7
+ import { applicationBuildInfo, applicationGoFlags, readSDKMetadata } from './application-version.mjs';
8
+ import { directGoDependencies } from './project-info.mjs';
9
+ try {
10
+ if (current().length) throw new Error('Stop this project before entering development mode');
11
+ process.env.ARCBASE_APPLICATION_BUILD_INFO = JSON.stringify(applicationBuildInfo(root));
12
+ npm(['run', 'build:server']);
13
+ const vite = resolve(dirname(require.resolve('vite/package.json')), 'bin/vite.js');
14
+ const [api, frontend] = await control(() => launch({ vite }));
15
+ const directory = resolve(root, '.arcbase/runtime/dev');
16
+ mkdirSync(directory, { recursive: true });
17
+ const binaries = new Set();
18
+ const prune = keep => {
19
+ if (realpathSync(directory).toLowerCase() !== directory.toLowerCase()) throw new Error('Development output must not traverse a symbolic link');
20
+ for (const path of binaries) {
21
+ if (keep && (process.platform === 'win32' ? path.toLowerCase() === keep.toLowerCase() : path === keep)) continue;
22
+ if (dirname(path) !== directory || !lstatSync(path, { throwIfNoEntry: false })?.isFile()) { binaries.delete(path); continue; }
23
+ if (existsSync(path)) unlinkSync(path);
24
+ binaries.delete(path);
25
+ }
26
+ };
27
+ let generation = 0;
28
+ process.exitCode = await superviseDevelopment({
29
+ api, frontend, snapshot: () => goSourceSnapshot(root, layout), stopped: stopping,
30
+ build: signal => new Promise((done, reject) => {
31
+ const candidate = resolve(directory, `arcbase-${process.pid}-${++generation}${process.platform === 'win32' ? '.exe' : ''}`);
32
+ binaries.add(candidate);
33
+ const env = environment();
34
+ const flags = applicationGoFlags(applicationBuildInfo(root), readSDKMetadata(root), directGoDependencies(root));
35
+ const child = spawn('go', ['build', '-trimpath', '-ldflags', flags, '-o', candidate, layout.goEntry], {
36
+ cwd: resolve(root, layout.goRoot), env: { ...env, GOWORK: 'off', GOFLAGS: `${env.GOFLAGS ?? ''} -mod=readonly`.trim() },
37
+ windowsHide: true, stdio: 'inherit', signal,
38
+ });
39
+ child.once('error', reject);
40
+ child.once('exit', code => code === 0 ? done(candidate) : reject(new Error('Fix the compile error; schema changes require npm run generate.')));
41
+ }),
42
+ reload: (candidate, pid) => control(async () => {
43
+ if (stopping()) return null;
44
+ const result = await reloadAPI(candidate, pid);
45
+ if (result) prune(current().find(record => record.kind === 'api')?.identity.executable);
46
+ return result;
47
+ }, { wait: 35000, command: 'reload' }),
48
+ cleanup: async () => { await control(stop, { wait: 35000, command: 'cleanup' }); prune(); },
49
+ });
50
+ } catch (error) { console.error(error.message); process.exitCode = 1; }