@angular/cli 14.0.0-next.8 → 14.0.0-rc.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 (40) hide show
  1. package/lib/cli/index.js +1 -1
  2. package/lib/config/schema.json +18 -0
  3. package/lib/config/workspace-schema.d.ts +12 -0
  4. package/lib/init.js +1 -1
  5. package/package.json +16 -16
  6. package/src/analytics/analytics.d.ts +1 -1
  7. package/src/analytics/analytics.js +22 -20
  8. package/src/command-builder/architect-base-command-module.d.ts +1 -1
  9. package/src/command-builder/architect-base-command-module.js +7 -1
  10. package/src/command-builder/architect-command-module.d.ts +4 -0
  11. package/src/command-builder/architect-command-module.js +26 -6
  12. package/src/command-builder/command-module.d.ts +1 -0
  13. package/src/command-builder/command-module.js +7 -0
  14. package/src/command-builder/command-runner.js +41 -30
  15. package/src/command-builder/schematics-command-module.js +10 -7
  16. package/src/command-builder/utilities/command.d.ts +1 -1
  17. package/src/command-builder/utilities/normalize-options-middleware.d.ts +18 -0
  18. package/src/command-builder/utilities/normalize-options-middleware.js +59 -0
  19. package/src/command-builder/utilities/schematic-engine-host.d.ts +2 -2
  20. package/src/command-builder/utilities/schematic-engine-host.js +33 -18
  21. package/src/commands/analytics/settings/cli.js +2 -2
  22. package/src/commands/cache/settings/cli.d.ts +2 -2
  23. package/src/commands/cache/settings/cli.js +2 -2
  24. package/src/commands/cache/utilities.d.ts +1 -1
  25. package/src/commands/cache/utilities.js +7 -8
  26. package/src/commands/completion/cli.d.ts +16 -0
  27. package/src/commands/completion/cli.js +68 -0
  28. package/src/commands/completion/long-description.md +73 -0
  29. package/src/commands/config/cli.js +15 -14
  30. package/src/commands/doc/cli.js +2 -2
  31. package/src/commands/run/cli.d.ts +2 -0
  32. package/src/commands/run/cli.js +24 -0
  33. package/src/commands/update/cli.js +3 -2
  34. package/src/utilities/completion.d.ts +30 -0
  35. package/src/utilities/completion.js +282 -0
  36. package/src/utilities/config.d.ts +4 -3
  37. package/src/utilities/config.js +11 -5
  38. package/src/utilities/environment-options.d.ts +1 -0
  39. package/src/utilities/environment-options.js +8 -1
  40. package/src/utilities/json-file.js +1 -0
@@ -0,0 +1,282 @@
1
+ "use strict";
2
+ /**
3
+ * @license
4
+ * Copyright Google LLC All Rights Reserved.
5
+ *
6
+ * Use of this source code is governed by an MIT-style license that can be
7
+ * found in the LICENSE file at https://angular.io/license
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || function (mod) {
26
+ if (mod && mod.__esModule) return mod;
27
+ var result = {};
28
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
29
+ __setModuleDefault(result, mod);
30
+ return result;
31
+ };
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.hasGlobalCliInstall = exports.initializeAutocomplete = exports.considerSettingUpAutocompletion = void 0;
34
+ const core_1 = require("@angular-devkit/core");
35
+ const child_process_1 = require("child_process");
36
+ const fs_1 = require("fs");
37
+ const path = __importStar(require("path"));
38
+ const process_1 = require("process");
39
+ const color_1 = require("../utilities/color");
40
+ const config_1 = require("../utilities/config");
41
+ const environment_options_1 = require("../utilities/environment-options");
42
+ const tty_1 = require("../utilities/tty");
43
+ /**
44
+ * Checks if it is appropriate to prompt the user to setup autocompletion. If not, does nothing. If
45
+ * so prompts and sets up autocompletion for the user. Returns an exit code if the program should
46
+ * terminate, otherwise returns `undefined`.
47
+ * @returns an exit code if the program should terminate, undefined otherwise.
48
+ */
49
+ async function considerSettingUpAutocompletion(command, logger) {
50
+ // Check if we should prompt the user to setup autocompletion.
51
+ const completionConfig = await getCompletionConfig();
52
+ if (!(await shouldPromptForAutocompletionSetup(command, completionConfig))) {
53
+ return undefined; // Already set up or prompted previously, nothing to do.
54
+ }
55
+ // Prompt the user and record their response.
56
+ const shouldSetupAutocompletion = await promptForAutocompletion();
57
+ if (!shouldSetupAutocompletion) {
58
+ // User rejected the prompt and doesn't want autocompletion.
59
+ logger.info(`
60
+ Ok, you won't be prompted again. Should you change your mind, the following command will set up autocompletion for you:
61
+
62
+ ${color_1.colors.yellow(`ng completion`)}
63
+ `.trim());
64
+ // Save configuration to remember that the user was prompted and avoid prompting again.
65
+ await setCompletionConfig({ ...completionConfig, prompted: true });
66
+ return undefined;
67
+ }
68
+ // User accepted the prompt, set up autocompletion.
69
+ let rcFile;
70
+ try {
71
+ rcFile = await initializeAutocomplete();
72
+ }
73
+ catch (err) {
74
+ // Failed to set up autocompeletion, log the error and abort.
75
+ logger.error(err.message);
76
+ return 1;
77
+ }
78
+ // Notify the user autocompletion was set up successfully.
79
+ logger.info(`
80
+ Appended \`source <(ng completion script)\` to \`${rcFile}\`. Restart your terminal or run the following to autocomplete \`ng\` commands:
81
+
82
+ ${color_1.colors.yellow(`source <(ng completion script)`)}
83
+ `.trim());
84
+ if ((await hasGlobalCliInstall()) === false) {
85
+ logger.warn('Setup completed successfully, but there does not seem to be a global install of the' +
86
+ ' Angular CLI. For autocompletion to work, the CLI will need to be on your `$PATH`, which' +
87
+ ' is typically done with the `-g` flag in `npm install -g @angular/cli`.' +
88
+ '\n\n' +
89
+ 'For more information, see https://angular.io/cli/completion#global-install');
90
+ }
91
+ // Save configuration to remember that the user was prompted.
92
+ await setCompletionConfig({ ...completionConfig, prompted: true });
93
+ return undefined;
94
+ }
95
+ exports.considerSettingUpAutocompletion = considerSettingUpAutocompletion;
96
+ async function getCompletionConfig() {
97
+ var _a;
98
+ const wksp = await (0, config_1.getWorkspace)('global');
99
+ return (_a = wksp === null || wksp === void 0 ? void 0 : wksp.getCli()) === null || _a === void 0 ? void 0 : _a['completion'];
100
+ }
101
+ async function setCompletionConfig(config) {
102
+ var _a;
103
+ var _b;
104
+ const wksp = await (0, config_1.getWorkspace)('global');
105
+ if (!wksp) {
106
+ throw new Error(`Could not find global workspace`);
107
+ }
108
+ (_a = (_b = wksp.extensions)['cli']) !== null && _a !== void 0 ? _a : (_b['cli'] = {});
109
+ const cli = wksp.extensions['cli'];
110
+ if (!core_1.json.isJsonObject(cli)) {
111
+ throw new Error(`Invalid config found at ${wksp.filePath}. \`extensions.cli\` should be an object.`);
112
+ }
113
+ cli.completion = config;
114
+ await wksp.save();
115
+ }
116
+ async function shouldPromptForAutocompletionSetup(command, config) {
117
+ // Force whether or not to prompt for autocomplete to give an easy path for e2e testing to skip.
118
+ if (environment_options_1.forceAutocomplete !== undefined) {
119
+ return environment_options_1.forceAutocomplete;
120
+ }
121
+ // Don't prompt on `ng update` or `ng completion`.
122
+ if (command === 'update' || command === 'completion') {
123
+ return false;
124
+ }
125
+ // Non-interactive and continuous integration systems don't care about autocompletion.
126
+ if (!(0, tty_1.isTTY)()) {
127
+ return false;
128
+ }
129
+ // Skip prompt if the user has already been prompted.
130
+ if (config === null || config === void 0 ? void 0 : config.prompted) {
131
+ return false;
132
+ }
133
+ // `$HOME` variable is necessary to find RC files to modify.
134
+ const home = process_1.env['HOME'];
135
+ if (!home) {
136
+ return false;
137
+ }
138
+ // Get possible RC files for the current shell.
139
+ const shell = process_1.env['SHELL'];
140
+ if (!shell) {
141
+ return false;
142
+ }
143
+ const rcFiles = getShellRunCommandCandidates(shell, home);
144
+ if (!rcFiles) {
145
+ return false; // Unknown shell.
146
+ }
147
+ // Don't prompt if the user is missing a global CLI install. Autocompletion won't work after setup
148
+ // anyway and could be annoying for users running one-off commands via `npx` or using `npm start`.
149
+ if ((await hasGlobalCliInstall()) === false) {
150
+ return false;
151
+ }
152
+ // Check each RC file if they already use `ng completion script` in any capacity and don't prompt.
153
+ for (const rcFile of rcFiles) {
154
+ const contents = await fs_1.promises.readFile(rcFile, 'utf-8').catch(() => undefined);
155
+ if (contents === null || contents === void 0 ? void 0 : contents.includes('ng completion script')) {
156
+ return false;
157
+ }
158
+ }
159
+ return true;
160
+ }
161
+ async function promptForAutocompletion() {
162
+ // Dynamically load `inquirer` so users don't have to pay the cost of parsing and executing it for
163
+ // the 99% of builds that *don't* prompt for autocompletion.
164
+ const { prompt } = await Promise.resolve().then(() => __importStar(require('inquirer')));
165
+ const { autocomplete } = await prompt([
166
+ {
167
+ name: 'autocomplete',
168
+ type: 'confirm',
169
+ message: `
170
+ Would you like to enable autocompletion? This will set up your terminal so pressing TAB while typing
171
+ Angular CLI commands will show possible options and autocomplete arguments. (Enabling autocompletion
172
+ will modify configuration files in your home directory.)
173
+ `
174
+ .split('\n')
175
+ .join(' ')
176
+ .trim(),
177
+ default: true,
178
+ },
179
+ ]);
180
+ return autocomplete;
181
+ }
182
+ /**
183
+ * Sets up autocompletion for the user's terminal. This attempts to find the configuration file for
184
+ * the current shell (`.bashrc`, `.zshrc`, etc.) and append a command which enables autocompletion
185
+ * for the Angular CLI. Supports only Bash and Zsh. Returns whether or not it was successful.
186
+ * @return The full path of the configuration file modified.
187
+ */
188
+ async function initializeAutocomplete() {
189
+ var _a, _b;
190
+ // Get the currently active `$SHELL` and `$HOME` environment variables.
191
+ const shell = process_1.env['SHELL'];
192
+ if (!shell) {
193
+ throw new Error('`$SHELL` environment variable not set. Angular CLI autocompletion only supports Bash or' +
194
+ " Zsh. If you're on Windows, Cmd and Powershell don't support command autocompletion," +
195
+ ' but Git Bash or Windows Subsystem for Linux should work, so please try again in one of' +
196
+ ' those environments.');
197
+ }
198
+ const home = process_1.env['HOME'];
199
+ if (!home) {
200
+ throw new Error('`$HOME` environment variable not set. Setting up autocompletion modifies configuration files' +
201
+ ' in the home directory and must be set.');
202
+ }
203
+ // Get all the files we can add `ng completion` to which apply to the user's `$SHELL`.
204
+ const runCommandCandidates = getShellRunCommandCandidates(shell, home);
205
+ if (!runCommandCandidates) {
206
+ throw new Error(`Unknown \`$SHELL\` environment variable value (${shell}). Angular CLI autocompletion only supports Bash or Zsh.`);
207
+ }
208
+ // Get the first file that already exists or fallback to a new file of the first candidate.
209
+ const candidates = await Promise.allSettled(runCommandCandidates.map((rcFile) => fs_1.promises.access(rcFile).then(() => rcFile)));
210
+ const rcFile = (_b = (_a = candidates.find((result) => result.status === 'fulfilled')) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : runCommandCandidates[0];
211
+ // Append Angular autocompletion setup to RC file.
212
+ try {
213
+ await fs_1.promises.appendFile(rcFile, '\n\n# Load Angular CLI autocompletion.\nsource <(ng completion script)\n');
214
+ }
215
+ catch (err) {
216
+ throw new Error(`Failed to append autocompletion setup to \`${rcFile}\`:\n${err.message}`);
217
+ }
218
+ return rcFile;
219
+ }
220
+ exports.initializeAutocomplete = initializeAutocomplete;
221
+ /** Returns an ordered list of possible candidates of RC files used by the given shell. */
222
+ function getShellRunCommandCandidates(shell, home) {
223
+ if (shell.toLowerCase().includes('bash')) {
224
+ return ['.bashrc', '.bash_profile', '.profile'].map((file) => path.join(home, file));
225
+ }
226
+ else if (shell.toLowerCase().includes('zsh')) {
227
+ return ['.zshrc', '.zsh_profile', '.profile'].map((file) => path.join(home, file));
228
+ }
229
+ else {
230
+ return undefined;
231
+ }
232
+ }
233
+ /**
234
+ * Returns whether the user has a global CLI install or `undefined` if this can't be determined.
235
+ * Execution from `npx` is *not* considered a global CLI install.
236
+ *
237
+ * This does *not* mean the current execution is from a global CLI install, only that a global
238
+ * install exists on the system.
239
+ */
240
+ async function hasGlobalCliInstall() {
241
+ var _a;
242
+ // List all binaries with the `ng` name on the user's `$PATH`.
243
+ const proc = (0, child_process_1.execFile)('which', ['-a', 'ng']);
244
+ let stdout = '';
245
+ (_a = proc.stdout) === null || _a === void 0 ? void 0 : _a.addListener('data', (content) => {
246
+ stdout += content;
247
+ });
248
+ const exitCode = await new Promise((resolve) => {
249
+ proc.addListener('exit', (exitCode) => {
250
+ resolve(exitCode);
251
+ });
252
+ });
253
+ switch (exitCode) {
254
+ case 0:
255
+ // Successfully listed all `ng` binaries on the `$PATH`. Look for at least one line which is a
256
+ // global install. We can't easily identify global installs, but local installs are typically
257
+ // placed in `node_modules/.bin` by NPM / Yarn. `npx` also currently caches files at
258
+ // `~/.npm/_npx/*/node_modules/.bin/`, so the same logic applies.
259
+ const lines = stdout.split('\n').filter((line) => line !== '');
260
+ const hasGlobalInstall = lines.some((line) => {
261
+ // A binary is a local install if it is a direct child of a `node_modules/.bin/` directory.
262
+ const parent = path.parse(path.parse(line).dir);
263
+ const grandparent = path.parse(parent.dir);
264
+ const localInstall = grandparent.base === 'node_modules' && parent.base === '.bin';
265
+ return !localInstall;
266
+ });
267
+ return hasGlobalInstall;
268
+ case 1:
269
+ // No instances of `ng` on the user's `$PATH`.
270
+ return false;
271
+ case null:
272
+ // `which` was killed by a signal and did not exit gracefully. Maybe it hung or something else
273
+ // went very wrong, so treat this as inconclusive.
274
+ return undefined;
275
+ default:
276
+ // `which` returns exit code 2 if an invalid option is specified and `-a` doesn't appear to be
277
+ // supported on all systems. Other exit codes mean unknown errors occurred. Can't tell whether
278
+ // CLI is globally installed, so treat this as inconclusive.
279
+ return undefined;
280
+ }
281
+ }
282
+ exports.hasGlobalCliInstall = hasGlobalCliInstall;
@@ -10,14 +10,15 @@ import { PackageManager } from '../../lib/config/workspace-schema';
10
10
  import { JSONFile } from './json-file';
11
11
  export declare const workspaceSchemaPath: string;
12
12
  export declare class AngularWorkspace {
13
- private workspace;
13
+ private readonly workspace;
14
14
  readonly filePath: string;
15
15
  readonly basePath: string;
16
16
  constructor(workspace: workspaces.WorkspaceDefinition, filePath: string);
17
17
  get extensions(): Record<string, json.JsonValue | undefined>;
18
18
  get projects(): workspaces.ProjectDefinitionCollection;
19
- getCli(): Record<string, any>;
20
- getProjectCli(projectName: string): Record<string, any>;
19
+ getCli(): Record<string, any> | undefined;
20
+ getProjectCli(projectName: string): Record<string, any> | undefined;
21
+ save(): Promise<void>;
21
22
  static load(workspaceFilePath: string): Promise<AngularWorkspace>;
22
23
  }
23
24
  export declare function getWorkspace(level?: 'local' | 'global'): Promise<AngularWorkspace | undefined>;
@@ -134,12 +134,15 @@ class AngularWorkspace {
134
134
  // Temporary helper functions to support refactoring
135
135
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
136
136
  getCli() {
137
- return this.workspace.extensions['cli'] || {};
137
+ return this.workspace.extensions['cli'];
138
138
  }
139
139
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
140
140
  getProjectCli(projectName) {
141
141
  const project = this.workspace.projects.get(projectName);
142
- return (project === null || project === void 0 ? void 0 : project.extensions['cli']) || {};
142
+ return project === null || project === void 0 ? void 0 : project.extensions['cli'];
143
+ }
144
+ save() {
145
+ return core_1.workspaces.writeWorkspace(this.workspace, createWorkspaceHost(), this.filePath);
143
146
  }
144
147
  static async load(workspaceFilePath) {
145
148
  const result = await core_1.workspaces.readWorkspace(workspaceFilePath, createWorkspaceHost(), core_1.workspaces.WorkspaceFormat.JSON);
@@ -152,10 +155,13 @@ async function getWorkspace(level = 'local') {
152
155
  if (cachedWorkspaces.has(level)) {
153
156
  return cachedWorkspaces.get(level);
154
157
  }
155
- const configPath = level === 'local' ? projectFilePath() : globalFilePath();
158
+ let configPath = level === 'local' ? projectFilePath() : globalFilePath();
156
159
  if (!configPath) {
157
- cachedWorkspaces.set(level, undefined);
158
- return undefined;
160
+ if (level === 'local') {
161
+ cachedWorkspaces.set(level, undefined);
162
+ return undefined;
163
+ }
164
+ configPath = createGlobalSettings();
159
165
  }
160
166
  try {
161
167
  const workspace = await AngularWorkspace.load(configPath);
@@ -10,3 +10,4 @@ export declare const analyticsShareDisabled: boolean;
10
10
  export declare const isCI: boolean;
11
11
  export declare const disableVersionCheck: boolean;
12
12
  export declare const ngDebug: boolean;
13
+ export declare const forceAutocomplete: boolean | undefined;
@@ -7,7 +7,7 @@
7
7
  * found in the LICENSE file at https://angular.io/license
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.ngDebug = exports.disableVersionCheck = exports.isCI = exports.analyticsShareDisabled = exports.analyticsDisabled = void 0;
10
+ exports.forceAutocomplete = exports.ngDebug = exports.disableVersionCheck = exports.isCI = exports.analyticsShareDisabled = exports.analyticsDisabled = void 0;
11
11
  function isPresent(variable) {
12
12
  return typeof variable === 'string' && variable !== '';
13
13
  }
@@ -17,8 +17,15 @@ function isDisabled(variable) {
17
17
  function isEnabled(variable) {
18
18
  return isPresent(variable) && (variable === '1' || variable.toLowerCase() === 'true');
19
19
  }
20
+ function optional(variable) {
21
+ if (!isPresent(variable)) {
22
+ return undefined;
23
+ }
24
+ return isEnabled(variable);
25
+ }
20
26
  exports.analyticsDisabled = isDisabled(process.env['NG_CLI_ANALYTICS']);
21
27
  exports.analyticsShareDisabled = isDisabled(process.env['NG_CLI_ANALYTICS_SHARE']);
22
28
  exports.isCI = isEnabled(process.env['CI']);
23
29
  exports.disableVersionCheck = isEnabled(process.env['NG_DISABLE_VERSION_CHECK']);
24
30
  exports.ngDebug = isEnabled(process.env['NG_DEBUG']);
31
+ exports.forceAutocomplete = optional(process.env['NG_FORCE_AUTOCOMPLETE']);
@@ -59,6 +59,7 @@ class JSONFile {
59
59
  }
60
60
  const edits = (0, jsonc_parser_1.modify)(this.content, jsonPath, value, {
61
61
  getInsertionIndex,
62
+ // TODO: use indentation from original file.
62
63
  formattingOptions: {
63
64
  insertSpaces: true,
64
65
  tabSize: 2,