nx 24.0.3 → 24.0.4

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 (55) hide show
  1. package/dist/release/changelog-renderer/index.js +12 -5
  2. package/dist/src/ai/clone-ai-config-repo.d.ts +2 -1
  3. package/dist/src/ai/clone-ai-config-repo.js +48 -11
  4. package/dist/src/ai/set-up-ai-agents/set-up-ai-agents.js +25 -7
  5. package/dist/src/analytics/analytics.js +7 -2
  6. package/dist/src/command-line/ai/ai-output.js +3 -3
  7. package/dist/src/command-line/configure-ai-agents/configure-ai-agents.js +2 -2
  8. package/dist/src/command-line/graph/graph.d.ts +10 -0
  9. package/dist/src/command-line/graph/graph.js +61 -2
  10. package/dist/src/command-line/import/import.js +18 -30
  11. package/dist/src/command-line/import/utils/merge-remote-source.d.ts +1 -0
  12. package/dist/src/command-line/import/utils/merge-remote-source.js +10 -1
  13. package/dist/src/command-line/init/implementation/angular/legacy-angular-versions.js +17 -5
  14. package/dist/src/command-line/init/init-v1.js +2 -2
  15. package/dist/src/command-line/init/init-v2.js +4 -4
  16. package/dist/src/command-line/migrate/migrate.js +6 -7
  17. package/dist/src/command-line/nx-cloud/record/record.js +3 -2
  18. package/dist/src/command-line/nx-commands.js +3 -1
  19. package/dist/src/command-line/release/changelog/version-plan-filtering.js +4 -1
  20. package/dist/src/command-line/release/changelog.js +2 -1
  21. package/dist/src/command-line/release/config/version-plans.js +29 -29
  22. package/dist/src/command-line/release/utils/git.d.ts +2 -0
  23. package/dist/src/command-line/release/utils/git.js +49 -26
  24. package/dist/src/command-line/release/utils/markdown.js +4 -1
  25. package/dist/src/command-line/release/utils/remote-release-clients/github.js +18 -7
  26. package/dist/src/command-line/release/utils/remote-release-clients/gitlab.js +3 -1
  27. package/dist/src/command-line/release/version/derive-specifier-from-conventional-commits.js +1 -1
  28. package/dist/src/command-line/release/version.js +2 -1
  29. package/dist/src/core/graph/styles.js +1 -1
  30. package/dist/src/daemon/server/latest-nx.js +2 -2
  31. package/dist/src/hasher/native-task-hasher-impl.js +5 -2
  32. package/dist/src/native/index.d.ts +11 -1
  33. package/dist/src/native/nx.wasm32-wasi.debug.wasm +0 -0
  34. package/dist/src/native/nx.wasm32-wasi.wasm +0 -0
  35. package/dist/src/nx-cloud/generators/connect-to-nx-cloud/connect-to-nx-cloud.js +5 -6
  36. package/dist/src/nx-cloud/utilities/get-cloud-options.d.ts +1 -1
  37. package/dist/src/nx-cloud/utilities/get-cloud-options.js +5 -2
  38. package/dist/src/nx-cloud/utilities/is-workspace-claimed.js +1 -1
  39. package/dist/src/nx-cloud/utilities/url-shorten.d.ts +1 -1
  40. package/dist/src/nx-cloud/utilities/url-shorten.js +4 -4
  41. package/dist/src/plugins/js/lock-file/yarn-parser.js +49 -2
  42. package/dist/src/tasks-runner/cache.js +24 -8
  43. package/dist/src/tasks-runner/default-tasks-runner.js +21 -13
  44. package/dist/src/tasks-runner/life-cycles/performance-report.js +2 -2
  45. package/dist/src/utils/git-utils.js +3 -3
  46. package/dist/src/utils/git-utils.tree-filter.js +102 -24
  47. package/dist/src/utils/package-manager.d.ts +7 -2
  48. package/dist/src/utils/package-manager.js +22 -22
  49. package/dist/src/utils/provenance.d.ts +14 -1
  50. package/dist/src/utils/provenance.js +44 -13
  51. package/dist/src/utils/redact-url-credentials.d.ts +1 -0
  52. package/dist/src/utils/redact-url-credentials.js +7 -0
  53. package/dist/src/utils/workspace-id.d.ts +4 -3
  54. package/dist/src/utils/workspace-id.js +4 -3
  55. package/package.json +11 -11
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const semver_1 = require("semver");
4
4
  // Stripped from breaking change explanations (e.g. bot/session markers).
5
5
  const HtmlCommentRegex = /<!--[\s\S]*?-->/g;
6
+ // git keeps \r, U+2028 and U+2029 inside commit text, and each of them ends a line.
7
+ const LineTerminatorRegex = /\r\n|[\n\r\u2028\u2029]/g;
6
8
  // Keyed on email: agent display names track model versions (e.g. "Claude Opus
7
9
  // 5 (1M context)"), and a human contributor can share a name with an agent.
8
10
  const AiAgentAuthorEmails = new Set([
@@ -249,7 +251,9 @@ class DefaultChangelogRenderer {
249
251
  markdownLines.push('', '### ' + '❤️ Thank You', '', ...authors
250
252
  .sort((a, b) => a.name.localeCompare(b.name))
251
253
  .map((i) => {
252
- const username = i.username ? ` @${i.username}` : '';
254
+ const username = i.username
255
+ ? ` @${i.username.replace(LineTerminatorRegex, ' ')}`
256
+ : '';
253
257
  return `- ${i.name}${username}`;
254
258
  }));
255
259
  }
@@ -259,8 +263,8 @@ class DefaultChangelogRenderer {
259
263
  let description = change.description;
260
264
  let extraLines = [];
261
265
  let extraLinesStr = '';
262
- if (description.includes('\n')) {
263
- [description, ...extraLines] = description.split('\n');
266
+ [description, ...extraLines] = description.split(LineTerminatorRegex);
267
+ if (extraLines.length > 0) {
264
268
  const indentation = ' ';
265
269
  extraLinesStr = (this.isVersionPlans
266
270
  ? // Preserve newlines for version plan sources to allow author to maintain maximum control over final contents
@@ -292,7 +296,9 @@ class DefaultChangelogRenderer {
292
296
  breakingLine += `**${change.scope.trim()}:** `;
293
297
  }
294
298
  if (change.description) {
295
- breakingLine += `${change.description.trim()}`;
299
+ breakingLine += change.description
300
+ .trim()
301
+ .replace(LineTerminatorRegex, ' ');
296
302
  }
297
303
  if (this.remoteReleaseClient.getRemoteRepoData() &&
298
304
  this.changelogRenderOptions.commitReferences &&
@@ -361,7 +367,7 @@ class DefaultChangelogRenderer {
361
367
  const lines = message
362
368
  .slice(startOfBreakingChange)
363
369
  .replace(HtmlCommentRegex, '')
364
- .split('\n');
370
+ .split(LineTerminatorRegex);
365
371
  // The rest of the "BREAKING CHANGE:" line is always kept; scan from the next.
366
372
  const explanationLines = [lines[0]];
367
373
  for (let i = 1; i < lines.length; i++) {
@@ -389,6 +395,7 @@ class DefaultChangelogRenderer {
389
395
  }
390
396
  formatName(name = '') {
391
397
  return name
398
+ .replace(LineTerminatorRegex, ' ')
392
399
  .split(' ')
393
400
  .map((p) => p.trim())
394
401
  .join(' ');
@@ -6,6 +6,7 @@
6
6
  * 3. If not, clones the repository and cleans up old caches
7
7
  *
8
8
  * @returns The path to the cached repository
9
- * @throws Error if unable to fetch or clone the repository
9
+ * @throws Error if unable to fetch or clone the repository, or a
10
+ * DirectoryRefusedError if no owner-only cache directory can be established
10
11
  */
11
12
  export declare function getAiConfigRepoPath(): string;
@@ -3,10 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getAiConfigRepoPath = getAiConfigRepoPath;
4
4
  const child_process_1 = require("child_process");
5
5
  const fs_1 = require("fs");
6
- const os_1 = require("os");
7
6
  const path_1 = require("path");
7
+ const nx_tmp_dir_1 = require("../utils/nx-tmp-dir");
8
+ const owned_private_dir_1 = require("../utils/owned-private-dir");
8
9
  const REPO_URL = 'https://github.com/nrwl/nx-ai-agents-config';
9
- const CACHE_DIR = (0, path_1.join)((0, os_1.tmpdir)(), 'nx-ai-agents-config');
10
+ const CACHE_DIR_NAME = 'nx-ai-agents-config';
10
11
  // `git rev-parse --local-env-vars`, plus GIT_NAMESPACE and the indexed
11
12
  // GIT_CONFIG_KEY_<n> / GIT_CONFIG_VALUE_<n> pairs. Hooks export GIT_INDEX_FILE;
12
13
  // inheriting it makes `git clone` rewrite the caller's index.
@@ -76,8 +77,6 @@ function getLatestCommitHash() {
76
77
  */
77
78
  function cloneRepo(targetPath) {
78
79
  try {
79
- // Ensure parent directory exists
80
- (0, fs_1.mkdirSync)(CACHE_DIR, { recursive: true });
81
80
  // Use a temporary path first to avoid race conditions
82
81
  const tempPath = `${targetPath}.tmp.${process.pid}`;
83
82
  // Clean up any leftover temp directory
@@ -132,15 +131,15 @@ function cloneRepo(targetPath) {
132
131
  /**
133
132
  * Clean up old cached versions, keeping only the current one.
134
133
  */
135
- function cleanupOldCaches(currentCommitHash) {
136
- if (!(0, fs_1.existsSync)(CACHE_DIR)) {
134
+ function cleanupOldCaches(cacheDir, currentCommitHash) {
135
+ if (!(0, fs_1.existsSync)(cacheDir)) {
137
136
  return;
138
137
  }
139
138
  try {
140
- const entries = (0, fs_1.readdirSync)(CACHE_DIR, { withFileTypes: true });
139
+ const entries = (0, fs_1.readdirSync)(cacheDir, { withFileTypes: true });
141
140
  for (const entry of entries) {
142
141
  if (entry.isDirectory() && entry.name !== currentCommitHash) {
143
- const oldCachePath = (0, path_1.join)(CACHE_DIR, entry.name);
142
+ const oldCachePath = (0, path_1.join)(cacheDir, entry.name);
144
143
  (0, fs_1.rmSync)(oldCachePath, { recursive: true, force: true });
145
144
  }
146
145
  }
@@ -157,14 +156,16 @@ function cleanupOldCaches(currentCommitHash) {
157
156
  * 3. If not, clones the repository and cleans up old caches
158
157
  *
159
158
  * @returns The path to the cached repository
160
- * @throws Error if unable to fetch or clone the repository
159
+ * @throws Error if unable to fetch or clone the repository, or a
160
+ * DirectoryRefusedError if no owner-only cache directory can be established
161
161
  */
162
162
  function getAiConfigRepoPath() {
163
+ const cacheDir = ensureOwnedCacheDir();
163
164
  // 1. Get latest commit hash (first 10 chars)
164
165
  const commitHash = getLatestCommitHash();
165
166
  // 2. Reuse cached version if it still has content (macOS may have
166
167
  // swept its files but left the directory tree).
167
- const cachedPath = (0, path_1.join)(CACHE_DIR, commitHash);
168
+ const cachedPath = (0, path_1.join)(cacheDir, commitHash);
168
169
  if (hasRootFile(cachedPath)) {
169
170
  return cachedPath;
170
171
  }
@@ -174,9 +175,45 @@ function getAiConfigRepoPath() {
174
175
  }
175
176
  cloneRepo(cachedPath);
176
177
  // 4. Clean up old cached versions
177
- cleanupOldCaches(commitHash);
178
+ cleanupOldCaches(cacheDir, commitHash);
178
179
  return cachedPath;
179
180
  }
181
+ /**
182
+ * The cached files are copied into the workspace, so every directory holding
183
+ * them must be owner-only. Falls back to `~/.nx` when the shared tmp root is
184
+ * refused, e.g. because another account created it.
185
+ */
186
+ function ensureOwnedCacheDir() {
187
+ const shared = (0, owned_private_dir_1.ensureSafeSharedRoot)(nx_tmp_dir_1.NX_TMP_DIR);
188
+ const sharedCache = (0, path_1.join)(nx_tmp_dir_1.NX_USER_TMP_DIR, CACHE_DIR_NAME);
189
+ const sharedRefusal = shared.status === 'ok'
190
+ ? ownedChainRefusal([nx_tmp_dir_1.NX_USER_TMP_DIR, sharedCache])
191
+ : shared.refusal;
192
+ if (!sharedRefusal) {
193
+ return sharedCache;
194
+ }
195
+ if (nx_tmp_dir_1.NX_HOME_TMP_DIR && !isSharedTmpDir(nx_tmp_dir_1.NX_HOME_TMP_DIR)) {
196
+ const homeCache = (0, path_1.join)(nx_tmp_dir_1.NX_HOME_TMP_DIR, CACHE_DIR_NAME);
197
+ if (!ownedChainRefusal([nx_tmp_dir_1.NX_HOME_TMP_DIR, homeCache])) {
198
+ return homeCache;
199
+ }
200
+ }
201
+ throw new owned_private_dir_1.DirectoryRefusedError(sharedRefusal);
202
+ }
203
+ function ownedChainRefusal(dirs) {
204
+ for (const dir of dirs) {
205
+ const owned = (0, owned_private_dir_1.ensureOwnedPrivateDir)(dir);
206
+ if (owned.status !== 'ok') {
207
+ return owned.refusal;
208
+ }
209
+ }
210
+ return undefined;
211
+ }
212
+ /** A `$HOME` of `/tmp` makes `~/.nx` the shared root itself, which must stay 1777. */
213
+ function isSharedTmpDir(dir) {
214
+ const resolved = (0, owned_private_dir_1.canonicalDir)(dir);
215
+ return [nx_tmp_dir_1.NX_TMP_DIR, nx_tmp_dir_1.NX_USER_TMP_DIR].some((shared) => (0, owned_private_dir_1.canonicalDir)(shared) === resolved);
216
+ }
180
217
  /**
181
218
  * The repo always has at least one regular file at its root (e.g. README).
182
219
  * If everything at the root is a directory, the cache was swept by macOS
@@ -8,7 +8,6 @@ const path_1 = require("path");
8
8
  const semver_1 = require("semver");
9
9
  const smol_toml_1 = tslib_1.__importDefault(require("smol-toml"));
10
10
  const format_changed_files_1 = require("../../generators/internal-utils/format-changed-files");
11
- const generate_files_1 = require("../../generators/utils/generate-files");
12
11
  const json_1 = require("../../generators/utils/json");
13
12
  const nx_json_1 = require("../../generators/utils/nx-json");
14
13
  const analytics_enabled_1 = require("../../utils/analytics-enabled");
@@ -21,6 +20,8 @@ const workspace_root_1 = require("../../utils/workspace-root");
21
20
  const installed_nx_version_1 = require("../../utils/installed-nx-version");
22
21
  const constants_1 = require("../constants");
23
22
  const clone_ai_config_repo_1 = require("../clone-ai-config-repo");
23
+ const logger_1 = require("../../utils/logger");
24
+ const owned_private_dir_1 = require("../../utils/owned-private-dir");
24
25
  const utils_1 = require("../utils");
25
26
  const handle_import_1 = require("../../utils/handle-import");
26
27
  /**
@@ -50,8 +51,8 @@ async function setupAiAgentsGenerator(tree, options, inner = false) {
50
51
  return await setupAiAgentsGeneratorImpl(tree, normalizedOptions);
51
52
  }
52
53
  try {
53
- await (0, provenance_1.ensurePackageHasProvenance)('nx', normalizedOptions.packageVersion);
54
- const { tempDir, cleanup } = (0, package_json_1.installPackageToTmp)('nx', normalizedOptions.packageVersion, (0, package_manager_1.detectPackageManager)(tree.root));
54
+ const version = await (0, provenance_1.resolveVersionWithProvenance)('nx', normalizedOptions.packageVersion, tree.root);
55
+ const { tempDir, cleanup } = (0, package_json_1.installPackageToTmp)('nx', version, (0, package_manager_1.detectPackageManager)(tree.root));
55
56
  let modulePath = (0, path_1.join)(tempDir, 'node_modules', 'nx', 'src/ai/set-up-ai-agents/set-up-ai-agents.js');
56
57
  const module = await (0, handle_import_1.handleImport)(modulePath);
57
58
  const setupAiAgentsGeneratorResult = await module.setupAiAgentsGenerator(tree, normalizedOptions, true);
@@ -70,6 +71,19 @@ function normalizeOptions(options) {
70
71
  agents: options.agents ?? [...utils_1.supportedAgents],
71
72
  };
72
73
  }
74
+ function copyFilesVerbatim(tree, srcDir, destDir) {
75
+ for (const entry of (0, fs_1.readdirSync)(srcDir)) {
76
+ const srcPath = (0, path_1.join)(srcDir, entry);
77
+ const destPath = (0, path_1.join)(destDir, entry);
78
+ const stats = (0, fs_1.lstatSync)(srcPath);
79
+ if (stats.isDirectory()) {
80
+ copyFilesVerbatim(tree, srcPath, destPath);
81
+ }
82
+ else if (stats.isFile()) {
83
+ tree.write(destPath, (0, fs_1.readFileSync)(srcPath));
84
+ }
85
+ }
86
+ }
73
87
  async function setupAiAgentsGeneratorImpl(tree, options) {
74
88
  const hasAgent = (agent) => options.agents.includes(agent);
75
89
  const nxVersion = (0, installed_nx_version_1.getInstalledNxVersion)() ?? getDeclaredNxVersionOrDefault();
@@ -189,8 +203,12 @@ async function setupAiAgentsGeneratorImpl(tree, options) {
189
203
  try {
190
204
  aiConfigRepoPath = (0, clone_ai_config_repo_1.getAiConfigRepoPath)();
191
205
  }
192
- catch {
193
- // Network/clone failure — individual consumers handle fallback
206
+ catch (e) {
207
+ // Individual consumers handle a missing repo; a refused cache dir is the
208
+ // one failure the user can fix, so say why skills were skipped.
209
+ if (e instanceof owned_private_dir_1.DirectoryRefusedError) {
210
+ logger_1.logger.warn(`Skipping Nx skills and commands for AI agents: ${e.message}`);
211
+ }
194
212
  }
195
213
  }
196
214
  if (hasAgent('codex')) {
@@ -224,7 +242,7 @@ async function setupAiAgentsGeneratorImpl(tree, options) {
224
242
  if (hasAgent('codex') || hasAgent('cursor') || hasAgent('gemini')) {
225
243
  const sharedSkillsSrc = (0, path_1.join)(repoPath, 'generated/.agents');
226
244
  if ((0, fs_1.existsSync)(sharedSkillsSrc)) {
227
- (0, generate_files_1.generateFiles)(tree, sharedSkillsSrc, (0, path_1.join)(options.directory, '.agents'), {});
245
+ copyFilesVerbatim(tree, sharedSkillsSrc, (0, path_1.join)(options.directory, '.agents'));
228
246
  }
229
247
  }
230
248
  // Agent-specific directories (commands, agents, config)
@@ -243,7 +261,7 @@ async function setupAiAgentsGeneratorImpl(tree, options) {
243
261
  if (hasAgent(agent)) {
244
262
  const srcPath = (0, path_1.join)(repoPath, src);
245
263
  if ((0, fs_1.existsSync)(srcPath)) {
246
- (0, generate_files_1.generateFiles)(tree, srcPath, (0, path_1.join)(options.directory, dest), {});
264
+ copyFilesVerbatim(tree, srcPath, (0, path_1.join)(options.directory, dest));
247
265
  }
248
266
  }
249
267
  }
@@ -63,12 +63,17 @@ async function startAnalytics() {
63
63
  if (!(0, analytics_enabled_1.isAnalyticsEnabled)(nxJson)) {
64
64
  return;
65
65
  }
66
- const workspaceId = (0, workspace_id_1.generateWorkspaceId)(workspace_root_1.workspaceRoot, nxJson);
67
- if (!workspaceId) {
66
+ const rawWorkspaceId = (0, workspace_id_1.generateWorkspaceId)(workspace_root_1.workspaceRoot, nxJson);
67
+ if (!rawWorkspaceId) {
68
68
  // Not a git repo — no telemetry
69
69
  return;
70
70
  }
71
71
  const isNxCloud = !!(nxJson?.nxCloudId ?? nxJson?.nxCloudAccessToken);
72
+ // The Nx Cloud id or access token is a credential; the repo key is
73
+ // already a digest.
74
+ const workspaceId = isNxCloud
75
+ ? (0, crypto_1.createHash)('sha256').update(rawWorkspaceId).digest('hex')
76
+ : rawWorkspaceId;
72
77
  // A CI fleet is not a user: shared images bake in /etc/machine-id, so a
73
78
  // uid would collapse whole fleets into one GA "user" (and trip per-user
74
79
  // collection caps). GA falls back to cid = workspace for CI traffic.
@@ -63,7 +63,6 @@ function logProgress(stage, message) {
63
63
  */
64
64
  function writeErrorLog(error, commandName = 'nx') {
65
65
  const timestamp = Date.now();
66
- const errorLogPath = (0, path_1.join)((0, os_1.tmpdir)(), `${commandName}-error-${timestamp}.log`);
67
66
  let errorDetails = `Nx ${commandName} Error Log\n`;
68
67
  errorDetails += `==================\n`;
69
68
  errorDetails += `Timestamp: ${new Date(timestamp).toISOString()}\n\n`;
@@ -77,10 +76,11 @@ function writeErrorLog(error, commandName = 'nx') {
77
76
  errorDetails += `Error: ${String(error)}\n`;
78
77
  }
79
78
  try {
80
- (0, fs_1.writeFileSync)(errorLogPath, errorDetails);
79
+ const errorLogPath = (0, path_1.join)((0, fs_1.mkdtempSync)((0, path_1.join)((0, os_1.tmpdir)(), `${commandName}-error-`)), `${commandName}-error-${timestamp}.log`);
80
+ (0, fs_1.writeFileSync)(errorLogPath, errorDetails, { mode: 0o600, flag: 'wx' });
81
+ return errorLogPath;
81
82
  }
82
83
  catch {
83
84
  return '';
84
85
  }
85
- return errorLogPath;
86
86
  }
@@ -44,8 +44,8 @@ async function configureAiAgentsHandler(args, inner = false) {
44
44
  }
45
45
  let cleanup;
46
46
  try {
47
- await (0, provenance_1.ensurePackageHasProvenance)('nx', 'latest');
48
- const packageInstallResults = (0, package_json_1.installPackageToTmp)('nx', 'latest', (0, package_manager_1.detectPackageManager)(workspace_root_1.workspaceRoot));
47
+ const version = await (0, provenance_1.resolveVersionWithProvenance)('nx', 'latest');
48
+ const packageInstallResults = (0, package_json_1.installPackageToTmp)('nx', version, (0, package_manager_1.detectPackageManager)(workspace_root_1.workspaceRoot));
49
49
  cleanup = packageInstallResults.cleanup;
50
50
  let modulePath = require.resolve('nx/src/command-line/configure-ai-agents/configure-ai-agents.js', { paths: [packageInstallResults.tempDir] });
51
51
  const module = await (0, handle_import_1.handleImport)(modulePath);
@@ -1,3 +1,6 @@
1
+ import * as http from 'node:http';
2
+ import { URL } from 'node:url';
3
+ import * as net from 'node:net';
1
4
  import { ProjectFileMap, ProjectGraph, ProjectGraphDependency, ProjectGraphProjectNode } from '../../config/project-graph';
2
5
  import { TaskGraph } from '../../config/task-graph';
3
6
  import { type TaskSelection } from '../../tasks-runner/run-command';
@@ -59,6 +62,13 @@ export declare function generateGraph(args: {
59
62
  /** The `-c` the tasks run with; their ids carry it. */
60
63
  configuration?: string;
61
64
  }, affectedProjects: string[]): Promise<void>;
65
+ export declare function startServer(html: string, environmentJs: string, host: string, port?: number, watchForChanges?: boolean, affected?: string[], focus?: string, groupByFolder?: boolean, exclude?: string[], selection?: TaskSelectionForGraph): Promise<{
66
+ app: net.Server;
67
+ url: URL;
68
+ }>;
69
+ export declare function isSameOriginLocalRequest(req: Pick<http.IncomingMessage, 'headers'> & {
70
+ socket: Pick<net.Socket, 'localPort'>;
71
+ }, host: string): boolean;
62
72
  export interface TaskSelectionForGraph {
63
73
  targets: string[];
64
74
  configuration?: string;
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateGraph = generateGraph;
4
+ exports.startServer = startServer;
5
+ exports.isSameOriginLocalRequest = isSameOriginLocalRequest;
4
6
  exports.selectedFor = selectedFor;
5
7
  exports.taskGraphForSelection = taskGraphForSelection;
6
8
  exports.getExpandedTaskInputs = getExpandedTaskInputs;
@@ -422,7 +424,12 @@ async function startServer(html, environmentJs, host, port = 4211, watchForChang
422
424
  currentProjectGraphClientResponse.exclude = exclude;
423
425
  currentSourceMapsClientResponse = sourceMapResponse;
424
426
  isFilteredGraph = !!(focus || exclude.length > 0);
425
- const app = http.createServer(async (req, res) => {
427
+ const handleRequest = async (req, res) => {
428
+ if (!isSameOriginLocalRequest(req, host)) {
429
+ res.writeHead(403, { 'Content-Type': 'text/plain' });
430
+ res.end('Forbidden');
431
+ return;
432
+ }
426
433
  // parse URL
427
434
  const parsedUrl = new node_url_1.URL(req.url, `http://${host}:${port}`);
428
435
  // extract URL path
@@ -465,9 +472,14 @@ async function startServer(html, environmentJs, host, port = 4211, watchForChang
465
472
  if (sanitizePath === 'task-inputs.json') {
466
473
  node_perf_hooks_1.performance.mark('task input generation:start');
467
474
  const taskId = parsedUrl.searchParams.get('taskId');
468
- res.writeHead(200, { 'Content-Type': 'application/json' });
475
+ if (!taskId) {
476
+ res.writeHead(400, { 'Content-Type': 'application/json' });
477
+ res.end(JSON.stringify({ error: 'Missing taskId' }));
478
+ return;
479
+ }
469
480
  const inputs = await getExpandedTaskInputs(currentProjectGraphClientResponse, expandedTaskInputsCache, taskId);
470
481
  node_perf_hooks_1.performance.mark('task input generation:end');
482
+ res.writeHead(200, { 'Content-Type': 'application/json' });
471
483
  res.end(JSON.stringify({ [taskId]: inputs }));
472
484
  node_perf_hooks_1.performance.measure('task input generation', 'task input generation:start', 'task input generation:end');
473
485
  return;
@@ -518,6 +530,18 @@ async function startServer(html, environmentJs, host, port = 4211, watchForChang
518
530
  res.statusCode = 500;
519
531
  res.end(`Error getting the file: ${err}.`);
520
532
  }
533
+ };
534
+ const app = http.createServer((req, res) => {
535
+ handleRequest(req, res).catch((err) => {
536
+ output_1.output.error({
537
+ title: `Failed to handle graph request ${req.url}`,
538
+ bodyLines: [err?.stack ?? String(err)],
539
+ });
540
+ if (!res.headersSent) {
541
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
542
+ }
543
+ res.end();
544
+ });
521
545
  });
522
546
  const handleTermination = async (exitCode) => {
523
547
  if (unregisterFileWatcher) {
@@ -543,6 +567,41 @@ async function startServer(html, environmentJs, host, port = 4211, watchForChang
543
567
  });
544
568
  });
545
569
  }
570
+ function isSameOriginLocalRequest(req, host) {
571
+ const authority = parseHostHeader(req.headers.host);
572
+ if (!authority ||
573
+ Number(authority.port || 80) !== req.socket.localPort ||
574
+ !isAllowedHostname(authority.hostname.replace(/^\[|\]$/g, ''), host)) {
575
+ return false;
576
+ }
577
+ const fetchSite = req.headers['sec-fetch-site'];
578
+ if (fetchSite && fetchSite !== 'same-origin' && fetchSite !== 'none') {
579
+ return false;
580
+ }
581
+ const origin = req.headers.origin;
582
+ return !origin || origin.toLowerCase() === authority.origin;
583
+ }
584
+ function parseHostHeader(hostHeader) {
585
+ if (!hostHeader || /[/\\@?#]/.test(hostHeader)) {
586
+ return null;
587
+ }
588
+ try {
589
+ return new node_url_1.URL(`http://${hostHeader}`);
590
+ }
591
+ catch {
592
+ return null;
593
+ }
594
+ }
595
+ const loopbackHostnames = new Set(['localhost', '127.0.0.1', '::1']);
596
+ function isAllowedHostname(hostname, boundHost) {
597
+ const bound = boundHost.toLowerCase();
598
+ if (loopbackHostnames.has(hostname) || hostname === bound) {
599
+ return true;
600
+ }
601
+ // DNS rebinding needs a domain name, so an IP literal is safe to accept
602
+ // once the user binds a non-loopback interface.
603
+ return !loopbackHostnames.has(bound) && net.isIP(hostname) !== 0;
604
+ }
546
605
  let currentProjectGraphClientResponse = {
547
606
  hash: null,
548
607
  projects: [],
@@ -15,6 +15,7 @@ const init_v2_1 = require("../init/init-v2");
15
15
  const nx_json_1 = require("../../config/nx-json");
16
16
  const fileutils_1 = require("../../utils/fileutils");
17
17
  const workspace_root_1 = require("../../utils/workspace-root");
18
+ const redact_url_credentials_1 = require("../../utils/redact-url-credentials");
18
19
  const package_manager_1 = require("../../utils/package-manager");
19
20
  const workspace_context_1 = require("../../utils/workspace-context");
20
21
  const utils_1 = require("../init/implementation/utils");
@@ -44,7 +45,7 @@ async function importHandler(options) {
44
45
  if (!destination)
45
46
  missingFields.push('destination');
46
47
  if (missingFields.length > 0) {
47
- (0, ai_output_1.writeAiOutput)((0, ai_output_1.buildImportNeedsOptionsResult)(missingFields, sourceRepository));
48
+ (0, ai_output_1.writeAiOutput)((0, ai_output_1.buildImportNeedsOptionsResult)(missingFields, sourceRepository && (0, redact_url_credentials_1.redactUrlCredentials)(sourceRepository)));
48
49
  process.exit(0);
49
50
  }
50
51
  // Check if this is a plugin-only call (second step of two-step flow)
@@ -75,7 +76,6 @@ async function importHandler(options) {
75
76
  ],
76
77
  });
77
78
  }
78
- const tempImportDirectory = (0, path_1.join)(tmp_1.tmpdir, 'nx-import');
79
79
  if (!sourceRepository) {
80
80
  sourceRepository = await (0, prompt_helpers_1.textPrompt)({
81
81
  message: 'What is the URL of the repository you want to import? (This can be a local git repository or a git remote URL)',
@@ -91,19 +91,16 @@ async function importHandler(options) {
91
91
  catch (e) {
92
92
  // It's a remote url
93
93
  }
94
+ const displayRepository = (0, redact_url_credentials_1.redactUrlCredentials)(sourceRepository);
95
+ const tempImportDirectory = await (0, promises_1.mkdtemp)((0, path_1.join)(tmp_1.tmpdir, 'nx-import-'));
94
96
  const sourceTempRepoPath = (0, path_1.join)(tempImportDirectory, 'repo');
95
97
  let spinner;
96
98
  if (aiMode) {
97
- (0, ai_output_1.logProgress)('cloning', `Cloning ${sourceRepository} into ${sourceTempRepoPath}...`);
99
+ (0, ai_output_1.logProgress)('cloning', `Cloning ${displayRepository} into ${sourceTempRepoPath}...`);
98
100
  }
99
101
  else {
100
- spinner = createSpinner(`Cloning ${sourceRepository} into a temporary directory: ${sourceTempRepoPath} (Use --depth to limit commit history and speed up clone times)`).start();
102
+ spinner = createSpinner(`Cloning ${displayRepository} into a temporary directory: ${sourceTempRepoPath} (Use --depth to limit commit history and speed up clone times)`).start();
101
103
  }
102
- try {
103
- await (0, promises_1.rm)(tempImportDirectory, { recursive: true });
104
- }
105
- catch { }
106
- await (0, promises_1.mkdir)(tempImportDirectory, { recursive: true });
107
104
  let sourceGitClient;
108
105
  try {
109
106
  sourceGitClient = await (0, git_utils_1.cloneFromUpstream)(sourceRepository, sourceTempRepoPath, {
@@ -113,10 +110,9 @@ async function importHandler(options) {
113
110
  }
114
111
  catch (e) {
115
112
  if (!aiMode) {
116
- spinner.fail(`Failed to clone ${sourceRepository} into ${sourceTempRepoPath}`);
113
+ spinner.fail(`Failed to clone ${displayRepository} into ${sourceTempRepoPath}`);
117
114
  }
118
- let errorMessage = `Failed to clone ${sourceRepository} into ${sourceTempRepoPath}. Please double check the remote and try again.\n${e.message}`;
119
- throw new Error(errorMessage);
115
+ throw new Error(`Failed to clone ${displayRepository} into ${sourceTempRepoPath}. Please double check the remote and try again.\n${(0, redact_url_credentials_1.redactUrlCredentials)(e.message)}`);
120
116
  }
121
117
  if (!aiMode) {
122
118
  spinner.succeed(`Cloned into ${sourceTempRepoPath}`);
@@ -164,12 +160,12 @@ async function importHandler(options) {
164
160
  await sourceGitClient.addFetchRemote(importRemoteName, ref);
165
161
  await sourceGitClient.fetch(importRemoteName, ref);
166
162
  if (!aiMode) {
167
- spinner.succeed(`Fetched ${ref} from ${sourceRepository}`);
163
+ spinner.succeed(`Fetched ${ref} from ${displayRepository}`);
168
164
  spinner.start(`Checking out a temporary branch, ${tempImportBranch} based on ${ref}`);
169
165
  }
170
166
  await sourceGitClient.checkout(tempImportBranch, {
171
167
  new: true,
172
- base: `${importRemoteName}/${ref}`,
168
+ base: `refs/remotes/${importRemoteName}/${ref}`,
173
169
  });
174
170
  if (!aiMode) {
175
171
  spinner.succeed(`Created a ${tempImportBranch} branch based on ${ref}`);
@@ -178,7 +174,7 @@ async function importHandler(options) {
178
174
  await (0, promises_1.stat)(absSource);
179
175
  }
180
176
  catch (e) {
181
- throw new Error(`The source directory ${source} does not exist in ${sourceRepository}. Please double check to make sure it exists.`);
177
+ throw new Error(`The source directory ${source} does not exist in ${displayRepository}. Please double check to make sure it exists.`);
182
178
  }
183
179
  const packageManager = (0, package_manager_1.detectPackageManager)(workspace_root_1.workspaceRoot);
184
180
  const sourceIsNxWorkspace = (0, node_fs_1.existsSync)((0, path_1.join)(sourceGitClient.root, 'nx.json'));
@@ -186,12 +182,12 @@ async function importHandler(options) {
186
182
  if (aiMode) {
187
183
  (0, ai_output_1.logProgress)('filtering', 'Filtering git history...');
188
184
  }
189
- await (0, prepare_source_repo_1.prepareSourceRepo)(sourceGitClient, ref, source, relativeDestination, tempImportBranch, sourceRepository);
190
- await createTemporaryRemote(destinationGitClient, (0, path_1.join)(sourceTempRepoPath, '.git'), importRemoteName);
185
+ await (0, prepare_source_repo_1.prepareSourceRepo)(sourceGitClient, ref, source, relativeDestination, tempImportBranch, displayRepository);
186
+ await (0, merge_remote_source_1.createTemporaryRemote)(destinationGitClient, (0, path_1.join)(sourceTempRepoPath, '.git'), importRemoteName);
191
187
  if (aiMode) {
192
188
  (0, ai_output_1.logProgress)('merging', 'Merging into workspace...');
193
189
  }
194
- await (0, merge_remote_source_1.mergeRemoteSource)(destinationGitClient, sourceRepository, tempImportBranch, destination, importRemoteName, ref);
190
+ await (0, merge_remote_source_1.mergeRemoteSource)(destinationGitClient, displayRepository, tempImportBranch, destination, importRemoteName, ref);
195
191
  if (!aiMode) {
196
192
  spinner.start('Cleaning up temporary files and remotes');
197
193
  }
@@ -320,7 +316,7 @@ async function importHandler(options) {
320
316
  output_1.output.log({
321
317
  title: `Check root dependencies`,
322
318
  bodyLines: [
323
- `"dependencies" and "devDependencies" are not imported from the source repository (${sourceRepository}).`,
319
+ `"dependencies" and "devDependencies" are not imported from the source repository (${displayRepository}).`,
324
320
  `You may need to add some of those dependencies to this workspace in order to run tasks successfully.`,
325
321
  ],
326
322
  });
@@ -344,7 +340,7 @@ async function importHandler(options) {
344
340
  name,
345
341
  reason: (0, init_v2_1.getPluginReason)(name),
346
342
  })),
347
- sourceRepository,
343
+ sourceRepository: displayRepository,
348
344
  ref,
349
345
  source: source || '.',
350
346
  destination,
@@ -381,7 +377,7 @@ async function importHandler(options) {
381
377
  });
382
378
  }
383
379
  (0, ai_output_1.writeAiOutput)((0, ai_output_1.buildImportSuccessResult)({
384
- sourceRepository,
380
+ sourceRepository: displayRepository,
385
381
  ref,
386
382
  source: source || '.',
387
383
  destination,
@@ -443,7 +439,7 @@ async function handlePluginOnlyMode(options, destinationGitClient, verbose) {
443
439
  }
444
440
  }
445
441
  (0, ai_output_1.writeAiOutput)((0, ai_output_1.buildImportSuccessResult)({
446
- sourceRepository: options.sourceRepository,
442
+ sourceRepository: (0, redact_url_credentials_1.redactUrlCredentials)(options.sourceRepository),
447
443
  ref: options.ref,
448
444
  source: options.source || '.',
449
445
  destination: options.destination,
@@ -453,14 +449,6 @@ async function handlePluginOnlyMode(options, destinationGitClient, verbose) {
453
449
  function getTempImportBranch(sourceBranch) {
454
450
  return `__nx_tmp_import__/${sourceBranch}`;
455
451
  }
456
- async function createTemporaryRemote(destinationGitClient, sourceRemoteUrl, remoteName) {
457
- try {
458
- await destinationGitClient.deleteGitRemote(remoteName);
459
- }
460
- catch { }
461
- await destinationGitClient.addGitRemote(remoteName, sourceRemoteUrl);
462
- await destinationGitClient.fetch(remoteName);
463
- }
464
452
  /**
465
453
  * Run install for the imported code and plugins
466
454
  * @returns true if the install failed
@@ -1,2 +1,3 @@
1
1
  import { GitRepository } from '../../../utils/git-utils';
2
2
  export declare function mergeRemoteSource(destinationGitClient: GitRepository, sourceRemoteUrl: string, tempBranch: string, destination: string, remoteName: string, branchName: string): Promise<void>;
3
+ export declare function createTemporaryRemote(destinationGitClient: GitRepository, sourceRemoteUrl: string, remoteName: string): Promise<void>;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.mergeRemoteSource = mergeRemoteSource;
4
+ exports.createTemporaryRemote = createTemporaryRemote;
4
5
  const createSpinner = require('ora');
5
6
  async function mergeRemoteSource(destinationGitClient, sourceRemoteUrl, tempBranch, destination, remoteName, branchName) {
6
7
  const spinner = createSpinner();
@@ -9,6 +10,14 @@ async function mergeRemoteSource(destinationGitClient, sourceRemoteUrl, tempBran
9
10
  await destinationGitClient.fetch(remoteName, tempBranch);
10
11
  spinner.succeed(`Fetched ${tempBranch} from ${remoteName}`);
11
12
  spinner.start(`Merging files and git history from ${branchName} from ${sourceRemoteUrl} into ${destination}`);
12
- await destinationGitClient.mergeUnrelatedHistories(`${remoteName}/${tempBranch}`, `feat(repo): merge ${branchName} from ${sourceRemoteUrl}`);
13
+ await destinationGitClient.mergeUnrelatedHistories(`refs/remotes/${remoteName}/${tempBranch}`, `feat(repo): merge ${branchName} from ${sourceRemoteUrl}`);
13
14
  spinner.succeed(`Merged files and git history from ${branchName} from ${sourceRemoteUrl} into ${destination}`);
14
15
  }
16
+ async function createTemporaryRemote(destinationGitClient, sourceRemoteUrl, remoteName) {
17
+ try {
18
+ await destinationGitClient.deleteGitRemote(remoteName);
19
+ }
20
+ catch { }
21
+ await destinationGitClient.addGitRemote(remoteName, sourceRemoteUrl);
22
+ await destinationGitClient.fetch(remoteName);
23
+ }
@@ -10,6 +10,7 @@ const object_sort_1 = require("../../../../utils/object-sort");
10
10
  const output_1 = require("../../../../utils/output");
11
11
  const package_json_1 = require("../../../../utils/package-json");
12
12
  const package_manager_1 = require("../../../../utils/package-manager");
13
+ const provenance_1 = require("../../../../utils/provenance");
13
14
  const connect_to_nx_cloud_1 = require("../../../nx-cloud/connect/connect-to-nx-cloud");
14
15
  const utils_1 = require("../utils");
15
16
  const format_1 = require("../format");
@@ -81,11 +82,22 @@ async function getLegacyMigrationFunctionIfApplicable(repoRoot, options) {
81
82
  legacyMigrationCommand = `ng g ${pkgName}:ng-add ${preserveAngularCliLayoutFlag}`;
82
83
  }
83
84
  else {
84
- // use the latest Nx version that supported the Angular version
85
- pkgVersion = await resolvePackageVersion('nx', nxAngularLegacyVersionMap[majorAngularVersion]);
86
- pkgScope = (0, semver_1.gte)(pkgVersion, versionWithRescopeToNx) ? '@nx' : '@nrwl';
87
- unscopedPkgName = 'angular';
88
- pkgName = `${pkgScope}/${unscopedPkgName}`;
85
+ try {
86
+ // use the latest Nx version that supported the Angular version
87
+ pkgVersion = await (0, package_manager_1.resolvePackageVersionUsingRegistry)('nx', nxAngularLegacyVersionMap[majorAngularVersion]);
88
+ pkgScope = (0, semver_1.gte)(pkgVersion, versionWithRescopeToNx) ? '@nx' : '@nrwl';
89
+ unscopedPkgName = 'angular';
90
+ pkgName = `${pkgScope}/${unscopedPkgName}`;
91
+ for (const pkg of ['nx', `${pkgScope}/workspace`, pkgName]) {
92
+ await (0, provenance_1.ensurePackageHasProvenance)(pkg, pkgVersion);
93
+ }
94
+ }
95
+ catch (e) {
96
+ // errors are caught in the initHandler and not logged to the user, so we
97
+ // log it first and then throw to ensure it is logged to the user
98
+ output_1.output.error({ title: e.message });
99
+ throw e;
100
+ }
89
101
  legacyMigrationCommand = `nx@${pkgVersion} init ${process.argv
90
102
  .slice(2)
91
103
  .join(' ')}`;