@reelout/core 0.5.3 → 0.6.0

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.
@@ -1,239 +1,19 @@
1
- import semver from "semver";
2
- import { colors } from "consola/utils";
3
- import { Writable } from "node:stream";
4
1
  import { spawn } from "node:child_process";
5
2
  import prettier from "prettier";
6
3
  import { minimatch } from "minimatch";
4
+ import { colors } from "consola/utils";
7
5
  import fs, { readFile } from "node:fs/promises";
8
6
  import path from "node:path";
9
7
  import { CommitParser } from "conventional-commits-parser";
10
8
  import { AsyncLocalStorage } from "node:async_hooks";
11
9
  import GitHost from "hosted-git-info";
10
+ import { Writable } from "node:stream";
11
+ import semver from "semver";
12
12
  import { fromMarkdown } from "mdast-util-from-markdown";
13
13
  import assert from "node:assert";
14
14
  import createPreset from "conventional-changelog-conventionalcommits";
15
15
  import { writeChangelogString } from "conventional-changelog-writer";
16
16
  import { toMarkdown } from "mdast-util-to-markdown";
17
- // src/workflow/versioning/extractVersionQualifier.ts
18
- /**
19
- * Extract the version qualifier string from a parsed `SemVer` instance.
20
- *
21
- * Strips the trailing numeric counter from the `prerelease` components if
22
- * present. Joins any remaining prerelease identifiers with a dot separator.
23
- *
24
- * @param version Parsed `SemVer` instance or nullish value to inspect
25
- * @returns The extracted qualifier string or `undefined` if no prerelease exists
26
- */
27
- function extractVersionQualifier(version) {
28
- if (version != null && version.prerelease.length > 0) {
29
- const prerelease = [...version.prerelease];
30
- if (typeof prerelease.at(-1) === "number") prerelease.pop();
31
- return prerelease.join(".");
32
- } else return;
33
- }
34
- // src/workflow/versioning/bumpVersion.ts
35
- /**
36
- * Bump a semantic version string based on release and transition rules.
37
- *
38
- * Parses the target version and determines the next version string using the
39
- * specified release type, prerelease identifier, and transition mode. Adjusts
40
- * prerelease types when continuing an existing qualifier and returns `null` when
41
- * `options.release` is omitted or if transition conditions fail.
42
- *
43
- * @param options Version bump configuration including release type, identifier, and transition rules
44
- * @returns The bumped semantic version string, or `null` if no bump occurs
45
- * @throws If `options.version` is not a valid semantic version
46
- */
47
- function bumpVersion(options) {
48
- const { version } = options;
49
- const parsed = semver.parse(version);
50
- if (!parsed) throw new Error(`Version "${version}" is not a valid semantic version.`);
51
- if (!options.release) return null;
52
- if (parsed.prerelease.length > 0) {
53
- if (options.transition === "advance" && options.identifier == null) return null;
54
- } else if (options.transition === "continue") return null;
55
- let release = options.release;
56
- let identifier;
57
- if (typeof options.identifier === "string") {
58
- release = `pre${options.release}`;
59
- identifier = options.identifier;
60
- const parsedIdentifier = extractVersionQualifier(parsed);
61
- const transition = options.transition ?? (parsedIdentifier && identifier === "" ? "advance" : "continue");
62
- if (typeof parsedIdentifier === "string" && transition === "continue") {
63
- if (release === "premajor" && parsed.minor === 0 && parsed.patch === 0 || release === "preminor" && parsed.patch === 0 || release === "prepatch") release = "prerelease";
64
- }
65
- }
66
- return semver.inc(parsed, release, { loose: false }, identifier, "0");
67
- }
68
- // src/workflow/versioning/determineReleaseType.ts
69
- /**
70
- * Determine the release type for a single commit.
71
- *
72
- * Returns `'minor'` for a commit marked as a breaking change while the
73
- * supplied `version` is zero-major (`0.y.z`), and `'major'` otherwise, since
74
- * SemVer treats `0.y.z` as initial development where breaking changes do not
75
- * require a new major version. Otherwise, routes the commit through the
76
- * custom `classifier` and ensures the resolved value is a valid semantic
77
- * versioning release type.
78
- *
79
- * @param classifier Function mapping commits to release types
80
- * @param commit Parsed commit to evaluate
81
- * @param version Current package version used to adjust zero-major breaking releases
82
- * @returns `ReleaseType` string, or `null` when no matching rule applies
83
- */
84
- function determineReleaseType(classifier, commit, version) {
85
- if (commit.notes.length > 0) return semver.parse(version)?.major === 0 ? "minor" : "major";
86
- const type = classifier(commit);
87
- switch (type) {
88
- case "major":
89
- case "minor":
90
- case "patch": return type;
91
- }
92
- return null;
93
- }
94
- // src/workflow/versioning/pickPriorityReleaseType.ts
95
- /**
96
- * Determine the highest-priority release type between two candidates.
97
- *
98
- * Compares release types by precedence order: `major` > `minor` > `patch`.
99
- * Returns the higher-precedence type, or `null` if neither applies.
100
- *
101
- * @param curr Current accumulated release type
102
- * @param next Candidate release type to consider
103
- * @returns Highest-precedence `ReleaseType`, or `null` if neither applies
104
- */
105
- function pickPriorityReleaseType(curr, next) {
106
- for (const type of [
107
- "major",
108
- "minor",
109
- "patch"
110
- ]) if (curr === type || next === type) return type;
111
- return null;
112
- }
113
- // src/workflow/versioning/deriveReleaseType.ts
114
- /**
115
- * Derive the combined release type from a release plan.
116
- *
117
- * Processes the plan's commits sequentially, accumulating the
118
- * highest-precedence release type found by evaluating each individual commit
119
- * and comparing it against the current maximum via `pickPriorityReleaseType`.
120
- * Breaking commits resolve to `minor` while the plan's package version is
121
- * zero-major (`0.y.z`).
122
- *
123
- * @param classifier Function mapping commits to release types
124
- * @param plan Release plan carrying the commit history and package version
125
- * @returns `ReleaseType` string, or `null` when no matching rule applies
126
- */
127
- function deriveReleaseType(classifier, plan) {
128
- let releaseType = null;
129
- for (const commit of plan.history) releaseType = pickPriorityReleaseType(releaseType, determineReleaseType(classifier, commit, plan.package.version));
130
- return releaseType;
131
- }
132
- // src/workflow/versioning/isSameReleaseCycle.ts
133
- /**
134
- * Determine whether two semantic version strings or objects belong to the same release cycle.
135
- *
136
- * Compares the main version components of `currentVersion` and `nextVersion` to
137
- * determine equality. Treats a transition from a non-zero `0.x` version to
138
- * `1.0.0` as part of the same release cycle. Returns `false` if either input
139
- * cannot be parsed.
140
- *
141
- * @param currentVersion Starting version string, `semver.SemVer` instance, or nullish value
142
- * @param nextVersion Target version string, `semver.SemVer` instance, or nullish value
143
- * @returns `true` if both versions belong to the same release cycle, `false` otherwise
144
- */
145
- function isSameReleaseCycle(currentVersion, nextVersion) {
146
- const current = semver.parse(currentVersion);
147
- const next = semver.parse(nextVersion);
148
- if (!current || !next) return false;
149
- if (current.compareMain(next) === 0) return true;
150
- return current.major === 0 && (current.minor > 0 || current.patch > 0) && next.major === 1 && next.minor === 0 && next.patch === 0;
151
- }
152
- // src/workflow/versioning/isStableVersion.ts
153
- /**
154
- * Determine whether a version string represents a stable SemVer release.
155
- *
156
- * A version is considered stable when:
157
- * - It is a valid SemVer string.
158
- * - Its major version is greater than 0 (not 0.x.x).
159
- * - It contains no prerelease identifiers (no `-alpha`, `-beta`, `-rc`, etc.).
160
- *
161
- * Build metadata (the `+` suffix) does not affect stability.
162
- *
163
- * @param version Semantic version string to check
164
- * @returns `true` if `version` is a stable SemVer; otherwise `false`
165
- * @throws If `version` is not a valid SemVer string
166
- */
167
- function isStableVersion(version) {
168
- const parsed = semver.parse(version);
169
- if (!parsed) throw new Error(`The version "${colors.bold(version)}" is not a valid SemVer.`);
170
- return parsed.major > 0 && parsed.prerelease.length === 0;
171
- }
172
- // src/config/const.ts
173
- var ALL_FILES = "**/*";
174
- var DEFAULT_CHANGELOG_FILE = "CHANGELOG.md";
175
- var GIT_TRAILER_RELEASE_AGENT = "Release-Agent";
176
- /**
177
- * 1. Primitive Building Blocks
178
- *
179
- * Base regular expression patterns for wildcards, alphanumeric strings with hyphens,
180
- * and standard non-negative integers.
181
- */
182
- var WILDCARD = "\\*";
183
- var ALPHANUM_DASH = "[0-9a-zA-Z-]+";
184
- var NUMERIC_IDENTIFIER = "0|[1-9]\\d*";
185
- /**
186
- * 2. Package Name & Prefix Constructs
187
- *
188
- * Matches package name prefixes (unscoped or scoped) or a simple `v` prefix.
189
- *
190
- * Capture Groups:
191
- * - Group 1: Package name (e.g., `my-package` or `@scope/my-package`)
192
- */
193
- var PKG_NAME_PART = `(?:${WILDCARD}|${ALPHANUM_DASH})`;
194
- var OPTIONAL_VERSION_PREFIX = `(?:v|${`(${PKG_NAME_PART}|@${PKG_NAME_PART}\\/${PKG_NAME_PART})`}@)`;
195
- /**
196
- * 3. Core SemVer Components
197
- *
198
- * Matches standard `MAJOR.MINOR.PATCH` versions or wildcard variants (e.g., `1.0.0`, `*.*.*`).
199
- *
200
- * Capture Groups:
201
- * - Group 3: Major version
202
- * - Group 4: Minor version
203
- * - Group 5: Patch version
204
- */
205
- var CAPTURED_VERSION_DIGIT = `(${WILDCARD}|${NUMERIC_IDENTIFIER})`;
206
- var SEMVER_CORE = `${CAPTURED_VERSION_DIGIT}\\.${CAPTURED_VERSION_DIGIT}\\.${CAPTURED_VERSION_DIGIT}`;
207
- var PRERELEASE_IDENTIFIER = `(?:${WILDCARD}|${NUMERIC_IDENTIFIER}|(\\d*[a-zA-Z-][0-9a-zA-Z-]*))`;
208
- var FULL_SEMVER_PATTERN = `${OPTIONAL_VERSION_PREFIX}?${`(${SEMVER_CORE}${`(?:-(${PRERELEASE_IDENTIFIER}(?:\\.${PRERELEASE_IDENTIFIER})*))`}?${`(?:\\+(${ALPHANUM_DASH}(?:\\.${ALPHANUM_DASH})*))`}?)`}`;
209
- /**
210
- * Regular expression to match and capture Semantic Versioning (SemVer) strings,
211
- * including optional package prefixes (e.g., `@scope/pkg@`) and `v` prefixes.
212
- *
213
- * @example
214
- * ```ts
215
- * SEMVER_REGEX.test('1.0.0') // true
216
- * SEMVER_REGEX.test('v1.2.3-beta.1+sha.1234') // true
217
- * SEMVER_REGEX.test('@scope/package@1.0.0') // true
218
- * ```
219
- *
220
- * @see {@link https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string SemVer Specification}
221
- */
222
- var SEMVER_REGEX = new RegExp(FULL_SEMVER_PATTERN);
223
- var DEV_NULL = new Writable({
224
- /* istanbul ignore next */
225
- write(_chunk, _encoding, callback) {
226
- callback();
227
- } });
228
- var RELEASE_HOOK_NAMES = [
229
- "configure",
230
- "discover",
231
- "analyze",
232
- "build",
233
- "write",
234
- "publish",
235
- "finalize"
236
- ];
237
17
  // src/util/buildTrailerPattern.ts
238
18
  /**
239
19
  * Build a regular expression to match trailer lines using custom markers.
@@ -540,18 +320,17 @@ function isClass(func) {
540
320
  /**
541
321
  * Determine whether a target string matches glob patterns.
542
322
  *
543
- * Matches positive and negative glob patterns using dotfile support. Automatically
544
- * expands a single negative pattern by prepending a global wildcard match.
323
+ * Matches positive and negative glob patterns using dotfile support.
324
+ * Negation-only patterns are expanded with a catch-all pattern so they match
325
+ * every named target the patterns do not exclude.
545
326
  *
546
327
  * @param target Target string to evaluate against glob patterns
547
328
  * @param patterns Single glob pattern or list of patterns to evaluate
548
329
  * @returns True if target matches positive patterns and satisfies negative patterns
549
330
  */
550
331
  function isMatch(target, patterns) {
551
- if (typeof patterns === "string") {
552
- if (patterns.startsWith("!")) patterns = ["**/*", patterns];
553
- else patterns = [patterns];
554
- }
332
+ if (typeof patterns === "string") patterns = [patterns];
333
+ if (patterns.length > 0 && patterns.every((pattern) => pattern.startsWith("!"))) patterns = ["**/*", ...patterns];
555
334
  const positives = [];
556
335
  const negatives = [];
557
336
  for (const pattern of patterns) if (pattern.startsWith("!")) negatives.push(pattern);
@@ -601,1256 +380,1532 @@ async function writeJson(filePath, payload) {
601
380
  await fs.mkdir(path.dirname(filePath), { recursive: true });
602
381
  await fs.writeFile(filePath, content);
603
382
  }
604
- // src/config/createPlugin.ts
383
+ // src/git/branch/getCurrentGitBranch.ts
605
384
  /**
606
- * Instantiate or invoke a plugin factory to produce a release plugin instance.
385
+ * Get the current Git branch name.
607
386
  *
608
- * Accepts class constructors, factory functions, tuple configurations, or
609
- * existing plugin objects. Instantiates classes using `new` or invokes factory
610
- * functions with options, validating that the resulting object satisfies the
611
- * plugin structure.
387
+ * Uses `execGit` to run `git symbolic-ref -q --short HEAD` in the provided
388
+ * working directory and trims the result. Returns an empty string when the
389
+ * repository is in a detached HEAD state.
612
390
  *
613
- * @param plugin A plugin constructor, factory function, tuple, or object
614
- * @returns A validated release plugin instance or null
391
+ * @param cwd The working directory to run the Git command in
392
+ * @returns The current branch name as a string
615
393
  */
616
- async function createPlugin(plugin) {
617
- let options;
618
- if (Array.isArray(plugin)) [plugin, options] = plugin;
619
- if (typeof plugin === "function") plugin = isClass(plugin) ? new plugin(options) : await plugin(options);
620
- if (plugin != null && typeof plugin === "object" && Object.hasOwn(plugin, "name") && typeof plugin.name === "string") return plugin;
621
- return null;
394
+ async function getCurrentGitBranch(cwd) {
395
+ return (await execGit(cwd, [
396
+ "symbolic-ref",
397
+ "-q",
398
+ "--short",
399
+ "HEAD"
400
+ ])).trim();
622
401
  }
623
- // src/config/findReleaseRule.ts
402
+ // src/git/commit/createGitCommit.ts
624
403
  /**
625
- * Find the first release rule matching a release reference.
404
+ * Stage all changes and create a git commit with the specified message.
626
405
  *
627
- * Matches rules sequentially against the reference type and pattern.
406
+ * Validates the commit message and working directory status before staging
407
+ * all changes and executing the commit command.
628
408
  *
629
- * @param ref Release reference object
630
- * @param rules Array of release rules to match against
631
- * @returns The first matching release rule or `undefined`
409
+ * @param cwd The target directory path for executing git commands
410
+ * @param message The message to associate with the commit
411
+ * @returns A promise that resolves when the operation completes
632
412
  */
633
- function findReleaseRule(ref, rules) {
634
- return rules.find((rule) => {
635
- return (rule.type == null || rule.type === ref.type) && isMatch(ref.name, rule.pattern);
636
- });
413
+ async function createGitCommit(cwd, message) {
414
+ if (!message) return;
415
+ await execGit(cwd, ["add", "."]);
416
+ if (!(await execGit(cwd, ["status", "--porcelain"])).trim()) return;
417
+ await execGit(cwd, [
418
+ "commit",
419
+ "--message",
420
+ message
421
+ ]);
637
422
  }
638
- // src/config/isSemVer.ts
423
+ // src/git/commit/extractMentions.ts
424
+ var ALPHANUMERIC = "[a-zA-Z0-9]";
425
+ var SEPARATOR = "[-_]";
426
+ var USERNAME = `${ALPHANUMERIC}+(?:${SEPARATOR}+${ALPHANUMERIC}+)*`;
427
+ var EMAIL_LOCAL = "[a-zA-Z0-9._%+-]";
428
+ var DOMAIN_SUFFIX = "[a-zA-Z0-9.-]*\\.[a-zA-Z]{2,}";
429
+ var SCOPED_PACKAGE_SPEC_SUFFIX = `/${USERNAME}@[0-9]+\\.[0-9]+\\.[0-9]+`;
639
430
  /**
640
- * Determine whether a value is a valid Semantic Versioning string.
431
+ * Extract unique mention handles from the input text string.
641
432
  *
642
- * Rejects non-string values, leading or trailing whitespace, and leading `v`
643
- * prefixes. Validates the candidate string using `semver.parse`.
433
+ * Evaluates `text` against boundary rules to isolate valid handles while
434
+ * excluding email addresses, domain names, and scoped package specs, then
435
+ * de-duplicates the resulting handles.
644
436
  *
645
- * @param version Candidate value to evaluate for SemVer compliance
646
- * @returns `true` if `version` is a valid SemVer string, or `false` otherwise
437
+ * @param text The input string to parse for mentions
438
+ * @returns An array of unique mention handles
647
439
  */
648
- function isSemVer(version) {
649
- if (typeof version !== "string") return false;
650
- if (version !== version.trim()) return false;
651
- if (version.startsWith("v")) return false;
652
- return semver.parse(version) != null;
440
+ function extractMentions(text) {
441
+ if (!text) return [];
442
+ const regex = new RegExp(`(?<!${EMAIL_LOCAL})@(${USERNAME})\\b(?!${SEPARATOR}|${DOMAIN_SUFFIX}|${SCOPED_PACKAGE_SPEC_SUFFIX})`, "g");
443
+ const matches = text.matchAll(regex);
444
+ const mentions = new Set(matches.map((match) => match[1]));
445
+ return Array.from(mentions);
653
446
  }
654
- // src/config/isSemVerGitTag.ts
447
+ // src/cache/TTLCache.ts
655
448
  /**
656
- * Determine whether a tag string is a valid SemVer-style Git tag.
449
+ * A simple time-to-live cache that automatically evicts entries after a TTL.
657
450
  *
658
- * Anchors `SEMVER_REGEX.source` for full-string matching and applies the
659
- * repository's Git-tag acceptance rules.
451
+ * - Entries are removed automatically when their TTL expires.
452
+ * - Reading an entry resets its TTL to the original value.
453
+ * - Setting an existing key clears its previous timer and resets the TTL.
660
454
  *
661
- * @param tag Tag string to validate
662
- * @returns `true` if `tag` is accepted as a SemVer-style Git tag; otherwise `false`
455
+ * @template K Type of cache keys
456
+ * @template V Type of cache values
663
457
  */
664
- function isSemVerGitTag(tag) {
665
- const match = new RegExp(`^${SEMVER_REGEX.source}$`).exec(tag);
666
- if (!match) return false;
667
- const isScopedPackage = Boolean(match[1]);
668
- const hasVersionPrefix = tag.startsWith("v");
669
- return isScopedPackage || hasVersionPrefix;
670
- }
671
- // src/config/sanitizePrereleaseLabel.ts
458
+ var TTLCache = class {
459
+ constructor() {
460
+ this.cache = /* @__PURE__ */ new Map();
461
+ }
462
+ /**
463
+ * Store a value under `key` for `ttl` milliseconds.
464
+ *
465
+ * If the key already exists its previous timer is cleared and the TTL is reset.
466
+ *
467
+ * @param key Cache key
468
+ * @param value Value to store
469
+ * @param ttl Time to live in milliseconds (default: 60_000)
470
+ */
471
+ set(key, value, ttl = 6e4) {
472
+ const ref = this.cache.get(key);
473
+ if (ref) clearTimeout(ref.timer);
474
+ const timer = setTimeout(() => {
475
+ this.cache.delete(key);
476
+ }, ttl).unref();
477
+ this.cache.set(key, {
478
+ value,
479
+ timer,
480
+ ttl
481
+ });
482
+ }
483
+ /**
484
+ * Retrieve the value for `key`, or `undefined` if not present.
485
+ *
486
+ * Reading an entry resets its TTL to the original `ttl` provided when it was set.
487
+ *
488
+ * @param key Cache key
489
+ * @returns The stored value or `undefined` if not present
490
+ */
491
+ get(key) {
492
+ const ref = this.cache.get(key);
493
+ if (!ref) return void 0;
494
+ this.set(key, ref.value, ref.ttl);
495
+ return ref.value;
496
+ }
497
+ /**
498
+ * Check whether `key` exists in the cache.
499
+ *
500
+ * @param key Cache key
501
+ * @returns `true` if present; otherwise `false`
502
+ */
503
+ has(key) {
504
+ return this.cache.has(key);
505
+ }
506
+ /**
507
+ * Remove `key` from the cache and clear its eviction timer.
508
+ *
509
+ * @param key Cache key
510
+ * @returns `true` if the key was present and removed; otherwise `false`
511
+ */
512
+ delete(key) {
513
+ const ref = this.cache.get(key);
514
+ if (!ref) return false;
515
+ clearTimeout(ref.timer);
516
+ return this.cache.delete(key);
517
+ }
518
+ /**
519
+ * Clear all entries and their timers.
520
+ */
521
+ clear() {
522
+ for (const { timer } of this.cache.values()) clearTimeout(timer);
523
+ this.cache.clear();
524
+ }
525
+ };
526
+ // src/git/commit/parseGitCommit.ts
527
+ var BREAKING_HEADER_REGEX = /^([\w-]+)(?:\(([^)]+)\))?!: (.*)$/;
528
+ var BREAKING_MARKERS = ["BREAKING CHANGE", "BREAKING-CHANGE"];
672
529
  /**
673
- * Sanitize a string into a safe, SemVer-compliant prerelease label.
530
+ * Parse a git log entry into a structured commit object.
674
531
  *
675
- * Replaces sequences of non-alphanumeric characters with a single hyphen and
676
- * removes leading or trailing hyphens.
532
+ * Combines the commit subject and body, extracts conventional commit metadata
533
+ * using custom trailer markers and breaking header patterns, and normalizes
534
+ * dates to ISO format strings.
677
535
  *
678
- * @param label Raw string to sanitize
679
- * @returns Safe SemVer prerelease label
536
+ * @param entry The raw git log entry to parse
537
+ * @param markers Optional array of custom trailer marker strings
538
+ * @returns A structured commit object containing parsed details, notes, and mentions
680
539
  */
681
- function sanitizePrereleaseLabel(label) {
682
- return label.replace(/[^a-zA-Z0-9]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
540
+ async function parseGitCommit(entry, markers = []) {
541
+ const message = [entry.subject, entry.body].filter(Boolean).join("\n\n");
542
+ const commit = new CommitParser({
543
+ breakingHeaderPattern: BREAKING_HEADER_REGEX,
544
+ noteKeywords: [],
545
+ notesPattern: () => buildTrailerPattern(BREAKING_MARKERS.concat(markers))
546
+ }).parse(message);
547
+ const notes = [];
548
+ const trailers = [];
549
+ for (const note of commit.notes) {
550
+ if (BREAKING_MARKERS.includes(note.title.toUpperCase())) notes.push(note);
551
+ trailers.push({
552
+ key: note.title,
553
+ value: note.text
554
+ });
555
+ }
556
+ if (notes.length === 0 && BREAKING_HEADER_REGEX.test(commit.header)) {
557
+ const note = {
558
+ title: "BREAKING CHANGE",
559
+ text: commit.subject
560
+ };
561
+ notes.push(note);
562
+ trailers.push({
563
+ key: note.title,
564
+ value: note.text
565
+ });
566
+ }
567
+ const mentions = extractMentions(message);
568
+ return {
569
+ ...commit,
570
+ hash: entry.hash,
571
+ parent: entry.parent,
572
+ authorDate: new Date(entry.authorDate).toISOString(),
573
+ committerDate: new Date(entry.committerDate).toISOString(),
574
+ type: commit.type?.toLowerCase() || null,
575
+ scope: commit.scope || null,
576
+ subject: commit.subject || null,
577
+ header: commit.header,
578
+ body: commit.body,
579
+ footer: commit.footer,
580
+ notes,
581
+ mentions,
582
+ trailers,
583
+ files: entry.files
584
+ };
683
585
  }
684
- // src/config/resolveReleaseChannel.ts
586
+ // src/git/commit/parseGitPrettyFormat.ts
685
587
  /**
686
- * Resolve the release channel for a release context.
687
- *
688
- * Uses the release rule when `channel` is `boolean` or omitted. Sanitizes the
689
- * reference name when enabling default channel resolution and interpolates
690
- * `templateParams` into the result.
691
- *
692
- * @param options Options for resolving the release channel
693
- * @returns Resolved release channel string or `undefined`
588
+ * Field separator used in the git pretty format to produce a single-line
589
+ *, machine-parseable record.
694
590
  */
695
- function resolveReleaseChannel(options) {
696
- const { ref, rule, templateParams } = options;
697
- let { channel } = options;
698
- let resolved;
699
- if (channel === true || channel == null) channel = rule?.releaseChannel ?? channel;
700
- if (typeof channel === "string") resolved = channel;
701
- else if (channel) resolved = sanitizePrereleaseLabel(ref.name);
702
- if (typeof resolved === "string") resolved = interpolate(resolved, templateParams);
703
- return resolved;
704
- }
705
- // src/config/resolveVersionQualifier.ts
591
+ var GIT_PRETTY_FIELD_SEPARATOR = "";
706
592
  /**
707
- * Resolve the version qualifier for a release context.
708
- *
709
- * Uses the release rule when `qualifier` is `boolean` or omitted. Interpolates
710
- * `templateParams` into `qualifier` and validates that the result forms a
711
- * valid SemVer prerelease identifier.
712
- *
713
- * @param options Options for resolving the version qualifier
714
- * @returns Resolved version qualifier string or `undefined`
715
- * @throws If the resolved string is not a valid SemVer prerelease identifier
593
+ * Pretty format string passed to `git log --pretty=format:`. Produces seven
594
+ * fields separated by `GIT_PRETTY_FIELD_SEPARATOR`:
595
+ * hash, parents, author date, committer date, subject, body, files.
716
596
  */
717
- function resolveVersionQualifier(options) {
718
- const { rule, templateParams } = options;
719
- let { qualifier } = options;
720
- let resolved;
721
- if (qualifier === true || qualifier == null) qualifier = rule?.versionQualifier ?? qualifier;
722
- if (typeof qualifier === "string") resolved = qualifier;
723
- else if (qualifier) resolved = "";
724
- if (typeof resolved === "string") resolved = interpolate(resolved, templateParams);
725
- if (resolved && !isSemVer(`1.0.0-${resolved}.1`)) throw new Error(`The resolved version qualifier "${resolved}" is not a valid SemVer prerelease identifier.`);
726
- return resolved;
727
- }
728
- // src/workflow/analysis/isCommitForPackage.ts
729
- /**
730
- * Test whether a commit modifies files in a package.
597
+ var GIT_PRETTY_FORMAT = [
598
+ "%H",
599
+ "%P",
600
+ "%aI",
601
+ "%cI",
602
+ "%s",
603
+ "%b",
604
+ ""
605
+ ].join("");
606
+ /**
607
+ * Parse a single line produced by `git log --pretty=format:${GIT_PRETTY_FORMAT}`.
731
608
  *
732
- * @param pkg Package with an explicit file pattern or base directory
733
- * @param commit Parsed commit containing changed file paths
734
- * @returns `true` if any changed file matches the package pattern
609
+ * The input is expected to contain seven fields separated by
610
+ * `GIT_PRETTY_FIELD_SEPARATOR`:
611
+ * 1. `hash` (commit hash)
612
+ * 2. `parent` (space-separated parent hashes)
613
+ * 3. `authorDate` (ISO 8601)
614
+ * 4. `committerDate` (ISO 8601)
615
+ * 5. `subject`
616
+ * 6. `body`
617
+ * 7. `files` (newline-separated list)
618
+ *
619
+ * The function trims fields, converts parent hashes into an array, normalizes
620
+ * dates to ISO strings, and splits `files` into an array. Missing optional
621
+ * fields are normalized to sensible defaults.
622
+ *
623
+ * @param raw Raw pretty-format string produced by git
624
+ * @returns Parsed `GitLogEntry` with `hash`, `parent`, `authorDate`, `committerDate`, `subject`, `body`, and `files`
625
+ * @throws If required fields (hash, authorDate, committerDate, subject) are missing or malformed
735
626
  */
736
- function isCommitForPackage(pkg, commit) {
737
- return commit.files.some((file) => {
738
- const { location } = pkg;
739
- return isMatch(file, pkg.files || path.join(location, "**/*"));
740
- });
627
+ function parseGitPrettyFormat(raw) {
628
+ let [hash, parentHashes, authorDate, committerDate, subject, body, files] = raw.split("");
629
+ hash = hash?.trim();
630
+ parentHashes = parentHashes?.trim();
631
+ authorDate = authorDate?.trim();
632
+ committerDate = committerDate?.trim();
633
+ subject = subject?.trim();
634
+ body = body?.trim();
635
+ files = files?.trim();
636
+ if (!hash || !authorDate || !committerDate || typeof subject !== "string") throw new Error(`The input "${colors.bold(raw)}" is not in the expected pretty format.`);
637
+ return {
638
+ hash,
639
+ parent: parentHashes ? parentHashes.split(/\s+/) : [],
640
+ authorDate: new Date(authorDate).toISOString(),
641
+ committerDate: new Date(committerDate).toISOString(),
642
+ subject,
643
+ body: body ?? "",
644
+ files: files ? files.split("\n") : []
645
+ };
741
646
  }
742
- // src/workflow/analysis/deriveChangeReleases.ts
647
+ // src/git/commit/getParsedGitCommit.ts
648
+ var cache = new TTLCache();
743
649
  /**
744
- * Analyze commit history to update release plans for packages.
650
+ * Retrieve and parse a git commit by its reference.
745
651
  *
746
- * Maps commit `history` across package release `plans` to associate matching
747
- * commits with their target packages. Calculates the release type for each
748
- * plan based on classified `history` and applies overrides according to the
749
- * provided `hint` or existing release priority. Downgrades breaking-change
750
- * `major` release types to `minor` while the package version is zero-major
751
- * (`0.y.z`).
652
+ * Fetches the raw git log entry for the specified `ref`, checking the local cache
653
+ * prior to parsing missing entries.
752
654
  *
753
- * @param hint Release type override hint or default preference
754
- * @param classifier Classifier function to determine commit release types
755
- * @param plans List of release plans to analyze and update
756
- * @param history Stream or iterable of git commits to process
757
- * @returns Updated release plans with updated commit histories and release types
655
+ * @param cwd Current working directory path
656
+ * @param ref Git reference to fetch
657
+ * @param markers Optional array of custom trailer marker strings
658
+ * @returns Structured commit object
758
659
  */
759
- async function deriveChangeReleases(hint, classifier, plans, history) {
760
- for await (const commit of history) plans = plans.map((plan) => {
761
- if (!isCommitForPackage(plan.package, commit)) return plan;
762
- return {
763
- ...plan,
764
- history: plan.history.concat(commit)
765
- };
766
- });
767
- return plans.map((plan) => {
768
- let { release } = plan;
769
- let releaseType = deriveReleaseType(classifier, plan);
770
- if (releaseType) switch (hint) {
771
- case "major":
772
- case "minor":
773
- case "patch":
774
- releaseType = hint;
775
- break;
776
- default: releaseType = pickPriorityReleaseType(release?.type, releaseType);
777
- }
778
- if (releaseType) release = {
779
- ...release,
780
- type: releaseType
781
- };
782
- return {
783
- ...plan,
784
- release
785
- };
786
- });
660
+ async function getParsedGitCommit(cwd, ref, markers = []) {
661
+ const entry = parseGitPrettyFormat(await execGit(cwd, [
662
+ "log",
663
+ "-1",
664
+ ref,
665
+ "--name-only",
666
+ `--pretty=format:${GIT_PRETTY_FORMAT}`
667
+ ]));
668
+ const key = `${entry.hash}:${entry.parent}:${markers}`;
669
+ const cached = cache.get(key);
670
+ if (cached) return cached;
671
+ const parsed = await parseGitCommit(entry, markers);
672
+ cache.set(key, parsed);
673
+ return parsed;
787
674
  }
788
- // src/workflow/analysis/deriveTransitionReleases.ts
675
+ // src/git/commit/getCurrentGitCommit.ts
789
676
  /**
790
- * Derive transition release types for release plans based on version qualifiers.
791
- *
792
- * Evaluates unreleased `plans` by parsing package `semver` strings and checking
793
- * prerelease tags. Compares parsed version qualifiers against
794
- * `versionQualifier` and assigns `major`, `minor`, or `patch` release types
795
- * according to `hint`. When `hint` is `patch`, every package receives an
796
- * update: stable packages are assigned a patch release even without a
797
- * `versionQualifier`, and prerelease packages (pre-major, pre-minor, and
798
- * pre-patch cycles) continue their cycle with an incremented counter,
799
- * redirect to `versionQualifier` when it differs, or release their stable
800
- * base when no `versionQualifier` is set.
677
+ * Resolve the current `HEAD` commit in the repository.
801
678
  *
802
- * @param hint Release type override hint to guide release classification
803
- * @param versionQualifier Optional qualifier string to compare against prerelease tags
804
- * @param plans List of release plans to analyze and update
805
- * @returns Updated release plans with derived transition release types
679
+ * @param cwd Repository working directory path
680
+ * @param markers Optional array of custom trailer marker strings
681
+ * @returns Parsed commit object for the current `HEAD` commit
806
682
  */
807
- function deriveTransitionReleases(hint, versionQualifier, plans) {
808
- return plans.map((plan) => {
809
- if (plan.release) return plan;
810
- const parsed = semver.parse(plan.package.version);
811
- if (!parsed) return plan;
812
- const { major, minor, patch } = parsed;
813
- const parsedVersionQualifier = extractVersionQualifier(parsed);
814
- let releaseType;
815
- let versionTransition;
816
- switch (hint) {
817
- case "major":
818
- if (parsed.prerelease.length === 0) {
819
- if (typeof versionQualifier === "string") releaseType = "major";
820
- else if (major === 0 && (minor > 0 || patch > 0)) releaseType = "major";
821
- } else if (minor === 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "major";
822
- break;
823
- case "minor":
824
- if (parsed.prerelease.length === 0) {
825
- if (typeof versionQualifier === "string") releaseType = "minor";
826
- } else if (minor > 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "minor";
827
- break;
828
- case "patch":
829
- releaseType = "patch";
830
- break;
831
- default: if (parsed.prerelease.length === 0) {
832
- if (major === 0 && (minor > 0 || patch > 0)) releaseType = "major";
833
- } else if (minor === 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "major";
834
- else if (minor > 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "minor";
835
- else if (patch > 0 && parsedVersionQualifier !== versionQualifier) releaseType = "patch";
836
- }
837
- if (parsedVersionQualifier == null || parsedVersionQualifier !== "" && versionQualifier === "") versionTransition = "advance";
838
- else versionTransition = "continue";
839
- if (!releaseType) return plan;
840
- return {
841
- ...plan,
842
- release: {
843
- type: releaseType,
844
- transition: versionTransition
845
- }
846
- };
847
- });
683
+ function getCurrentGitCommit(cwd, markers = []) {
684
+ return getParsedGitCommit(cwd, "HEAD", markers);
848
685
  }
849
- // src/workflow/analysis/promotePrereleaseVersions.ts
686
+ // src/git/history/countGitHistory.ts
850
687
  /**
851
- * Promote prerelease versions when they have no explicit release type.
688
+ * Count mainline commits reachable from a given reference.
852
689
  *
853
- * Analyzes prerelease and zero-major versions to determine an appropriate
854
- * release type for graduation:
855
- * - Prerelease versions are promoted based on their highest incremented component
856
- * (patch, minor, or major)
857
- * - Zero-major versions (0.y.z) are promoted to major
858
- * - Stable versions (1.0.0+) remain unchanged
859
- * - Plans with explicit releases are preserved as-is
690
+ * Uses `git rev-list --count --first-parent` to calculate the length of the
691
+ * primary history trunk, excluding commits introduced by side-branch merges.
860
692
  *
861
- * @param plans Release plans to analyze
862
- * @returns Plans with inferred release types for prerelease versions
693
+ * @param cwd Repository working directory
694
+ * @param ref Commit reference to count from (defaults to `HEAD`)
695
+ * @returns Number of commits along the primary branch line up to `ref`
863
696
  */
864
- async function promotePrereleaseVersions(plans) {
865
- return plans.map((plan) => {
866
- if (plan.release) return plan;
867
- if (!plan.package.tag) return plan;
868
- const parsed = semver.parse(plan.package.version);
869
- if (!parsed) return plan;
870
- let type;
871
- if (parsed.prerelease.length) {
872
- if (parsed.patch !== 0) type = "patch";
873
- else if (parsed.minor !== 0) type = "minor";
874
- else if (parsed.major !== 0) type = "major";
875
- else type = "major";
876
- } else if (parsed.major === 0) type = "major";
877
- if (type) return {
878
- ...plan,
879
- release: { type }
880
- };
881
- return plan;
882
- });
697
+ async function countGitHistory(cwd, ref = "HEAD") {
698
+ const stdout = await execGit(cwd, [
699
+ "rev-list",
700
+ "--count",
701
+ "--first-parent",
702
+ ref
703
+ ]);
704
+ return Number.parseInt(stdout.trim(), 10);
883
705
  }
884
- // src/git/branch/getCurrentGitBranch.ts
706
+ // src/git/repository/isGitShallowRepository.ts
885
707
  /**
886
- * Get the current Git branch name.
708
+ * Determine whether the repository at `cwd` is a shallow clone.
887
709
  *
888
- * Uses `execGit` to run `git symbolic-ref -q --short HEAD` in the provided
889
- * working directory and trims the result. Returns an empty string when the
890
- * repository is in a detached HEAD state.
710
+ * Runs `git rev-parse --is-shallow-repository` to detect shallow clones.
711
+ * Useful before operations that require full history.
891
712
  *
892
- * @param cwd The working directory to run the Git command in
893
- * @returns The current branch name as a string
713
+ * @param cwd Repository working directory
714
+ * @returns `true` if shallow, `false` if full clone, or `null` on error
894
715
  */
895
- async function getCurrentGitBranch(cwd) {
896
- return (await execGit(cwd, [
897
- "symbolic-ref",
898
- "-q",
899
- "--short",
900
- "HEAD"
901
- ])).trim();
716
+ async function isGitShallowRepository(cwd) {
717
+ return (await execGit(cwd, ["rev-parse", "--is-shallow-repository"])).trim() === "true";
902
718
  }
903
- // src/git/commit/createGitCommit.ts
719
+ // src/git/repository/withShallowLock.ts
720
+ var lockQueue = /* @__PURE__ */ new Map();
721
+ var context = new AsyncLocalStorage();
904
722
  /**
905
- * Stage all changes and create a git commit with the specified message.
723
+ * Serialize access to a shallow Git repository while running a callback.
906
724
  *
907
- * Validates the commit message and working directory status before staging
908
- * all changes and executing the commit command.
725
+ * If `cwd` is a shallow clone, callers from different async contexts are
726
+ * executed one at a time; nested calls within the same async context run
727
+ * immediately without waiting. If the repository becomes non-shallow before
728
+ * a queued turn runs, downstream waiters are released early.
909
729
  *
910
- * @param cwd The target directory path for executing git commands
911
- * @param message The message to associate with the commit
912
- * @returns A promise that resolves when the operation completes
730
+ * @param cwd Repository working directory path string
731
+ * @param callback Function to execute while the lock is held
732
+ * @returns Promise resolving to the result of `callback`
913
733
  */
914
- async function createGitCommit(cwd, message) {
915
- if (!message) return;
916
- await execGit(cwd, ["add", "."]);
917
- if (!(await execGit(cwd, ["status", "--porcelain"])).trim()) return;
918
- await execGit(cwd, [
919
- "commit",
920
- "--message",
921
- message
922
- ]);
734
+ async function withShallowLock(cwd, callback) {
735
+ if (!await isGitShallowRepository(cwd)) return callback();
736
+ const active = context.getStore();
737
+ if (active?.has(cwd)) return callback();
738
+ const { promise, resolve } = Promise.withResolvers();
739
+ const previous = lockQueue.get(cwd) ?? Promise.resolve();
740
+ const queued = previous.then(() => promise);
741
+ lockQueue.set(cwd, queued);
742
+ await previous;
743
+ if (!await isGitShallowRepository(cwd)) resolve();
744
+ try {
745
+ return await context.run(new Set(active).add(cwd), callback);
746
+ } finally {
747
+ resolve();
748
+ if (lockQueue.get(cwd) === queued) lockQueue.delete(cwd);
749
+ }
923
750
  }
924
- // src/git/commit/extractMentions.ts
925
- var ALPHANUMERIC = "[a-zA-Z0-9]";
926
- var SEPARATOR = "[-_]";
927
- var USERNAME = `${ALPHANUMERIC}+(?:${SEPARATOR}+${ALPHANUMERIC}+)*`;
928
- var EMAIL_LOCAL = "[a-zA-Z0-9._%+-]";
929
- var DOMAIN_SUFFIX = "[a-zA-Z0-9.-]*\\.[a-zA-Z]{2,}";
930
- var SCOPED_PACKAGE_SPEC_SUFFIX = `/${USERNAME}@[0-9]+\\.[0-9]+\\.[0-9]+`;
751
+ // src/git/revision/isGitAncestor.ts
931
752
  /**
932
- * Extract unique mention handles from the input text string.
753
+ * Determine whether `ancestor` is an ancestor of `descendant`.
933
754
  *
934
- * Evaluates `text` against boundary rules to isolate valid handles while
935
- * excluding email addresses, domain names, and scoped package specs, then
936
- * de-duplicates the resulting handles.
755
+ * Runs `git merge-base --is-ancestor <ancestor> <descendant>` in the repository at `cwd`.
756
+ * Resolves to `true` if `ancestor` is an ancestor, `false` if not.
757
+ * Rethrows errors for invalid refs or other failures.
937
758
  *
938
- * @param text The input string to parse for mentions
939
- * @returns An array of unique mention handles
759
+ * @param cwd Repository working directory
760
+ * @param ancestor Candidate ancestor ref
761
+ * @param descendant Candidate descendant ref
762
+ * @returns Resolves to `true` if `ancestor` is an ancestor of `descendant`, `false` otherwise
763
+ * @throws If a ref is invalid or the Git command fails
940
764
  */
941
- function extractMentions(text) {
942
- if (!text) return [];
943
- const regex = new RegExp(`(?<!${EMAIL_LOCAL})@(${USERNAME})\\b(?!${SEPARATOR}|${DOMAIN_SUFFIX}|${SCOPED_PACKAGE_SPEC_SUFFIX})`, "g");
944
- const matches = text.matchAll(regex);
945
- const mentions = new Set(matches.map((match) => match[1]));
946
- return Array.from(mentions);
765
+ function isGitAncestor(cwd, ancestor, descendant) {
766
+ return execGit(cwd, [
767
+ "merge-base",
768
+ "--is-ancestor",
769
+ ancestor,
770
+ descendant
771
+ ]).then(() => true).catch((err) => {
772
+ if (err?.code === 1) return false;
773
+ throw err;
774
+ });
947
775
  }
948
- // src/cache/TTLCache.ts
776
+ // src/git/revision/resolveGitRevision.ts
949
777
  /**
950
- * A simple time-to-live cache that automatically evicts entries after a TTL.
778
+ * Resolve a Git revision or commit-ish expression to its full commit hash.
951
779
  *
952
- * - Entries are removed automatically when their TTL expires.
953
- * - Reading an entry resets its TTL to the original value.
954
- * - Setting an existing key clears its previous timer and resets the TTL.
780
+ * Runs `git rev-parse --verify <revision>^{commit}` under the hood. Peels annotated
781
+ * tags, branches, short SHAs, and relative expressions down to a verified commit object.
955
782
  *
956
- * @template K Type of cache keys
957
- * @template V Type of cache values
783
+ * @param cwd The repository working directory
784
+ * @param revision The Git revision or expression to resolve
785
+ * @returns A promise that resolves to the full, trimmed commit SHA-1 string
958
786
  */
959
- var TTLCache = class {
960
- constructor() {
961
- this.cache = /* @__PURE__ */ new Map();
962
- }
963
- /**
964
- * Store a value under `key` for `ttl` milliseconds.
965
- *
966
- * If the key already exists its previous timer is cleared and the TTL is reset.
967
- *
968
- * @param key Cache key
969
- * @param value Value to store
970
- * @param ttl Time to live in milliseconds (default: 60_000)
971
- */
972
- set(key, value, ttl = 6e4) {
973
- const ref = this.cache.get(key);
974
- if (ref) clearTimeout(ref.timer);
975
- const timer = setTimeout(() => {
976
- this.cache.delete(key);
977
- }, ttl).unref();
978
- this.cache.set(key, {
979
- value,
980
- timer,
981
- ttl
982
- });
983
- }
984
- /**
985
- * Retrieve the value for `key`, or `undefined` if not present.
986
- *
987
- * Reading an entry resets its TTL to the original `ttl` provided when it was set.
988
- *
989
- * @param key Cache key
990
- * @returns The stored value or `undefined` if not present
991
- */
992
- get(key) {
993
- const ref = this.cache.get(key);
994
- if (!ref) return void 0;
995
- this.set(key, ref.value, ref.ttl);
996
- return ref.value;
997
- }
998
- /**
999
- * Check whether `key` exists in the cache.
1000
- *
1001
- * @param key Cache key
1002
- * @returns `true` if present; otherwise `false`
1003
- */
1004
- has(key) {
1005
- return this.cache.has(key);
1006
- }
1007
- /**
1008
- * Remove `key` from the cache and clear its eviction timer.
1009
- *
1010
- * @param key Cache key
1011
- * @returns `true` if the key was present and removed; otherwise `false`
1012
- */
1013
- delete(key) {
1014
- const ref = this.cache.get(key);
1015
- if (!ref) return false;
1016
- clearTimeout(ref.timer);
1017
- return this.cache.delete(key);
1018
- }
1019
- /**
1020
- * Clear all entries and their timers.
1021
- */
1022
- clear() {
1023
- for (const { timer } of this.cache.values()) clearTimeout(timer);
1024
- this.cache.clear();
1025
- }
787
+ async function resolveGitRevision(cwd, revision) {
788
+ return (await execGit(cwd, [
789
+ "rev-parse",
790
+ "--verify",
791
+ `${revision}^{commit}`
792
+ ])).trim();
793
+ }
794
+ // src/git/history/expandGitHistory.ts
795
+ /**
796
+ * Deepen a shallow clone so additional commits become available.
797
+ *
798
+ * Attempts a single `--shallow-since` fetch to reach `until` (if provided),
799
+ * otherwise deepens by `pageSize`, accounting for existing depth when `from`
800
+ * is supplied. Operation is serialized to avoid concurrent deepens.
801
+ *
802
+ * @param cwd Repository working directory
803
+ * @param options Options: { pageSize?, from?, until? }
804
+ * @returns true if history was deepened or already sufficient, otherwise false
805
+ */
806
+ async function expandGitHistory(cwd, options = {}) {
807
+ if (!await isGitShallowRepository(cwd)) return false;
808
+ return withShallowLock(cwd, async () => {
809
+ const { until } = options;
810
+ let { from } = options;
811
+ let { pageSize = 50 } = options;
812
+ if (until) {
813
+ if (await isGitAncestor(cwd, until, "HEAD")) return true;
814
+ const commitDate = (await execGit(cwd, [
815
+ "show",
816
+ "-s",
817
+ "--format=%cI",
818
+ `${until}^{commit}`
819
+ ])).trim();
820
+ try {
821
+ await execGit(cwd, [
822
+ "-c",
823
+ "fetch.negotiationAlgorithm=skipping",
824
+ "fetch",
825
+ `--shallow-since=${commitDate}`,
826
+ "--update-shallow",
827
+ "--filter=blob:none"
828
+ ]);
829
+ return true;
830
+ } catch {}
831
+ }
832
+ if (from) {
833
+ from = await resolveGitRevision(cwd, from);
834
+ const depth = await countGitHistory(cwd, from);
835
+ if (depth > pageSize) return true;
836
+ pageSize -= depth - 1;
837
+ }
838
+ try {
839
+ await execGit(cwd, [
840
+ "-c",
841
+ "fetch.negotiationAlgorithm=skipping",
842
+ "fetch",
843
+ `--deepen=${pageSize}`,
844
+ "--update-shallow",
845
+ "--filter=blob:none",
846
+ ...from && !await isGitAncestor(cwd, from, "HEAD") ? [
847
+ "origin",
848
+ from,
849
+ "HEAD"
850
+ ] : []
851
+ ]);
852
+ return true;
853
+ } catch {
854
+ return false;
855
+ }
856
+ });
857
+ }
858
+ // src/git/revision/detectGitRelationship.ts
859
+ var GIT_REL_FLAGS = {
860
+ NONE: 0,
861
+ IS_ANCESTOR: 1,
862
+ IS_DESCENDANT: 2,
863
+ IS_EQUAL: 3
1026
864
  };
1027
- // src/git/commit/parseGitCommit.ts
1028
- var BREAKING_HEADER_REGEX = /^([\w-]+)(?:\(([^)]+)\))?!: (.*)$/;
1029
- var BREAKING_MARKERS = ["BREAKING CHANGE", "BREAKING-CHANGE"];
1030
865
  /**
1031
- * Parse a git log entry into a structured commit object.
866
+ * Determine the relationship between two git refs.
1032
867
  *
1033
- * Combines the commit subject and body, extracts conventional commit metadata
1034
- * using custom trailer markers and breaking header patterns, and normalizes
1035
- * dates to ISO format strings.
868
+ * Runs `git merge-base --is-ancestor` in both directions and returns a
869
+ * numeric bitmask using `GIT_REL_FLAGS`. A successful check (exit code 0)
870
+ * indicates an ancestor relationship; non-zero exit is treated as "not ancestor".
1036
871
  *
1037
- * @param entry The raw git log entry to parse
1038
- * @param markers Optional array of custom trailer marker strings
1039
- * @returns A structured commit object containing parsed details, notes, and mentions
872
+ * @param cwd Repository working directory
873
+ * @param refA First ref (candidate ancestor)
874
+ * @param refB Second ref (candidate descendant)
875
+ * @returns Bitmask of type `GitRelFlags`
1040
876
  */
1041
- async function parseGitCommit(entry, markers = []) {
1042
- const message = [entry.subject, entry.body].filter(Boolean).join("\n\n");
1043
- const commit = new CommitParser({
1044
- breakingHeaderPattern: BREAKING_HEADER_REGEX,
1045
- noteKeywords: [],
1046
- notesPattern: () => buildTrailerPattern(BREAKING_MARKERS.concat(markers))
1047
- }).parse(message);
1048
- const notes = [];
1049
- const trailers = [];
1050
- for (const note of commit.notes) {
1051
- if (BREAKING_MARKERS.includes(note.title.toUpperCase())) notes.push(note);
1052
- trailers.push({
1053
- key: note.title,
1054
- value: note.text
1055
- });
877
+ async function detectGitRelationship(cwd, refA, refB) {
878
+ let flags = GIT_REL_FLAGS.NONE;
879
+ const [aIsAncestor, bIsAncestor] = await Promise.all([isGitAncestor(cwd, refA, refB), isGitAncestor(cwd, refB, refA)]);
880
+ if (aIsAncestor) flags |= GIT_REL_FLAGS.IS_ANCESTOR;
881
+ if (bIsAncestor) flags |= GIT_REL_FLAGS.IS_DESCENDANT;
882
+ return flags;
883
+ }
884
+ // src/git/history/mergeGitHistory.ts
885
+ /**
886
+ * Merge two newest-first commit lists into a single deduplicated newest-first list.
887
+ *
888
+ * Compares commits by hash, uses git relationship (ancestor/descendant) when needed,
889
+ * and falls back to committerDate for unrelated commits.
890
+ *
891
+ * @param cwd Repository working directory used for relationship checks
892
+ * @param a Commits from the first source (newest-first)
893
+ * @param b Commits from the second source (newest-first)
894
+ * @returns Merged commits in newest-first order with duplicates removed
895
+ */
896
+ async function mergeGitHistory(cwd, a, b) {
897
+ const merged = [];
898
+ const a2 = [...a];
899
+ const b2 = [...b];
900
+ let i = a2.shift();
901
+ let j = b2.shift();
902
+ while (i && j) switch (i.hash === j.hash ? GIT_REL_FLAGS.IS_EQUAL : await detectGitRelationship(cwd, i.hash, j.hash)) {
903
+ case GIT_REL_FLAGS.IS_EQUAL:
904
+ merged.push(i);
905
+ i = a2.shift();
906
+ j = b2.shift();
907
+ break;
908
+ case GIT_REL_FLAGS.IS_ANCESTOR:
909
+ merged.push(j);
910
+ j = b2.shift();
911
+ break;
912
+ case GIT_REL_FLAGS.IS_DESCENDANT:
913
+ merged.push(i);
914
+ i = a2.shift();
915
+ break;
916
+ case GIT_REL_FLAGS.NONE: if (i.committerDate < j.committerDate) {
917
+ merged.push(j);
918
+ j = b2.shift();
919
+ } else {
920
+ merged.push(i);
921
+ i = a2.shift();
922
+ }
1056
923
  }
1057
- if (notes.length === 0 && BREAKING_HEADER_REGEX.test(commit.header)) {
1058
- const note = {
1059
- title: "BREAKING CHANGE",
1060
- text: commit.subject
1061
- };
1062
- notes.push(note);
1063
- trailers.push({
1064
- key: note.title,
1065
- value: note.text
1066
- });
924
+ if (i) merged.push(i);
925
+ if (j) merged.push(j);
926
+ return merged.concat(a2).concat(b2);
927
+ }
928
+ // src/git/history/restoreFullGitHistory.ts
929
+ /**
930
+ * Convert a shallow clone into a full clone by fetching additional history.
931
+ *
932
+ * Runs `git fetch --unshallow`. Returns `true` when the operation succeeds
933
+ * and `false` on error.
934
+ *
935
+ * @param cwd Repository working directory
936
+ * @returns `true` when the operation succeeded, otherwise `false`
937
+ */
938
+ function restoreFullGitHistory(cwd) {
939
+ return execGit(cwd, ["fetch", "--unshallow"]).then(() => true).catch(() => false);
940
+ }
941
+ // src/git/history/showGitHistory.ts
942
+ /**
943
+ * Yield commit SHAs from repository history in paginated order.
944
+ *
945
+ * Ensures commits are available via `expandGitHistory`, resolves `until` to a
946
+ * commit id, and pages from `from` toward `until`, yielding each commit SHA.
947
+ * If a git command fails the generator ends silently.
948
+ *
949
+ * @param cwd Repository working directory
950
+ * @param options Supports `from`, `until`, `pageSize`, and `filePath`
951
+ * @yields Commit SHA strings in paginated order
952
+ */
953
+ async function* showGitHistory(cwd, options = {}) {
954
+ try {
955
+ const { filePath, pageSize = 50 } = options;
956
+ let from = options.from || "HEAD";
957
+ let until = options.until || void 0;
958
+ if (until) until = await resolveGitRevision(cwd, until);
959
+ while (true) {
960
+ await expandGitHistory(cwd, {
961
+ from,
962
+ until,
963
+ pageSize
964
+ });
965
+ const args = [
966
+ "rev-list",
967
+ `--max-count=${pageSize}`,
968
+ from
969
+ ];
970
+ if (until) args.push(`^${until}`);
971
+ if (filePath) args.push("--", ...(Array.isArray(filePath) ? filePath : [filePath]).filter(Boolean));
972
+ const list = (await execGit(cwd, args)).trim().split("\n").filter(Boolean);
973
+ for (const item of list.slice(0, -1)) yield item;
974
+ const tail = list.at(-1);
975
+ if (!tail) return;
976
+ if (tail === from) {
977
+ yield tail;
978
+ from = `${tail}^`;
979
+ from = await resolveGitRevision(cwd, from);
980
+ } else from = tail;
981
+ }
982
+ } catch {}
983
+ }
984
+ // src/git/history/showParsedGitHistory.ts
985
+ /**
986
+ * Yield parsed commits sequentially from repository history.
987
+ *
988
+ * Fetches commits using `showGitHistory` and parses each commit with
989
+ * `getParsedGitCommit`. Yields successfully parsed `GitCommit` objects on demand
990
+ * and skips unparsable commits.
991
+ *
992
+ * @param cwd Repository working directory path
993
+ * @param options Filter and pagination options passed to `showGitHistory`
994
+ * @yields Parsed `GitCommit` objects in historical order
995
+ */
996
+ async function* showParsedGitHistory(cwd, options) {
997
+ for await (const commit of showGitHistory(cwd, options)) try {
998
+ yield await getParsedGitCommit(cwd, commit);
999
+ } catch {}
1000
+ }
1001
+ // src/git/repository/getGitConfigValue.ts
1002
+ /**
1003
+ * Get a local git configuration value for `key` in the repository at `cwd`.
1004
+ *
1005
+ * Returns the config value when present; otherwise `undefined`.
1006
+ *
1007
+ * @param cwd Repository working directory
1008
+ * @param key Git config key to read
1009
+ * @returns The config value or `undefined` if not set
1010
+ */
1011
+ async function getGitConfigValue(cwd, key) {
1012
+ try {
1013
+ const value = (await execGit(cwd, [
1014
+ "config",
1015
+ "--local",
1016
+ "--get",
1017
+ key
1018
+ ])).trim();
1019
+ return value ? value : void 0;
1020
+ } catch {
1021
+ return;
1067
1022
  }
1068
- const mentions = extractMentions(message);
1069
- return {
1070
- ...commit,
1071
- hash: entry.hash,
1072
- parent: entry.parent,
1073
- authorDate: new Date(entry.authorDate).toISOString(),
1074
- committerDate: new Date(entry.committerDate).toISOString(),
1075
- type: commit.type?.toLowerCase() || null,
1076
- scope: commit.scope || null,
1077
- subject: commit.subject || null,
1078
- header: commit.header,
1079
- body: commit.body,
1080
- footer: commit.footer,
1081
- notes,
1082
- mentions,
1083
- trailers,
1084
- files: entry.files
1085
- };
1086
1023
  }
1087
- // src/git/commit/parseGitPrettyFormat.ts
1024
+ // src/git/repository/ensureGitUserConfig.ts
1088
1025
  /**
1089
- * Field separator used in the git pretty format to produce a single-line
1090
- *, machine-parseable record.
1026
+ * Ensure Git user configuration is set and return a cleanup handle.
1027
+ *
1028
+ * Checks the existing `user.name` and `user.email` configuration for the given
1029
+ * working directory. Updates the configuration if either value is missing and
1030
+ * returns an `AsyncDisposable` resource that restores the original state upon
1031
+ * disposal.
1032
+ *
1033
+ * @param cwd Working directory path in which to check and set Git configuration
1034
+ * @param user Git author details containing name and email
1035
+ * @returns Async disposable cleanup object if updated, or undefined if already set
1091
1036
  */
1092
- var GIT_PRETTY_FIELD_SEPARATOR = "";
1037
+ async function ensureGitUserConfig(cwd, user) {
1038
+ const initialName = await getGitConfigValue(cwd, "user.name");
1039
+ const initialEmail = await getGitConfigValue(cwd, "user.email");
1040
+ if (initialName && initialEmail) return;
1041
+ await execGit(cwd, [
1042
+ "config",
1043
+ "user.name",
1044
+ user.name
1045
+ ]);
1046
+ await execGit(cwd, [
1047
+ "config",
1048
+ "user.email",
1049
+ user.email
1050
+ ]);
1051
+ return { async [Symbol.asyncDispose]() {
1052
+ if (initialName) await execGit(cwd, [
1053
+ "config",
1054
+ "user.name",
1055
+ initialName
1056
+ ]);
1057
+ else await execGit(cwd, [
1058
+ "config",
1059
+ "--unset",
1060
+ "user.name"
1061
+ ]);
1062
+ if (initialEmail) await execGit(cwd, [
1063
+ "config",
1064
+ "user.email",
1065
+ initialEmail
1066
+ ]);
1067
+ else await execGit(cwd, [
1068
+ "config",
1069
+ "--unset",
1070
+ "user.email"
1071
+ ]);
1072
+ } };
1073
+ }
1074
+ // src/git/repository/getGitRemote.ts
1093
1075
  /**
1094
- * Pretty format string passed to `git log --pretty=format:`. Produces seven
1095
- * fields separated by `GIT_PRETTY_FIELD_SEPARATOR`:
1096
- * hash, parents, author date, committer date, subject, body, files.
1076
+ * Get the URL for the named remote (defaults to `origin`).
1077
+ *
1078
+ * @param cwd Repository working directory
1079
+ * @param remoteName Remote name (defaults to `'origin'`)
1080
+ * @returns Remote URL string or `null` when unavailable
1097
1081
  */
1098
- var GIT_PRETTY_FORMAT = [
1099
- "%H",
1100
- "%P",
1101
- "%aI",
1102
- "%cI",
1103
- "%s",
1104
- "%b",
1105
- ""
1106
- ].join("");
1082
+ function getGitRemote(cwd, remoteName = "origin") {
1083
+ return execGit(cwd, [
1084
+ "remote",
1085
+ "get-url",
1086
+ remoteName
1087
+ ]).then((stdout) => stdout.trim()).catch(() => null);
1088
+ }
1089
+ // src/git/repository/pushGitChanges.ts
1107
1090
  /**
1108
- * Parse a single line produced by `git log --pretty=format:${GIT_PRETTY_FORMAT}`.
1091
+ * Push a branch and optional tags to the `origin` remote using an atomic push.
1109
1092
  *
1110
- * The input is expected to contain seven fields separated by
1111
- * `GIT_PRETTY_FIELD_SEPARATOR`:
1112
- * 1. `hash` (commit hash)
1113
- * 2. `parent` (space-separated parent hashes)
1114
- * 3. `authorDate` (ISO 8601)
1115
- * 4. `committerDate` (ISO 8601)
1116
- * 5. `subject`
1117
- * 6. `body`
1118
- * 7. `files` (newline-separated list)
1093
+ * @param cwd Repository working directory
1094
+ * @param branch Branch name to push
1095
+ * @param additionalTags Optional list of tag names to push alongside the branch
1096
+ * @returns Promise that resolves when the push completes
1097
+ */
1098
+ async function pushGitChanges(cwd, branch, ...additionalTags) {
1099
+ await execGit(cwd, [
1100
+ "push",
1101
+ "origin",
1102
+ ...compact([branch, ...additionalTags]),
1103
+ "--atomic",
1104
+ "--no-verify"
1105
+ ]);
1106
+ }
1107
+ // src/git/repository/resolveGitRepository.ts
1108
+ /**
1109
+ * Resolve Git repository host, owner, and project metadata from the `origin` remote URL.
1110
+ *
1111
+ * @param cwd Repository working directory
1112
+ * @returns Promise that resolves to a `GitRepository` object, or `null` when unavailable
1113
+ */
1114
+ async function resolveGitRepository(cwd) {
1115
+ const origin = await getGitRemote(cwd);
1116
+ if (!origin) return null;
1117
+ const info = GitHost.fromUrl(origin);
1118
+ if (info && typeof info.type === "string" && typeof info.user === "string" && typeof info.project === "string") return {
1119
+ host: info.type,
1120
+ owner: info.user,
1121
+ repo: info.project,
1122
+ url: info.browse()
1123
+ };
1124
+ return null;
1125
+ }
1126
+ // src/git/revision/readGitFile.ts
1127
+ /**
1128
+ * Read a file's contents from a specific Git revision.
1129
+ *
1130
+ * Runs `git show <ref>:<filePath>` and returns the command output as a
1131
+ * string. If the file does not exist at the given revision or the Git
1132
+ * command fails for any reason, the function returns `null`.
1133
+ *
1134
+ * The returned string is the raw file contents as emitted by Git; callers
1135
+ * that need binary-safe handling should decode or process the bytes
1136
+ * accordingly. This function intentionally swallows Git errors and signals
1137
+ * absence via a `null` result rather than throwing.
1138
+ *
1139
+ * @param cwd Repository working directory
1140
+ * @param ref Commit-ish reference (commit SHA, tag, or branch) to read from
1141
+ * @param filePath Path to the file relative to the repository root
1142
+ * @returns File contents as a string, or `null` if the file is unavailable at the ref
1143
+ */
1144
+ function readGitFile(cwd, ref, filePath) {
1145
+ return execGit(cwd, ["show", `${ref}:${filePath}`]).catch(() => null);
1146
+ }
1147
+ // src/git/tag/createGitTag.ts
1148
+ /**
1149
+ * Create a git tag in the repository at `cwd`.
1119
1150
  *
1120
- * The function trims fields, converts parent hashes into an array, normalizes
1121
- * dates to ISO strings, and splits `files` into an array. Missing optional
1122
- * fields are normalized to sensible defaults.
1151
+ * Creates an annotated tag when `message` is provided.
1123
1152
  *
1124
- * @param raw Raw pretty-format string produced by git
1125
- * @returns Parsed `GitLogEntry` with `hash`, `parent`, `authorDate`, `committerDate`, `subject`, `body`, and `files`
1126
- * @throws If required fields (hash, authorDate, committerDate, subject) are missing or malformed
1153
+ * @param cwd Repository working directory
1154
+ * @param tag Tag name to create
1155
+ * @param message Optional tag message (creates an annotated tag when present)
1156
+ * @returns Promise that resolves when the tag is created
1127
1157
  */
1128
- function parseGitPrettyFormat(raw) {
1129
- let [hash, parentHashes, authorDate, committerDate, subject, body, files] = raw.split("");
1130
- hash = hash?.trim();
1131
- parentHashes = parentHashes?.trim();
1132
- authorDate = authorDate?.trim();
1133
- committerDate = committerDate?.trim();
1134
- subject = subject?.trim();
1135
- body = body?.trim();
1136
- files = files?.trim();
1137
- if (!hash || !authorDate || !committerDate || typeof subject !== "string") throw new Error(`The input "${colors.bold(raw)}" is not in the expected pretty format.`);
1138
- return {
1139
- hash,
1140
- parent: parentHashes ? parentHashes.split(/\s+/) : [],
1141
- authorDate: new Date(authorDate).toISOString(),
1142
- committerDate: new Date(committerDate).toISOString(),
1143
- subject,
1144
- body: body ?? "",
1145
- files: files ? files.split("\n") : []
1146
- };
1158
+ async function createGitTag(cwd, tag, message) {
1159
+ await execGit(cwd, ["tag", ...message ? [
1160
+ "-a",
1161
+ tag,
1162
+ "-m",
1163
+ message,
1164
+ "--cleanup=whitespace"
1165
+ ] : [tag]]);
1147
1166
  }
1148
- // src/git/commit/getParsedGitCommit.ts
1149
- var cache = new TTLCache();
1167
+ // src/git/tag/deleteGitTag.ts
1150
1168
  /**
1151
- * Retrieve and parse a git commit by its reference.
1152
- *
1153
- * Fetches the raw git log entry for the specified `ref`, checking the local cache
1154
- * prior to parsing missing entries.
1169
+ * Delete a local git tag in the repository at `cwd`.
1155
1170
  *
1156
- * @param cwd Current working directory path
1157
- * @param ref Git reference to fetch
1158
- * @param markers Optional array of custom trailer marker strings
1159
- * @returns Structured commit object
1171
+ * @param cwd Repository working directory
1172
+ * @param tag Tag name to delete
1173
+ * @returns `true` when deletion succeeded, otherwise `false`
1160
1174
  */
1161
- async function getParsedGitCommit(cwd, ref, markers = []) {
1162
- const entry = parseGitPrettyFormat(await execGit(cwd, [
1163
- "log",
1164
- "-1",
1165
- ref,
1166
- "--name-only",
1167
- `--pretty=format:${GIT_PRETTY_FORMAT}`
1168
- ]));
1169
- const key = `${entry.hash}:${entry.parent}:${markers}`;
1170
- const cached = cache.get(key);
1171
- if (cached) return cached;
1172
- const parsed = await parseGitCommit(entry, markers);
1173
- cache.set(key, parsed);
1174
- return parsed;
1175
+ function deleteGitTag(cwd, tag) {
1176
+ return execGit(cwd, [
1177
+ "tag",
1178
+ "-d",
1179
+ tag
1180
+ ]).then(() => true).catch(() => false);
1175
1181
  }
1176
- // src/git/commit/getCurrentGitCommit.ts
1182
+ // src/git/tag/isGitTagPresent.ts
1177
1183
  /**
1178
- * Resolve the current `HEAD` commit in the repository.
1184
+ * Determine whether a specific git tag exists locally in the repository.
1179
1185
  *
1180
- * @param cwd Repository working directory path
1181
- * @param markers Optional array of custom trailer marker strings
1182
- * @returns Parsed commit object for the current `HEAD` commit
1186
+ * @param cwd Working directory for the git command
1187
+ * @param tag Name of the tag to evaluate
1188
+ * @returns True if the tag reference exists locally, false otherwise
1183
1189
  */
1184
- function getCurrentGitCommit(cwd, markers = []) {
1185
- return getParsedGitCommit(cwd, "HEAD", markers);
1190
+ function isGitTagPresent(cwd, tag) {
1191
+ return resolveGitRevision(cwd, `refs/tags/${tag}`).then(() => true).catch(() => false);
1186
1192
  }
1187
- // src/git/history/countGitHistory.ts
1193
+ // src/git/tag/ensureGitTag.ts
1194
+ var MIN_HISTORY_DEPTH = 2;
1195
+ var ORIGIN_NOT_REPO = `fatal: 'origin' does not appear to be a git repository`;
1196
+ var REMOTE_REF_NOT_FOUND = `fatal: couldn't find remote ref`;
1188
1197
  /**
1189
- * Count mainline commits reachable from a given reference.
1198
+ * Ensure a tag exists locally, fetching it shallowly from `origin` if needed.
1190
1199
  *
1191
- * Uses `git rev-list --count --first-parent` to calculate the length of the
1192
- * primary history trunk, excluding commits introduced by side-branch merges.
1200
+ * Acquires a shallow-fetch lock, verifies local presence and history depth,
1201
+ * attempts a shallow fetch of `refs/tags/<tag>` when required, and removes a
1202
+ * local tag if the remote reports the tag is missing.
1203
+ *
1204
+ * @param cwd Working directory
1205
+ * @param tag Tag name (for example `v1.2.0`)
1206
+ * @returns `true` if the tag is present or was fetched; otherwise `false`
1207
+ */
1208
+ function ensureGitTag(cwd, tag) {
1209
+ return withShallowLock(cwd, async () => {
1210
+ const tagRef = `refs/tags/${tag}`;
1211
+ if (await isGitTagPresent(cwd, tag) && await countGitHistory(cwd, tagRef) >= MIN_HISTORY_DEPTH) return true;
1212
+ try {
1213
+ await execGit(cwd, [
1214
+ "fetch",
1215
+ "origin",
1216
+ `${tagRef}:${tagRef}`,
1217
+ `--depth=${MIN_HISTORY_DEPTH}`,
1218
+ "--update-shallow",
1219
+ "--force"
1220
+ ]);
1221
+ return true;
1222
+ } catch (err) {
1223
+ const errorMessage = err?.message;
1224
+ if (errorMessage?.includes(ORIGIN_NOT_REPO)) return await isGitTagPresent(cwd, tag);
1225
+ if (errorMessage?.includes(REMOTE_REF_NOT_FOUND)) {
1226
+ if (await isGitTagPresent(cwd, tag)) await deleteGitTag(cwd, tag);
1227
+ }
1228
+ }
1229
+ return false;
1230
+ });
1231
+ }
1232
+ // src/git/tag/generateGitTagName.ts
1233
+ function generateGitTagName(entry, name, version) {
1234
+ if (!version) return null;
1235
+ if (entry) return `v${version}`;
1236
+ if (!name) throw new Error("Package name is required to build a tag name.");
1237
+ return `${name}@${version}`;
1238
+ }
1239
+ // src/git/tag/getCurrentGitTag.ts
1240
+ /**
1241
+ * Get the tag name that exactly matches the current `HEAD`, if any.
1193
1242
  *
1194
1243
  * @param cwd Repository working directory
1195
- * @param ref Commit reference to count from (defaults to `HEAD`)
1196
- * @returns Number of commits along the primary branch line up to `ref`
1244
+ * @returns Tag name or `null` when no exact tag matches HEAD
1197
1245
  */
1198
- async function countGitHistory(cwd, ref = "HEAD") {
1199
- const stdout = await execGit(cwd, [
1200
- "rev-list",
1201
- "--count",
1202
- "--first-parent",
1203
- ref
1204
- ]);
1205
- return Number.parseInt(stdout.trim(), 10);
1246
+ async function getCurrentGitTag(cwd) {
1247
+ try {
1248
+ const tag = (await execGit(cwd, [
1249
+ "describe",
1250
+ "--tags",
1251
+ "--exact-match"
1252
+ ])).trim();
1253
+ /* istanbul ignore next */
1254
+ return tag ? tag : null;
1255
+ } catch {
1256
+ return null;
1257
+ }
1206
1258
  }
1207
- // src/git/repository/isGitShallowRepository.ts
1259
+ // src/git/tag/getGitTagMessage.ts
1208
1260
  /**
1209
- * Determine whether the repository at `cwd` is a shallow clone.
1261
+ * Get the message of an annotated git tag in the repository at `cwd`.
1210
1262
  *
1211
- * Runs `git rev-parse --is-shallow-repository` to detect shallow clones.
1212
- * Useful before operations that require full history.
1263
+ * @param cwd Repository working directory
1264
+ * @param tag Tag name to query
1265
+ * @returns The tag message string when found, otherwise `undefined`
1266
+ */
1267
+ async function getGitTagMessage(cwd, tag) {
1268
+ try {
1269
+ const [objectType, message] = (await execGit(cwd, [
1270
+ "for-each-ref",
1271
+ "--format=%(objecttype)%00%(contents)",
1272
+ `refs/tags/${tag}`
1273
+ ])).split("\0");
1274
+ if (objectType?.trim() !== "tag") return;
1275
+ return message?.trim() || void 0;
1276
+ } catch {
1277
+ /* istanbul ignore next */
1278
+ return;
1279
+ }
1280
+ }
1281
+ // src/git/tag/getLatestGitTag.ts
1282
+ /**
1283
+ * Get the most recent tag reachable from `HEAD`.
1213
1284
  *
1214
1285
  * @param cwd Repository working directory
1215
- * @returns `true` if shallow, `false` if full clone, or `null` on error
1286
+ * @returns Latest tag string or `null` when none is found
1216
1287
  */
1217
- async function isGitShallowRepository(cwd) {
1218
- return (await execGit(cwd, ["rev-parse", "--is-shallow-repository"])).trim() === "true";
1288
+ async function getLatestGitTag(cwd) {
1289
+ try {
1290
+ const tag = (await execGit(cwd, [
1291
+ "describe",
1292
+ "--tags",
1293
+ "--abbrev=0"
1294
+ ])).trim();
1295
+ /* istanbul ignore next */
1296
+ return tag ? tag : null;
1297
+ } catch {
1298
+ return null;
1299
+ }
1219
1300
  }
1220
- // src/git/repository/withShallowLock.ts
1221
- var lockQueue = /* @__PURE__ */ new Map();
1222
- var context = new AsyncLocalStorage();
1301
+ // src/git/tag/isGitTagConnected.ts
1223
1302
  /**
1224
- * Serialize access to a shallow Git repository while running a callback.
1303
+ * Determine whether a specific git tag commit is reachable from the current HEAD.
1225
1304
  *
1226
- * If `cwd` is a shallow clone, callers from different async contexts are
1227
- * executed one at a time; nested calls within the same async context run
1228
- * immediately without waiting. If the repository becomes non-shallow before
1229
- * a queued turn runs, downstream waiters are released early.
1305
+ * Uses `git merge-base --is-ancestor refs/tags/<tag>^{commit} HEAD` to verify
1306
+ * that the tag's commit is an ancestor of the current reference. Any non-zero
1307
+ * exit status or execution error is treated as "not reachable".
1230
1308
  *
1231
- * @param cwd Repository working directory path string
1232
- * @param callback Function to execute while the lock is held
1233
- * @returns Promise resolving to the result of `callback`
1309
+ * @param cwd Working directory where the git command will run
1310
+ * @param tag Tag name to evaluate (for example, "v1.2.0")
1311
+ * @returns True if the tag commit is reachable from HEAD, false otherwise
1234
1312
  */
1235
- async function withShallowLock(cwd, callback) {
1236
- if (!await isGitShallowRepository(cwd)) return callback();
1237
- const active = context.getStore();
1238
- if (active?.has(cwd)) return callback();
1239
- const { promise, resolve } = Promise.withResolvers();
1240
- const previous = lockQueue.get(cwd) ?? Promise.resolve();
1241
- const queued = previous.then(() => promise);
1242
- lockQueue.set(cwd, queued);
1243
- await previous;
1244
- if (!await isGitShallowRepository(cwd)) resolve();
1313
+ async function isGitTagConnected(cwd, tag) {
1314
+ try {
1315
+ await execGit(cwd, [
1316
+ "merge-base",
1317
+ "--is-ancestor",
1318
+ `refs/tags/${tag}^{commit}`,
1319
+ "HEAD"
1320
+ ]);
1321
+ return true;
1322
+ } catch {
1323
+ return false;
1324
+ }
1325
+ }
1326
+ // src/git/tag/isGitTagPointed.ts
1327
+ /**
1328
+ * Check whether a given tag points to the provided commit.
1329
+ *
1330
+ * @param cwd Repository working directory
1331
+ * @param tag Tag name to resolve
1332
+ * @param commit Commit hash to compare against
1333
+ * @returns `true` when the tag points at `commit`, otherwise `false`
1334
+ */
1335
+ async function isGitTagPointed(cwd, tag, commit) {
1245
1336
  try {
1246
- return await context.run(new Set(active).add(cwd), callback);
1247
- } finally {
1248
- resolve();
1249
- if (lockQueue.get(cwd) === queued) lockQueue.delete(cwd);
1337
+ await execGit(cwd, [
1338
+ "merge-base",
1339
+ "--is-ancestor",
1340
+ `refs/tags/${tag}^{commit}`,
1341
+ commit
1342
+ ]);
1343
+ await execGit(cwd, [
1344
+ "merge-base",
1345
+ "--is-ancestor",
1346
+ commit,
1347
+ `refs/tags/${tag}^{commit}`
1348
+ ]);
1349
+ return true;
1350
+ } catch {
1351
+ return false;
1250
1352
  }
1251
1353
  }
1252
- // src/git/revision/isGitAncestor.ts
1354
+ // src/config/const.ts
1355
+ var ALL_FILES = "**/*";
1356
+ var DEFAULT_CHANGELOG_FILE = "CHANGELOG.md";
1357
+ var GIT_TRAILER_RELEASE_AGENT = "Release-Agent";
1358
+ var GIT_TRAILER_RELEASE_FILTER = "Release-Filter";
1253
1359
  /**
1254
- * Determine whether `ancestor` is an ancestor of `descendant`.
1360
+ * 1. Primitive Building Blocks
1255
1361
  *
1256
- * Runs `git merge-base --is-ancestor <ancestor> <descendant>` in the repository at `cwd`.
1257
- * Resolves to `true` if `ancestor` is an ancestor, `false` if not.
1258
- * Rethrows errors for invalid refs or other failures.
1362
+ * Base regular expression patterns for wildcards, alphanumeric strings with hyphens,
1363
+ * and standard non-negative integers.
1364
+ */
1365
+ var WILDCARD = "\\*";
1366
+ var ALPHANUM_DASH = "[0-9a-zA-Z-]+";
1367
+ var NUMERIC_IDENTIFIER = "0|[1-9]\\d*";
1368
+ /**
1369
+ * 2. Package Name & Prefix Constructs
1259
1370
  *
1260
- * @param cwd Repository working directory
1261
- * @param ancestor Candidate ancestor ref
1262
- * @param descendant Candidate descendant ref
1263
- * @returns Resolves to `true` if `ancestor` is an ancestor of `descendant`, `false` otherwise
1264
- * @throws If a ref is invalid or the Git command fails
1371
+ * Matches package name prefixes (unscoped or scoped) or a simple `v` prefix.
1372
+ *
1373
+ * Capture Groups:
1374
+ * - Group 1: Package name (e.g., `my-package` or `@scope/my-package`)
1265
1375
  */
1266
- function isGitAncestor(cwd, ancestor, descendant) {
1267
- return execGit(cwd, [
1268
- "merge-base",
1269
- "--is-ancestor",
1270
- ancestor,
1271
- descendant
1272
- ]).then(() => true).catch((err) => {
1273
- if (err?.code === 1) return false;
1274
- throw err;
1275
- });
1276
- }
1277
- // src/git/revision/resolveGitRevision.ts
1376
+ var PKG_NAME_PART = `(?:${WILDCARD}|${ALPHANUM_DASH})`;
1377
+ var OPTIONAL_VERSION_PREFIX = `(?:v|${`(${PKG_NAME_PART}|@${PKG_NAME_PART}\\/${PKG_NAME_PART})`}@)`;
1278
1378
  /**
1279
- * Resolve a Git revision or commit-ish expression to its full commit hash.
1379
+ * 3. Core SemVer Components
1280
1380
  *
1281
- * Runs `git rev-parse --verify <revision>^{commit}` under the hood. Peels annotated
1282
- * tags, branches, short SHAs, and relative expressions down to a verified commit object.
1381
+ * Matches standard `MAJOR.MINOR.PATCH` versions or wildcard variants (e.g., `1.0.0`, `*.*.*`).
1283
1382
  *
1284
- * @param cwd The repository working directory
1285
- * @param revision The Git revision or expression to resolve
1286
- * @returns A promise that resolves to the full, trimmed commit SHA-1 string
1383
+ * Capture Groups:
1384
+ * - Group 3: Major version
1385
+ * - Group 4: Minor version
1386
+ * - Group 5: Patch version
1287
1387
  */
1288
- async function resolveGitRevision(cwd, revision) {
1289
- return (await execGit(cwd, [
1290
- "rev-parse",
1291
- "--verify",
1292
- `${revision}^{commit}`
1293
- ])).trim();
1294
- }
1295
- // src/git/history/expandGitHistory.ts
1388
+ var CAPTURED_VERSION_DIGIT = `(${WILDCARD}|${NUMERIC_IDENTIFIER})`;
1389
+ var SEMVER_CORE = `${CAPTURED_VERSION_DIGIT}\\.${CAPTURED_VERSION_DIGIT}\\.${CAPTURED_VERSION_DIGIT}`;
1390
+ var PRERELEASE_IDENTIFIER = `(?:${WILDCARD}|${NUMERIC_IDENTIFIER}|(\\d*[a-zA-Z-][0-9a-zA-Z-]*))`;
1391
+ var FULL_SEMVER_PATTERN = `${OPTIONAL_VERSION_PREFIX}?${`(${SEMVER_CORE}${`(?:-(${PRERELEASE_IDENTIFIER}(?:\\.${PRERELEASE_IDENTIFIER})*))`}?${`(?:\\+(${ALPHANUM_DASH}(?:\\.${ALPHANUM_DASH})*))`}?)`}`;
1296
1392
  /**
1297
- * Deepen a shallow clone so additional commits become available.
1393
+ * Regular expression to match and capture Semantic Versioning (SemVer) strings,
1394
+ * including optional package prefixes (e.g., `@scope/pkg@`) and `v` prefixes.
1298
1395
  *
1299
- * Attempts a single `--shallow-since` fetch to reach `until` (if provided),
1300
- * otherwise deepens by `pageSize`, accounting for existing depth when `from`
1301
- * is supplied. Operation is serialized to avoid concurrent deepens.
1396
+ * @example
1397
+ * ```ts
1398
+ * SEMVER_REGEX.test('1.0.0') // true
1399
+ * SEMVER_REGEX.test('v1.2.3-beta.1+sha.1234') // true
1400
+ * SEMVER_REGEX.test('@scope/package@1.0.0') // true
1401
+ * ```
1302
1402
  *
1303
- * @param cwd Repository working directory
1304
- * @param options Options: { pageSize?, from?, until? }
1305
- * @returns true if history was deepened or already sufficient, otherwise false
1403
+ * @see {@link https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string SemVer Specification}
1306
1404
  */
1307
- async function expandGitHistory(cwd, options = {}) {
1308
- if (!await isGitShallowRepository(cwd)) return false;
1309
- return withShallowLock(cwd, async () => {
1310
- const { until } = options;
1311
- let { from } = options;
1312
- let { pageSize = 50 } = options;
1313
- if (until) {
1314
- if (await isGitAncestor(cwd, until, "HEAD")) return true;
1315
- const commitDate = (await execGit(cwd, [
1316
- "show",
1317
- "-s",
1318
- "--format=%cI",
1319
- `${until}^{commit}`
1320
- ])).trim();
1321
- try {
1322
- await execGit(cwd, [
1323
- "-c",
1324
- "fetch.negotiationAlgorithm=skipping",
1325
- "fetch",
1326
- `--shallow-since=${commitDate}`,
1327
- "--update-shallow",
1328
- "--filter=blob:none"
1329
- ]);
1330
- return true;
1331
- } catch {}
1332
- }
1333
- if (from) {
1334
- from = await resolveGitRevision(cwd, from);
1335
- const depth = await countGitHistory(cwd, from);
1336
- if (depth > pageSize) return true;
1337
- pageSize -= depth - 1;
1338
- }
1339
- try {
1340
- await execGit(cwd, [
1341
- "-c",
1342
- "fetch.negotiationAlgorithm=skipping",
1343
- "fetch",
1344
- `--deepen=${pageSize}`,
1345
- "--update-shallow",
1346
- "--filter=blob:none",
1347
- ...from && !await isGitAncestor(cwd, from, "HEAD") ? [
1348
- "origin",
1349
- from,
1350
- "HEAD"
1351
- ] : []
1352
- ]);
1353
- return true;
1354
- } catch {
1355
- return false;
1356
- }
1357
- });
1358
- }
1359
- // src/git/revision/detectGitRelationship.ts
1360
- var GIT_REL_FLAGS = {
1361
- NONE: 0,
1362
- IS_ANCESTOR: 1,
1363
- IS_DESCENDANT: 2,
1364
- IS_EQUAL: 3
1365
- };
1405
+ var SEMVER_REGEX = new RegExp(FULL_SEMVER_PATTERN);
1406
+ var DEV_NULL = new Writable({
1407
+ /* istanbul ignore next */
1408
+ write(_chunk, _encoding, callback) {
1409
+ callback();
1410
+ } });
1411
+ var RELEASE_HOOK_NAMES = [
1412
+ "configure",
1413
+ "discover",
1414
+ "analyze",
1415
+ "build",
1416
+ "write",
1417
+ "publish",
1418
+ "finalize"
1419
+ ];
1420
+ // src/config/createPlugin.ts
1366
1421
  /**
1367
- * Determine the relationship between two git refs.
1422
+ * Instantiate or invoke a plugin factory to produce a release plugin instance.
1368
1423
  *
1369
- * Runs `git merge-base --is-ancestor` in both directions and returns a
1370
- * numeric bitmask using `GIT_REL_FLAGS`. A successful check (exit code 0)
1371
- * indicates an ancestor relationship; non-zero exit is treated as "not ancestor".
1424
+ * Accepts class constructors, factory functions, tuple configurations, or
1425
+ * existing plugin objects. Instantiates classes using `new` or invokes factory
1426
+ * functions with options, validating that the resulting object satisfies the
1427
+ * plugin structure.
1372
1428
  *
1373
- * @param cwd Repository working directory
1374
- * @param refA First ref (candidate ancestor)
1375
- * @param refB Second ref (candidate descendant)
1376
- * @returns Bitmask of type `GitRelFlags`
1429
+ * @param plugin A plugin constructor, factory function, tuple, or object
1430
+ * @returns A validated release plugin instance or null
1377
1431
  */
1378
- async function detectGitRelationship(cwd, refA, refB) {
1379
- let flags = GIT_REL_FLAGS.NONE;
1380
- const [aIsAncestor, bIsAncestor] = await Promise.all([isGitAncestor(cwd, refA, refB), isGitAncestor(cwd, refB, refA)]);
1381
- if (aIsAncestor) flags |= GIT_REL_FLAGS.IS_ANCESTOR;
1382
- if (bIsAncestor) flags |= GIT_REL_FLAGS.IS_DESCENDANT;
1383
- return flags;
1432
+ async function createPlugin(plugin) {
1433
+ let options;
1434
+ if (Array.isArray(plugin)) [plugin, options] = plugin;
1435
+ if (typeof plugin === "function") plugin = isClass(plugin) ? new plugin(options) : await plugin(options);
1436
+ if (plugin != null && typeof plugin === "object" && Object.hasOwn(plugin, "name") && typeof plugin.name === "string") return plugin;
1437
+ return null;
1384
1438
  }
1385
- // src/git/history/mergeGitHistory.ts
1439
+ // src/config/findReleaseRule.ts
1386
1440
  /**
1387
- * Merge two newest-first commit lists into a single deduplicated newest-first list.
1441
+ * Find the first release rule matching a release reference.
1388
1442
  *
1389
- * Compares commits by hash, uses git relationship (ancestor/descendant) when needed,
1390
- * and falls back to committerDate for unrelated commits.
1443
+ * Matches rules sequentially against the reference type and pattern.
1391
1444
  *
1392
- * @param cwd Repository working directory used for relationship checks
1393
- * @param a Commits from the first source (newest-first)
1394
- * @param b Commits from the second source (newest-first)
1395
- * @returns Merged commits in newest-first order with duplicates removed
1445
+ * @param ref Release reference object
1446
+ * @param rules Array of release rules to match against
1447
+ * @returns The first matching release rule or `undefined`
1396
1448
  */
1397
- async function mergeGitHistory(cwd, a, b) {
1398
- const merged = [];
1399
- const a2 = [...a];
1400
- const b2 = [...b];
1401
- let i = a2.shift();
1402
- let j = b2.shift();
1403
- while (i && j) switch (i.hash === j.hash ? GIT_REL_FLAGS.IS_EQUAL : await detectGitRelationship(cwd, i.hash, j.hash)) {
1404
- case GIT_REL_FLAGS.IS_EQUAL:
1405
- merged.push(i);
1406
- i = a2.shift();
1407
- j = b2.shift();
1408
- break;
1409
- case GIT_REL_FLAGS.IS_ANCESTOR:
1410
- merged.push(j);
1411
- j = b2.shift();
1412
- break;
1413
- case GIT_REL_FLAGS.IS_DESCENDANT:
1414
- merged.push(i);
1415
- i = a2.shift();
1416
- break;
1417
- case GIT_REL_FLAGS.NONE: if (i.committerDate < j.committerDate) {
1418
- merged.push(j);
1419
- j = b2.shift();
1420
- } else {
1421
- merged.push(i);
1422
- i = a2.shift();
1423
- }
1424
- }
1425
- if (i) merged.push(i);
1426
- if (j) merged.push(j);
1427
- return merged.concat(a2).concat(b2);
1449
+ function findReleaseRule(ref, rules) {
1450
+ return rules.find((rule) => {
1451
+ return (rule.type == null || rule.type === ref.type) && isMatch(ref.name, rule.pattern);
1452
+ });
1428
1453
  }
1429
- // src/git/history/restoreFullGitHistory.ts
1454
+ // src/config/isSemVer.ts
1430
1455
  /**
1431
- * Convert a shallow clone into a full clone by fetching additional history.
1456
+ * Determine whether a value is a valid Semantic Versioning string.
1432
1457
  *
1433
- * Runs `git fetch --unshallow`. Returns `true` when the operation succeeds
1434
- * and `false` on error.
1458
+ * Rejects non-string values, leading or trailing whitespace, and leading `v`
1459
+ * prefixes. Validates the candidate string using `semver.parse`.
1435
1460
  *
1436
- * @param cwd Repository working directory
1437
- * @returns `true` when the operation succeeded, otherwise `false`
1461
+ * @param version Candidate value to evaluate for SemVer compliance
1462
+ * @returns `true` if `version` is a valid SemVer string, or `false` otherwise
1438
1463
  */
1439
- function restoreFullGitHistory(cwd) {
1440
- return execGit(cwd, ["fetch", "--unshallow"]).then(() => true).catch(() => false);
1464
+ function isSemVer(version) {
1465
+ if (typeof version !== "string") return false;
1466
+ if (version !== version.trim()) return false;
1467
+ if (version.startsWith("v")) return false;
1468
+ return semver.parse(version) != null;
1441
1469
  }
1442
- // src/git/history/showGitHistory.ts
1470
+ // src/config/isSemVerGitTag.ts
1443
1471
  /**
1444
- * Yield commit SHAs from repository history in paginated order.
1472
+ * Determine whether a tag string is a valid SemVer-style Git tag.
1445
1473
  *
1446
- * Ensures commits are available via `expandGitHistory`, resolves `until` to a
1447
- * commit id, and pages from `from` toward `until`, yielding each commit SHA.
1448
- * If a git command fails the generator ends silently.
1474
+ * Anchors `SEMVER_REGEX.source` for full-string matching and applies the
1475
+ * repository's Git-tag acceptance rules.
1449
1476
  *
1450
- * @param cwd Repository working directory
1451
- * @param options Supports `from`, `until`, `pageSize`, and `filePath`
1452
- * @yields Commit SHA strings in paginated order
1477
+ * @param tag Tag string to validate
1478
+ * @returns `true` if `tag` is accepted as a SemVer-style Git tag; otherwise `false`
1453
1479
  */
1454
- async function* showGitHistory(cwd, options = {}) {
1455
- try {
1456
- const { filePath, pageSize = 50 } = options;
1457
- let from = options.from || "HEAD";
1458
- let until = options.until || void 0;
1459
- if (until) until = await resolveGitRevision(cwd, until);
1460
- while (true) {
1461
- await expandGitHistory(cwd, {
1462
- from,
1463
- until,
1464
- pageSize
1465
- });
1466
- const args = [
1467
- "rev-list",
1468
- `--max-count=${pageSize}`,
1469
- from
1470
- ];
1471
- if (until) args.push(`^${until}`);
1472
- if (filePath) args.push("--", ...(Array.isArray(filePath) ? filePath : [filePath]).filter(Boolean));
1473
- const list = (await execGit(cwd, args)).trim().split("\n").filter(Boolean);
1474
- for (const item of list.slice(0, -1)) yield item;
1475
- const tail = list.at(-1);
1476
- if (!tail) return;
1477
- if (tail === from) {
1478
- yield tail;
1479
- from = `${tail}^`;
1480
- from = await resolveGitRevision(cwd, from);
1481
- } else from = tail;
1482
- }
1483
- } catch {}
1480
+ function isSemVerGitTag(tag) {
1481
+ const match = new RegExp(`^${SEMVER_REGEX.source}$`).exec(tag);
1482
+ if (!match) return false;
1483
+ const isScopedPackage = Boolean(match[1]);
1484
+ const hasVersionPrefix = tag.startsWith("v");
1485
+ return isScopedPackage || hasVersionPrefix;
1484
1486
  }
1485
- // src/git/history/showParsedGitHistory.ts
1487
+ // src/config/sanitizePrereleaseLabel.ts
1486
1488
  /**
1487
- * Yield parsed commits sequentially from repository history.
1489
+ * Sanitize a string into a safe, SemVer-compliant prerelease label.
1488
1490
  *
1489
- * Fetches commits using `showGitHistory` and parses each commit with
1490
- * `getParsedGitCommit`. Yields successfully parsed `GitCommit` objects on demand
1491
- * and skips unparsable commits.
1491
+ * Replaces sequences of non-alphanumeric characters with a single hyphen and
1492
+ * removes leading or trailing hyphens.
1492
1493
  *
1493
- * @param cwd Repository working directory path
1494
- * @param options Filter and pagination options passed to `showGitHistory`
1495
- * @yields Parsed `GitCommit` objects in historical order
1494
+ * @param label Raw string to sanitize
1495
+ * @returns Safe SemVer prerelease label
1496
1496
  */
1497
- async function* showParsedGitHistory(cwd, options) {
1498
- for await (const commit of showGitHistory(cwd, options)) try {
1499
- yield await getParsedGitCommit(cwd, commit);
1500
- } catch {}
1497
+ function sanitizePrereleaseLabel(label) {
1498
+ return label.replace(/[^a-zA-Z0-9]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
1501
1499
  }
1502
- // src/git/repository/getGitConfigValue.ts
1500
+ // src/config/resolveReleaseChannel.ts
1503
1501
  /**
1504
- * Get a local git configuration value for `key` in the repository at `cwd`.
1502
+ * Resolve the release channel for a release context.
1505
1503
  *
1506
- * Returns the config value when present; otherwise `undefined`.
1504
+ * Uses the release rule when `channel` is `boolean` or omitted. Sanitizes the
1505
+ * reference name when enabling default channel resolution and interpolates
1506
+ * `templateParams` into the result.
1507
1507
  *
1508
- * @param cwd Repository working directory
1509
- * @param key Git config key to read
1510
- * @returns The config value or `undefined` if not set
1508
+ * @param options Options for resolving the release channel
1509
+ * @returns Resolved release channel string or `undefined`
1511
1510
  */
1512
- async function getGitConfigValue(cwd, key) {
1513
- try {
1514
- const value = (await execGit(cwd, [
1515
- "config",
1516
- "--local",
1517
- "--get",
1518
- key
1519
- ])).trim();
1520
- return value ? value : void 0;
1521
- } catch {
1522
- return;
1523
- }
1511
+ function resolveReleaseChannel(options) {
1512
+ const { ref, rule, templateParams } = options;
1513
+ let { channel } = options;
1514
+ let resolved;
1515
+ if (channel === true || channel == null) channel = rule?.releaseChannel ?? channel;
1516
+ if (typeof channel === "string") resolved = channel;
1517
+ else if (channel) resolved = sanitizePrereleaseLabel(ref.name);
1518
+ if (typeof resolved === "string") resolved = interpolate(resolved, templateParams);
1519
+ return resolved;
1524
1520
  }
1525
- // src/git/repository/ensureGitUserConfig.ts
1521
+ // src/config/resolveVersionQualifier.ts
1526
1522
  /**
1527
- * Ensure Git user configuration is set and return a cleanup handle.
1523
+ * Resolve the version qualifier for a release context.
1528
1524
  *
1529
- * Checks the existing `user.name` and `user.email` configuration for the given
1530
- * working directory. Updates the configuration if either value is missing and
1531
- * returns an `AsyncDisposable` resource that restores the original state upon
1532
- * disposal.
1525
+ * Uses the release rule when `qualifier` is `boolean` or omitted. Interpolates
1526
+ * `templateParams` into `qualifier` and validates that the result forms a
1527
+ * valid SemVer prerelease identifier.
1533
1528
  *
1534
- * @param cwd Working directory path in which to check and set Git configuration
1535
- * @param user Git author details containing name and email
1536
- * @returns Async disposable cleanup object if updated, or undefined if already set
1529
+ * @param options Options for resolving the version qualifier
1530
+ * @returns Resolved version qualifier string or `undefined`
1531
+ * @throws If the resolved string is not a valid SemVer prerelease identifier
1537
1532
  */
1538
- async function ensureGitUserConfig(cwd, user) {
1539
- const initialName = await getGitConfigValue(cwd, "user.name");
1540
- const initialEmail = await getGitConfigValue(cwd, "user.email");
1541
- if (initialName && initialEmail) return;
1542
- await execGit(cwd, [
1543
- "config",
1544
- "user.name",
1545
- user.name
1546
- ]);
1547
- await execGit(cwd, [
1548
- "config",
1549
- "user.email",
1550
- user.email
1551
- ]);
1552
- return { async [Symbol.asyncDispose]() {
1553
- if (initialName) await execGit(cwd, [
1554
- "config",
1555
- "user.name",
1556
- initialName
1557
- ]);
1558
- else await execGit(cwd, [
1559
- "config",
1560
- "--unset",
1561
- "user.name"
1562
- ]);
1563
- if (initialEmail) await execGit(cwd, [
1564
- "config",
1565
- "user.email",
1566
- initialEmail
1567
- ]);
1568
- else await execGit(cwd, [
1569
- "config",
1570
- "--unset",
1571
- "user.email"
1572
- ]);
1573
- } };
1533
+ function resolveVersionQualifier(options) {
1534
+ const { rule, templateParams } = options;
1535
+ let { qualifier } = options;
1536
+ let resolved;
1537
+ if (qualifier === true || qualifier == null) qualifier = rule?.versionQualifier ?? qualifier;
1538
+ if (typeof qualifier === "string") resolved = qualifier;
1539
+ else if (qualifier) resolved = "";
1540
+ if (typeof resolved === "string") resolved = interpolate(resolved, templateParams);
1541
+ if (resolved && !isSemVer(`1.0.0-${resolved}.1`)) throw new Error(`The resolved version qualifier "${resolved}" is not a valid SemVer prerelease identifier.`);
1542
+ return resolved;
1574
1543
  }
1575
- // src/git/repository/getGitRemote.ts
1544
+ // src/workflow/committing/isReleaseCommit.ts
1576
1545
  /**
1577
- * Get the URL for the named remote (defaults to `origin`).
1546
+ * Determine whether a commit represents a release or matches a release marker.
1578
1547
  *
1579
- * @param cwd Repository working directory
1580
- * @param remoteName Remote name (defaults to `'origin'`)
1581
- * @returns Remote URL string or `null` when unavailable
1548
+ * Resolves string commit identifiers to parsed commit objects, checks if any
1549
+ * associated trailer matches the `marker` predicate, and falls back to
1550
+ * verifying exact tag matches for the `commit` hash.
1551
+ *
1552
+ * @param cwd Working directory path for Git commands
1553
+ * @param commit Commit object, hash string, or nullish value
1554
+ * @param marker Trailer key string or predicate function to evaluate
1555
+ * @returns `true` if the commit is a release commit, otherwise `false`
1582
1556
  */
1583
- function getGitRemote(cwd, remoteName = "origin") {
1557
+ async function isReleaseCommit(cwd, commit, marker = GIT_TRAILER_RELEASE_AGENT) {
1558
+ if (typeof commit === "string") try {
1559
+ commit = await getParsedGitCommit(cwd, commit, typeof marker === "string" ? [marker] : []);
1560
+ } catch {
1561
+ commit = null;
1562
+ }
1563
+ if (!commit) return false;
1564
+ const predicate = typeof marker === "string" ? (trailer) => trailer.key === marker && !!trailer.value : marker;
1565
+ if (commit.trailers.some(predicate)) return true;
1584
1566
  return execGit(cwd, [
1585
- "remote",
1586
- "get-url",
1587
- remoteName
1588
- ]).then((stdout) => stdout.trim()).catch(() => null);
1567
+ "describe",
1568
+ "--tags",
1569
+ "--exact-match",
1570
+ commit.hash
1571
+ ]).then(() => true).catch(() => false);
1589
1572
  }
1590
- // src/git/repository/pushGitChanges.ts
1573
+ // src/workflow/analysis/collectUnreleased.ts
1591
1574
  /**
1592
- * Push a branch and optional tags to the `origin` remote using an atomic push.
1575
+ * Collect unreleased commits from repository history.
1593
1576
  *
1594
- * @param cwd Repository working directory
1595
- * @param branch Branch name to push
1596
- * @param additionalTags Optional list of tag names to push alongside the branch
1597
- * @returns Promise that resolves when the push completes
1598
- */
1599
- async function pushGitChanges(cwd, branch, ...additionalTags) {
1600
- await execGit(cwd, [
1601
- "push",
1602
- "origin",
1603
- ...compact([branch, ...additionalTags]),
1604
- "--atomic",
1605
- "--no-verify"
1606
- ]);
1607
- }
1608
- // src/git/repository/resolveGitRepository.ts
1609
- /**
1610
- * Resolve Git repository host, owner, and project metadata from the `origin` remote URL.
1577
+ * Walks parsed commit history in order and gathers every commit preceding the
1578
+ * first release commit. Exposes the release commit that ended the walk so
1579
+ * callers can inspect it, for example to read its release filter trailer.
1611
1580
  *
1612
- * @param cwd Repository working directory
1613
- * @returns Promise that resolves to a `GitRepository` object, or `null` when unavailable
1581
+ * @param cwd Path to the working directory for git commands
1582
+ * @param options Options for configuring Git history retrieval
1583
+ * @returns The unreleased commits and the release commit that stopped the walk
1614
1584
  */
1615
- async function resolveGitRepository(cwd) {
1616
- const origin = await getGitRemote(cwd);
1617
- if (!origin) return null;
1618
- const info = GitHost.fromUrl(origin);
1619
- if (info && typeof info.type === "string" && typeof info.user === "string" && typeof info.project === "string") return {
1620
- host: info.type,
1621
- owner: info.user,
1622
- repo: info.project,
1623
- url: info.browse()
1585
+ async function collectUnreleased(cwd, options = {}) {
1586
+ const history = [];
1587
+ for await (const commit of showParsedGitHistory(cwd, options)) {
1588
+ if (await isReleaseCommit(cwd, commit, options.marker)) return {
1589
+ history,
1590
+ stop: commit
1591
+ };
1592
+ history.push(commit);
1593
+ }
1594
+ return {
1595
+ history,
1596
+ stop: null
1624
1597
  };
1625
- return null;
1626
1598
  }
1627
- // src/git/revision/readGitFile.ts
1599
+ // src/workflow/versioning/extractVersionQualifier.ts
1628
1600
  /**
1629
- * Read a file's contents from a specific Git revision.
1630
- *
1631
- * Runs `git show <ref>:<filePath>` and returns the command output as a
1632
- * string. If the file does not exist at the given revision or the Git
1633
- * command fails for any reason, the function returns `null`.
1601
+ * Extract the version qualifier string from a parsed `SemVer` instance.
1634
1602
  *
1635
- * The returned string is the raw file contents as emitted by Git; callers
1636
- * that need binary-safe handling should decode or process the bytes
1637
- * accordingly. This function intentionally swallows Git errors and signals
1638
- * absence via a `null` result rather than throwing.
1603
+ * Strips the trailing numeric counter from the `prerelease` components if
1604
+ * present. Joins any remaining prerelease identifiers with a dot separator.
1639
1605
  *
1640
- * @param cwd Repository working directory
1641
- * @param ref Commit-ish reference (commit SHA, tag, or branch) to read from
1642
- * @param filePath Path to the file relative to the repository root
1643
- * @returns File contents as a string, or `null` if the file is unavailable at the ref
1606
+ * @param version Parsed `SemVer` instance or nullish value to inspect
1607
+ * @returns The extracted qualifier string or `undefined` if no prerelease exists
1644
1608
  */
1645
- function readGitFile(cwd, ref, filePath) {
1646
- return execGit(cwd, ["show", `${ref}:${filePath}`]).catch(() => null);
1609
+ function extractVersionQualifier(version) {
1610
+ if (version != null && version.prerelease.length > 0) {
1611
+ const prerelease = [...version.prerelease];
1612
+ if (typeof prerelease.at(-1) === "number") prerelease.pop();
1613
+ return prerelease.join(".");
1614
+ } else return;
1647
1615
  }
1648
- // src/git/tag/createGitTag.ts
1616
+ // src/workflow/versioning/bumpVersion.ts
1649
1617
  /**
1650
- * Create a git tag in the repository at `cwd`.
1618
+ * Bump a semantic version string based on release and transition rules.
1651
1619
  *
1652
- * Creates an annotated tag when `message` is provided.
1620
+ * Parses the target version and determines the next version string using the
1621
+ * specified release type, prerelease identifier, and transition mode. Adjusts
1622
+ * prerelease types when continuing an existing qualifier and returns `null` when
1623
+ * `options.release` is omitted or if transition conditions fail.
1653
1624
  *
1654
- * @param cwd Repository working directory
1655
- * @param tag Tag name to create
1656
- * @param message Optional tag message (creates an annotated tag when present)
1657
- * @returns Promise that resolves when the tag is created
1625
+ * @param options Version bump configuration including release type, identifier, and transition rules
1626
+ * @returns The bumped semantic version string, or `null` if no bump occurs
1627
+ * @throws If `options.version` is not a valid semantic version
1658
1628
  */
1659
- async function createGitTag(cwd, tag, message) {
1660
- await execGit(cwd, ["tag", ...message ? [
1661
- "-a",
1662
- tag,
1663
- "-m",
1664
- message,
1665
- "--cleanup=whitespace"
1666
- ] : [tag]]);
1629
+ function bumpVersion(options) {
1630
+ const { version } = options;
1631
+ const parsed = semver.parse(version);
1632
+ if (!parsed) throw new Error(`Version "${version}" is not a valid semantic version.`);
1633
+ if (!options.release) return null;
1634
+ if (parsed.prerelease.length > 0) {
1635
+ if (options.transition === "advance" && options.identifier == null) return null;
1636
+ } else if (options.transition === "continue") return null;
1637
+ let release = options.release;
1638
+ let identifier;
1639
+ if (typeof options.identifier === "string") {
1640
+ release = `pre${options.release}`;
1641
+ identifier = options.identifier;
1642
+ const parsedIdentifier = extractVersionQualifier(parsed);
1643
+ const transition = options.transition ?? (parsedIdentifier && identifier === "" ? "advance" : "continue");
1644
+ if (typeof parsedIdentifier === "string" && transition === "continue") {
1645
+ if (release === "premajor" && parsed.minor === 0 && parsed.patch === 0 || release === "preminor" && parsed.patch === 0 || release === "prepatch") release = "prerelease";
1646
+ }
1647
+ }
1648
+ return semver.inc(parsed, release, { loose: false }, identifier, "0");
1667
1649
  }
1668
- // src/git/tag/deleteGitTag.ts
1650
+ // src/workflow/versioning/determineReleaseType.ts
1669
1651
  /**
1670
- * Delete a local git tag in the repository at `cwd`.
1652
+ * Determine the release type for a single commit.
1671
1653
  *
1672
- * @param cwd Repository working directory
1673
- * @param tag Tag name to delete
1674
- * @returns `true` when deletion succeeded, otherwise `false`
1654
+ * Returns `'minor'` for a commit marked as a breaking change while the
1655
+ * supplied `version` is zero-major (`0.y.z`), and `'major'` otherwise, since
1656
+ * SemVer treats `0.y.z` as initial development where breaking changes do not
1657
+ * require a new major version. Otherwise, routes the commit through the
1658
+ * custom `classifier` and ensures the resolved value is a valid semantic
1659
+ * versioning release type.
1660
+ *
1661
+ * @param classifier Function mapping commits to release types
1662
+ * @param commit Parsed commit to evaluate
1663
+ * @param version Current package version used to adjust zero-major breaking releases
1664
+ * @returns `ReleaseType` string, or `null` when no matching rule applies
1675
1665
  */
1676
- function deleteGitTag(cwd, tag) {
1677
- return execGit(cwd, [
1678
- "tag",
1679
- "-d",
1680
- tag
1681
- ]).then(() => true).catch(() => false);
1666
+ function determineReleaseType(classifier, commit, version) {
1667
+ if (commit.notes.length > 0) return semver.parse(version)?.major === 0 ? "minor" : "major";
1668
+ const type = classifier(commit);
1669
+ switch (type) {
1670
+ case "major":
1671
+ case "minor":
1672
+ case "patch": return type;
1673
+ }
1674
+ return null;
1682
1675
  }
1683
- // src/git/tag/isGitTagPresent.ts
1676
+ // src/workflow/versioning/pickPriorityReleaseType.ts
1684
1677
  /**
1685
- * Determine whether a specific git tag exists locally in the repository.
1678
+ * Determine the highest-priority release type between two candidates.
1686
1679
  *
1687
- * @param cwd Working directory for the git command
1688
- * @param tag Name of the tag to evaluate
1689
- * @returns True if the tag reference exists locally, false otherwise
1680
+ * Compares release types by precedence order: `major` > `minor` > `patch`.
1681
+ * Returns the higher-precedence type, or `null` if neither applies.
1682
+ *
1683
+ * @param curr Current accumulated release type
1684
+ * @param next Candidate release type to consider
1685
+ * @returns Highest-precedence `ReleaseType`, or `null` if neither applies
1690
1686
  */
1691
- function isGitTagPresent(cwd, tag) {
1692
- return resolveGitRevision(cwd, `refs/tags/${tag}`).then(() => true).catch(() => false);
1687
+ function pickPriorityReleaseType(curr, next) {
1688
+ for (const type of [
1689
+ "major",
1690
+ "minor",
1691
+ "patch"
1692
+ ]) if (curr === type || next === type) return type;
1693
+ return null;
1693
1694
  }
1694
- // src/git/tag/ensureGitTag.ts
1695
- var MIN_HISTORY_DEPTH = 2;
1696
- var ORIGIN_NOT_REPO = `fatal: 'origin' does not appear to be a git repository`;
1697
- var REMOTE_REF_NOT_FOUND = `fatal: couldn't find remote ref`;
1695
+ // src/workflow/versioning/deriveReleaseType.ts
1698
1696
  /**
1699
- * Ensure a tag exists locally, fetching it shallowly from `origin` if needed.
1697
+ * Derive the combined release type from a release plan.
1700
1698
  *
1701
- * Acquires a shallow-fetch lock, verifies local presence and history depth,
1702
- * attempts a shallow fetch of `refs/tags/<tag>` when required, and removes a
1703
- * local tag if the remote reports the tag is missing.
1699
+ * Processes the plan's commits sequentially, accumulating the
1700
+ * highest-precedence release type found by evaluating each individual commit
1701
+ * and comparing it against the current maximum via `pickPriorityReleaseType`.
1702
+ * Breaking commits resolve to `minor` while the plan's package version is
1703
+ * zero-major (`0.y.z`).
1704
1704
  *
1705
- * @param cwd Working directory
1706
- * @param tag Tag name (for example `v1.2.0`)
1707
- * @returns `true` if the tag is present or was fetched; otherwise `false`
1705
+ * @param classifier Function mapping commits to release types
1706
+ * @param plan Release plan carrying the commit history and package version
1707
+ * @returns `ReleaseType` string, or `null` when no matching rule applies
1708
1708
  */
1709
- function ensureGitTag(cwd, tag) {
1710
- return withShallowLock(cwd, async () => {
1711
- const tagRef = `refs/tags/${tag}`;
1712
- if (await isGitTagPresent(cwd, tag) && await countGitHistory(cwd, tagRef) >= MIN_HISTORY_DEPTH) return true;
1713
- try {
1714
- await execGit(cwd, [
1715
- "fetch",
1716
- "origin",
1717
- `${tagRef}:${tagRef}`,
1718
- `--depth=${MIN_HISTORY_DEPTH}`,
1719
- "--update-shallow",
1720
- "--force"
1721
- ]);
1722
- return true;
1723
- } catch (err) {
1724
- const errorMessage = err?.message;
1725
- if (errorMessage?.includes(ORIGIN_NOT_REPO)) return await isGitTagPresent(cwd, tag);
1726
- if (errorMessage?.includes(REMOTE_REF_NOT_FOUND)) {
1727
- if (await isGitTagPresent(cwd, tag)) await deleteGitTag(cwd, tag);
1728
- }
1729
- }
1730
- return false;
1731
- });
1709
+ function deriveReleaseType(classifier, plan) {
1710
+ let releaseType = null;
1711
+ for (const commit of plan.history) releaseType = pickPriorityReleaseType(releaseType, determineReleaseType(classifier, commit, plan.package.version));
1712
+ return releaseType;
1732
1713
  }
1733
- // src/git/tag/generateGitTagName.ts
1734
- function generateGitTagName(entry, name, version) {
1735
- if (!version) return null;
1736
- if (entry) return `v${version}`;
1737
- if (!name) throw new Error("Package name is required to build a tag name.");
1738
- return `${name}@${version}`;
1714
+ // src/workflow/versioning/isSameReleaseCycle.ts
1715
+ /**
1716
+ * Determine whether two semantic version strings or objects belong to the same release cycle.
1717
+ *
1718
+ * Compares the main version components of `currentVersion` and `nextVersion` to
1719
+ * determine equality. Treats a transition from a non-zero `0.x` version to
1720
+ * `1.0.0` as part of the same release cycle. Returns `false` if either input
1721
+ * cannot be parsed.
1722
+ *
1723
+ * @param currentVersion Starting version string, `semver.SemVer` instance, or nullish value
1724
+ * @param nextVersion Target version string, `semver.SemVer` instance, or nullish value
1725
+ * @returns `true` if both versions belong to the same release cycle, `false` otherwise
1726
+ */
1727
+ function isSameReleaseCycle(currentVersion, nextVersion) {
1728
+ const current = semver.parse(currentVersion);
1729
+ const next = semver.parse(nextVersion);
1730
+ if (!current || !next) return false;
1731
+ if (current.compareMain(next) === 0) return true;
1732
+ return current.major === 0 && (current.minor > 0 || current.patch > 0) && next.major === 1 && next.minor === 0 && next.patch === 0;
1739
1733
  }
1740
- // src/git/tag/getCurrentGitTag.ts
1734
+ // src/workflow/versioning/isStableVersion.ts
1741
1735
  /**
1742
- * Get the tag name that exactly matches the current `HEAD`, if any.
1736
+ * Determine whether a version string represents a stable SemVer release.
1743
1737
  *
1744
- * @param cwd Repository working directory
1745
- * @returns Tag name or `null` when no exact tag matches HEAD
1738
+ * A version is considered stable when:
1739
+ * - It is a valid SemVer string.
1740
+ * - Its major version is greater than 0 (not 0.x.x).
1741
+ * - It contains no prerelease identifiers (no `-alpha`, `-beta`, `-rc`, etc.).
1742
+ *
1743
+ * Build metadata (the `+` suffix) does not affect stability.
1744
+ *
1745
+ * @param version Semantic version string to check
1746
+ * @returns `true` if `version` is a stable SemVer; otherwise `false`
1747
+ * @throws If `version` is not a valid SemVer string
1746
1748
  */
1747
- async function getCurrentGitTag(cwd) {
1748
- try {
1749
- const tag = (await execGit(cwd, [
1750
- "describe",
1751
- "--tags",
1752
- "--exact-match"
1753
- ])).trim();
1754
- /* istanbul ignore next */
1755
- return tag ? tag : null;
1756
- } catch {
1757
- return null;
1758
- }
1749
+ function isStableVersion(version) {
1750
+ const parsed = semver.parse(version);
1751
+ if (!parsed) throw new Error(`The version "${colors.bold(version)}" is not a valid SemVer.`);
1752
+ return parsed.major > 0 && parsed.prerelease.length === 0;
1759
1753
  }
1760
- // src/git/tag/getGitTagMessage.ts
1754
+ // src/workflow/analysis/isCommitForPackage.ts
1761
1755
  /**
1762
- * Get the message of an annotated git tag in the repository at `cwd`.
1756
+ * Test whether a commit modifies files in a package.
1763
1757
  *
1764
- * @param cwd Repository working directory
1765
- * @param tag Tag name to query
1766
- * @returns The tag message string when found, otherwise `undefined`
1758
+ * @param pkg Package with an explicit file pattern or base directory
1759
+ * @param commit Parsed commit containing changed file paths
1760
+ * @returns `true` if any changed file matches the package pattern
1767
1761
  */
1768
- async function getGitTagMessage(cwd, tag) {
1769
- try {
1770
- const [objectType, message] = (await execGit(cwd, [
1771
- "for-each-ref",
1772
- "--format=%(objecttype)%00%(contents)",
1773
- `refs/tags/${tag}`
1774
- ])).split("\0");
1775
- if (objectType?.trim() !== "tag") return;
1776
- return message?.trim() || void 0;
1777
- } catch {
1778
- /* istanbul ignore next */
1779
- return;
1780
- }
1762
+ function isCommitForPackage(pkg, commit) {
1763
+ return commit.files.some((file) => {
1764
+ const { location } = pkg;
1765
+ return isMatch(file, pkg.files || path.join(location, "**/*"));
1766
+ });
1781
1767
  }
1782
- // src/git/tag/getLatestGitTag.ts
1768
+ // src/workflow/analysis/deriveChangeReleases.ts
1783
1769
  /**
1784
- * Get the most recent tag reachable from `HEAD`.
1770
+ * Analyze commit history to update release plans for packages.
1785
1771
  *
1786
- * @param cwd Repository working directory
1787
- * @returns Latest tag string or `null` when none is found
1772
+ * Maps commit `history` across package release `plans` to associate matching
1773
+ * commits with their target packages. Calculates the release type for each
1774
+ * plan based on classified `history` and applies overrides according to the
1775
+ * provided `hint` or existing release priority. Downgrades breaking-change
1776
+ * `major` release types to `minor` while the package version is zero-major
1777
+ * (`0.y.z`).
1778
+ *
1779
+ * @param hint Release type override hint or default preference
1780
+ * @param classifier Classifier function to determine commit release types
1781
+ * @param plans List of release plans to analyze and update
1782
+ * @param history Stream or iterable of git commits to process
1783
+ * @returns Updated release plans with updated commit histories and release types
1788
1784
  */
1789
- async function getLatestGitTag(cwd) {
1790
- try {
1791
- const tag = (await execGit(cwd, [
1792
- "describe",
1793
- "--tags",
1794
- "--abbrev=0"
1795
- ])).trim();
1796
- /* istanbul ignore next */
1797
- return tag ? tag : null;
1798
- } catch {
1799
- return null;
1800
- }
1785
+ async function deriveChangeReleases(hint, classifier, plans, history) {
1786
+ for await (const commit of history) plans = plans.map((plan) => {
1787
+ if (!isCommitForPackage(plan.package, commit)) return plan;
1788
+ return {
1789
+ ...plan,
1790
+ history: plan.history.concat(commit)
1791
+ };
1792
+ });
1793
+ return plans.map((plan) => {
1794
+ let { release } = plan;
1795
+ let releaseType = deriveReleaseType(classifier, plan);
1796
+ if (releaseType) switch (hint) {
1797
+ case "major":
1798
+ case "minor":
1799
+ case "patch":
1800
+ releaseType = hint;
1801
+ break;
1802
+ default: releaseType = pickPriorityReleaseType(release?.type, releaseType);
1803
+ }
1804
+ if (releaseType) release = {
1805
+ ...release,
1806
+ type: releaseType
1807
+ };
1808
+ return {
1809
+ ...plan,
1810
+ release
1811
+ };
1812
+ });
1801
1813
  }
1802
- // src/git/tag/isGitTagConnected.ts
1814
+ // src/workflow/analysis/deriveTransitionReleases.ts
1803
1815
  /**
1804
- * Determine whether a specific git tag commit is reachable from the current HEAD.
1816
+ * Derive transition release types for release plans based on version qualifiers.
1805
1817
  *
1806
- * Uses `git merge-base --is-ancestor refs/tags/<tag>^{commit} HEAD` to verify
1807
- * that the tag's commit is an ancestor of the current reference. Any non-zero
1808
- * exit status or execution error is treated as "not reachable".
1818
+ * Evaluates unreleased `plans` by parsing package `semver` strings and checking
1819
+ * prerelease tags. Compares parsed version qualifiers against
1820
+ * `versionQualifier` and assigns `major`, `minor`, or `patch` release types
1821
+ * according to `hint`. When `hint` is `patch`, every package receives an
1822
+ * update: stable packages are assigned a patch release even without a
1823
+ * `versionQualifier`, and prerelease packages (pre-major, pre-minor, and
1824
+ * pre-patch cycles) continue their cycle with an incremented counter,
1825
+ * redirect to `versionQualifier` when it differs, or release their stable
1826
+ * base when no `versionQualifier` is set.
1809
1827
  *
1810
- * @param cwd Working directory where the git command will run
1811
- * @param tag Tag name to evaluate (for example, "v1.2.0")
1812
- * @returns True if the tag commit is reachable from HEAD, false otherwise
1828
+ * @param hint Release type override hint to guide release classification
1829
+ * @param versionQualifier Optional qualifier string to compare against prerelease tags
1830
+ * @param plans List of release plans to analyze and update
1831
+ * @returns Updated release plans with derived transition release types
1813
1832
  */
1814
- async function isGitTagConnected(cwd, tag) {
1815
- try {
1816
- await execGit(cwd, [
1817
- "merge-base",
1818
- "--is-ancestor",
1819
- `refs/tags/${tag}^{commit}`,
1820
- "HEAD"
1821
- ]);
1822
- return true;
1823
- } catch {
1824
- return false;
1825
- }
1833
+ function deriveTransitionReleases(hint, versionQualifier, plans) {
1834
+ return plans.map((plan) => {
1835
+ if (plan.release) return plan;
1836
+ const parsed = semver.parse(plan.package.version);
1837
+ if (!parsed) return plan;
1838
+ const { major, minor, patch } = parsed;
1839
+ const parsedVersionQualifier = extractVersionQualifier(parsed);
1840
+ let releaseType;
1841
+ let versionTransition;
1842
+ switch (hint) {
1843
+ case "major":
1844
+ if (parsed.prerelease.length === 0) {
1845
+ if (typeof versionQualifier === "string") releaseType = "major";
1846
+ else if (major === 0 && (minor > 0 || patch > 0)) releaseType = "major";
1847
+ } else if (minor === 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "major";
1848
+ break;
1849
+ case "minor":
1850
+ if (parsed.prerelease.length === 0) {
1851
+ if (typeof versionQualifier === "string") releaseType = "minor";
1852
+ } else if (minor > 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "minor";
1853
+ break;
1854
+ case "patch":
1855
+ releaseType = "patch";
1856
+ break;
1857
+ default: if (parsed.prerelease.length === 0) {
1858
+ if (major === 0 && (minor > 0 || patch > 0)) releaseType = "major";
1859
+ } else if (minor === 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "major";
1860
+ else if (minor > 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "minor";
1861
+ else if (patch > 0 && parsedVersionQualifier !== versionQualifier) releaseType = "patch";
1862
+ }
1863
+ if (parsedVersionQualifier == null || parsedVersionQualifier !== "" && versionQualifier === "") versionTransition = "advance";
1864
+ else versionTransition = "continue";
1865
+ if (!releaseType) return plan;
1866
+ return {
1867
+ ...plan,
1868
+ release: {
1869
+ type: releaseType,
1870
+ transition: versionTransition
1871
+ }
1872
+ };
1873
+ });
1826
1874
  }
1827
- // src/git/tag/isGitTagPointed.ts
1875
+ // src/workflow/analysis/promotePrereleaseVersions.ts
1828
1876
  /**
1829
- * Check whether a given tag points to the provided commit.
1877
+ * Promote prerelease versions when they have no explicit release type.
1830
1878
  *
1831
- * @param cwd Repository working directory
1832
- * @param tag Tag name to resolve
1833
- * @param commit Commit hash to compare against
1834
- * @returns `true` when the tag points at `commit`, otherwise `false`
1879
+ * Analyzes prerelease and zero-major versions to determine an appropriate
1880
+ * release type for graduation:
1881
+ * - Prerelease versions are promoted based on their highest incremented component
1882
+ * (patch, minor, or major)
1883
+ * - Zero-major versions (0.y.z) are promoted to major
1884
+ * - Stable versions (1.0.0+) remain unchanged
1885
+ * - Plans with explicit releases are preserved as-is
1886
+ *
1887
+ * @param plans Release plans to analyze
1888
+ * @returns Plans with inferred release types for prerelease versions
1835
1889
  */
1836
- async function isGitTagPointed(cwd, tag, commit) {
1837
- try {
1838
- await execGit(cwd, [
1839
- "merge-base",
1840
- "--is-ancestor",
1841
- `refs/tags/${tag}^{commit}`,
1842
- commit
1843
- ]);
1844
- await execGit(cwd, [
1845
- "merge-base",
1846
- "--is-ancestor",
1847
- commit,
1848
- `refs/tags/${tag}^{commit}`
1849
- ]);
1850
- return true;
1851
- } catch {
1852
- return false;
1853
- }
1890
+ async function promotePrereleaseVersions(plans) {
1891
+ return plans.map((plan) => {
1892
+ if (plan.release) return plan;
1893
+ if (!plan.package.tag) return plan;
1894
+ const parsed = semver.parse(plan.package.version);
1895
+ if (!parsed) return plan;
1896
+ let type;
1897
+ if (parsed.prerelease.length) {
1898
+ if (parsed.patch !== 0) type = "patch";
1899
+ else if (parsed.minor !== 0) type = "minor";
1900
+ else if (parsed.major !== 0) type = "major";
1901
+ else type = "major";
1902
+ } else if (parsed.major === 0) type = "major";
1903
+ if (type) return {
1904
+ ...plan,
1905
+ release: { type }
1906
+ };
1907
+ return plan;
1908
+ });
1854
1909
  }
1855
1910
  // src/workflow/discovery/buildDependencyGraph.ts
1856
1911
  /**
@@ -2030,6 +2085,22 @@ async function discoverPackageTag(cwd, pkg) {
2030
2085
  message: await getGitTagMessage(cwd, expectedTagName)
2031
2086
  };
2032
2087
  }
2088
+ // src/workflow/discovery/filterPackages.ts
2089
+ /**
2090
+ * Filter packages by name patterns.
2091
+ *
2092
+ * Keeps the packages whose names match `patterns`, scoping a release run to
2093
+ * a subset of the discovered workspace. Returns a copy of every package when
2094
+ * `patterns` is empty.
2095
+ *
2096
+ * @param packages Workspace packages to filter
2097
+ * @param patterns Minimatch patterns to match package names against
2098
+ * @returns Packages whose names match the patterns
2099
+ */
2100
+ function filterPackages(packages, patterns) {
2101
+ if (patterns.length === 0) return [...packages];
2102
+ return packages.filter((pkg) => isMatch(pkg.name ?? "", patterns));
2103
+ }
2033
2104
  // src/workflow/discovery/resolvePackageStableTag.ts
2034
2105
  /**
2035
2106
  * Resolve the latest stable Git tag for a package.
@@ -2136,70 +2207,81 @@ async function propagateDependencyUpdates(cwd, plans) {
2136
2207
  return plan;
2137
2208
  });
2138
2209
  }
2139
- // src/workflow/committing/isReleaseCommit.ts
2210
+ // src/workflow/analysis/readPackageHistory.ts
2140
2211
  /**
2141
- * Determine whether a commit represents a release or matches a release marker.
2212
+ * Yield commits from git history associated with a package.
2142
2213
  *
2143
- * Resolves string commit identifiers to parsed commit objects, checks if any
2144
- * associated trailer matches the `marker` predicate, and falls back to
2145
- * verifying exact tag matches for the `commit` hash.
2214
+ * Filters git commit history to yield only entries relevant to the target
2215
+ * `pkg` directory.
2146
2216
  *
2147
- * @param cwd Working directory path for Git commands
2148
- * @param commit Commit object, hash string, or nullish value
2149
- * @param marker Trailer key string or predicate function to evaluate
2150
- * @returns `true` if the commit is a release commit, otherwise `false`
2217
+ * @param cwd Path to the working directory for git commands
2218
+ * @param pkg Package configuration containing the target directory
2219
+ * @param options Options for parsing and filtering git history
2220
+ * @yields Commits belonging to the specified package
2151
2221
  */
2152
- async function isReleaseCommit(cwd, commit, marker = GIT_TRAILER_RELEASE_AGENT) {
2153
- if (typeof commit === "string") try {
2154
- commit = await getParsedGitCommit(cwd, commit, typeof marker === "string" ? [marker] : []);
2155
- } catch {
2156
- commit = null;
2157
- }
2158
- if (!commit) return false;
2159
- const predicate = typeof marker === "string" ? (trailer) => trailer.key === marker && !!trailer.value : marker;
2160
- if (commit.trailers.some(predicate)) return true;
2161
- return execGit(cwd, [
2162
- "describe",
2163
- "--tags",
2164
- "--exact-match",
2165
- commit.hash
2166
- ]).then(() => true).catch(() => false);
2222
+ async function* readPackageHistory(cwd, pkg, options = {}) {
2223
+ options = {
2224
+ ...options,
2225
+ filePath: options.filePath || pkg.location
2226
+ };
2227
+ for await (const commit of showParsedGitHistory(cwd, options)) if (isCommitForPackage(pkg, commit)) yield commit;
2167
2228
  }
2168
2229
  // src/workflow/analysis/sliceUnreleased.ts
2169
2230
  /**
2170
2231
  * Yield parsed commits from the workspace until a release commit is found.
2171
2232
  *
2172
- * Iterates through parsed commit history and yields unreleased commits in
2173
- * order. Stops processing upon reaching the first release commit.
2233
+ * Collects unreleased commits ahead of the most recent release commit and
2234
+ * yields them in order.
2174
2235
  *
2175
2236
  * @param cwd Path to the working directory
2176
2237
  * @param options Options for configuring Git history retrieval
2177
2238
  * @yields Parsed `Commit` objects up to the most recent release commit
2178
2239
  */
2179
2240
  async function* sliceUnreleased(cwd, options) {
2180
- for await (const commit of showParsedGitHistory(cwd, options)) {
2181
- if (await isReleaseCommit(cwd, commit, options?.marker)) break;
2182
- yield commit;
2183
- }
2241
+ const { history } = await collectUnreleased(cwd, options);
2242
+ yield* history;
2184
2243
  }
2185
- // src/workflow/analysis/streamPackageCommits.ts
2244
+ // src/workflow/committing/readReleaseFilterPatterns.ts
2186
2245
  /**
2187
- * Yield commits from git history associated with a package.
2246
+ * Read release filter patterns from a parsed commit.
2188
2247
  *
2189
- * Filters git commit history to stream only entries relevant to the target
2190
- * `pkg` directory.
2248
+ * Collects the release filter trailer values and splits them into individual
2249
+ * comma-separated filter patterns, unescaping the commas within patterns.
2250
+ * Returns `null` when the commit carries no release filter trailer, so
2251
+ * callers can treat it as a release of every package.
2252
+ *
2253
+ * @param commit Parsed commit object or nullish value
2254
+ * @returns Filter patterns carried by the trailer, or `null` when absent
2255
+ */
2256
+ function readReleaseFilterPatterns(commit) {
2257
+ if (!commit) return null;
2258
+ const values = commit.trailers.filter((trailer) => trailer.key === GIT_TRAILER_RELEASE_FILTER).map((trailer) => trailer.value);
2259
+ if (values.length === 0) return null;
2260
+ return values.flatMap((value) => value.split(/(?<!\\),/)).map((pattern) => pattern.trim()).map((pattern) => pattern.replaceAll("\\,", ",")).filter((pattern) => pattern.length > 0);
2261
+ }
2262
+ // src/workflow/analysis/sliceUnreleasedForPackage.ts
2263
+ /**
2264
+ * Yield unreleased commits from the history of a single package.
2265
+ *
2266
+ * Streams commits that touch the package files in historical order and stops
2267
+ * at the first release commit that released the package. Release commits
2268
+ * created by filtered runs that excluded the package are themselves yielded
2269
+ * as unreleased changes, so every package keeps its own release boundary
2270
+ * instead of sharing the latest repository-wide release commit.
2191
2271
  *
2192
2272
  * @param cwd Path to the working directory for git commands
2193
- * @param pkg Package configuration containing the target directory
2194
- * @param options Options for parsing and filtering git history
2195
- * @yields Commits belonging to the specified package
2273
+ * @param pkg Package whose files scope the commit history
2274
+ * @param options Options for configuring Git history retrieval
2275
+ * @yields Parsed commits up to the package's most recent release commit
2196
2276
  */
2197
- async function* streamPackageCommits(cwd, pkg, options = {}) {
2198
- options = {
2199
- ...options,
2200
- filePath: options.filePath || pkg.location
2201
- };
2202
- for await (const commit of showParsedGitHistory(cwd, options)) if (isCommitForPackage(pkg, commit)) yield commit;
2277
+ async function* sliceUnreleasedForPackage(cwd, pkg, options = {}) {
2278
+ for await (const commit of readPackageHistory(cwd, pkg, options)) {
2279
+ if (await isReleaseCommit(cwd, commit, options.marker)) {
2280
+ const patterns = readReleaseFilterPatterns(commit);
2281
+ if (patterns === null || isMatch(pkg.name ?? "", patterns)) break;
2282
+ }
2283
+ yield commit;
2284
+ }
2203
2285
  }
2204
2286
  // src/workflow/changelog/buildChangelog.ts
2205
2287
  var preset = await createPreset();
@@ -2355,7 +2437,7 @@ async function writeChangelog(cwd, plan) {
2355
2437
  }
2356
2438
  }
2357
2439
  // package.json
2358
- var version = "0.5.2";
2440
+ var version = "0.5.3";
2359
2441
  // src/workflow/committing/generateReleaseCommitMessage.ts
2360
2442
  var NOTABLE_TYPES = [
2361
2443
  "feat",
@@ -2653,6 +2735,6 @@ async function executeReleaseWorkflow(context, plugins) {
2653
2735
  printReleaseReport(context.logger, generateReleaseReport(context));
2654
2736
  }
2655
2737
  }
2656
- export { countGitHistory as $, getCurrentGitTag as A, isDefined as At, ensureGitUserConfig as B, deriveReleaseType as Bt, extractSemVer as C, isMatch as Ct, isGitTagConnected as D, execGit as Dt, isGitTagPointed as E, formatFile as Et, createGitTag as F, GIT_TRAILER_RELEASE_AGENT as Ft, mergeGitHistory as G, showParsedGitHistory as H, determineReleaseType as Ht, readGitFile as I, RELEASE_HOOK_NAMES as It, expandGitHistory as J, GIT_REL_FLAGS as K, resolveGitRepository as L, SEMVER_REGEX as Lt, ensureGitTag as M, ALL_FILES as Mt, isGitTagPresent as N, DEFAULT_CHANGELOG_FILE as Nt, getLatestGitTag as O, execCommand as Ot, deleteGitTag as P, DEV_NULL as Pt, isGitShallowRepository as Q, pushGitChanges as R, isStableVersion as Rt, iterateChangelogVersions as S, readJson as St, buildDependencyGraph as T, interpolate as Tt, showGitHistory as U, bumpVersion as Ut, getGitConfigValue as V, pickPriorityReleaseType as Vt, restoreFullGitHistory as W, extractVersionQualifier as Wt, isGitAncestor as X, resolveGitRevision as Y, withShallowLock as Z, resolvePackageTag as _, isSemVerGitTag as _t, HookPriority as a, parseGitCommit as at, verifyPackageTag as b, createPlugin as bt, writeChangelog as c, createGitCommit as ct, buildReleaseNotes as d, deriveTransitionReleases as dt, getCurrentGitCommit as et, buildChangelog as f, deriveChangeReleases as ft, propagateDependencyUpdates as g, sanitizePrereleaseLabel as gt, isReleaseCommit as h, resolveReleaseChannel as ht, HookManager as i, parseGitPrettyFormat as it, generateGitTagName as j, buildTrailerPattern as jt, getGitTagMessage as k, compact as kt, prependChangelog as l, getCurrentGitBranch as lt, sliceUnreleased as m, resolveVersionQualifier as mt, printReleaseReport as n, GIT_PRETTY_FIELD_SEPARATOR as nt, generateReleaseCommitMessage as o, TTLCache as ot, streamPackageCommits as p, isCommitForPackage as pt, detectGitRelationship as q, generateReleaseReport as r, GIT_PRETTY_FORMAT as rt, version as s, extractMentions as st, executeReleaseWorkflow as t, getParsedGitCommit as tt, extractPreviousVersion as u, promotePrereleaseVersions as ut, resolvePackageStableTag as v, isSemVer as vt, extractPlainText as w, isClass as wt, extractLatestVersion as x, writeJson as xt, discoverPackageTag as y, findReleaseRule as yt, getGitRemote as z, isSameReleaseCycle as zt };
2738
+ export { RELEASE_HOOK_NAMES as $, deriveChangeReleases as A, getParsedGitCommit as At, isReleaseCommit as B, readJson as Bt, extractLatestVersion as C, expandGitHistory as Ct, buildDependencyGraph as D, isGitShallowRepository as Dt, extractPlainText as E, withShallowLock as Et, pickPriorityReleaseType as F, TTLCache as Ft, isSemVer as G, execGit as Gt, resolveReleaseChannel as H, isClass as Ht, determineReleaseType as I, extractMentions as It, ALL_FILES as J, isDefined as Jt, findReleaseRule as K, execCommand as Kt, bumpVersion as L, createGitCommit as Lt, isStableVersion as M, GIT_PRETTY_FORMAT as Mt, isSameReleaseCycle as N, parseGitPrettyFormat as Nt, promotePrereleaseVersions as O, countGitHistory as Ot, deriveReleaseType as P, parseGitCommit as Pt, GIT_TRAILER_RELEASE_FILTER as Q, extractVersionQualifier as R, getCurrentGitBranch as Rt, verifyPackageTag as S, detectGitRelationship as St, extractSemVer as T, isGitAncestor as Tt, sanitizePrereleaseLabel as U, interpolate as Ut, resolveVersionQualifier as V, isMatch as Vt, isSemVerGitTag as W, formatFile as Wt, DEV_NULL as X, DEFAULT_CHANGELOG_FILE as Y, buildTrailerPattern as Yt, GIT_TRAILER_RELEASE_AGENT as Z, propagateDependencyUpdates as _, showParsedGitHistory as _t, HookPriority as a, getCurrentGitTag as at, filterPackages as b, mergeGitHistory as bt, writeChangelog as c, isGitTagPresent as ct, buildReleaseNotes as d, readGitFile as dt, SEMVER_REGEX as et, buildChangelog as f, resolveGitRepository as ft, readPackageHistory as g, getGitConfigValue as gt, sliceUnreleased as h, ensureGitUserConfig as ht, HookManager as i, getGitTagMessage as it, isCommitForPackage as j, GIT_PRETTY_FIELD_SEPARATOR as jt, deriveTransitionReleases as k, getCurrentGitCommit as kt, prependChangelog as l, deleteGitTag as lt, readReleaseFilterPatterns as m, getGitRemote as mt, printReleaseReport as n, isGitTagConnected as nt, generateReleaseCommitMessage as o, generateGitTagName as ot, sliceUnreleasedForPackage as p, pushGitChanges as pt, createPlugin as q, compact as qt, generateReleaseReport as r, getLatestGitTag as rt, version as s, ensureGitTag as st, executeReleaseWorkflow as t, isGitTagPointed as tt, extractPreviousVersion as u, createGitTag as ut, resolvePackageTag as v, showGitHistory as vt, iterateChangelogVersions as w, resolveGitRevision as wt, discoverPackageTag as x, GIT_REL_FLAGS as xt, resolvePackageStableTag as y, restoreFullGitHistory as yt, collectUnreleased as z, writeJson as zt };
2657
2739
 
2658
- //# sourceMappingURL=workflow-CxxvBV04.js.map
2740
+ //# sourceMappingURL=workflow-c9uKSARL.js.map