@nocobase/cli 2.1.0-alpha.2 → 2.1.0-alpha.21

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 (129) hide show
  1. package/LICENSE.txt +107 -0
  2. package/README.md +332 -19
  3. package/README.zh-CN.md +332 -0
  4. package/bin/run.cmd +3 -0
  5. package/bin/run.js +114 -0
  6. package/dist/commands/api/resource/create.js +15 -0
  7. package/dist/commands/api/resource/destroy.js +15 -0
  8. package/dist/commands/api/resource/get.js +15 -0
  9. package/dist/commands/api/resource/index.js +20 -0
  10. package/dist/commands/api/resource/list.js +16 -0
  11. package/dist/commands/api/resource/query.js +15 -0
  12. package/dist/commands/api/resource/update.js +15 -0
  13. package/dist/commands/build.js +57 -0
  14. package/dist/commands/db/logs.js +85 -0
  15. package/dist/commands/db/ps.js +60 -0
  16. package/dist/commands/db/shared.js +81 -0
  17. package/dist/commands/db/start.js +70 -0
  18. package/dist/commands/db/stop.js +70 -0
  19. package/dist/commands/dev.js +149 -0
  20. package/dist/commands/down.js +193 -0
  21. package/dist/commands/download.js +732 -0
  22. package/dist/commands/env/add.js +300 -0
  23. package/dist/commands/env/auth.js +62 -0
  24. package/dist/commands/env/list.js +41 -0
  25. package/dist/commands/env/remove.js +65 -0
  26. package/dist/commands/env/update.js +73 -0
  27. package/dist/commands/env/use.js +36 -0
  28. package/dist/commands/init.js +779 -0
  29. package/dist/commands/install.js +1725 -0
  30. package/dist/commands/logs.js +90 -0
  31. package/dist/commands/pm/disable.js +63 -0
  32. package/dist/commands/pm/enable.js +63 -0
  33. package/dist/commands/pm/list.js +54 -0
  34. package/dist/commands/prompts-stages.js +144 -0
  35. package/dist/commands/prompts-test.js +175 -0
  36. package/dist/commands/ps.js +116 -0
  37. package/dist/commands/scaffold/migration.js +38 -0
  38. package/dist/commands/scaffold/plugin.js +37 -0
  39. package/dist/commands/start.js +211 -0
  40. package/dist/commands/stop.js +90 -0
  41. package/dist/commands/upgrade.js +583 -0
  42. package/dist/generated/command-registry.js +133 -0
  43. package/dist/help/runtime-help.js +20 -0
  44. package/dist/lib/api-client.js +199 -0
  45. package/dist/lib/app-runtime.js +142 -0
  46. package/dist/lib/auth-store.js +241 -0
  47. package/dist/lib/bootstrap.js +387 -0
  48. package/dist/lib/build-config.js +10 -0
  49. package/dist/lib/cli-home.js +30 -0
  50. package/dist/lib/command-discovery.js +39 -0
  51. package/dist/lib/env-auth.js +872 -0
  52. package/dist/lib/generated-command.js +142 -0
  53. package/dist/lib/naming.js +70 -0
  54. package/dist/lib/openapi.js +62 -0
  55. package/dist/lib/post-processors.js +23 -0
  56. package/dist/lib/prompt-catalog.js +552 -0
  57. package/dist/lib/prompt-validators.js +184 -0
  58. package/dist/lib/prompt-web-ui.js +2027 -0
  59. package/dist/lib/resource-command.js +335 -0
  60. package/dist/lib/resource-request.js +104 -0
  61. package/dist/lib/run-npm.js +123 -0
  62. package/dist/lib/runtime-generator.js +408 -0
  63. package/dist/lib/runtime-store.js +56 -0
  64. package/dist/lib/ui.js +175 -0
  65. package/dist/post-processors/data-modeling.js +66 -0
  66. package/dist/post-processors/data-source-manager.js +114 -0
  67. package/dist/post-processors/index.js +19 -0
  68. package/nocobase-ctl.config.json +287 -0
  69. package/package.json +52 -26
  70. package/LICENSE +0 -661
  71. package/bin/index.js +0 -39
  72. package/nocobase.conf.tpl +0 -95
  73. package/src/cli.js +0 -19
  74. package/src/commands/benchmark.js +0 -73
  75. package/src/commands/build.js +0 -49
  76. package/src/commands/clean.js +0 -30
  77. package/src/commands/client.js +0 -166
  78. package/src/commands/create-nginx-conf.js +0 -37
  79. package/src/commands/create-plugin.js +0 -33
  80. package/src/commands/dev.js +0 -200
  81. package/src/commands/doc.js +0 -76
  82. package/src/commands/e2e.js +0 -265
  83. package/src/commands/global.js +0 -43
  84. package/src/commands/index.js +0 -45
  85. package/src/commands/instance-id.js +0 -47
  86. package/src/commands/locale/cronstrue.js +0 -122
  87. package/src/commands/locale/react-js-cron/en-US.json +0 -75
  88. package/src/commands/locale/react-js-cron/index.js +0 -17
  89. package/src/commands/locale/react-js-cron/zh-CN.json +0 -33
  90. package/src/commands/locale/react-js-cron/zh-TW.json +0 -33
  91. package/src/commands/locale.js +0 -81
  92. package/src/commands/p-test.js +0 -88
  93. package/src/commands/perf.js +0 -63
  94. package/src/commands/pkg.js +0 -321
  95. package/src/commands/pm2.js +0 -37
  96. package/src/commands/postinstall.js +0 -88
  97. package/src/commands/start.js +0 -148
  98. package/src/commands/tar.js +0 -36
  99. package/src/commands/test-coverage.js +0 -55
  100. package/src/commands/test.js +0 -107
  101. package/src/commands/umi.js +0 -33
  102. package/src/commands/update-deps.js +0 -72
  103. package/src/commands/upgrade.js +0 -47
  104. package/src/commands/view-license-key.js +0 -44
  105. package/src/index.js +0 -14
  106. package/src/license.js +0 -76
  107. package/src/logger.js +0 -75
  108. package/src/plugin-generator.js +0 -80
  109. package/src/util.js +0 -517
  110. package/templates/bundle-status.html +0 -338
  111. package/templates/create-app-package.json +0 -39
  112. package/templates/plugin/.npmignore.tpl +0 -2
  113. package/templates/plugin/README.md.tpl +0 -1
  114. package/templates/plugin/client.d.ts +0 -2
  115. package/templates/plugin/client.js +0 -1
  116. package/templates/plugin/package.json.tpl +0 -11
  117. package/templates/plugin/server.d.ts +0 -2
  118. package/templates/plugin/server.js +0 -1
  119. package/templates/plugin/src/client/client.d.ts +0 -249
  120. package/templates/plugin/src/client/index.tsx.tpl +0 -1
  121. package/templates/plugin/src/client/locale.ts +0 -21
  122. package/templates/plugin/src/client/models/index.ts +0 -12
  123. package/templates/plugin/src/client/plugin.tsx.tpl +0 -10
  124. package/templates/plugin/src/index.ts +0 -2
  125. package/templates/plugin/src/locale/en-US.json +0 -1
  126. package/templates/plugin/src/locale/zh-CN.json +0 -1
  127. package/templates/plugin/src/server/collections/.gitkeep +0 -0
  128. package/templates/plugin/src/server/index.ts.tpl +0 -1
  129. package/templates/plugin/src/server/plugin.ts.tpl +0 -19
@@ -0,0 +1,779 @@
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 { Command, Flags } from '@oclif/core';
10
+ import * as p from '@clack/prompts';
11
+ import pc from 'picocolors';
12
+ import { existsSync } from 'node:fs';
13
+ import path from 'node:path';
14
+ import { stdin as stdinStream, stdout as stdoutStream } from 'node:process';
15
+ import { getEnv, upsertEnv } from "../lib/auth-store.js";
16
+ import { runPromptCatalog, } from "../lib/prompt-catalog.js";
17
+ import { runPromptCatalogWebUI, } from "../lib/prompt-web-ui.js";
18
+ import { validateApiBaseUrl, validateEnvKey } from "../lib/prompt-validators.js";
19
+ import { run } from "../lib/run-npm.js";
20
+ import Download from "./download.js";
21
+ import EnvAdd from "./env/add.js";
22
+ import Install, { defaultDbPortForDialect } from "./install.js";
23
+ import _ from 'lodash';
24
+ const DEFAULT_INIT_API_BASE_URL = 'http://localhost:13000/api';
25
+ const DEFAULT_INIT_APP_NAME = 'local';
26
+ const DOWNLOAD_OUTPUT_DIR_PROMPT = Download.prompts.outputDir;
27
+ const CONFIG_SCOPE = 'project';
28
+ function withExtraHidden(def, extraHidden) {
29
+ if (def.type === 'run') {
30
+ return def;
31
+ }
32
+ return {
33
+ ...def,
34
+ hidden: (values) => extraHidden(values) || (def.hidden?.(values) ?? false),
35
+ };
36
+ }
37
+ function existingAppOnly(def) {
38
+ return withExtraHidden(def, (values) => values.hasNocobase !== 'yes');
39
+ }
40
+ function newInstallOnly(def) {
41
+ return withExtraHidden(def, (values) => values.hasNocobase !== 'no');
42
+ }
43
+ function downloadInNewInstallOnly(def) {
44
+ return withExtraHidden(def, (values) => values.hasNocobase !== 'no' || values.fetchSource !== true);
45
+ }
46
+ function argvHasToken(argv, tokens) {
47
+ return tokens.some((token) => argv.includes(token));
48
+ }
49
+ function shouldAllowExistingInitEnv() {
50
+ return argvHasToken(process.argv.slice(2), ['--force', '-f']);
51
+ }
52
+ async function validateInitAppName(value) {
53
+ const formatError = validateEnvKey(value);
54
+ if (formatError) {
55
+ return formatError;
56
+ }
57
+ const envName = String(value ?? '').trim();
58
+ if (!envName) {
59
+ return undefined;
60
+ }
61
+ const existingEnv = await getEnv(envName, { scope: 'project' });
62
+ if (existingEnv) {
63
+ if (shouldAllowExistingInitEnv()) {
64
+ return undefined;
65
+ }
66
+ return `Env "${envName}" already exists in this workspace. Choose another app name.`;
67
+ }
68
+ return undefined;
69
+ }
70
+ function highlightInitValidationMessage(message) {
71
+ return message.replace(/Env "([^"]+)"/, (_match, envName) => `Env ${pc.cyan(pc.bold(`"${envName}"`))}`);
72
+ }
73
+ function formatInitValidationMessage(message) {
74
+ if (/"appName" is required/.test(message)) {
75
+ return [
76
+ 'App name is required when prompts are skipped.',
77
+ 'The app name is also the CLI env name. Use `nb init --yes --env <envName>` to continue.',
78
+ ].join('\n');
79
+ }
80
+ return message;
81
+ }
82
+ function formatResumeEnvRequiredMessage() {
83
+ return [
84
+ 'Env name is required when resuming setup.',
85
+ 'App name is also the CLI env name. Use `nb init --resume --env <envName>` to continue.',
86
+ ].join('\n');
87
+ }
88
+ export default class Init extends Command {
89
+ static summary = 'Set up NocoBase so coding agents can connect and work with it';
90
+ static description = `Set up NocoBase for coding agents in the current workspace.
91
+
92
+ \`nb init\` prepares a NocoBase environment that coding agents can use. It supports two setup paths:
93
+
94
+ - Connect an existing NocoBase app and save it as a CLI env.
95
+ - Install a new NocoBase app, then save it as a CLI env.
96
+
97
+ It can also install NocoBase AI coding skills (\`nocobase/skills\`) so agents get the project-specific workflow guidance.
98
+
99
+ If setup was interrupted earlier, use \`--resume\` with an existing env name to continue from the saved workspace config.
100
+
101
+ Prompt modes:
102
+ - Default: guided prompts in the terminal.
103
+ - \`--ui\`: open the same setup flow in a local browser form.
104
+ - \`-y\`, \`--yes\`: skip prompts. In this mode \`--env <envName>\` is required, and init creates a new local NocoBase app with safe defaults.
105
+
106
+ \`--ui\` cannot be combined with \`--yes\`.`;
107
+ static examples = [
108
+ '<%= config.bin %> <%= command.id %>',
109
+ '<%= config.bin %> <%= command.id %> --env app1',
110
+ '<%= config.bin %> <%= command.id %> --env app1 --ui',
111
+ '<%= config.bin %> <%= command.id %> --ui',
112
+ '<%= config.bin %> <%= command.id %> --env app1 --yes',
113
+ '<%= config.bin %> <%= command.id %> --env app1 --resume',
114
+ '<%= config.bin %> <%= command.id %> --env app1 --yes --source docker --version alpha',
115
+ '<%= config.bin %> <%= command.id %> --env app1 --yes --source npm --version alpha --app-port 13080',
116
+ '<%= config.bin %> <%= command.id %> --env app1 --yes --source git --version fix/cli-v2',
117
+ '<%= config.bin %> <%= command.id %> --ui --ui-port 3000',
118
+ ];
119
+ static prompts = {
120
+ appName: {
121
+ type: 'text',
122
+ message: 'App name (also used as the CLI env name)',
123
+ placeholder: DEFAULT_INIT_APP_NAME,
124
+ required: true,
125
+ validate: validateInitAppName,
126
+ },
127
+ hasNocobase: {
128
+ type: 'select',
129
+ variant: 'radio',
130
+ message: 'Do you already have a NocoBase application?',
131
+ options: [
132
+ {
133
+ value: 'no',
134
+ label: "I don't have a NocoBase application yet",
135
+ },
136
+ {
137
+ value: 'yes',
138
+ label: 'I already have a NocoBase application',
139
+ },
140
+ ],
141
+ initialValue: 'no',
142
+ yesInitialValue: 'no',
143
+ required: true,
144
+ },
145
+ installSkills: {
146
+ type: 'boolean',
147
+ message: 'Install NocoBase AI coding skills (nocobase/skills)?',
148
+ initialValue: true,
149
+ yesInitialValue: true,
150
+ },
151
+ apiBaseUrl: existingAppOnly({
152
+ type: 'text',
153
+ message: 'API base URL',
154
+ placeholder: DEFAULT_INIT_API_BASE_URL,
155
+ required: true,
156
+ validate: validateApiBaseUrl,
157
+ }),
158
+ authType: existingAppOnly(EnvAdd.prompts.authType),
159
+ accessToken: existingAppOnly(EnvAdd.prompts.accessToken),
160
+ lang: newInstallOnly(Install.appPrompts.lang),
161
+ appRootPath: newInstallOnly(Install.appPrompts.appRootPath),
162
+ appPort: newInstallOnly(Install.appPrompts.appPort),
163
+ storagePath: newInstallOnly(Install.appPrompts.storagePath),
164
+ fetchSource: newInstallOnly(Install.appPrompts.fetchSource),
165
+ source: downloadInNewInstallOnly(Download.prompts.source),
166
+ version: downloadInNewInstallOnly(Download.prompts.version),
167
+ dockerRegistry: downloadInNewInstallOnly(Download.prompts.dockerRegistry),
168
+ dockerPlatform: downloadInNewInstallOnly(Download.prompts.dockerPlatform),
169
+ dockerSave: downloadInNewInstallOnly(Download.prompts.dockerSave),
170
+ gitUrl: downloadInNewInstallOnly(Download.prompts.gitUrl),
171
+ outputDir: downloadInNewInstallOnly({
172
+ ...DOWNLOAD_OUTPUT_DIR_PROMPT,
173
+ hidden: (values) => {
174
+ const source = String(values.source ?? '').trim();
175
+ if (source === 'npm' || source === 'git') {
176
+ return true;
177
+ }
178
+ return DOWNLOAD_OUTPUT_DIR_PROMPT.hidden?.(values) ?? false;
179
+ },
180
+ initialValue: (values) => {
181
+ const source = String(values.source ?? '').trim();
182
+ if (source === 'npm' || source === 'git') {
183
+ const appRootPath = String(values.appRootPath ?? '').trim();
184
+ if (appRootPath) {
185
+ return appRootPath;
186
+ }
187
+ }
188
+ const initialValue = DOWNLOAD_OUTPUT_DIR_PROMPT.initialValue;
189
+ return typeof initialValue === 'function' ? initialValue(values) : String(initialValue ?? '');
190
+ },
191
+ }),
192
+ npmRegistry: downloadInNewInstallOnly(Download.prompts.npmRegistry),
193
+ replace: downloadInNewInstallOnly(Download.prompts.replace),
194
+ devDependencies: downloadInNewInstallOnly(Download.prompts.devDependencies),
195
+ build: downloadInNewInstallOnly(Download.prompts.build),
196
+ buildDts: downloadInNewInstallOnly(Download.prompts.buildDts),
197
+ builtinDb: newInstallOnly(Install.dbPrompts.builtinDb),
198
+ dbDialect: newInstallOnly(Install.dbPrompts.dbDialect),
199
+ dbHost: newInstallOnly(Install.dbPrompts.dbHost),
200
+ dbPort: newInstallOnly(Install.dbPrompts.dbPort),
201
+ dbDatabase: newInstallOnly(Install.dbPrompts.dbDatabase),
202
+ dbUser: newInstallOnly(Install.dbPrompts.dbUser),
203
+ dbPassword: newInstallOnly(Install.dbPrompts.dbPassword),
204
+ rootUsername: newInstallOnly(Install.rootUserPrompts.rootUsername),
205
+ rootEmail: newInstallOnly(Install.rootUserPrompts.rootEmail),
206
+ rootPassword: newInstallOnly(Install.rootUserPrompts.rootPassword),
207
+ rootNickname: newInstallOnly(Install.rootUserPrompts.rootNickname),
208
+ };
209
+ static flags = {
210
+ yes: Flags.boolean({
211
+ char: 'y',
212
+ description: 'Skip prompts and create a new local NocoBase app. Requires an app/env name.',
213
+ default: false,
214
+ }),
215
+ env: Flags.string({
216
+ char: 'e',
217
+ description: 'App name / CLI env name for this setup. Required with --yes and --resume',
218
+ }),
219
+ 'install-skills': Flags.boolean({
220
+ description: 'Install NocoBase AI coding skills (`nocobase/skills`) for this workspace',
221
+ default: false,
222
+ }),
223
+ ui: Flags.boolean({
224
+ description: 'Open the guided setup flow in a local browser form (not valid with --yes)',
225
+ default: false,
226
+ }),
227
+ 'ui-host': Flags.string({
228
+ description: 'Host for the local --ui setup server (default: 127.0.0.1)',
229
+ }),
230
+ 'ui-port': Flags.integer({
231
+ description: 'Port for the local --ui setup server; 0 lets the OS choose an available port',
232
+ min: 0,
233
+ max: 65535,
234
+ }),
235
+ ..._.omit(Install.flags, ['yes', 'env']),
236
+ };
237
+ async run() {
238
+ const parsedResult = await this.parse(Init);
239
+ const flags = parsedResult.flags;
240
+ const normalizedFlags = { ...flags };
241
+ if (normalizedFlags.ui && normalizedFlags.yes) {
242
+ this.error('--ui cannot be used with --yes.');
243
+ }
244
+ if (normalizedFlags.ui && normalizedFlags.resume) {
245
+ this.error('--ui cannot be used with --resume.');
246
+ }
247
+ if (!normalizedFlags.ui &&
248
+ (normalizedFlags['ui-host'] !== undefined || normalizedFlags['ui-port'] !== undefined)) {
249
+ this.error('--ui-host and --ui-port require --ui.');
250
+ }
251
+ if (normalizedFlags.resume) {
252
+ const envName = String(normalizedFlags.env ?? '').trim();
253
+ if (!envName) {
254
+ p.log.error(formatResumeEnvRequiredMessage());
255
+ this.exit(1);
256
+ }
257
+ p.intro('Set Up NocoBase for Coding Agents');
258
+ if (Boolean(normalizedFlags['install-skills'])) {
259
+ try {
260
+ p.log.step('Installing NocoBase agent skills (npx -y skills add nocobase/skills)');
261
+ await run('npx', ['-y', 'skills', 'add', 'nocobase/skills', '-y']);
262
+ }
263
+ catch (error) {
264
+ const message = error instanceof Error ? error.message : String(error);
265
+ p.outro(pc.red(`Skills install failed: ${message}`));
266
+ this.error(message);
267
+ }
268
+ }
269
+ try {
270
+ p.log.step(`Resuming setup for env "${envName}" from the saved workspace config`);
271
+ await this.config.runCommand('install', this.buildResumeInstallArgv(normalizedFlags));
272
+ }
273
+ catch (error) {
274
+ const message = error instanceof Error ? error.message : String(error);
275
+ p.outro(pc.red(message));
276
+ this.error(message);
277
+ }
278
+ p.outro('Workspace init finished.');
279
+ return;
280
+ }
281
+ const interactive = Boolean(stdinStream.isTTY && stdoutStream.isTTY);
282
+ const useBrowserUi = Boolean(normalizedFlags.ui);
283
+ let presetValues = this.buildPresetValuesFromFlags(normalizedFlags);
284
+ if (normalizedFlags.yes && !String(presetValues.appName ?? '').trim()) {
285
+ const formatted = formatInitValidationMessage('Non-interactive: "appName" is required; set initialValues.appName, yesInitialValues.appName, yesInitialValue on the block, or initialValue.');
286
+ p.log.error(highlightInitValidationMessage(formatted));
287
+ this.exit(1);
288
+ }
289
+ const appName = String(presetValues.appName ?? '').trim();
290
+ if (useBrowserUi) {
291
+ p.intro('Set Up NocoBase for Coding Agents');
292
+ p.log.info('A local setup form will open in your browser. Submit the form there to continue in this terminal.');
293
+ }
294
+ else {
295
+ p.intro('Set Up NocoBase for Coding Agents');
296
+ if (normalizedFlags.yes) {
297
+ p.log.info(`Prompts skipped (--yes). NocoBase will be installed for env "${appName}" using the provided flags and safe defaults.`);
298
+ }
299
+ else if (!interactive) {
300
+ p.log.warn('No interactive terminal detected. NocoBase will be installed using the provided flags and safe defaults.');
301
+ }
302
+ }
303
+ const dynamicInitialValues = await Init.buildDynamicInitialValuesForInstall(normalizedFlags, presetValues);
304
+ if (useBrowserUi) {
305
+ presetValues = await runPromptCatalogWebUI({
306
+ stages: Init.buildWebUiStages(),
307
+ values: {
308
+ ...dynamicInitialValues,
309
+ ...presetValues,
310
+ },
311
+ host: normalizedFlags['ui-host']?.trim() || '127.0.0.1',
312
+ port: normalizedFlags['ui-port'] ?? 0,
313
+ pageTitle: 'Set Up NocoBase for Coding Agents',
314
+ documentHeading: 'Set Up NocoBase for Coding Agents',
315
+ documentHint: 'Connect an existing NocoBase app or install a new one, then save it as an agent-ready CLI environment.',
316
+ onServerStart: ({ host, port, url }) => {
317
+ this.log(`Local setup form ready at ${url} (listening on ${host}:${port}). Submit it in your browser to continue here.`);
318
+ },
319
+ onOpenBrowserError: (url, err) => {
320
+ this.log(`Open this URL in your browser to continue setup: ${url} (${err instanceof Error ? err.message : String(err)})`);
321
+ },
322
+ });
323
+ }
324
+ const results = await runPromptCatalog(Init.prompts, {
325
+ initialValues: dynamicInitialValues,
326
+ values: presetValues,
327
+ yes: normalizedFlags.yes || useBrowserUi || !interactive,
328
+ hooks: {
329
+ onCancel: () => {
330
+ p.cancel('Init cancelled.');
331
+ this.exit(0);
332
+ },
333
+ onMissingNonInteractive: (message) => {
334
+ const formatted = formatInitValidationMessage(message);
335
+ p.log.error(highlightInitValidationMessage(formatted));
336
+ this.exit(1);
337
+ },
338
+ },
339
+ command: this,
340
+ });
341
+ const installSkills = Boolean(results.installSkills);
342
+ const hasNocobase = results.hasNocobase === 'yes';
343
+ const existingEnv = !hasNocobase
344
+ ? await getEnv(String(results.appName ?? '').trim(), { scope: 'project' })
345
+ : undefined;
346
+ if (existingEnv && Boolean(normalizedFlags.force)) {
347
+ p.log.warn(`Reconfiguring existing env ${pc.cyan(pc.bold(`"${existingEnv.name}"`))} in this workspace because ${pc.bold('--force')} was set. The env config will be updated before install starts, then refreshed again after install succeeds.`);
348
+ }
349
+ if (installSkills) {
350
+ try {
351
+ p.log.step('Installing NocoBase agent skills (npx -y skills add nocobase/skills)');
352
+ await run('npx', ['-y', 'skills', 'add', 'nocobase/skills', '-y']);
353
+ }
354
+ catch (error) {
355
+ const message = error instanceof Error ? error.message : String(error);
356
+ p.outro(pc.red(`Skills install failed: ${message}`));
357
+ this.error(message);
358
+ }
359
+ }
360
+ else {
361
+ p.log.info('Skipped NocoBase agent skills install.');
362
+ }
363
+ try {
364
+ // oclif explicit registry keys use `:` (e.g. `env:add`); users still type `nb env add`.
365
+ if (hasNocobase) {
366
+ p.log.step('Running nb env add');
367
+ await this.config.runCommand('env:add', this.buildEnvAddArgv(results));
368
+ }
369
+ else {
370
+ p.log.step('Saving the local env config');
371
+ await this.persistManagedEnvConfig(results);
372
+ p.log.step('Running nb install');
373
+ await this.config.runCommand('install', this.buildInstallArgv(results, normalizedFlags));
374
+ }
375
+ }
376
+ catch (error) {
377
+ const message = error instanceof Error ? error.message : String(error);
378
+ p.outro(pc.red(message));
379
+ this.error(message);
380
+ }
381
+ p.outro('Workspace init finished.');
382
+ }
383
+ static async buildDynamicInitialValuesForInstall(flags, presetValues) {
384
+ const out = {};
385
+ if (!Object.prototype.hasOwnProperty.call(presetValues, 'appPort')) {
386
+ const appInitialValues = await Install.buildAppPromptInitialValues({
387
+ envName: String(presetValues.appName ?? '').trim(),
388
+ flags: {
389
+ ...flags,
390
+ 'app-root-path': flags['app-root-path'] ?? '',
391
+ 'storage-path': flags['storage-path'] ?? '',
392
+ },
393
+ });
394
+ if (appInitialValues.appPort !== undefined) {
395
+ out.appPort = appInitialValues.appPort;
396
+ }
397
+ }
398
+ const downloadSeed = { ...presetValues };
399
+ if (flags.yes
400
+ && !Object.prototype.hasOwnProperty.call(downloadSeed, 'source')
401
+ && downloadSeed.fetchSource !== false) {
402
+ downloadSeed.source = 'docker';
403
+ }
404
+ const dbInitial = await Install.buildDbPromptInitialValues({
405
+ flags,
406
+ downloadResults: downloadSeed,
407
+ dbPreset: presetValues,
408
+ });
409
+ for (const [key, value] of Object.entries(dbInitial)) {
410
+ if (!Object.prototype.hasOwnProperty.call(presetValues, key)) {
411
+ out[key] = value;
412
+ }
413
+ }
414
+ return out;
415
+ }
416
+ static buildWebUiStages() {
417
+ const c = Init.prompts;
418
+ return [
419
+ {
420
+ sectionTitle: 'Getting started',
421
+ sectionDescription: 'Pick your setup path.',
422
+ catalog: {
423
+ appName: c.appName,
424
+ hasNocobase: c.hasNocobase,
425
+ installSkills: c.installSkills,
426
+ },
427
+ },
428
+ {
429
+ sectionTitle: 'Connect an existing app',
430
+ sectionDescription: 'Add your app connection.',
431
+ catalog: {
432
+ apiBaseUrl: c.apiBaseUrl,
433
+ authType: c.authType,
434
+ accessToken: c.accessToken,
435
+ },
436
+ },
437
+ {
438
+ sectionTitle: 'Create a new app',
439
+ sectionDescription: 'Set project basics.',
440
+ catalog: {
441
+ lang: c.lang,
442
+ appRootPath: c.appRootPath,
443
+ appPort: c.appPort,
444
+ storagePath: c.storagePath,
445
+ fetchSource: c.fetchSource,
446
+ },
447
+ },
448
+ {
449
+ sectionTitle: 'Download app files',
450
+ sectionDescription: 'Choose source and options.',
451
+ catalog: {
452
+ source: c.source,
453
+ version: c.version,
454
+ dockerRegistry: c.dockerRegistry,
455
+ dockerPlatform: c.dockerPlatform,
456
+ dockerSave: c.dockerSave,
457
+ gitUrl: c.gitUrl,
458
+ outputDir: c.outputDir,
459
+ npmRegistry: c.npmRegistry,
460
+ replace: c.replace,
461
+ devDependencies: c.devDependencies,
462
+ build: c.build,
463
+ buildDts: c.buildDts,
464
+ },
465
+ },
466
+ {
467
+ sectionTitle: 'Configure the database',
468
+ sectionDescription: 'Use built-in or custom.',
469
+ catalog: {
470
+ builtinDb: c.builtinDb,
471
+ dbDialect: c.dbDialect,
472
+ dbHost: c.dbHost,
473
+ dbPort: c.dbPort,
474
+ dbDatabase: c.dbDatabase,
475
+ dbUser: c.dbUser,
476
+ dbPassword: c.dbPassword,
477
+ },
478
+ },
479
+ {
480
+ sectionTitle: 'Create an admin account',
481
+ sectionDescription: 'Set up the first admin.',
482
+ catalog: {
483
+ rootUsername: c.rootUsername,
484
+ rootEmail: c.rootEmail,
485
+ rootPassword: c.rootPassword,
486
+ rootNickname: c.rootNickname,
487
+ },
488
+ },
489
+ ];
490
+ }
491
+ buildPresetValuesFromFlags(flags) {
492
+ const preset = {};
493
+ const argv = process.argv.slice(2);
494
+ if (flags.env !== undefined && String(flags.env).trim() !== '') {
495
+ preset.appName = String(flags.env).trim();
496
+ }
497
+ if (flags.lang !== undefined && String(flags.lang).trim() !== '') {
498
+ preset.lang = String(flags.lang).trim();
499
+ }
500
+ if (flags['app-root-path'] !== undefined && String(flags['app-root-path']).trim() !== '') {
501
+ preset.appRootPath = String(flags['app-root-path']).trim();
502
+ }
503
+ if (flags['app-port'] !== undefined && String(flags['app-port']).trim() !== '') {
504
+ preset.appPort = String(flags['app-port']).trim();
505
+ }
506
+ if (flags['storage-path'] !== undefined && String(flags['storage-path']).trim() !== '') {
507
+ preset.storagePath = String(flags['storage-path']).trim();
508
+ }
509
+ if (flags['root-username'] !== undefined) {
510
+ preset.rootUsername = String(flags['root-username'] ?? '').trim();
511
+ }
512
+ if (flags['root-email'] !== undefined) {
513
+ preset.rootEmail = String(flags['root-email'] ?? '').trim();
514
+ }
515
+ if (flags['root-password'] !== undefined) {
516
+ preset.rootPassword = String(flags['root-password'] ?? '');
517
+ }
518
+ if (flags['root-nickname'] !== undefined) {
519
+ preset.rootNickname = String(flags['root-nickname'] ?? '').trim();
520
+ }
521
+ if (flags['db-dialect'] !== undefined && String(flags['db-dialect']).trim() !== '') {
522
+ preset.dbDialect = String(flags['db-dialect']).trim();
523
+ }
524
+ if (flags['db-host'] !== undefined && String(flags['db-host']).trim() !== '') {
525
+ preset.dbHost = String(flags['db-host']).trim();
526
+ }
527
+ if (flags['db-port'] !== undefined && String(flags['db-port']).trim() !== '') {
528
+ preset.dbPort = String(flags['db-port']).trim();
529
+ }
530
+ if (flags['db-database'] !== undefined && String(flags['db-database']).trim() !== '') {
531
+ preset.dbDatabase = String(flags['db-database']).trim();
532
+ }
533
+ if (flags['db-user'] !== undefined && String(flags['db-user']).trim() !== '') {
534
+ preset.dbUser = String(flags['db-user']).trim();
535
+ }
536
+ if (flags['db-password'] !== undefined) {
537
+ preset.dbPassword = String(flags['db-password'] ?? '');
538
+ }
539
+ if (argvHasToken(argv, ['--fetch-source'])) {
540
+ preset.fetchSource = Boolean(flags['fetch-source']);
541
+ }
542
+ if (flags.source !== undefined && String(flags.source).trim() !== '') {
543
+ preset.source = String(flags.source).trim();
544
+ }
545
+ if (flags.version !== undefined) {
546
+ preset.version = String(flags.version).trim() || 'latest';
547
+ }
548
+ if (flags['docker-registry'] !== undefined && String(flags['docker-registry']).trim() !== '') {
549
+ preset.dockerRegistry = String(flags['docker-registry']).trim();
550
+ }
551
+ if (flags['docker-platform'] !== undefined && String(flags['docker-platform']).trim() !== '') {
552
+ preset.dockerPlatform = String(flags['docker-platform']).trim();
553
+ }
554
+ if (flags['output-dir'] !== undefined && String(flags['output-dir']).trim() !== '') {
555
+ preset.outputDir = String(flags['output-dir']).trim();
556
+ }
557
+ if (flags['git-url'] !== undefined && String(flags['git-url']).trim() !== '') {
558
+ preset.gitUrl = String(flags['git-url']).trim();
559
+ }
560
+ if (flags['npm-registry'] !== undefined) {
561
+ preset.npmRegistry = String(flags['npm-registry'] ?? '');
562
+ }
563
+ if (argvHasToken(argv, ['--replace', '-r'])) {
564
+ preset.replace = Boolean(flags.replace);
565
+ }
566
+ if (argvHasToken(argv, ['--dev-dependencies', '--no-dev-dependencies', '-D'])) {
567
+ preset.devDependencies = Boolean(flags['dev-dependencies']);
568
+ }
569
+ if (argvHasToken(argv, ['--docker-save', '--no-docker-save'])) {
570
+ preset.dockerSave = Boolean(flags['docker-save']);
571
+ }
572
+ if (argvHasToken(argv, ['--build', '--no-build'])) {
573
+ preset.build = Boolean(flags.build);
574
+ }
575
+ if (argvHasToken(argv, ['--build-dts', '--no-build-dts'])) {
576
+ preset.buildDts = Boolean(flags['build-dts']);
577
+ }
578
+ if (argvHasToken(argv, ['--builtin-db'])) {
579
+ preset.builtinDb = Boolean(flags['builtin-db']);
580
+ }
581
+ if (argvHasToken(argv, ['--install-skills'])) {
582
+ preset.installSkills = Boolean(flags['install-skills']);
583
+ }
584
+ else if (this.hasAgentsDirInCwd()) {
585
+ preset.installSkills = false;
586
+ }
587
+ return preset;
588
+ }
589
+ hasAgentsDirInCwd() {
590
+ return existsSync(path.resolve(process.cwd(), '.agents'));
591
+ }
592
+ async persistManagedEnvConfig(results) {
593
+ const envName = String(results.appName ?? DEFAULT_INIT_APP_NAME).trim() || DEFAULT_INIT_APP_NAME;
594
+ const appPort = String(results.appPort ?? '').trim();
595
+ const source = String(results.source ?? '').trim();
596
+ const version = String(results.version ?? '').trim();
597
+ const dockerRegistry = String(results.dockerRegistry ?? '').trim();
598
+ const dockerPlatform = String(results.dockerPlatform ?? '').trim();
599
+ const gitUrl = String(results.gitUrl ?? '').trim();
600
+ const npmRegistry = String(results.npmRegistry ?? '').trim();
601
+ const appRootPath = String(results.appRootPath ?? '').trim();
602
+ const storagePath = String(results.storagePath ?? '').trim();
603
+ const dbDialect = String(results.dbDialect ?? '').trim();
604
+ const dbHost = String(results.dbHost ?? '').trim();
605
+ const dbPort = String(results.dbPort ?? '').trim();
606
+ const dbDatabase = String(results.dbDatabase ?? '').trim();
607
+ const dbUser = String(results.dbUser ?? '').trim();
608
+ const dbPassword = String(results.dbPassword ?? '');
609
+ await upsertEnv(envName, {
610
+ ...(appPort ? { baseUrl: `http://127.0.0.1:${appPort}/api` } : {}),
611
+ ...(source ? { source } : {}),
612
+ ...(version ? { downloadVersion: version } : {}),
613
+ ...(dockerRegistry ? { dockerRegistry } : {}),
614
+ ...(dockerPlatform ? { dockerPlatform } : {}),
615
+ ...(gitUrl ? { gitUrl } : {}),
616
+ ...(npmRegistry ? { npmRegistry } : {}),
617
+ ...(appRootPath ? { appRootPath } : {}),
618
+ ...(storagePath ? { storagePath } : {}),
619
+ ...(appPort ? { appPort } : {}),
620
+ ...(results.devDependencies !== undefined ? { devDependencies: Boolean(results.devDependencies) } : {}),
621
+ ...(results.build !== undefined ? { build: Boolean(results.build) } : {}),
622
+ ...(results.buildDts !== undefined ? { buildDts: Boolean(results.buildDts) } : {}),
623
+ ...(results.builtinDb !== undefined ? { builtinDb: Boolean(results.builtinDb) } : {}),
624
+ ...(dbDialect ? { dbDialect } : {}),
625
+ ...(dbHost ? { dbHost } : {}),
626
+ ...(dbPort ? { dbPort } : {}),
627
+ ...(dbDatabase ? { dbDatabase } : {}),
628
+ ...(dbUser ? { dbUser } : {}),
629
+ ...(dbPassword ? { dbPassword } : {}),
630
+ }, { scope: CONFIG_SCOPE });
631
+ }
632
+ buildEnvAddArgv(results) {
633
+ const argv = [String(results.appName ?? DEFAULT_INIT_APP_NAME)];
634
+ argv.push('--no-intro');
635
+ argv.push('--scope', CONFIG_SCOPE);
636
+ argv.push('--api-base-url', String(results.apiBaseUrl ?? DEFAULT_INIT_API_BASE_URL));
637
+ argv.push('--auth-type', String(results.authType ?? 'oauth'));
638
+ if (results.authType === 'token') {
639
+ argv.push('--access-token', String(results.accessToken ?? ''));
640
+ }
641
+ return argv;
642
+ }
643
+ buildInstallArgv(results, flags, options) {
644
+ const argv = ['--no-intro'];
645
+ if (options?.nonInteractive ?? true) {
646
+ argv.unshift('-y');
647
+ }
648
+ const processArgv = process.argv.slice(2);
649
+ const envName = String(results.appName ?? DEFAULT_INIT_APP_NAME).trim() || DEFAULT_INIT_APP_NAME;
650
+ const source = String(results.source ?? '').trim();
651
+ argv.push('--env', envName);
652
+ if (options?.resume) {
653
+ argv.push('--resume');
654
+ }
655
+ const lang = String(results.lang ?? '').trim();
656
+ if (lang) {
657
+ argv.push('--lang', lang);
658
+ }
659
+ const appRootPath = String(results.appRootPath ?? '').trim();
660
+ if (appRootPath) {
661
+ argv.push('--app-root-path', appRootPath);
662
+ }
663
+ const appPort = String(results.appPort ?? '').trim();
664
+ if (appPort && (!flags.yes || argvHasToken(processArgv, ['--app-port']) || appPort !== '13000')) {
665
+ argv.push('--app-port', appPort);
666
+ }
667
+ const storagePath = String(results.storagePath ?? '').trim();
668
+ if (storagePath) {
669
+ argv.push('--storage-path', storagePath);
670
+ }
671
+ if (Boolean(flags.force)) {
672
+ argv.push('--force');
673
+ }
674
+ if (Boolean(results.fetchSource)) {
675
+ argv.push('--fetch-source');
676
+ if (source) {
677
+ argv.push('--source', source);
678
+ }
679
+ const version = String(results.version ?? '').trim();
680
+ if (version) {
681
+ argv.push('--version', version);
682
+ }
683
+ const outputDir = String(results.outputDir ?? '').trim();
684
+ if (outputDir) {
685
+ argv.push('--output-dir', outputDir);
686
+ }
687
+ const gitUrl = String(results.gitUrl ?? '').trim();
688
+ if (gitUrl) {
689
+ argv.push('--git-url', gitUrl);
690
+ }
691
+ const dockerRegistry = String(results.dockerRegistry ?? '').trim();
692
+ if (dockerRegistry) {
693
+ argv.push('--docker-registry', dockerRegistry);
694
+ }
695
+ const dockerPlatform = String(results.dockerPlatform ?? '').trim();
696
+ if (dockerPlatform) {
697
+ argv.push('--docker-platform', dockerPlatform);
698
+ }
699
+ const npmRegistry = String(results.npmRegistry ?? '').trim();
700
+ if (npmRegistry) {
701
+ argv.push('--npm-registry', npmRegistry);
702
+ }
703
+ if (Boolean(results.replace)) {
704
+ argv.push('--replace');
705
+ }
706
+ if (Boolean(results.devDependencies)) {
707
+ argv.push('--dev-dependencies');
708
+ }
709
+ if (Boolean(results.dockerSave)) {
710
+ argv.push('--docker-save');
711
+ }
712
+ if (results.build !== undefined && !Boolean(results.build)) {
713
+ argv.push('--no-build');
714
+ }
715
+ else if (argvHasToken(processArgv, ['--build', '--no-build']) && flags.build === false) {
716
+ argv.push('--no-build');
717
+ }
718
+ if (Boolean(results.buildDts)) {
719
+ argv.push('--build-dts');
720
+ }
721
+ }
722
+ const builtinDb = Boolean(results.builtinDb);
723
+ if (builtinDb) {
724
+ argv.push('--builtin-db');
725
+ }
726
+ const dbDialect = String(results.dbDialect ?? '').trim();
727
+ if (dbDialect) {
728
+ argv.push('--db-dialect', dbDialect);
729
+ }
730
+ const dbHost = String(results.dbHost ?? '').trim();
731
+ if (dbHost) {
732
+ argv.push('--db-host', dbHost);
733
+ }
734
+ const dbPort = String(results.dbPort ?? '').trim();
735
+ const dbPortWasProvided = argvHasToken(processArgv, ['--db-port']);
736
+ const dockerBuiltinDbPortIsHidden = builtinDb && source === 'docker';
737
+ const dbDefaultPort = defaultDbPortForDialect(dbDialect);
738
+ if (dbPort
739
+ && (!dockerBuiltinDbPortIsHidden || dbPortWasProvided)
740
+ && (!flags.yes || dbPortWasProvided || dbPort !== dbDefaultPort)) {
741
+ argv.push('--db-port', dbPort);
742
+ }
743
+ const dbDatabase = String(results.dbDatabase ?? '').trim();
744
+ if (dbDatabase) {
745
+ argv.push('--db-database', dbDatabase);
746
+ }
747
+ const dbUser = String(results.dbUser ?? '').trim();
748
+ if (dbUser) {
749
+ argv.push('--db-user', dbUser);
750
+ }
751
+ const dbPassword = String(results.dbPassword ?? '');
752
+ if (dbPassword) {
753
+ argv.push('--db-password', dbPassword);
754
+ }
755
+ const rootUsername = String(results.rootUsername ?? '').trim();
756
+ if (rootUsername) {
757
+ argv.push('--root-username', rootUsername);
758
+ }
759
+ const rootEmail = String(results.rootEmail ?? '').trim();
760
+ if (rootEmail) {
761
+ argv.push('--root-email', rootEmail);
762
+ }
763
+ const rootPassword = String(results.rootPassword ?? '');
764
+ if (rootPassword) {
765
+ argv.push('--root-password', rootPassword);
766
+ }
767
+ const rootNickname = String(results.rootNickname ?? '').trim();
768
+ if (rootNickname) {
769
+ argv.push('--root-nickname', rootNickname);
770
+ }
771
+ return argv;
772
+ }
773
+ buildResumeInstallArgv(flags) {
774
+ return this.buildInstallArgv(this.buildPresetValuesFromFlags(flags), flags, {
775
+ nonInteractive: Boolean(flags.yes),
776
+ resume: true,
777
+ });
778
+ }
779
+ }