@nocobase/cli 2.1.0-alpha.4 → 2.1.0-alpha.40

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 (211) hide show
  1. package/LICENSE.txt +107 -0
  2. package/README.md +393 -19
  3. package/README.zh-CN.md +343 -0
  4. package/bin/run.cmd +3 -0
  5. package/bin/run.js +135 -0
  6. package/bin/session-env.js +39 -0
  7. package/dist/commands/api/resource/create.js +15 -0
  8. package/dist/commands/api/resource/destroy.js +15 -0
  9. package/dist/commands/api/resource/get.js +15 -0
  10. package/dist/commands/api/resource/index.js +20 -0
  11. package/dist/commands/api/resource/list.js +16 -0
  12. package/dist/commands/api/resource/query.js +15 -0
  13. package/dist/commands/api/resource/update.js +15 -0
  14. package/dist/commands/app/down.js +301 -0
  15. package/dist/commands/app/logs.js +114 -0
  16. package/dist/commands/app/restart.js +158 -0
  17. package/dist/commands/app/start.js +305 -0
  18. package/dist/commands/app/stop.js +115 -0
  19. package/dist/commands/app/upgrade.js +636 -0
  20. package/dist/commands/backup/create.js +147 -0
  21. package/dist/commands/backup/index.js +20 -0
  22. package/dist/commands/backup/restore.js +105 -0
  23. package/{src/cli.js → dist/commands/build.js} +4 -11
  24. package/dist/commands/config/delete.js +30 -0
  25. package/dist/commands/config/get.js +29 -0
  26. package/dist/commands/config/index.js +20 -0
  27. package/dist/commands/config/list.js +29 -0
  28. package/dist/commands/config/set.js +35 -0
  29. package/dist/commands/db/check.js +240 -0
  30. package/dist/commands/db/logs.js +85 -0
  31. package/dist/commands/db/ps.js +60 -0
  32. package/dist/commands/db/shared.js +96 -0
  33. package/dist/commands/db/start.js +71 -0
  34. package/dist/commands/db/stop.js +71 -0
  35. package/{templates/plugin/src/client/models/index.ts → dist/commands/dev.js} +4 -4
  36. package/{src/commands/locale/react-js-cron/index.js → dist/commands/down.js} +3 -8
  37. package/dist/commands/download.js +13 -0
  38. package/dist/commands/env/add.js +366 -0
  39. package/dist/commands/env/auth.js +130 -0
  40. package/dist/commands/env/current.js +21 -0
  41. package/dist/commands/env/info.js +157 -0
  42. package/dist/commands/env/list.js +44 -0
  43. package/dist/commands/env/remove.js +84 -0
  44. package/dist/commands/env/shared.js +158 -0
  45. package/dist/commands/env/status.js +90 -0
  46. package/dist/commands/env/update.js +74 -0
  47. package/dist/commands/env/use.js +38 -0
  48. package/dist/commands/examples/prompts-stages.js +150 -0
  49. package/dist/commands/examples/prompts-test.js +181 -0
  50. package/dist/commands/init.js +1092 -0
  51. package/dist/commands/install.js +2378 -0
  52. package/dist/commands/license/activate.js +360 -0
  53. package/dist/commands/license/env.js +94 -0
  54. package/dist/commands/license/generate-id.js +108 -0
  55. package/dist/commands/license/id.js +70 -0
  56. package/dist/commands/license/index.js +20 -0
  57. package/dist/commands/license/plugins/clean.js +115 -0
  58. package/dist/commands/license/plugins/index.js +20 -0
  59. package/dist/commands/license/plugins/list.js +64 -0
  60. package/dist/commands/license/plugins/shared.js +325 -0
  61. package/dist/commands/license/plugins/sync.js +285 -0
  62. package/dist/commands/license/shared.js +423 -0
  63. package/dist/commands/license/status.js +64 -0
  64. package/dist/commands/logs.js +12 -0
  65. package/dist/commands/plugin/disable.js +86 -0
  66. package/dist/commands/plugin/enable.js +86 -0
  67. package/dist/commands/plugin/list.js +82 -0
  68. package/dist/commands/pm/disable.js +12 -0
  69. package/dist/commands/pm/enable.js +12 -0
  70. package/dist/commands/pm/list.js +12 -0
  71. package/dist/commands/restart.js +12 -0
  72. package/dist/commands/scaffold/migration.js +38 -0
  73. package/dist/commands/scaffold/plugin.js +37 -0
  74. package/dist/commands/self/check.js +71 -0
  75. package/dist/commands/self/index.js +20 -0
  76. package/dist/commands/self/update.js +95 -0
  77. package/dist/commands/session/id.js +24 -0
  78. package/dist/commands/session/remove.js +57 -0
  79. package/dist/commands/session/setup.js +62 -0
  80. package/dist/commands/skills/check.js +69 -0
  81. package/dist/commands/skills/index.js +20 -0
  82. package/dist/commands/skills/install.js +80 -0
  83. package/dist/commands/skills/remove.js +80 -0
  84. package/dist/commands/skills/update.js +87 -0
  85. package/dist/commands/source/build.js +58 -0
  86. package/dist/commands/source/dev.js +182 -0
  87. package/dist/commands/source/download.js +880 -0
  88. package/dist/commands/source/publish.js +109 -0
  89. package/dist/commands/source/registry/logs.js +70 -0
  90. package/dist/commands/source/registry/start.js +57 -0
  91. package/dist/commands/source/registry/status.js +33 -0
  92. package/dist/commands/source/registry/stop.js +48 -0
  93. package/dist/commands/source/test.js +477 -0
  94. package/dist/commands/start.js +12 -0
  95. package/dist/commands/stop.js +12 -0
  96. package/dist/commands/test.js +12 -0
  97. package/dist/commands/upgrade.js +12 -0
  98. package/dist/commands/v1.js +210 -0
  99. package/dist/generated/command-registry.js +133 -0
  100. package/dist/help/runtime-help.js +23 -0
  101. package/dist/lib/api-client.js +329 -0
  102. package/dist/lib/app-health.js +126 -0
  103. package/dist/lib/app-managed-resources.js +316 -0
  104. package/dist/lib/app-runtime.js +180 -0
  105. package/dist/lib/auth-store.js +368 -0
  106. package/dist/lib/backup.js +171 -0
  107. package/dist/lib/bootstrap.js +403 -0
  108. package/dist/lib/build-config.js +18 -0
  109. package/dist/lib/builtin-db.js +86 -0
  110. package/dist/lib/cli-config.js +176 -0
  111. package/dist/lib/cli-home.js +47 -0
  112. package/dist/lib/cli-locale.js +129 -0
  113. package/dist/lib/command-discovery.js +39 -0
  114. package/dist/lib/db-connection-check.js +158 -0
  115. package/dist/lib/docker-env-file.js +52 -0
  116. package/dist/lib/docker-image.js +37 -0
  117. package/dist/lib/env-auth.js +873 -0
  118. package/dist/lib/env-config.js +94 -0
  119. package/dist/lib/env-guard.js +62 -0
  120. package/dist/lib/generated-command.js +186 -0
  121. package/dist/lib/http-request.js +49 -0
  122. package/dist/lib/inquirer-theme.js +17 -0
  123. package/dist/lib/inquirer.js +244 -0
  124. package/dist/lib/naming.js +70 -0
  125. package/dist/lib/object-utils.js +76 -0
  126. package/dist/lib/openapi.js +62 -0
  127. package/dist/lib/plugin-storage.js +64 -0
  128. package/dist/lib/post-processors.js +23 -0
  129. package/dist/lib/prompt-catalog-core.js +185 -0
  130. package/dist/lib/prompt-catalog-terminal.js +375 -0
  131. package/{src/index.js → dist/lib/prompt-catalog.js} +2 -6
  132. package/dist/lib/prompt-validators.js +240 -0
  133. package/dist/lib/prompt-web-ui.js +2103 -0
  134. package/dist/lib/resource-command.js +357 -0
  135. package/dist/lib/resource-request.js +104 -0
  136. package/dist/lib/run-npm.js +275 -0
  137. package/dist/lib/runtime-env-vars.js +32 -0
  138. package/dist/lib/runtime-generator.js +498 -0
  139. package/dist/lib/runtime-store.js +56 -0
  140. package/dist/lib/self-manager.js +301 -0
  141. package/dist/lib/session-id.js +17 -0
  142. package/dist/lib/session-integration.js +703 -0
  143. package/dist/lib/session-store.js +118 -0
  144. package/dist/lib/skills-manager.js +360 -0
  145. package/dist/lib/source-publish.js +306 -0
  146. package/dist/lib/source-registry.js +188 -0
  147. package/dist/lib/startup-update.js +285 -0
  148. package/dist/lib/ui.js +155 -0
  149. package/dist/locale/en-US.json +344 -0
  150. package/dist/locale/zh-CN.json +344 -0
  151. package/dist/post-processors/data-modeling.js +84 -0
  152. package/dist/post-processors/data-source-manager.js +138 -0
  153. package/dist/post-processors/index.js +19 -0
  154. package/nocobase-ctl.config.json +388 -0
  155. package/package.json +100 -26
  156. package/LICENSE +0 -661
  157. package/bin/index.js +0 -39
  158. package/nocobase.conf.tpl +0 -95
  159. package/src/commands/benchmark.js +0 -73
  160. package/src/commands/build.js +0 -49
  161. package/src/commands/clean.js +0 -30
  162. package/src/commands/client.js +0 -166
  163. package/src/commands/create-nginx-conf.js +0 -37
  164. package/src/commands/create-plugin.js +0 -33
  165. package/src/commands/dev.js +0 -200
  166. package/src/commands/doc.js +0 -76
  167. package/src/commands/e2e.js +0 -265
  168. package/src/commands/global.js +0 -43
  169. package/src/commands/index.js +0 -45
  170. package/src/commands/instance-id.js +0 -47
  171. package/src/commands/locale/cronstrue.js +0 -122
  172. package/src/commands/locale/react-js-cron/en-US.json +0 -75
  173. package/src/commands/locale/react-js-cron/zh-CN.json +0 -33
  174. package/src/commands/locale/react-js-cron/zh-TW.json +0 -33
  175. package/src/commands/locale.js +0 -81
  176. package/src/commands/p-test.js +0 -88
  177. package/src/commands/perf.js +0 -63
  178. package/src/commands/pkg.js +0 -321
  179. package/src/commands/pm2.js +0 -37
  180. package/src/commands/postinstall.js +0 -88
  181. package/src/commands/start.js +0 -148
  182. package/src/commands/tar.js +0 -36
  183. package/src/commands/test-coverage.js +0 -55
  184. package/src/commands/test.js +0 -107
  185. package/src/commands/umi.js +0 -33
  186. package/src/commands/update-deps.js +0 -72
  187. package/src/commands/upgrade.js +0 -47
  188. package/src/commands/view-license-key.js +0 -44
  189. package/src/license.js +0 -76
  190. package/src/logger.js +0 -75
  191. package/src/plugin-generator.js +0 -80
  192. package/src/util.js +0 -517
  193. package/templates/bundle-status.html +0 -338
  194. package/templates/create-app-package.json +0 -39
  195. package/templates/plugin/.npmignore.tpl +0 -2
  196. package/templates/plugin/README.md.tpl +0 -1
  197. package/templates/plugin/client.d.ts +0 -2
  198. package/templates/plugin/client.js +0 -1
  199. package/templates/plugin/package.json.tpl +0 -11
  200. package/templates/plugin/server.d.ts +0 -2
  201. package/templates/plugin/server.js +0 -1
  202. package/templates/plugin/src/client/client.d.ts +0 -249
  203. package/templates/plugin/src/client/index.tsx.tpl +0 -1
  204. package/templates/plugin/src/client/locale.ts +0 -21
  205. package/templates/plugin/src/client/plugin.tsx.tpl +0 -10
  206. package/templates/plugin/src/index.ts +0 -2
  207. package/templates/plugin/src/locale/en-US.json +0 -1
  208. package/templates/plugin/src/locale/zh-CN.json +0 -1
  209. package/templates/plugin/src/server/collections/.gitkeep +0 -0
  210. package/templates/plugin/src/server/index.ts.tpl +0 -1
  211. package/templates/plugin/src/server/plugin.ts.tpl +0 -19
@@ -0,0 +1,126 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ import { printInfo, startTask, stopTask, updateTask } from './ui.js';
10
+ const APP_HEALTH_CHECK_INTERVAL_MS = 2_000;
11
+ const APP_HEALTH_CHECK_TIMEOUT_MS = 600_000;
12
+ const APP_HEALTH_CHECK_REQUEST_TIMEOUT_MS = 5_000;
13
+ function trimValue(value) {
14
+ return String(value ?? '').trim();
15
+ }
16
+ function buildHealthCheckUrl(apiBaseUrl) {
17
+ return `${apiBaseUrl.replace(/\/+$/, '')}/__health_check`;
18
+ }
19
+ async function sleep(ms) {
20
+ await new Promise((resolve) => setTimeout(resolve, ms));
21
+ }
22
+ async function requestAppHealthCheck(params) {
23
+ const controller = new AbortController();
24
+ const timeout = setTimeout(() => {
25
+ controller.abort();
26
+ }, params.requestTimeoutMs ?? APP_HEALTH_CHECK_REQUEST_TIMEOUT_MS);
27
+ try {
28
+ const response = await (params.fetchImpl ?? fetch)(params.healthCheckUrl, {
29
+ method: 'GET',
30
+ signal: controller.signal,
31
+ });
32
+ const text = await response.text().catch(() => '');
33
+ const body = text.replace(/\s+/g, ' ').trim() || 'No response yet';
34
+ return {
35
+ ok: response.ok && text.trim().toLowerCase() === 'ok',
36
+ message: `HTTP ${response.status}: ${body}`,
37
+ };
38
+ }
39
+ catch (error) {
40
+ if (error instanceof Error && error.name === 'AbortError') {
41
+ return {
42
+ ok: false,
43
+ message: `No response within ${Math.ceil((params.requestTimeoutMs ?? APP_HEALTH_CHECK_REQUEST_TIMEOUT_MS) / 1000)}s`,
44
+ };
45
+ }
46
+ return {
47
+ ok: false,
48
+ message: error instanceof Error ? error.message : String(error),
49
+ };
50
+ }
51
+ finally {
52
+ clearTimeout(timeout);
53
+ }
54
+ }
55
+ export class AppHealthCheckError extends Error {
56
+ }
57
+ export function formatAppUrl(port) {
58
+ const value = trimValue(port);
59
+ return value ? `http://127.0.0.1:${value}` : undefined;
60
+ }
61
+ export function resolveManagedAppApiBaseUrl(runtime, options) {
62
+ const override = trimValue(options?.portOverride);
63
+ if (override) {
64
+ return `http://127.0.0.1:${override}/api`;
65
+ }
66
+ const baseUrl = trimValue(runtime.env.baseUrl);
67
+ if (baseUrl) {
68
+ return baseUrl.replace(/\/+$/, '');
69
+ }
70
+ const appPort = runtime.env.appPort === undefined || runtime.env.appPort === null
71
+ ? ''
72
+ : trimValue(runtime.env.appPort);
73
+ return appPort ? `http://127.0.0.1:${appPort}/api` : undefined;
74
+ }
75
+ export async function isAppReady(apiBaseUrl, options) {
76
+ const baseUrl = trimValue(apiBaseUrl);
77
+ if (!baseUrl) {
78
+ return false;
79
+ }
80
+ const result = await requestAppHealthCheck({
81
+ healthCheckUrl: buildHealthCheckUrl(baseUrl),
82
+ fetchImpl: options?.fetchImpl,
83
+ requestTimeoutMs: options?.requestTimeoutMs,
84
+ });
85
+ return result.ok;
86
+ }
87
+ export async function waitForAppReady(params) {
88
+ const apiBaseUrl = trimValue(params.apiBaseUrl);
89
+ if (!apiBaseUrl) {
90
+ printInfo(`Skipping health check for "${params.envName}" because no local API URL is saved for this env.`);
91
+ return;
92
+ }
93
+ const healthCheckUrl = buildHealthCheckUrl(apiBaseUrl);
94
+ const startedAt = Date.now();
95
+ let lastMessage = 'No response yet';
96
+ let spinnerActive = true;
97
+ startTask(`Waiting for NocoBase to become ready for "${params.envName}"...`);
98
+ try {
99
+ while (Date.now() - startedAt < APP_HEALTH_CHECK_TIMEOUT_MS) {
100
+ const result = await requestAppHealthCheck({
101
+ healthCheckUrl,
102
+ fetchImpl: params.fetchImpl,
103
+ });
104
+ if (result.ok) {
105
+ stopTask();
106
+ spinnerActive = false;
107
+ return;
108
+ }
109
+ lastMessage = result.message;
110
+ const elapsedSeconds = Math.max(1, Math.floor((Date.now() - startedAt) / 1000));
111
+ updateTask(`Waiting for NocoBase to become ready for "${params.envName}"... (${elapsedSeconds}s elapsed, last status: ${lastMessage})`);
112
+ await sleep(APP_HEALTH_CHECK_INTERVAL_MS);
113
+ }
114
+ }
115
+ finally {
116
+ if (spinnerActive) {
117
+ stopTask();
118
+ }
119
+ }
120
+ const hints = [
121
+ params.logHint,
122
+ params.containerName ? `docker logs ${params.containerName}` : undefined,
123
+ ].filter(Boolean);
124
+ const hintText = hints.length > 0 ? ` ${hints.join(' ')}` : '';
125
+ throw new AppHealthCheckError(`NocoBase did not become ready in time for "${params.envName}". Expected \`${healthCheckUrl}\` to respond with \`ok\`, but the last status was: ${lastMessage}.${hintText}`);
126
+ }
@@ -0,0 +1,316 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ import { mkdir, readdir } from 'node:fs/promises';
10
+ import { dockerContainerExists, runLocalNocoBaseCommand, startDockerContainer } from './app-runtime.js';
11
+ import { deriveBuiltinDbConnection, resolveBuiltinDbConnection } from './builtin-db.js';
12
+ import { resolveConfiguredEnvPath } from './cli-home.js';
13
+ import { resolveDockerEnvFileArg } from "./docker-env-file.js";
14
+ import { DEFAULT_DOCKER_REGISTRY, DEFAULT_DOCKER_VERSION, resolveDockerImageRef, } from "./docker-image.js";
15
+ import { commandSucceeds, run } from './run-npm.js';
16
+ import Install from '../commands/install.js';
17
+ const DOCKER_APP_STORAGE_DESTINATION = '/app/nocobase/storage';
18
+ function commandStdio(verbose) {
19
+ return verbose ? 'inherit' : 'ignore';
20
+ }
21
+ async function ensureDockerNetwork(networkName) {
22
+ if (await commandSucceeds('docker', ['network', 'inspect', networkName])) {
23
+ return;
24
+ }
25
+ await run('docker', ['network', 'create', networkName], {
26
+ errorName: 'docker network create',
27
+ });
28
+ }
29
+ function localSourceLabel(source) {
30
+ return source === 'git' ? 'Git checkout' : 'npm app';
31
+ }
32
+ function trimValue(value) {
33
+ return String(value ?? '').trim();
34
+ }
35
+ function pushOptionalEnvArg(args, key, value) {
36
+ if (typeof value === 'string') {
37
+ if (!value) {
38
+ return;
39
+ }
40
+ args.push('-e', `${key}=${value}`);
41
+ return;
42
+ }
43
+ if (typeof value === 'boolean') {
44
+ args.push('-e', `${key}=${String(value)}`);
45
+ }
46
+ }
47
+ function normalizeDockerPlatform(value) {
48
+ const text = trimValue(value);
49
+ if (!text || text === 'auto') {
50
+ return undefined;
51
+ }
52
+ if (text === 'linux/amd64' || text === 'linux/arm64') {
53
+ return text;
54
+ }
55
+ return undefined;
56
+ }
57
+ function formatBuiltinDbFailure(envName, message) {
58
+ return [
59
+ `Couldn't restore the built-in database for "${envName}".`,
60
+ 'Check the saved database settings, local storage path, and Docker runtime, then try again.',
61
+ `Details: ${message}`,
62
+ ].join('\n');
63
+ }
64
+ function formatLocalSourceRestoreFailure(envName, source, message) {
65
+ const sourceLabel = source === 'git' ? 'the saved Git checkout' : 'the saved npm app';
66
+ return [
67
+ `Couldn't restore NocoBase files for "${envName}".`,
68
+ `The CLI was not able to download ${sourceLabel} before starting the app again.`,
69
+ 'Check the saved source settings for this env, then try again.',
70
+ `Details: ${message}`,
71
+ ].join('\n');
72
+ }
73
+ function formatLocalPostinstallFailure(envName, message) {
74
+ return [
75
+ `Couldn't prepare NocoBase for "${envName}".`,
76
+ 'The CLI was not able to run `nocobase-v1 postinstall` before starting the local app.',
77
+ 'Check the local dependencies, storage path, and saved env settings, then try again.',
78
+ `Details: ${message}`,
79
+ ].join('\n');
80
+ }
81
+ function formatSavedDockerSettingsIncomplete(envName, missing) {
82
+ return [
83
+ `Can't start NocoBase for "${envName}" yet.`,
84
+ `The saved Docker settings for this env are incomplete. Missing: ${missing.join(', ')}.`,
85
+ 'Re-run `nb init` or `nb env add` to refresh this env config, then try again.',
86
+ ].join('\n');
87
+ }
88
+ function formatDockerAppRecreateFailure(envName, message) {
89
+ return [
90
+ `Couldn't start NocoBase for "${envName}".`,
91
+ 'The CLI was not able to recreate the saved Docker app container successfully.',
92
+ 'Check the saved Docker image, container settings, and database connection, then try again.',
93
+ `Details: ${message}`,
94
+ ].join('\n');
95
+ }
96
+ async function localProjectHasFiles(projectRoot) {
97
+ try {
98
+ const entries = await readdir(projectRoot);
99
+ return entries.length > 0;
100
+ }
101
+ catch (_error) {
102
+ return false;
103
+ }
104
+ }
105
+ export async function buildSavedDockerRunArgs(runtime) {
106
+ const config = runtime.env.config ?? {};
107
+ const configuredStoragePath = trimValue(config.storagePath);
108
+ const storagePath = configuredStoragePath
109
+ ? trimValue(resolveConfiguredEnvPath(configuredStoragePath))
110
+ : '';
111
+ const envFile = await resolveDockerEnvFileArg(runtime.envName, config);
112
+ const appPort = runtime.env.appPort === undefined || runtime.env.appPort === null
113
+ ? ''
114
+ : trimValue(runtime.env.appPort);
115
+ const appKey = trimValue(config.appKey);
116
+ const timeZone = trimValue(config.timezone) || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
117
+ const builtinDbConnection = config.builtinDb ? deriveBuiltinDbConnection(runtime) : undefined;
118
+ const dbDialect = builtinDbConnection?.dbDialect || trimValue(config.dbDialect);
119
+ const dbHost = builtinDbConnection?.dbHost || trimValue(config.dbHost);
120
+ const dbPort = builtinDbConnection?.dbPort || trimValue(config.dbPort);
121
+ const dbDatabase = trimValue(config.dbDatabase);
122
+ const dbUser = trimValue(config.dbUser);
123
+ const dbPassword = trimValue(config.dbPassword);
124
+ const dbSchema = trimValue(config.dbSchema);
125
+ const dbTablePrefix = trimValue(config.dbTablePrefix);
126
+ const dbUnderscored = typeof config.dbUnderscored === 'boolean' ? config.dbUnderscored : undefined;
127
+ const dockerRegistry = trimValue(config.dockerRegistry) || DEFAULT_DOCKER_REGISTRY;
128
+ const version = trimValue(config.downloadVersion) || DEFAULT_DOCKER_VERSION;
129
+ const imageRef = resolveDockerImageRef(dockerRegistry, version, {
130
+ defaultRegistry: DEFAULT_DOCKER_REGISTRY,
131
+ defaultVersion: DEFAULT_DOCKER_VERSION,
132
+ });
133
+ const missing = [];
134
+ if (!storagePath) {
135
+ missing.push('storagePath');
136
+ }
137
+ if (!appKey) {
138
+ missing.push('appKey');
139
+ }
140
+ if (!dbDialect) {
141
+ missing.push('dbDialect');
142
+ }
143
+ if (!dbHost) {
144
+ missing.push('dbHost');
145
+ }
146
+ if (!dbPort) {
147
+ missing.push('dbPort');
148
+ }
149
+ if (!dbDatabase) {
150
+ missing.push('dbDatabase');
151
+ }
152
+ if (!dbUser) {
153
+ missing.push('dbUser');
154
+ }
155
+ if (!dbPassword) {
156
+ missing.push('dbPassword');
157
+ }
158
+ if (missing.length > 0) {
159
+ throw new Error(formatSavedDockerSettingsIncomplete(runtime.envName, missing));
160
+ }
161
+ const args = [
162
+ 'run',
163
+ '-d',
164
+ '--name',
165
+ runtime.containerName,
166
+ '--restart',
167
+ 'always',
168
+ '--network',
169
+ runtime.workspaceName,
170
+ ];
171
+ const dockerPlatform = normalizeDockerPlatform(config.dockerPlatform);
172
+ if (dockerPlatform) {
173
+ args.push('--platform', dockerPlatform);
174
+ }
175
+ if (appPort) {
176
+ args.push('-p', `${appPort}:80`);
177
+ }
178
+ if (envFile) {
179
+ args.push('--env-file', envFile);
180
+ }
181
+ args.push('-e', `APP_KEY=${appKey}`, '-e', `DB_DIALECT=${dbDialect}`, '-e', `DB_HOST=${dbHost}`, '-e', `DB_PORT=${dbPort}`, '-e', `DB_DATABASE=${dbDatabase}`, '-e', `DB_USER=${dbUser}`, '-e', `DB_PASSWORD=${dbPassword}`, '-e', `TZ=${timeZone}`, '-v', `${storagePath}:${DOCKER_APP_STORAGE_DESTINATION}`);
182
+ pushOptionalEnvArg(args, 'DB_SCHEMA', dbSchema || undefined);
183
+ pushOptionalEnvArg(args, 'DB_TABLE_PREFIX', dbTablePrefix || undefined);
184
+ pushOptionalEnvArg(args, 'DB_UNDERSCORED', dbUnderscored);
185
+ args.push(imageRef);
186
+ return {
187
+ appPort: appPort || undefined,
188
+ storagePath,
189
+ envFile,
190
+ imageRef,
191
+ args,
192
+ };
193
+ }
194
+ export async function recreateSavedDockerApp(runtime, options) {
195
+ const plan = await buildSavedDockerRunArgs(runtime);
196
+ try {
197
+ await ensureDockerNetwork(runtime.workspaceName);
198
+ await mkdir(plan.storagePath, { recursive: true });
199
+ await run('docker', plan.args, {
200
+ errorName: 'docker run',
201
+ stdio: commandStdio(options?.verbose),
202
+ });
203
+ }
204
+ catch (error) {
205
+ const message = error instanceof Error ? error.message : String(error);
206
+ if (message.includes(`Can't start NocoBase for "${runtime.envName}" yet.`)
207
+ || message.includes(`Couldn't start NocoBase for "${runtime.envName}".`)) {
208
+ throw error instanceof Error ? error : new Error(message);
209
+ }
210
+ throw new Error(formatDockerAppRecreateFailure(runtime.envName, message));
211
+ }
212
+ }
213
+ export async function ensureBuiltinDbReady(runtime, options) {
214
+ const config = runtime.env.config ?? {};
215
+ if (!config.builtinDb) {
216
+ return;
217
+ }
218
+ const builtinDbConnection = await resolveBuiltinDbConnection(runtime);
219
+ const plan = Install.buildBuiltinDbPlan({
220
+ envName: runtime.envName,
221
+ workspaceName: runtime.workspaceName,
222
+ dockerContainerPrefix: runtime.dockerContainerPrefix,
223
+ storagePath: config.storagePath,
224
+ source: runtime.source,
225
+ dbDialect: builtinDbConnection.dbDialect,
226
+ dbHost: builtinDbConnection.dbHost,
227
+ dbPort: builtinDbConnection.dbPort,
228
+ dbDatabase: config.dbDatabase,
229
+ dbUser: config.dbUser,
230
+ dbPassword: config.dbPassword,
231
+ builtinDbImage: config.builtinDbImage,
232
+ });
233
+ options?.onStartTask?.(`Restoring the built-in ${plan.dbDialect} database for "${runtime.envName}"...`);
234
+ try {
235
+ await ensureDockerNetwork(plan.networkName);
236
+ if (await dockerContainerExists(plan.containerName)) {
237
+ const state = await startDockerContainer(plan.containerName, {
238
+ stdio: commandStdio(options?.verbose),
239
+ });
240
+ options?.onSucceedTask?.(state === 'already-running'
241
+ ? `The built-in ${plan.dbDialect} database is already running for "${runtime.envName}" at ${plan.dbHost}:${plan.dbPort}.`
242
+ : `The built-in ${plan.dbDialect} database is running for "${runtime.envName}" at ${plan.dbHost}:${plan.dbPort}.`);
243
+ return;
244
+ }
245
+ await mkdir(plan.dataDir, { recursive: true });
246
+ await run('docker', plan.args, {
247
+ errorName: 'docker run',
248
+ stdio: commandStdio(options?.verbose),
249
+ });
250
+ options?.onSucceedTask?.(`The built-in ${plan.dbDialect} database is running for "${runtime.envName}" at ${plan.dbHost}:${plan.dbPort}.`);
251
+ }
252
+ catch (error) {
253
+ options?.onFailTask?.(`Failed to restore the built-in database for "${runtime.envName}".`);
254
+ throw new Error(formatBuiltinDbFailure(runtime.envName, error instanceof Error ? error.message : String(error)));
255
+ }
256
+ }
257
+ export function buildSavedLocalDownloadArgv(runtime, options) {
258
+ const config = runtime.env.config ?? {};
259
+ const argv = ['-y', '--no-intro'];
260
+ if (options?.verbose) {
261
+ argv.push('--verbose');
262
+ }
263
+ argv.push('--source', runtime.source, '--replace', '--output-dir', runtime.projectRoot);
264
+ const version = String(config.downloadVersion ?? '').trim();
265
+ const gitUrl = String(config.gitUrl ?? '').trim();
266
+ const npmRegistry = String(config.npmRegistry ?? '').trim();
267
+ if (version) {
268
+ argv.push('--version', version);
269
+ }
270
+ if (gitUrl) {
271
+ argv.push('--git-url', gitUrl);
272
+ }
273
+ if (npmRegistry) {
274
+ argv.push('--npm-registry', npmRegistry);
275
+ }
276
+ if (config.devDependencies === true) {
277
+ argv.push('--dev-dependencies');
278
+ }
279
+ if (config.build === false) {
280
+ argv.push('--no-build');
281
+ }
282
+ if (config.buildDts === true) {
283
+ argv.push('--build-dts');
284
+ }
285
+ return argv;
286
+ }
287
+ export async function ensureSavedLocalSource(runtime, runCommand, options) {
288
+ if (await localProjectHasFiles(runtime.projectRoot)) {
289
+ return;
290
+ }
291
+ const sourceLabel = localSourceLabel(runtime.source);
292
+ options?.onStartTask?.(`Restoring the saved ${sourceLabel} for "${runtime.envName}"...`);
293
+ try {
294
+ await runCommand('source:download', buildSavedLocalDownloadArgv(runtime, {
295
+ verbose: options?.verbose,
296
+ }));
297
+ options?.onSucceedTask?.(`NocoBase files are ready for "${runtime.envName}".`);
298
+ }
299
+ catch (error) {
300
+ options?.onFailTask?.(`Failed to restore NocoBase files for "${runtime.envName}".`);
301
+ throw new Error(formatLocalSourceRestoreFailure(runtime.envName, runtime.source, error instanceof Error ? error.message : String(error)));
302
+ }
303
+ }
304
+ export async function ensureLocalPostinstall(runtime, options) {
305
+ options?.onStartTask?.(`Running local postinstall for "${runtime.envName}"...`);
306
+ try {
307
+ await runLocalNocoBaseCommand(runtime, ['postinstall'], {
308
+ stdio: commandStdio(options?.verbose),
309
+ });
310
+ options?.onSucceedTask?.(`Local postinstall finished for "${runtime.envName}".`);
311
+ }
312
+ catch (error) {
313
+ options?.onFailTask?.(`Failed to run local postinstall for "${runtime.envName}".`);
314
+ throw new Error(formatLocalPostinstallFailure(runtime.envName, error instanceof Error ? error.message : String(error)));
315
+ }
316
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ import path from 'node:path';
10
+ import { resolveEnvKind } from './auth-store.js';
11
+ import { getEnv, loadAuthConfig } from './auth-store.js';
12
+ import { DEFAULT_DOCKER_CONTAINER_PREFIX, DEFAULT_DOCKER_NETWORK, getEffectiveCliConfigValue, } from './cli-config.js';
13
+ import { commandOutput, commandSucceeds, run, runNocoBaseCommand } from './run-npm.js';
14
+ import { buildRuntimeEnvVars } from './runtime-env-vars.js';
15
+ const DOCKER_APP_WORKDIR = '/app/nocobase';
16
+ function sanitizeDockerResourceName(value) {
17
+ const normalized = value
18
+ .trim()
19
+ .toLowerCase()
20
+ .replace(/[^a-z0-9_.-]+/g, '-')
21
+ .replace(/-+/g, '-')
22
+ .replace(/^-+|-+$/g, '');
23
+ return normalized || 'nocobase';
24
+ }
25
+ export function defaultWorkspaceName(cwd = process.cwd()) {
26
+ return sanitizeDockerResourceName(`nb-${path.basename(cwd)}`);
27
+ }
28
+ export function defaultDockerContainerPrefix(cwd = process.cwd()) {
29
+ const configured = String(DEFAULT_DOCKER_CONTAINER_PREFIX ?? '').trim();
30
+ if (configured) {
31
+ return sanitizeDockerResourceName(configured);
32
+ }
33
+ return defaultWorkspaceName(cwd);
34
+ }
35
+ export function defaultDockerNetworkName() {
36
+ return sanitizeDockerResourceName(DEFAULT_DOCKER_NETWORK);
37
+ }
38
+ export function buildDockerAppContainerName(envName, containerPrefix) {
39
+ const prefix = containerPrefix?.trim() || defaultDockerContainerPrefix();
40
+ return sanitizeDockerResourceName(`${prefix}-${envName}-app`);
41
+ }
42
+ export function buildDockerDbContainerName(envName, dbDialect, containerPrefix) {
43
+ const prefix = containerPrefix?.trim() || defaultDockerContainerPrefix();
44
+ const dialect = dbDialect.trim() || 'postgres';
45
+ return sanitizeDockerResourceName(`${prefix}-${envName}-${dialect}`);
46
+ }
47
+ function normalizeEnvSource(env) {
48
+ const source = String(env.config.source ?? '').trim();
49
+ if (source === 'docker' || source === 'npm' || source === 'git') {
50
+ return source;
51
+ }
52
+ const kind = resolveEnvKind(env.config);
53
+ if (kind === 'local') {
54
+ return 'local';
55
+ }
56
+ return undefined;
57
+ }
58
+ export async function resolveManagedAppRuntime(envName) {
59
+ const config = await loadAuthConfig();
60
+ const env = await getEnv(envName, { config });
61
+ if (!env) {
62
+ return undefined;
63
+ }
64
+ const resolvedName = env.name || envName?.trim() || config.lastEnv || 'default';
65
+ const source = normalizeEnvSource(env);
66
+ const dockerNetworkName = sanitizeDockerResourceName(getEffectiveCliConfigValue(config, 'docker.network') || defaultDockerNetworkName());
67
+ const dockerContainerPrefix = sanitizeDockerResourceName(getEffectiveCliConfigValue(config, 'docker.container-prefix') || defaultDockerContainerPrefix());
68
+ const kind = env.kind ?? resolveEnvKind(env.config);
69
+ if (kind === 'docker') {
70
+ return {
71
+ kind: 'docker',
72
+ env,
73
+ envName: resolvedName,
74
+ source: 'docker',
75
+ dockerNetworkName,
76
+ dockerContainerPrefix,
77
+ workspaceName: dockerNetworkName,
78
+ containerName: buildDockerAppContainerName(resolvedName, dockerContainerPrefix),
79
+ };
80
+ }
81
+ if (kind === 'local') {
82
+ return {
83
+ kind: 'local',
84
+ env,
85
+ envName: resolvedName,
86
+ source: source === 'git' ? 'git' : source === 'npm' ? 'npm' : 'local',
87
+ projectRoot: env.appRootPath,
88
+ dockerNetworkName,
89
+ dockerContainerPrefix,
90
+ workspaceName: dockerNetworkName,
91
+ };
92
+ }
93
+ if (kind === 'ssh') {
94
+ return {
95
+ kind: 'ssh',
96
+ env,
97
+ envName: resolvedName,
98
+ source,
99
+ };
100
+ }
101
+ return {
102
+ kind: 'http',
103
+ env,
104
+ envName: resolvedName,
105
+ source,
106
+ };
107
+ }
108
+ export function formatMissingManagedAppEnvMessage(envName) {
109
+ const requested = String(envName ?? '').trim();
110
+ if (requested) {
111
+ return [
112
+ `Env "${requested}" is not configured in this workspace.`,
113
+ `If you want to create a new NocoBase AI environment, run \`nb init --env ${requested}\` first.`,
114
+ ].join('\n');
115
+ }
116
+ return 'No NocoBase env is configured yet. Run `nb init` to create one first.';
117
+ }
118
+ export async function runLocalNocoBaseCommand(runtime, args, options) {
119
+ const envVars = await buildRuntimeEnvVars(runtime);
120
+ await runNocoBaseCommand(args, {
121
+ cwd: runtime.projectRoot,
122
+ env: {
123
+ ...envVars,
124
+ ...options?.env,
125
+ },
126
+ stdio: options?.stdio,
127
+ onStdout: options?.onStdout,
128
+ onStderr: options?.onStderr,
129
+ });
130
+ }
131
+ export async function dockerContainerExists(containerName) {
132
+ return await commandSucceeds('docker', ['container', 'inspect', containerName]);
133
+ }
134
+ export async function dockerContainerIsRunning(containerName) {
135
+ try {
136
+ const output = await commandOutput('docker', ['inspect', '--format', '{{.State.Running}}', containerName], { errorName: 'docker inspect' });
137
+ return output.trim() === 'true';
138
+ }
139
+ catch (_error) {
140
+ return false;
141
+ }
142
+ }
143
+ export async function startDockerContainer(containerName, options) {
144
+ const exists = await dockerContainerExists(containerName);
145
+ if (!exists) {
146
+ throw new Error(`Docker app container "${containerName}" does not exist.`);
147
+ }
148
+ if (await dockerContainerIsRunning(containerName)) {
149
+ return 'already-running';
150
+ }
151
+ await run('docker', ['start', containerName], {
152
+ errorName: 'docker start',
153
+ stdio: options?.stdio,
154
+ });
155
+ return 'started';
156
+ }
157
+ export async function stopDockerContainer(containerName, options) {
158
+ const exists = await dockerContainerExists(containerName);
159
+ if (!exists) {
160
+ throw new Error(`Docker app container "${containerName}" does not exist.`);
161
+ }
162
+ if (!(await dockerContainerIsRunning(containerName))) {
163
+ return 'already-stopped';
164
+ }
165
+ await run('docker', ['stop', containerName], {
166
+ errorName: 'docker stop',
167
+ stdio: options?.stdio,
168
+ });
169
+ return 'stopped';
170
+ }
171
+ export async function runDockerNocoBaseCommand(containerName, args, options) {
172
+ await startDockerContainer(containerName, { stdio: options?.stdio });
173
+ const dockerEnvArgs = Object.entries(options?.env ?? {}).flatMap(([key, value]) => ['-e', `${key}=${value}`]);
174
+ await run('docker', ['exec', ...dockerEnvArgs, '-w', DOCKER_APP_WORKDIR, containerName, 'yarn', 'nocobase', ...args], {
175
+ errorName: 'docker exec',
176
+ stdio: options?.stdio,
177
+ onStdout: options?.onStdout,
178
+ onStderr: options?.onStderr,
179
+ });
180
+ }