@eldrforge/git-tools 0.1.6 → 0.1.9

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.
package/dist/index.js CHANGED
@@ -1,5 +1,1372 @@
1
- export { ConsoleLogger, getLogger, setLogger } from './logger.js';
2
- export { escapeShellArg, run, runSecure, runSecureWithDryRunSupport, runSecureWithInheritedStdio, runWithDryRunSupport, runWithInheritedStdio, validateFilePath, validateGitRef } from './child.js';
3
- export { safeJsonParse, validateHasProperty, validatePackageJson, validateString } from './validation.js';
4
- export { findPreviousReleaseTag, getBranchCommitSha, getCurrentBranch, getCurrentVersion, getDefaultFromRef, getGitStatusSummary, getGloballyLinkedPackages, getLinkCompatibilityProblems, getLinkProblems, getLinkedDependencies, getRemoteDefaultBranch, isBranchInSyncWithRemote, isNpmLinked, isValidGitRef, localBranchExists, remoteBranchExists, safeSyncBranchWithRemote } from './git.js';
1
+ import { spawn, exec } from 'child_process';
2
+ import util from 'util';
3
+ import fs from 'fs/promises';
4
+ import path from 'path';
5
+ import * as semver from 'semver';
6
+
7
+ /**
8
+ * Minimal logging interface that git-tools requires.
9
+ * Allows consumers to provide their own logger implementation (e.g., Winston, console, etc.)
10
+ */ function _define_property(obj, key, value) {
11
+ if (key in obj) {
12
+ Object.defineProperty(obj, key, {
13
+ value: value,
14
+ enumerable: true,
15
+ configurable: true,
16
+ writable: true
17
+ });
18
+ } else {
19
+ obj[key] = value;
20
+ }
21
+ return obj;
22
+ }
23
+ /**
24
+ * Default console-based logger implementation
25
+ */ class ConsoleLogger {
26
+ shouldLog(level) {
27
+ const levels = [
28
+ 'error',
29
+ 'warn',
30
+ 'info',
31
+ 'verbose',
32
+ 'debug'
33
+ ];
34
+ const currentLevelIndex = levels.indexOf(this.level);
35
+ const messageLevelIndex = levels.indexOf(level);
36
+ return messageLevelIndex <= currentLevelIndex;
37
+ }
38
+ error(message, ...meta) {
39
+ if (this.shouldLog('error')) {
40
+ // eslint-disable-next-line no-console
41
+ console.error(message, ...meta);
42
+ }
43
+ }
44
+ warn(message, ...meta) {
45
+ if (this.shouldLog('warn')) {
46
+ // eslint-disable-next-line no-console
47
+ console.warn(message, ...meta);
48
+ }
49
+ }
50
+ info(message, ...meta) {
51
+ if (this.shouldLog('info')) {
52
+ // eslint-disable-next-line no-console
53
+ console.info(message, ...meta);
54
+ }
55
+ }
56
+ verbose(message, ...meta) {
57
+ if (this.shouldLog('verbose')) {
58
+ // eslint-disable-next-line no-console
59
+ console.log('[VERBOSE]', message, ...meta);
60
+ }
61
+ }
62
+ debug(message, ...meta) {
63
+ if (this.shouldLog('debug')) {
64
+ // eslint-disable-next-line no-console
65
+ console.log('[DEBUG]', message, ...meta);
66
+ }
67
+ }
68
+ constructor(level = 'info'){
69
+ _define_property(this, "level", void 0);
70
+ this.level = level;
71
+ }
72
+ }
73
+ /**
74
+ * Global logger instance - defaults to console logger
75
+ * Use setLogger() to replace with your own implementation
76
+ */ let globalLogger = new ConsoleLogger();
77
+ /**
78
+ * Set the global logger instance
79
+ */ function setLogger(logger) {
80
+ globalLogger = logger;
81
+ }
82
+ /**
83
+ * Get the global logger instance
84
+ */ function getLogger() {
85
+ return globalLogger;
86
+ }
87
+
88
+ /**
89
+ * Escapes shell arguments to prevent command injection
90
+ */ function escapeShellArg(arg) {
91
+ // For Windows, we need different escaping
92
+ if (process.platform === 'win32') {
93
+ // Escape double quotes and backslashes
94
+ return `"${arg.replace(/[\\"]/g, '\\$&')}"`;
95
+ } else {
96
+ // For Unix-like systems, escape single quotes
97
+ return `'${arg.replace(/'/g, "'\\''")}'`;
98
+ }
99
+ }
100
+ /**
101
+ * Validates git references to prevent injection
102
+ */ function validateGitRef(ref) {
103
+ // Git refs can contain letters, numbers, hyphens, underscores, slashes, and dots
104
+ // But cannot contain certain dangerous characters
105
+ const validRefPattern = /^[a-zA-Z0-9._/-]+$/;
106
+ const invalidPatterns = [
107
+ /\.\./,
108
+ /^-/,
109
+ /[\s;<>|&`$(){}[\]]/ // No shell metacharacters
110
+ ];
111
+ if (!validRefPattern.test(ref)) {
112
+ return false;
113
+ }
114
+ return !invalidPatterns.some((pattern)=>pattern.test(ref));
115
+ }
116
+ /**
117
+ * Validates file paths to prevent injection
118
+ */ function validateFilePath(filePath) {
119
+ // Basic validation - no shell metacharacters
120
+ const invalidChars = /[;<>|&`$(){}[\]]/;
121
+ return !invalidChars.test(filePath);
122
+ }
123
+ /**
124
+ * Securely executes a command with arguments array (no shell injection risk)
125
+ */ async function runSecure(command, args = [], options = {}) {
126
+ const logger = getLogger();
127
+ return new Promise((resolve, reject)=>{
128
+ logger.verbose(`Executing command securely: ${command} ${args.join(' ')}`);
129
+ logger.verbose(`Working directory: ${(options === null || options === void 0 ? void 0 : options.cwd) || process.cwd()}`);
130
+ const child = spawn(command, args, {
131
+ ...options,
132
+ shell: false,
133
+ stdio: 'pipe'
134
+ });
135
+ let stdout = '';
136
+ let stderr = '';
137
+ if (child.stdout) {
138
+ child.stdout.on('data', (data)=>{
139
+ stdout += data.toString();
140
+ });
141
+ }
142
+ if (child.stderr) {
143
+ child.stderr.on('data', (data)=>{
144
+ stderr += data.toString();
145
+ });
146
+ }
147
+ child.on('close', (code)=>{
148
+ if (code === 0) {
149
+ logger.verbose(`Command completed successfully`);
150
+ logger.verbose(`stdout: ${stdout}`);
151
+ if (stderr) {
152
+ logger.verbose(`stderr: ${stderr}`);
153
+ }
154
+ resolve({
155
+ stdout,
156
+ stderr
157
+ });
158
+ } else {
159
+ logger.error(`Command failed with exit code ${code}`);
160
+ logger.error(`stdout: ${stdout}`);
161
+ logger.error(`stderr: ${stderr}`);
162
+ reject(new Error(`Command "${[
163
+ command,
164
+ ...args
165
+ ].join(' ')}" failed with exit code ${code}`));
166
+ }
167
+ });
168
+ child.on('error', (error)=>{
169
+ logger.error(`Command failed to start: ${error.message}`);
170
+ reject(error);
171
+ });
172
+ });
173
+ }
174
+ /**
175
+ * Securely executes a command with inherited stdio (no shell injection risk)
176
+ */ async function runSecureWithInheritedStdio(command, args = [], options = {}) {
177
+ const logger = getLogger();
178
+ return new Promise((resolve, reject)=>{
179
+ logger.verbose(`Executing command securely with inherited stdio: ${command} ${args.join(' ')}`);
180
+ logger.verbose(`Working directory: ${(options === null || options === void 0 ? void 0 : options.cwd) || process.cwd()}`);
181
+ const child = spawn(command, args, {
182
+ ...options,
183
+ shell: false,
184
+ stdio: 'inherit'
185
+ });
186
+ child.on('close', (code)=>{
187
+ if (code === 0) {
188
+ logger.verbose(`Command completed successfully with code ${code}`);
189
+ resolve();
190
+ } else {
191
+ logger.error(`Command failed with exit code ${code}`);
192
+ reject(new Error(`Command "${[
193
+ command,
194
+ ...args
195
+ ].join(' ')}" failed with exit code ${code}`));
196
+ }
197
+ });
198
+ child.on('error', (error)=>{
199
+ logger.error(`Command failed to start: ${error.message}`);
200
+ reject(error);
201
+ });
202
+ });
203
+ }
204
+ async function run(command, options = {}) {
205
+ const logger = getLogger();
206
+ const execPromise = util.promisify(exec);
207
+ // Extract our custom option and pass the rest to exec
208
+ const { suppressErrorLogging = false, ...execOptions } = options || {};
209
+ // Ensure encoding is set to 'utf8' to get string output instead of Buffer
210
+ const finalOptions = {
211
+ encoding: 'utf8',
212
+ ...execOptions
213
+ };
214
+ logger.verbose(`Executing command: ${command}`);
215
+ logger.verbose(`Working directory: ${(finalOptions === null || finalOptions === void 0 ? void 0 : finalOptions.cwd) || process.cwd()}`);
216
+ logger.verbose(`Environment variables: ${Object.keys((finalOptions === null || finalOptions === void 0 ? void 0 : finalOptions.env) || process.env).length} variables`);
217
+ try {
218
+ const result = await execPromise(command, finalOptions);
219
+ logger.verbose(`Command completed successfully`);
220
+ logger.verbose(`stdout: ${result.stdout}`);
221
+ if (result.stderr) {
222
+ logger.verbose(`stderr: ${result.stderr}`);
223
+ }
224
+ // Ensure result is properly typed as strings
225
+ return {
226
+ stdout: String(result.stdout),
227
+ stderr: String(result.stderr)
228
+ };
229
+ } catch (error) {
230
+ if (!suppressErrorLogging) {
231
+ logger.error(`Command failed: ${command}`);
232
+ logger.error(`Error: ${error.message}`);
233
+ logger.error(`Exit code: ${error.code}`);
234
+ logger.error(`Signal: ${error.signal}`);
235
+ if (error.stdout) {
236
+ logger.error(`stdout: ${error.stdout}`);
237
+ }
238
+ if (error.stderr) {
239
+ logger.error(`stderr: ${error.stderr}`);
240
+ }
241
+ } else {
242
+ // Still log at verbose level for debugging
243
+ logger.verbose(`Command exited with non-zero code (suppressed): ${command}`);
244
+ logger.verbose(`Exit code: ${error.code}`);
245
+ }
246
+ throw error;
247
+ }
248
+ }
249
+ /**
250
+ * @deprecated Use runSecureWithInheritedStdio instead for better security
251
+ * Legacy function for backward compatibility - parses shell command string
252
+ */ async function runWithInheritedStdio(command, options = {}) {
253
+ // Parse command to extract command and arguments safely
254
+ const parts = command.trim().split(/\s+/);
255
+ if (parts.length === 0) {
256
+ throw new Error('Empty command provided');
257
+ }
258
+ const cmd = parts[0];
259
+ const args = parts.slice(1);
260
+ // Use the secure version
261
+ return runSecureWithInheritedStdio(cmd, args, options);
262
+ }
263
+ async function runWithDryRunSupport(command, isDryRun, options = {}, useInheritedStdio = false) {
264
+ const logger = getLogger();
265
+ if (isDryRun) {
266
+ logger.info(`DRY RUN: Would execute command: ${command}`);
267
+ return {
268
+ stdout: '',
269
+ stderr: ''
270
+ };
271
+ }
272
+ if (useInheritedStdio) {
273
+ await runWithInheritedStdio(command, options);
274
+ return {
275
+ stdout: '',
276
+ stderr: ''
277
+ }; // No output captured when using inherited stdio
278
+ }
279
+ return run(command, options);
280
+ }
281
+ /**
282
+ * Secure version of runWithDryRunSupport using argument arrays
283
+ */ async function runSecureWithDryRunSupport(command, args = [], isDryRun, options = {}, useInheritedStdio = false) {
284
+ const logger = getLogger();
285
+ if (isDryRun) {
286
+ logger.info(`DRY RUN: Would execute command: ${command} ${args.join(' ')}`);
287
+ return {
288
+ stdout: '',
289
+ stderr: ''
290
+ };
291
+ }
292
+ if (useInheritedStdio) {
293
+ await runSecureWithInheritedStdio(command, args, options);
294
+ return {
295
+ stdout: '',
296
+ stderr: ''
297
+ }; // No output captured when using inherited stdio
298
+ }
299
+ return runSecure(command, args, options);
300
+ }
301
+
302
+ /**
303
+ * Runtime validation utilities for safe type handling
304
+ */ /**
305
+ * Safely parses JSON with error handling
306
+ */ const safeJsonParse = (jsonString, context)=>{
307
+ try {
308
+ const parsed = JSON.parse(jsonString);
309
+ if (parsed === null || parsed === undefined) {
310
+ throw new Error('Parsed JSON is null or undefined');
311
+ }
312
+ return parsed;
313
+ } catch (error) {
314
+ const contextStr = context ? ` (${context})` : '';
315
+ throw new Error(`Failed to parse JSON${contextStr}: ${error instanceof Error ? error.message : 'Unknown error'}`);
316
+ }
317
+ };
318
+ /**
319
+ * Validates that a value is a non-empty string
320
+ */ const validateString = (value, fieldName)=>{
321
+ if (typeof value !== 'string') {
322
+ throw new Error(`${fieldName} must be a string, got ${typeof value}`);
323
+ }
324
+ if (value.trim() === '') {
325
+ throw new Error(`${fieldName} cannot be empty`);
326
+ }
327
+ return value;
328
+ };
329
+ /**
330
+ * Validates that a value exists and has a specific property
331
+ */ const validateHasProperty = (obj, property, context)=>{
332
+ if (!obj || typeof obj !== 'object') {
333
+ const contextStr = context ? ` in ${context}` : '';
334
+ throw new Error(`Object is null or not an object${contextStr}`);
335
+ }
336
+ if (!(property in obj)) {
337
+ const contextStr = context ? ` in ${context}` : '';
338
+ throw new Error(`Missing required property '${property}'${contextStr}`);
339
+ }
340
+ };
341
+ /**
342
+ * Validates package.json structure has basic required fields
343
+ */ const validatePackageJson = (data, context, requireName = true)=>{
344
+ if (!data || typeof data !== 'object') {
345
+ const contextStr = context ? ` (${context})` : '';
346
+ throw new Error(`Invalid package.json${contextStr}: not an object`);
347
+ }
348
+ if (requireName && typeof data.name !== 'string') {
349
+ const contextStr = context ? ` (${context})` : '';
350
+ throw new Error(`Invalid package.json${contextStr}: name must be a string`);
351
+ }
352
+ return data;
353
+ };
354
+
355
+ /**
356
+ * Validates that a git remote name is safe (prevents option injection).
357
+ * Git remote names must not start with '-' and should match /^[A-Za-z0-9._\/-]+$/
358
+ */ function isValidGitRemoteName(remote) {
359
+ // Disallow starting dash, spaces, and only allow common git remote name characters.
360
+ // See: https://git-scm.com/docs/git-remote#_remotes
361
+ return typeof remote === 'string' && remote.length > 0 && !remote.startsWith('-') && /^[A-Za-z0-9._/-]+$/.test(remote);
362
+ }
363
+ /**
364
+ * Tests if a git reference exists and is valid (silent version that doesn't log errors)
365
+ */ const isValidGitRefSilent = async (ref)=>{
366
+ try {
367
+ // Validate the ref first to prevent injection
368
+ if (!validateGitRef(ref)) {
369
+ return false;
370
+ }
371
+ await runSecure('git', [
372
+ 'rev-parse',
373
+ '--verify',
374
+ ref
375
+ ], {
376
+ stdio: 'ignore'
377
+ });
378
+ return true;
379
+ } catch {
380
+ return false;
381
+ }
382
+ };
383
+ /**
384
+ * Tests if a git reference exists and is valid
385
+ */ const isValidGitRef = async (ref)=>{
386
+ const logger = getLogger();
387
+ try {
388
+ // Validate the ref first to prevent injection
389
+ if (!validateGitRef(ref)) {
390
+ logger.debug(`Git reference '${ref}' contains invalid characters`);
391
+ return false;
392
+ }
393
+ await runSecure('git', [
394
+ 'rev-parse',
395
+ '--verify',
396
+ ref
397
+ ], {
398
+ stdio: 'ignore'
399
+ });
400
+ logger.debug(`Git reference '${ref}' is valid`);
401
+ return true;
402
+ } catch (error) {
403
+ logger.debug(`Git reference '${ref}' is not valid: ${error}`);
404
+ return false;
405
+ }
406
+ };
407
+ /**
408
+ * Finds the previous release tag based on the current version using semantic versioning.
409
+ * Returns the highest version tag that is less than the current version.
410
+ *
411
+ * @param currentVersion The current version (e.g., "1.2.3", "2.0.0")
412
+ * @param tagPattern The pattern to match tags (e.g., "v*", "working/v*")
413
+ * @returns The previous release tag or null if none found
414
+ */ const findPreviousReleaseTag = async (currentVersion, tagPattern = 'v*')=>{
415
+ const logger = getLogger();
416
+ try {
417
+ // Parse current version first to validate it
418
+ const currentSemver = semver.parse(currentVersion);
419
+ if (!currentSemver) {
420
+ logger.warn(`❌ Invalid version format: ${currentVersion}`);
421
+ return null;
422
+ }
423
+ logger.info(`🔍 findPreviousReleaseTag: Looking for tags matching "${tagPattern}" < ${currentVersion}`);
424
+ // Get all tags - try sorted first, fallback to unsorted
425
+ let tags;
426
+ try {
427
+ logger.info(` Running: git tag -l "${tagPattern}" --sort=-version:refname`);
428
+ const { stdout } = await runSecure('git', [
429
+ 'tag',
430
+ '-l',
431
+ tagPattern,
432
+ '--sort=-version:refname'
433
+ ]);
434
+ tags = stdout.trim().split('\n').filter((tag)=>tag.length > 0);
435
+ logger.info(` ✅ Found ${tags.length} tags matching pattern "${tagPattern}"`);
436
+ if (tags.length > 0) {
437
+ logger.info(` 📋 Tags (newest first): ${tags.slice(0, 15).join(', ')}${tags.length > 15 ? ` ... (${tags.length - 15} more)` : ''}`);
438
+ }
439
+ } catch (sortError) {
440
+ // Fallback for older git versions that don't support --sort
441
+ logger.info(` ⚠️ Git tag --sort failed: ${sortError.message}`);
442
+ logger.info(` Falling back to manual sorting...`);
443
+ const { stdout } = await runSecure('git', [
444
+ 'tag',
445
+ '-l',
446
+ tagPattern
447
+ ]);
448
+ tags = stdout.trim().split('\n').filter((tag)=>tag.length > 0);
449
+ logger.info(` Found ${tags.length} tags (unsorted) matching pattern "${tagPattern}"`);
450
+ // Manual semantic version sorting
451
+ tags.sort((a, b)=>{
452
+ const aMatch = a.match(/v?(\d+\.\d+\.\d+.*?)$/);
453
+ const bMatch = b.match(/v?(\d+\.\d+\.\d+.*?)$/);
454
+ if (!aMatch || !bMatch) return 0;
455
+ const aSemver = semver.parse(aMatch[1]);
456
+ const bSemver = semver.parse(bMatch[1]);
457
+ if (!aSemver || !bSemver) return 0;
458
+ return semver.rcompare(aSemver, bSemver);
459
+ });
460
+ logger.info(` ✅ Sorted ${tags.length} tags manually`);
461
+ }
462
+ if (tags.length === 0) {
463
+ logger.warn('');
464
+ logger.warn(`❌ NO TAGS FOUND matching pattern "${tagPattern}"`);
465
+ logger.warn(` To verify, run: git tag -l '${tagPattern}'`);
466
+ logger.warn('');
467
+ return null;
468
+ }
469
+ logger.info(` 🔬 Processing ${tags.length} tags to find the highest version < ${currentVersion}...`);
470
+ // Find the highest version that is less than the current version
471
+ let previousTag = null;
472
+ let previousVersion = null;
473
+ let validTags = 0;
474
+ let skippedTags = 0;
475
+ for (const tag of tags){
476
+ // Extract version from tag - handle "v1.2.13", "1.2.13", and "working/v1.2.13"
477
+ const versionMatch = tag.match(/v?(\d+\.\d+\.\d+.*?)$/);
478
+ if (!versionMatch) {
479
+ logger.debug(` ⏭️ Skipping tag "${tag}" (doesn't match version pattern)`);
480
+ continue;
481
+ }
482
+ const versionString = versionMatch[1];
483
+ const tagSemver = semver.parse(versionString);
484
+ if (tagSemver) {
485
+ validTags++;
486
+ // Check if this tag version is less than current version
487
+ if (semver.lt(tagSemver, currentSemver)) {
488
+ // If we don't have a previous version yet, or this one is higher than our current previous
489
+ if (!previousVersion || semver.gt(tagSemver, previousVersion)) {
490
+ previousVersion = tagSemver;
491
+ previousTag = tag; // Keep the original tag format
492
+ logger.info(` ✅ New best candidate: ${tag} (${versionString} < ${currentVersion})`);
493
+ } else {
494
+ logger.debug(` ⏭️ ${tag} (${versionString}) is < current but not better than ${previousTag}`);
495
+ }
496
+ } else {
497
+ skippedTags++;
498
+ logger.debug(` ⏭️ ${tag} (${versionString}) >= current (${currentVersion}), skipping`);
499
+ }
500
+ }
501
+ }
502
+ logger.info('');
503
+ logger.info(` 📊 Tag analysis results:`);
504
+ logger.info(` - Total tags examined: ${tags.length}`);
505
+ logger.info(` - Valid semver tags: ${validTags}`);
506
+ logger.info(` - Tags >= current version (skipped): ${skippedTags}`);
507
+ logger.info(` - Best match: ${previousTag || 'none'}`);
508
+ logger.info('');
509
+ if (previousTag) {
510
+ logger.info(`✅ SUCCESS: Found previous tag: ${previousTag}`);
511
+ logger.info(` Version comparison: ${previousVersion === null || previousVersion === void 0 ? void 0 : previousVersion.version} < ${currentVersion}`);
512
+ logger.info('');
513
+ return previousTag;
514
+ }
515
+ logger.warn(`❌ FAILED: No previous tag found for version ${currentVersion}`);
516
+ logger.warn(` Pattern searched: "${tagPattern}"`);
517
+ logger.warn(` Reason: All ${validTags} valid tags were >= ${currentVersion}`);
518
+ logger.warn('');
519
+ return null;
520
+ } catch (error) {
521
+ logger.debug(`Error finding previous release tag: ${error.message}`);
522
+ return null;
523
+ }
524
+ };
525
+ /**
526
+ * Gets the current version from package.json
527
+ *
528
+ * @returns The current version string or null if not found
529
+ */ const getCurrentVersion = async ()=>{
530
+ const logger = getLogger();
531
+ try {
532
+ // First try to get from committed version in HEAD
533
+ const { stdout } = await runSecure('git', [
534
+ 'show',
535
+ 'HEAD:package.json'
536
+ ]);
537
+ const packageJson = safeJsonParse(stdout, 'package.json');
538
+ const validated = validatePackageJson(packageJson, 'package.json');
539
+ if (validated.version) {
540
+ logger.debug(`Current version from HEAD:package.json: ${validated.version}`);
541
+ return validated.version;
542
+ }
543
+ return null;
544
+ } catch (error) {
545
+ logger.debug(`Could not read version from HEAD:package.json: ${error.message}`);
546
+ // Fallback to reading from working directory
547
+ try {
548
+ const packageJsonPath = path.join(process.cwd(), 'package.json');
549
+ const content = await fs.readFile(packageJsonPath, 'utf-8');
550
+ const packageJson = safeJsonParse(content, 'package.json');
551
+ const validated = validatePackageJson(packageJson, 'package.json');
552
+ if (validated.version) {
553
+ logger.debug(`Current version from working directory package.json: ${validated.version}`);
554
+ return validated.version;
555
+ }
556
+ return null;
557
+ } catch (fallbackError) {
558
+ logger.debug(`Error reading current version from filesystem: ${fallbackError.message}`);
559
+ return null;
560
+ }
561
+ }
562
+ };
563
+ /**
564
+ * Gets a reliable default for the --from parameter by trying multiple fallbacks
565
+ *
566
+ * Tries in order:
567
+ * 1. Previous working branch tag (if on working branch)
568
+ * 2. Previous release tag (if current version can be determined)
569
+ * 3. main (local main branch - typical release comparison base)
570
+ * 4. master (local master branch - legacy default)
571
+ * 5. origin/main (remote main branch fallback)
572
+ * 6. origin/master (remote master branch fallback)
573
+ *
574
+ * @param forceMainBranch If true, skip tag detection and use main branch
575
+ * @param currentBranch Current branch name for branch-aware tag detection
576
+ * @returns A valid git reference to use as the default from parameter
577
+ * @throws Error if no valid reference can be found
578
+ */ const getDefaultFromRef = async (forceMainBranch = false, currentBranch)=>{
579
+ const logger = getLogger();
580
+ logger.info('');
581
+ logger.info('═══════════════════════════════════════════════════════════');
582
+ logger.info('🔍 DETECTING DEFAULT --from REFERENCE FOR RELEASE NOTES');
583
+ logger.info('═══════════════════════════════════════════════════════════');
584
+ logger.info(`📋 Input parameters:`);
585
+ logger.info(` - forceMainBranch: ${forceMainBranch}`);
586
+ logger.info(` - currentBranch: "${currentBranch}"`);
587
+ logger.info('');
588
+ // If forced to use main branch, skip tag detection
589
+ if (forceMainBranch) {
590
+ logger.info('⚡ Forced to use main branch, skipping tag detection');
591
+ } else {
592
+ // If on working branch, look for working branch tags first
593
+ logger.info(`🎯 Branch check: currentBranch="${currentBranch}", isWorking=${currentBranch === 'working'}`);
594
+ if (currentBranch && currentBranch === 'working') {
595
+ logger.info('');
596
+ logger.info('📍 DETECTED WORKING BRANCH - Searching for working branch tags...');
597
+ logger.info('───────────────────────────────────────────────────────────');
598
+ try {
599
+ const currentVersion = await getCurrentVersion();
600
+ logger.info(`📦 Current version from package.json: ${currentVersion}`);
601
+ if (currentVersion) {
602
+ logger.info(`🔍 Searching for tags matching pattern: "working/v*"`);
603
+ logger.info(` (Looking for tags < ${currentVersion})`);
604
+ logger.info('');
605
+ const previousTag = await findPreviousReleaseTag(currentVersion, 'working/v*');
606
+ logger.info(`🎯 findPreviousReleaseTag result: ${previousTag || 'null (no tag found)'}`);
607
+ if (previousTag) {
608
+ logger.info(`🔬 Validating tag reference: "${previousTag}"`);
609
+ const isValid = await isValidGitRef(previousTag);
610
+ logger.info(` Tag is valid git ref: ${isValid}`);
611
+ if (isValid) {
612
+ logger.info('');
613
+ logger.info(`✅ SUCCESS: Using previous working branch tag '${previousTag}'`);
614
+ logger.info(` This shows commits added since the last release`);
615
+ logger.info('═══════════════════════════════════════════════════════════');
616
+ logger.info('');
617
+ return previousTag;
618
+ } else {
619
+ logger.warn('');
620
+ logger.warn(`⚠️ VALIDATION FAILED: Tag "${previousTag}" exists but is not a valid git reference`);
621
+ logger.warn(` This should not happen - the tag might be corrupted`);
622
+ }
623
+ } else {
624
+ logger.warn('');
625
+ logger.warn('❌ NO WORKING BRANCH TAG FOUND matching pattern "working/v*"');
626
+ logger.warn(` Current version: ${currentVersion}`);
627
+ logger.warn(' 💡 To create working branch tags for past releases, run:');
628
+ logger.warn(' kodrdriv development --create-retroactive-tags');
629
+ logger.warn('');
630
+ logger.warn(' Falling back to regular tag search...');
631
+ }
632
+ } else {
633
+ logger.warn('');
634
+ logger.warn('❌ CANNOT READ VERSION from package.json');
635
+ logger.warn(' Cannot search for working branch tags without current version');
636
+ }
637
+ } catch (error) {
638
+ logger.warn('');
639
+ logger.warn(`❌ ERROR while searching for working branch tag: ${error.message}`);
640
+ logger.debug(`Full error stack: ${error.stack}`);
641
+ logger.warn(' Falling back to regular tag search...');
642
+ }
643
+ logger.info('───────────────────────────────────────────────────────────');
644
+ logger.info('');
645
+ } else {
646
+ logger.info(`ℹ️ Not on "working" branch - skipping working tag search`);
647
+ logger.info(` (Only search for working/v* tags when on working branch)`);
648
+ logger.info('');
649
+ }
650
+ // First, try to find the previous release tag
651
+ try {
652
+ const currentVersion = await getCurrentVersion();
653
+ if (currentVersion) {
654
+ const previousTag = await findPreviousReleaseTag(currentVersion);
655
+ if (previousTag && await isValidGitRef(previousTag)) {
656
+ logger.info(`Using previous release tag '${previousTag}' as default --from reference`);
657
+ return previousTag;
658
+ }
659
+ }
660
+ } catch (error) {
661
+ logger.debug(`Could not determine previous release tag: ${error.message}`);
662
+ }
663
+ }
664
+ // Fallback to branch-based references
665
+ const candidates = [
666
+ 'main',
667
+ 'master',
668
+ 'origin/main',
669
+ 'origin/master'
670
+ ];
671
+ for (const candidate of candidates){
672
+ logger.debug(`Testing git reference candidate: ${candidate}`);
673
+ if (await isValidGitRef(candidate)) {
674
+ if (forceMainBranch) {
675
+ logger.info(`Using '${candidate}' as forced main branch reference`);
676
+ } else {
677
+ logger.info(`Using '${candidate}' as fallback --from reference (no previous release tag found)`);
678
+ }
679
+ return candidate;
680
+ }
681
+ }
682
+ // If we get here, something is seriously wrong with the git repository
683
+ throw new Error('Could not find a valid default git reference for --from parameter. ' + 'Please specify --from explicitly or check your git repository configuration. ' + `Tried: ${forceMainBranch ? 'main branch only' : 'previous release tag'}, ${candidates.join(', ')}`);
684
+ };
685
+ /**
686
+ * Gets the default branch name from the remote repository
687
+ */ const getRemoteDefaultBranch = async ()=>{
688
+ const logger = getLogger();
689
+ try {
690
+ // Try to get the symbolic reference for origin/HEAD
691
+ const { stdout } = await run('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""');
692
+ if (stdout.trim()) {
693
+ // Extract branch name from refs/remotes/origin/branch-name
694
+ const match = stdout.trim().match(/refs\/remotes\/origin\/(.+)$/);
695
+ if (match) {
696
+ const branchName = match[1];
697
+ logger.debug(`Remote default branch is: ${branchName}`);
698
+ return branchName;
699
+ }
700
+ }
701
+ // Fallback: try to get it from ls-remote
702
+ const { stdout: lsRemoteOutput } = await run('git ls-remote --symref origin HEAD');
703
+ const symrefMatch = lsRemoteOutput.match(/ref: refs\/heads\/(.+)\s+HEAD/);
704
+ if (symrefMatch) {
705
+ const branchName = symrefMatch[1];
706
+ logger.debug(`Remote default branch from ls-remote: ${branchName}`);
707
+ return branchName;
708
+ }
709
+ logger.debug('Could not determine remote default branch');
710
+ return null;
711
+ } catch (error) {
712
+ logger.debug(`Failed to get remote default branch: ${error}`);
713
+ return null;
714
+ }
715
+ };
716
+ /**
717
+ * Checks if a local branch exists
718
+ */ const localBranchExists = async (branchName)=>{
719
+ const logger = getLogger();
720
+ const result = await isValidGitRefSilent(`refs/heads/${branchName}`);
721
+ if (result) {
722
+ logger.debug(`Local branch '${branchName}' exists`);
723
+ } else {
724
+ logger.debug(`Local branch '${branchName}' does not exist`);
725
+ }
726
+ return result;
727
+ };
728
+ /**
729
+ * Checks if a remote branch exists
730
+ */ const remoteBranchExists = async (branchName, remote = 'origin')=>{
731
+ const logger = getLogger();
732
+ const result = await isValidGitRefSilent(`refs/remotes/${remote}/${branchName}`);
733
+ if (result) {
734
+ logger.debug(`Remote branch '${remote}/${branchName}' exists`);
735
+ } else {
736
+ logger.debug(`Remote branch '${remote}/${branchName}' does not exist`);
737
+ }
738
+ return result;
739
+ };
740
+ /**
741
+ * Gets the commit SHA for a given branch (local or remote)
742
+ */ const getBranchCommitSha = async (branchRef)=>{
743
+ // Validate the ref first to prevent injection
744
+ if (!validateGitRef(branchRef)) {
745
+ throw new Error(`Invalid git reference: ${branchRef}`);
746
+ }
747
+ const { stdout } = await runSecure('git', [
748
+ 'rev-parse',
749
+ branchRef
750
+ ]);
751
+ return stdout.trim();
752
+ };
753
+ /**
754
+ * Checks if a local branch is in sync with its remote counterpart
755
+ */ const isBranchInSyncWithRemote = async (branchName, remote = 'origin')=>{
756
+ const logger = getLogger();
757
+ try {
758
+ // Validate inputs first to prevent injection
759
+ if (!validateGitRef(branchName)) {
760
+ throw new Error(`Invalid branch name: ${branchName}`);
761
+ }
762
+ if (!validateGitRef(remote)) {
763
+ throw new Error(`Invalid remote name: ${remote}`);
764
+ }
765
+ // First, fetch latest remote refs without affecting working directory
766
+ await runSecure('git', [
767
+ 'fetch',
768
+ remote,
769
+ '--quiet'
770
+ ]);
771
+ const localExists = await localBranchExists(branchName);
772
+ const remoteExists = await remoteBranchExists(branchName, remote);
773
+ if (!localExists) {
774
+ return {
775
+ inSync: false,
776
+ localExists: false,
777
+ remoteExists,
778
+ error: `Local branch '${branchName}' does not exist`
779
+ };
780
+ }
781
+ if (!remoteExists) {
782
+ return {
783
+ inSync: false,
784
+ localExists: true,
785
+ remoteExists: false,
786
+ error: `Remote branch '${remote}/${branchName}' does not exist`
787
+ };
788
+ }
789
+ // Both branches exist, compare their SHAs
790
+ const localSha = await getBranchCommitSha(`refs/heads/${branchName}`);
791
+ const remoteSha = await getBranchCommitSha(`refs/remotes/${remote}/${branchName}`);
792
+ const inSync = localSha === remoteSha;
793
+ logger.debug(`Branch sync check for '${branchName}': local=${localSha.substring(0, 8)}, remote=${remoteSha.substring(0, 8)}, inSync=${inSync}`);
794
+ return {
795
+ inSync,
796
+ localSha,
797
+ remoteSha,
798
+ localExists: true,
799
+ remoteExists: true
800
+ };
801
+ } catch (error) {
802
+ logger.debug(`Failed to check branch sync for '${branchName}': ${error.message}`);
803
+ return {
804
+ inSync: false,
805
+ localExists: false,
806
+ remoteExists: false,
807
+ error: `Failed to check branch sync: ${error.message}`
808
+ };
809
+ }
810
+ };
811
+ /**
812
+ * Attempts to safely sync a local branch with its remote counterpart
813
+ * Returns true if successful, false if conflicts exist that require manual resolution
814
+ */ const safeSyncBranchWithRemote = async (branchName, remote = 'origin')=>{
815
+ const logger = getLogger();
816
+ // Validate the remote parameter to prevent command injection
817
+ if (!isValidGitRemoteName(remote)) {
818
+ return {
819
+ success: false,
820
+ error: `Invalid remote name: '${remote}'`
821
+ };
822
+ }
823
+ try {
824
+ // Validate inputs first to prevent injection
825
+ if (!validateGitRef(branchName)) {
826
+ throw new Error(`Invalid branch name: ${branchName}`);
827
+ }
828
+ if (!validateGitRef(remote)) {
829
+ throw new Error(`Invalid remote name: ${remote}`);
830
+ }
831
+ // Explicitly disallow remotes that look like command-line options (e.g. "--upload-pack")
832
+ if (remote.startsWith('-')) {
833
+ throw new Error(`Disallowed remote name (cannot start with '-'): ${remote}`);
834
+ }
835
+ // Check current branch to restore later if needed
836
+ const { stdout: currentBranch } = await runSecure('git', [
837
+ 'branch',
838
+ '--show-current'
839
+ ]);
840
+ const originalBranch = currentBranch.trim();
841
+ // Fetch latest remote refs
842
+ await runSecure('git', [
843
+ 'fetch',
844
+ remote,
845
+ '--quiet'
846
+ ]);
847
+ // Check if local branch exists
848
+ const localExists = await localBranchExists(branchName);
849
+ const remoteExists = await remoteBranchExists(branchName, remote);
850
+ if (!remoteExists) {
851
+ return {
852
+ success: false,
853
+ error: `Remote branch '${remote}/${branchName}' does not exist`
854
+ };
855
+ }
856
+ if (!localExists) {
857
+ // Create local branch tracking the remote
858
+ await runSecure('git', [
859
+ 'branch',
860
+ branchName,
861
+ `${remote}/${branchName}`
862
+ ]);
863
+ logger.debug(`Created local branch '${branchName}' tracking '${remote}/${branchName}'`);
864
+ return {
865
+ success: true
866
+ };
867
+ }
868
+ // Check if we need to switch to the target branch
869
+ const needToSwitch = originalBranch !== branchName;
870
+ if (needToSwitch) {
871
+ // Check for uncommitted changes before switching
872
+ const { stdout: statusOutput } = await runSecure('git', [
873
+ 'status',
874
+ '--porcelain'
875
+ ]);
876
+ if (statusOutput.trim()) {
877
+ return {
878
+ success: false,
879
+ error: `Cannot switch to branch '${branchName}' because you have uncommitted changes. Please commit or stash your changes first.`
880
+ };
881
+ }
882
+ // Switch to target branch
883
+ await runSecure('git', [
884
+ 'checkout',
885
+ branchName
886
+ ]);
887
+ }
888
+ try {
889
+ // Try to pull with fast-forward only
890
+ await runSecure('git', [
891
+ 'pull',
892
+ remote,
893
+ branchName,
894
+ '--ff-only'
895
+ ]);
896
+ logger.debug(`Successfully synced '${branchName}' with '${remote}/${branchName}'`);
897
+ // Switch back to original branch if we switched
898
+ if (needToSwitch && originalBranch) {
899
+ await runSecure('git', [
900
+ 'checkout',
901
+ originalBranch
902
+ ]);
903
+ }
904
+ return {
905
+ success: true
906
+ };
907
+ } catch (pullError) {
908
+ // Switch back to original branch if we switched
909
+ if (needToSwitch && originalBranch) {
910
+ try {
911
+ await runSecure('git', [
912
+ 'checkout',
913
+ originalBranch
914
+ ]);
915
+ } catch (checkoutError) {
916
+ logger.warn(`Failed to switch back to original branch '${originalBranch}': ${checkoutError}`);
917
+ }
918
+ }
919
+ // Check if this is a merge conflict or diverged branches
920
+ if (pullError.message.includes('diverged') || pullError.message.includes('non-fast-forward') || pullError.message.includes('conflict') || pullError.message.includes('CONFLICT')) {
921
+ return {
922
+ success: false,
923
+ conflictResolutionRequired: true,
924
+ error: `Branch '${branchName}' has diverged from '${remote}/${branchName}' and requires manual conflict resolution`
925
+ };
926
+ }
927
+ return {
928
+ success: false,
929
+ error: `Failed to sync branch '${branchName}': ${pullError.message}`
930
+ };
931
+ }
932
+ } catch (error) {
933
+ return {
934
+ success: false,
935
+ error: `Failed to sync branch '${branchName}': ${error.message}`
936
+ };
937
+ }
938
+ };
939
+ /**
940
+ * Gets the current branch name
941
+ */ const getCurrentBranch = async ()=>{
942
+ const { stdout } = await runSecure('git', [
943
+ 'branch',
944
+ '--show-current'
945
+ ]);
946
+ return stdout.trim();
947
+ };
948
+ /**
949
+ * Gets git status summary including unstaged files, uncommitted changes, and unpushed commits
950
+ */ const getGitStatusSummary = async (workingDir)=>{
951
+ const logger = getLogger();
952
+ try {
953
+ const originalCwd = process.cwd();
954
+ if (workingDir) {
955
+ process.chdir(workingDir);
956
+ }
957
+ try {
958
+ // Get current branch
959
+ const branch = await getCurrentBranch();
960
+ // Get git status for unstaged and uncommitted changes
961
+ const { stdout: statusOutput } = await runSecure('git', [
962
+ 'status',
963
+ '--porcelain'
964
+ ]);
965
+ const statusLines = statusOutput.trim().split('\n').filter((line)=>line.trim());
966
+ // Count different types of changes
967
+ let unstagedCount = 0;
968
+ let uncommittedCount = 0;
969
+ for (const line of statusLines){
970
+ const statusCode = line.substring(0, 2);
971
+ // For untracked files (??) count as unstaged only once
972
+ if (statusCode === '??') {
973
+ unstagedCount++;
974
+ continue;
975
+ }
976
+ // Check for unstaged changes (working directory changes)
977
+ // Second character represents working tree status
978
+ if (statusCode[1] !== ' ' && statusCode[1] !== '') {
979
+ unstagedCount++;
980
+ }
981
+ // Check for uncommitted changes (staged changes)
982
+ // First character represents index status
983
+ if (statusCode[0] !== ' ' && statusCode[0] !== '') {
984
+ uncommittedCount++;
985
+ }
986
+ }
987
+ // Check for unpushed commits by comparing with remote
988
+ let unpushedCount = 0;
989
+ let hasUnpushedCommits = false;
990
+ try {
991
+ // First fetch to get latest remote refs
992
+ await runSecure('git', [
993
+ 'fetch',
994
+ 'origin',
995
+ '--quiet'
996
+ ]);
997
+ // Check if remote branch exists
998
+ const remoteExists = await remoteBranchExists(branch);
999
+ if (remoteExists) {
1000
+ // Get count of commits ahead of remote (branch already validated in calling function)
1001
+ const { stdout: aheadOutput } = await runSecure('git', [
1002
+ 'rev-list',
1003
+ '--count',
1004
+ `origin/${branch}..HEAD`
1005
+ ]);
1006
+ unpushedCount = parseInt(aheadOutput.trim()) || 0;
1007
+ hasUnpushedCommits = unpushedCount > 0;
1008
+ }
1009
+ } catch (error) {
1010
+ logger.debug(`Could not check for unpushed commits: ${error}`);
1011
+ // Remote might not exist or other issues - not critical for status
1012
+ }
1013
+ const hasUnstagedFiles = unstagedCount > 0;
1014
+ const hasUncommittedChanges = uncommittedCount > 0;
1015
+ // Build status summary
1016
+ const statusParts = [];
1017
+ if (hasUnstagedFiles) {
1018
+ statusParts.push(`${unstagedCount} unstaged`);
1019
+ }
1020
+ if (hasUncommittedChanges) {
1021
+ statusParts.push(`${uncommittedCount} uncommitted`);
1022
+ }
1023
+ if (hasUnpushedCommits) {
1024
+ statusParts.push(`${unpushedCount} unpushed`);
1025
+ }
1026
+ const status = statusParts.length > 0 ? statusParts.join(', ') : 'clean';
1027
+ return {
1028
+ branch,
1029
+ hasUnstagedFiles,
1030
+ hasUncommittedChanges,
1031
+ hasUnpushedCommits,
1032
+ unstagedCount,
1033
+ uncommittedCount,
1034
+ unpushedCount,
1035
+ status
1036
+ };
1037
+ } finally{
1038
+ if (workingDir) {
1039
+ process.chdir(originalCwd);
1040
+ }
1041
+ }
1042
+ } catch (error) {
1043
+ logger.debug(`Failed to get git status summary: ${error.message}`);
1044
+ return {
1045
+ branch: 'unknown',
1046
+ hasUnstagedFiles: false,
1047
+ hasUncommittedChanges: false,
1048
+ hasUnpushedCommits: false,
1049
+ unstagedCount: 0,
1050
+ uncommittedCount: 0,
1051
+ unpushedCount: 0,
1052
+ status: 'error'
1053
+ };
1054
+ }
1055
+ };
1056
+ /**
1057
+ * Gets the list of globally linked packages (packages available to be linked to)
1058
+ */ const getGloballyLinkedPackages = async ()=>{
1059
+ const execPromise = util.promisify(exec);
1060
+ try {
1061
+ const { stdout } = await execPromise('npm ls --link -g --json');
1062
+ const result = safeJsonParse(stdout, 'npm ls global output');
1063
+ if (result.dependencies && typeof result.dependencies === 'object') {
1064
+ return new Set(Object.keys(result.dependencies));
1065
+ }
1066
+ return new Set();
1067
+ } catch (error) {
1068
+ // Try to parse from error stdout if available
1069
+ if (error.stdout) {
1070
+ try {
1071
+ const result = safeJsonParse(error.stdout, 'npm ls global error output');
1072
+ if (result.dependencies && typeof result.dependencies === 'object') {
1073
+ return new Set(Object.keys(result.dependencies));
1074
+ }
1075
+ } catch {
1076
+ // If JSON parsing fails, return empty set
1077
+ }
1078
+ }
1079
+ return new Set();
1080
+ }
1081
+ };
1082
+ /**
1083
+ * Gets the list of packages that this package is actively linking to (consuming linked packages)
1084
+ */ const getLinkedDependencies = async (packageDir)=>{
1085
+ const execPromise = util.promisify(exec);
1086
+ try {
1087
+ const { stdout } = await execPromise('npm ls --link --json', {
1088
+ cwd: packageDir
1089
+ });
1090
+ const result = safeJsonParse(stdout, 'npm ls local output');
1091
+ if (result.dependencies && typeof result.dependencies === 'object') {
1092
+ return new Set(Object.keys(result.dependencies));
1093
+ }
1094
+ return new Set();
1095
+ } catch (error) {
1096
+ // npm ls --link often exits with non-zero code but still provides valid JSON in stdout
1097
+ if (error.stdout) {
1098
+ try {
1099
+ const result = safeJsonParse(error.stdout, 'npm ls local error output');
1100
+ if (result.dependencies && typeof result.dependencies === 'object') {
1101
+ return new Set(Object.keys(result.dependencies));
1102
+ }
1103
+ } catch {
1104
+ // If JSON parsing fails, return empty set
1105
+ }
1106
+ }
1107
+ return new Set();
1108
+ }
1109
+ };
1110
+ /**
1111
+ * Checks for actual semantic version compatibility issues between linked packages and their consumers
1112
+ * Returns a set of dependency names that have real compatibility problems
1113
+ *
1114
+ * This function ignores npm's strict prerelease handling and focuses on actual compatibility:
1115
+ * - "^4.4" is compatible with "4.4.53-dev.0" (prerelease of compatible minor version)
1116
+ * - "^4.4" is incompatible with "4.5.3" (different minor version)
1117
+ */ const getLinkCompatibilityProblems = async (packageDir, allPackagesInfo)=>{
1118
+ try {
1119
+ // Read the consumer package.json
1120
+ const packageJsonPath = path.join(packageDir, 'package.json');
1121
+ const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');
1122
+ const parsed = safeJsonParse(packageJsonContent, packageJsonPath);
1123
+ const packageJson = validatePackageJson(parsed, packageJsonPath);
1124
+ const problemDependencies = new Set();
1125
+ // Get linked dependencies
1126
+ const linkedDeps = await getLinkedDependencies(packageDir);
1127
+ // Check each dependency type
1128
+ const dependencyTypes = [
1129
+ 'dependencies',
1130
+ 'devDependencies',
1131
+ 'peerDependencies',
1132
+ 'optionalDependencies'
1133
+ ];
1134
+ for (const depType of dependencyTypes){
1135
+ const deps = packageJson[depType];
1136
+ if (!deps || typeof deps !== 'object') continue;
1137
+ for (const [depName, versionRange] of Object.entries(deps)){
1138
+ // Only check dependencies that are currently linked
1139
+ if (!linkedDeps.has(depName)) continue;
1140
+ // Skip if version range is not a string or is invalid
1141
+ if (typeof versionRange !== 'string') continue;
1142
+ try {
1143
+ let linkedVersion;
1144
+ // If we have package info provided, use it
1145
+ if (allPackagesInfo) {
1146
+ const packageInfo = allPackagesInfo.get(depName);
1147
+ if (packageInfo) {
1148
+ linkedVersion = packageInfo.version;
1149
+ }
1150
+ }
1151
+ // If we don't have version from package info, try to read it from the linked package
1152
+ if (!linkedVersion) {
1153
+ try {
1154
+ // Get the linked package path and read its version
1155
+ const nodeModulesPath = path.join(packageDir, 'node_modules', depName, 'package.json');
1156
+ const linkedPackageJson = await fs.readFile(nodeModulesPath, 'utf-8');
1157
+ const linkedParsed = safeJsonParse(linkedPackageJson, nodeModulesPath);
1158
+ const linkedValidated = validatePackageJson(linkedParsed, nodeModulesPath);
1159
+ linkedVersion = linkedValidated.version;
1160
+ } catch {
1161
+ continue;
1162
+ }
1163
+ }
1164
+ if (!linkedVersion) continue;
1165
+ // Check compatibility with custom logic for prerelease versions
1166
+ if (!isVersionCompatibleWithRange(linkedVersion, versionRange)) {
1167
+ problemDependencies.add(depName);
1168
+ }
1169
+ } catch {
1170
+ continue;
1171
+ }
1172
+ }
1173
+ }
1174
+ return problemDependencies;
1175
+ } catch {
1176
+ // If we can't read the package.json or process it, return empty set
1177
+ return new Set();
1178
+ }
1179
+ };
1180
+ /**
1181
+ * Custom semver compatibility check that handles prerelease versions more intelligently
1182
+ * than npm's strict checking, with stricter caret range handling
1183
+ *
1184
+ * Examples:
1185
+ * - isVersionCompatibleWithRange("4.4.53-dev.0", "^4.4") => true
1186
+ * - isVersionCompatibleWithRange("4.5.3", "^4.4") => false
1187
+ * - isVersionCompatibleWithRange("4.4.1", "^4.4") => true
1188
+ */ const isVersionCompatibleWithRange = (version, range)=>{
1189
+ try {
1190
+ const parsedVersion = semver.parse(version);
1191
+ if (!parsedVersion) return false;
1192
+ // Parse the range to understand what we're comparing against
1193
+ const rangeObj = semver.validRange(range);
1194
+ if (!rangeObj) return false;
1195
+ // For caret ranges like "^4.4", we want more strict checking than semver's default
1196
+ if (range.startsWith('^')) {
1197
+ const rangeVersion = range.substring(1); // Remove the ^
1198
+ // Try to parse as a complete version first
1199
+ let parsedRange = semver.parse(rangeVersion);
1200
+ // If that fails, try to coerce it (handles cases like "4.4" -> "4.4.0")
1201
+ if (!parsedRange) {
1202
+ const coercedRange = semver.coerce(rangeVersion);
1203
+ if (coercedRange) {
1204
+ parsedRange = coercedRange;
1205
+ } else {
1206
+ return false;
1207
+ }
1208
+ }
1209
+ // For prerelease versions, check if the base version (without prerelease)
1210
+ // matches the major.minor from the range
1211
+ if (parsedVersion.prerelease.length > 0) {
1212
+ return parsedVersion.major === parsedRange.major && parsedVersion.minor === parsedRange.minor;
1213
+ }
1214
+ // For regular versions with caret ranges, be strict about minor version
1215
+ // ^4.4 should only accept 4.4.x, not 4.5.x
1216
+ return parsedVersion.major === parsedRange.major && parsedVersion.minor === parsedRange.minor;
1217
+ }
1218
+ // For other range types (exact, tilde, etc.), use standard semver checking
1219
+ if (parsedVersion.prerelease.length > 0) {
1220
+ const baseVersion = `${parsedVersion.major}.${parsedVersion.minor}.${parsedVersion.patch}`;
1221
+ return semver.satisfies(baseVersion, range);
1222
+ }
1223
+ return semver.satisfies(version, range);
1224
+ } catch {
1225
+ // If semver parsing fails, assume incompatible
1226
+ return false;
1227
+ }
1228
+ };
1229
+ /**
1230
+ * Checks for npm link problems (version mismatches) in a package directory
1231
+ * Returns a set of dependency names that have link problems
1232
+ *
1233
+ * @deprecated Use getLinkCompatibilityProblems instead for better prerelease version handling
1234
+ */ const getLinkProblems = async (packageDir)=>{
1235
+ const execPromise = util.promisify(exec);
1236
+ try {
1237
+ const { stdout } = await execPromise('npm ls --link --json', {
1238
+ cwd: packageDir
1239
+ });
1240
+ const result = safeJsonParse(stdout, 'npm ls troubleshoot output');
1241
+ const problemDependencies = new Set();
1242
+ // Check if there are any problems reported
1243
+ if (result.problems && Array.isArray(result.problems)) {
1244
+ // Parse problems array to extract dependency names
1245
+ for (const problem of result.problems){
1246
+ if (typeof problem === 'string' && problem.includes('invalid:')) {
1247
+ // Extract package name from problem string like "invalid: @fjell/eslint-config@1.1.20-dev.0 ..."
1248
+ // Handle both scoped (@scope/name) and unscoped (name) packages
1249
+ const match = problem.match(/invalid:\s+(@[^/]+\/[^@\s]+|[^@\s]+)@/);
1250
+ if (match) {
1251
+ problemDependencies.add(match[1]);
1252
+ }
1253
+ }
1254
+ }
1255
+ }
1256
+ // Also check individual dependencies for problems
1257
+ if (result.dependencies && typeof result.dependencies === 'object') {
1258
+ for (const [depName, depInfo] of Object.entries(result.dependencies)){
1259
+ if (depInfo && typeof depInfo === 'object') {
1260
+ const dep = depInfo;
1261
+ // Check if this dependency has problems or is marked as invalid
1262
+ if (dep.problems && Array.isArray(dep.problems) && dep.problems.length > 0 || dep.invalid) {
1263
+ problemDependencies.add(depName);
1264
+ }
1265
+ }
1266
+ }
1267
+ }
1268
+ return problemDependencies;
1269
+ } catch (error) {
1270
+ // npm ls --link often exits with non-zero code when there are problems
1271
+ // but still provides valid JSON in stdout
1272
+ if (error.stdout) {
1273
+ try {
1274
+ const result = safeJsonParse(error.stdout, 'npm ls troubleshoot error output');
1275
+ const problemDependencies = new Set();
1276
+ // Check if there are any problems reported
1277
+ if (result.problems && Array.isArray(result.problems)) {
1278
+ for (const problem of result.problems){
1279
+ if (typeof problem === 'string' && problem.includes('invalid:')) {
1280
+ const match = problem.match(/invalid:\s+(@[^/]+\/[^@\s]+|[^@\s]+)@/);
1281
+ if (match) {
1282
+ problemDependencies.add(match[1]);
1283
+ }
1284
+ }
1285
+ }
1286
+ }
1287
+ // Also check individual dependencies for problems
1288
+ if (result.dependencies && typeof result.dependencies === 'object') {
1289
+ for (const [depName, depInfo] of Object.entries(result.dependencies)){
1290
+ if (depInfo && typeof depInfo === 'object') {
1291
+ const dep = depInfo;
1292
+ if (dep.problems && Array.isArray(dep.problems) && dep.problems.length > 0 || dep.invalid) {
1293
+ problemDependencies.add(depName);
1294
+ }
1295
+ }
1296
+ }
1297
+ }
1298
+ return problemDependencies;
1299
+ } catch {
1300
+ // If JSON parsing fails, return empty set
1301
+ return new Set();
1302
+ }
1303
+ }
1304
+ return new Set();
1305
+ }
1306
+ };
1307
+ /**
1308
+ * Checks if a package directory is npm linked (has a global symlink)
1309
+ */ const isNpmLinked = async (packageDir)=>{
1310
+ const logger = getLogger();
1311
+ try {
1312
+ // Read package.json to get the package name
1313
+ const packageJsonPath = path.join(packageDir, 'package.json');
1314
+ try {
1315
+ await fs.access(packageJsonPath);
1316
+ } catch {
1317
+ // No package.json found
1318
+ return false;
1319
+ }
1320
+ const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');
1321
+ const packageJson = safeJsonParse(packageJsonContent, packageJsonPath);
1322
+ const packageName = packageJson.name;
1323
+ if (!packageName) {
1324
+ return false;
1325
+ }
1326
+ // Check if the package is globally linked by running npm ls -g --depth=0
1327
+ try {
1328
+ const { stdout } = await runSecure('npm', [
1329
+ 'ls',
1330
+ '-g',
1331
+ '--depth=0',
1332
+ '--json'
1333
+ ]);
1334
+ const globalPackages = safeJsonParse(stdout, 'npm ls global depth check output');
1335
+ // Check if our package is in the global dependencies
1336
+ if (globalPackages.dependencies && globalPackages.dependencies[packageName]) {
1337
+ // Verify the symlink actually points to our directory
1338
+ const globalPath = globalPackages.dependencies[packageName].resolved;
1339
+ if (globalPath && globalPath.startsWith('file:')) {
1340
+ const linkedPath = globalPath.replace('file:', '');
1341
+ const realPackageDir = await fs.realpath(packageDir);
1342
+ const realLinkedPath = await fs.realpath(linkedPath);
1343
+ return realPackageDir === realLinkedPath;
1344
+ }
1345
+ }
1346
+ } catch (error) {
1347
+ // If npm ls fails, try alternative approach
1348
+ logger.debug(`npm ls failed for ${packageName}, trying alternative check: ${error}`);
1349
+ // Alternative: check if there's a symlink in npm's global node_modules
1350
+ try {
1351
+ const { stdout: npmPrefix } = await run('npm prefix -g');
1352
+ const globalNodeModules = path.join(npmPrefix.trim(), 'node_modules', packageName);
1353
+ const stat = await fs.lstat(globalNodeModules);
1354
+ if (stat.isSymbolicLink()) {
1355
+ const realGlobalPath = await fs.realpath(globalNodeModules);
1356
+ const realPackageDir = await fs.realpath(packageDir);
1357
+ return realGlobalPath === realPackageDir;
1358
+ }
1359
+ } catch {
1360
+ // If all else fails, assume not linked
1361
+ return false;
1362
+ }
1363
+ }
1364
+ return false;
1365
+ } catch (error) {
1366
+ logger.debug(`Error checking npm link status for ${packageDir}: ${error}`);
1367
+ return false;
1368
+ }
1369
+ };
1370
+
1371
+ export { ConsoleLogger, escapeShellArg, findPreviousReleaseTag, getBranchCommitSha, getCurrentBranch, getCurrentVersion, getDefaultFromRef, getGitStatusSummary, getGloballyLinkedPackages, getLinkCompatibilityProblems, getLinkProblems, getLinkedDependencies, getLogger, getRemoteDefaultBranch, isBranchInSyncWithRemote, isNpmLinked, isValidGitRef, localBranchExists, remoteBranchExists, run, runSecure, runSecureWithDryRunSupport, runSecureWithInheritedStdio, runWithDryRunSupport, runWithInheritedStdio, safeJsonParse, safeSyncBranchWithRemote, setLogger, validateFilePath, validateGitRef, validateHasProperty, validatePackageJson, validateString };
5
1372
  //# sourceMappingURL=index.js.map