@reelout/core 0.1.1 → 0.5.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.
Files changed (138) hide show
  1. package/LICENSE +21 -0
  2. package/dist/analyzer.js +33 -0
  3. package/dist/analyzer.js.map +1 -0
  4. package/dist/builder.js +64 -0
  5. package/dist/builder.js.map +1 -0
  6. package/dist/changelog.js +63 -0
  7. package/dist/changelog.js.map +1 -0
  8. package/dist/formatError-BXNdyRfu.js +23 -0
  9. package/dist/formatError-BXNdyRfu.js.map +1 -0
  10. package/dist/index.js +225 -1
  11. package/dist/index.js.map +1 -0
  12. package/dist/types-la_KkjCS.js +1 -0
  13. package/dist/types.js +2 -0
  14. package/dist/workflow-CroJ6v4g.js +2736 -0
  15. package/dist/workflow-CroJ6v4g.js.map +1 -0
  16. package/package.json +35 -6
  17. package/src/analyzer.ts +59 -0
  18. package/src/builder.ts +116 -0
  19. package/src/cache/TTLCache.ts +100 -0
  20. package/src/cache/index.ts +4 -0
  21. package/src/changelog.ts +107 -0
  22. package/src/config/const.ts +104 -0
  23. package/src/config/createPlugin.ts +41 -0
  24. package/src/config/findReleaseRule.ts +26 -0
  25. package/src/config/index.ts +15 -0
  26. package/src/config/isSemVer.ts +31 -0
  27. package/src/config/isSemVerGitTag.ts +25 -0
  28. package/src/config/normalizeCommitFilter.ts +37 -0
  29. package/src/config/normalizeReleaseRule.ts +66 -0
  30. package/src/config/normalizeWorkspace.ts +34 -0
  31. package/src/config/resolvePlugin.ts +57 -0
  32. package/src/config/resolveReleaseChannel.ts +47 -0
  33. package/src/config/resolveVersionQualifier.ts +53 -0
  34. package/src/config/sanitizePrereleaseLabel.ts +18 -0
  35. package/src/git/branch/getCurrentGitBranch.ts +18 -0
  36. package/src/git/branch/index.ts +4 -0
  37. package/src/git/commit/createGitCommit.ts +29 -0
  38. package/src/git/commit/extractMentions.ts +34 -0
  39. package/src/git/commit/getCurrentGitCommit.ts +19 -0
  40. package/src/git/commit/getParsedGitCommit.ts +49 -0
  41. package/src/git/commit/index.ts +9 -0
  42. package/src/git/commit/parseGitCommit.ts +114 -0
  43. package/src/git/commit/parseGitPrettyFormat.ts +76 -0
  44. package/src/git/history/countGitHistory.ts +28 -0
  45. package/src/git/history/expandGitHistory.ts +112 -0
  46. package/src/git/history/index.ts +9 -0
  47. package/src/git/history/mergeGitHistory.ts +76 -0
  48. package/src/git/history/restoreFullGitHistory.ts +19 -0
  49. package/src/git/history/showGitHistory.ts +80 -0
  50. package/src/git/history/showParsedGitHistory.ts +28 -0
  51. package/src/git/index.ts +9 -0
  52. package/src/git/repository/ensureGitUserConfig.ts +50 -0
  53. package/src/git/repository/getGitConfigValue.ts +27 -0
  54. package/src/git/repository/getGitRemote.ts +20 -0
  55. package/src/git/repository/index.ts +10 -0
  56. package/src/git/repository/isGitShallowRepository.ts +21 -0
  57. package/src/git/repository/pushGitChanges.ts +26 -0
  58. package/src/git/repository/resolveGitRepository.ts +40 -0
  59. package/src/git/repository/withShallowLock.ts +62 -0
  60. package/src/git/revision/detectGitRelationship.ts +43 -0
  61. package/src/git/revision/index.ts +7 -0
  62. package/src/git/revision/isGitAncestor.ts +33 -0
  63. package/src/git/revision/readGitFile.ts +29 -0
  64. package/src/git/revision/resolveGitRevision.ts +23 -0
  65. package/src/git/tag/createGitTag.ts +25 -0
  66. package/src/git/tag/deleteGitTag.ts +17 -0
  67. package/src/git/tag/ensureGitTag.ts +63 -0
  68. package/src/git/tag/generateGitTagName.ts +43 -0
  69. package/src/git/tag/getCurrentGitTag.ts +23 -0
  70. package/src/git/tag/getGitTagMessage.ts +35 -0
  71. package/src/git/tag/getLatestGitTag.ts +22 -0
  72. package/src/git/tag/index.ts +13 -0
  73. package/src/git/tag/isGitTagConnected.ts +33 -0
  74. package/src/git/tag/isGitTagPointed.ts +38 -0
  75. package/src/git/tag/isGitTagPresent.ts +17 -0
  76. package/src/index.ts +9 -2
  77. package/src/plugin/HookManager.ts +128 -0
  78. package/src/plugin/index.ts +4 -0
  79. package/src/types.ts +259 -0
  80. package/src/util/buildTrailerPattern.ts +20 -0
  81. package/src/util/compact.ts +14 -0
  82. package/src/util/execCommand.ts +196 -0
  83. package/src/util/execGit.ts +27 -0
  84. package/src/util/formatError.ts +21 -0
  85. package/src/util/formatFile.ts +41 -0
  86. package/src/util/index.ts +19 -0
  87. package/src/util/interpolate.ts +141 -0
  88. package/src/util/isCI.ts +18 -0
  89. package/src/util/isClass.ts +34 -0
  90. package/src/util/isDefined.ts +12 -0
  91. package/src/util/isMatch.ts +43 -0
  92. package/src/util/isQuietEnvironment.ts +35 -0
  93. package/src/util/isTruthyString.ts +19 -0
  94. package/src/util/readJson.ts +47 -0
  95. package/src/util/unique.ts +26 -0
  96. package/src/util/writeJson.ts +28 -0
  97. package/src/workflow/analysis/deriveChangeReleases.ts +76 -0
  98. package/src/workflow/analysis/deriveTransitionReleases.ts +134 -0
  99. package/src/workflow/analysis/index.ts +10 -0
  100. package/src/workflow/analysis/isCommitForPackage.ts +23 -0
  101. package/src/workflow/analysis/promotePrereleaseVersions.ts +51 -0
  102. package/src/workflow/analysis/propagateDependencyUpdates.ts +71 -0
  103. package/src/workflow/analysis/sliceUnreleased.ts +36 -0
  104. package/src/workflow/analysis/streamPackageCommits.ts +34 -0
  105. package/src/workflow/changelog/buildChangelog.ts +79 -0
  106. package/src/workflow/changelog/buildReleaseNotes.ts +50 -0
  107. package/src/workflow/changelog/conventional-changelog-conventionalcommits.d.ts +7 -0
  108. package/src/workflow/changelog/extractLatestVersion.ts +22 -0
  109. package/src/workflow/changelog/extractPlainText.ts +38 -0
  110. package/src/workflow/changelog/extractPreviousVersion.ts +77 -0
  111. package/src/workflow/changelog/extractSemVer.ts +33 -0
  112. package/src/workflow/changelog/index.ts +12 -0
  113. package/src/workflow/changelog/iterateChangelogVersions.ts +70 -0
  114. package/src/workflow/changelog/prependChangelog.ts +59 -0
  115. package/src/workflow/changelog/writeChangelog.ts +27 -0
  116. package/src/workflow/committing/generateReleaseCommitMessage.ts +121 -0
  117. package/src/workflow/committing/index.ts +5 -0
  118. package/src/workflow/committing/isReleaseCommit.ts +56 -0
  119. package/src/workflow/discovery/buildDependencyGraph.ts +43 -0
  120. package/src/workflow/discovery/discoverPackageTag.ts +98 -0
  121. package/src/workflow/discovery/index.ts +9 -0
  122. package/src/workflow/discovery/resolvePackageStableTag.ts +88 -0
  123. package/src/workflow/discovery/resolvePackageTag.ts +45 -0
  124. package/src/workflow/discovery/sortPackages.ts +75 -0
  125. package/src/workflow/discovery/verifyPackageTag.ts +49 -0
  126. package/src/workflow/executeReleaseWorkflow.ts +130 -0
  127. package/src/workflow/index.ts +10 -0
  128. package/src/workflow/report/generateReleaseReport.ts +54 -0
  129. package/src/workflow/report/index.ts +5 -0
  130. package/src/workflow/report/printReleaseReport.ts +97 -0
  131. package/src/workflow/versioning/bumpVersion.ts +76 -0
  132. package/src/workflow/versioning/deriveReleaseType.ts +33 -0
  133. package/src/workflow/versioning/determineReleaseType.ts +35 -0
  134. package/src/workflow/versioning/extractVersionQualifier.ts +29 -0
  135. package/src/workflow/versioning/index.ts +10 -0
  136. package/src/workflow/versioning/isSameReleaseCycle.ts +36 -0
  137. package/src/workflow/versioning/isStableVersion.ts +31 -0
  138. package/src/workflow/versioning/pickPriorityReleaseType.ts +27 -0
@@ -0,0 +1,121 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { GIT_TRAILER_RELEASE_AGENT } from '#config'
5
+ import { mergeGitHistory } from '#git'
6
+ import type { GitCommit, GitCommitType, ReleasePlan } from '#types'
7
+ import { version } from '../../../package.json'
8
+
9
+ const NOTABLE_TYPES: readonly GitCommitType[] = [
10
+ 'feat',
11
+ 'fix',
12
+ 'perf',
13
+ 'refactor',
14
+ 'revert',
15
+ ]
16
+
17
+ /**
18
+ * Generate a formatted release commit message based on release plans and
19
+ * custom trailers.
20
+ *
21
+ * Compiles package version updates and included commit logs into a standardized
22
+ * conventional commit message body, appending configured release agent and
23
+ * custom trailers. Returns `null` if no valid release subject can be derived.
24
+ *
25
+ * @param cwd The working directory path
26
+ * @param plans Readonly array of release plans containing package changes and commit history
27
+ * @param trailers Optional record of custom git trailers to append to the commit
28
+ * @returns The formatted release commit message string or `null` if the subject is empty
29
+ * @example
30
+ * ```
31
+ * chore: release pkg-a@2.1.0, pkg-b@1.0.4
32
+ *
33
+ * Version Updates:
34
+ * - pkg-a: 2.0.0 → 2.1.0
35
+ * - pkg-b: 1.0.3 → 1.0.4
36
+ *
37
+ * Notable Changes:
38
+ * - feat(pkg-a): support custom plugin entrypoints (#210)
39
+ * - fix(pkg-b): correct minor typography bug in help text (#212)
40
+ *
41
+ * Release-Mode: Deferred
42
+ * ```
43
+ */
44
+ export async function generateReleaseCommitMessage(
45
+ cwd: string,
46
+ plans: readonly ReleasePlan[],
47
+ trailers: Readonly<Record<string, string | number | null | undefined>> = {}
48
+ ): Promise<string | null> {
49
+ const standalone = plans.length === 1
50
+
51
+ trailers = {
52
+ [GIT_TRAILER_RELEASE_AGENT]: `ReelOut/${import.meta.env.MODE === 'test' ? '0.0.0' : /* istanbul ignore next */ version}`,
53
+ ...trailers,
54
+ }
55
+
56
+ plans = plans
57
+ .filter((plan) => plan.release?.tag?.name)
58
+ .toSorted((a, b) => {
59
+ if (a.package.entry) return -1
60
+ if (b.package.entry) return 1
61
+ /* istanbul ignore next */
62
+ return (a.package.name ?? '').localeCompare(b.package.name ?? '')
63
+ })
64
+
65
+ let subject: string | null | undefined
66
+
67
+ if (plans.length === 1) {
68
+ subject = standalone
69
+ ? plans[0]?.release?.version
70
+ : plans[0]?.release?.tag?.name
71
+ } else if (plans.length >= 2 && plans.length <= 3) {
72
+ subject = plans.map((plan) => plan.release?.tag?.name).join(', ')
73
+ } else if (plans.length > 3) {
74
+ subject = `${plans.length} packages (${plans
75
+ .slice(0, 2)
76
+ .map((plan) => plan.release?.tag?.name)
77
+ .join(', ')}, +${plans.length - 2} more)`
78
+ }
79
+
80
+ if (!subject) {
81
+ return null
82
+ }
83
+
84
+ const packages = plans.map((plan) => {
85
+ return `- ${plan.package.name || plan.package.location}: ${plan.package.version} → ${plan.release?.version}`
86
+ })
87
+
88
+ const commits = (
89
+ await plans.reduce(
90
+ async (acc, plan) => mergeGitHistory(cwd, await acc, plan.history),
91
+ Promise.resolve<GitCommit[]>([])
92
+ )
93
+ )
94
+ .filter((commit) => {
95
+ const isNotableType = commit.type && NOTABLE_TYPES.includes(commit.type)
96
+ const isBreaking = commit.notes.length > 0
97
+
98
+ return isNotableType || isBreaking
99
+ })
100
+ .toReversed()
101
+ .map(({ header }) => `- ${header}`)
102
+
103
+ return [
104
+ `chore: release ${subject}`,
105
+
106
+ packages.length >= 2
107
+ ? ['Version Updates:', ...packages].join('\n')
108
+ : undefined,
109
+
110
+ commits.length > 0
111
+ ? ['Notable Changes:', ...commits].join('\n')
112
+ : undefined,
113
+
114
+ Object.entries(trailers)
115
+ .map(([key, value]) => (key && value != null ? `${key}: ${value}` : ''))
116
+ .filter(Boolean)
117
+ .join('\n'),
118
+ ]
119
+ .filter(Boolean)
120
+ .join('\n\n')
121
+ }
@@ -0,0 +1,5 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ export * from './generateReleaseCommitMessage'
5
+ export * from './isReleaseCommit'
@@ -0,0 +1,56 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { GIT_TRAILER_RELEASE_AGENT } from '#config'
5
+ import { getParsedGitCommit } from '#git'
6
+ import type { GitCommit, GitCommitTrailer } from '#types'
7
+ import { execGit } from '#util'
8
+
9
+ export type ReleaseMarker = string | ((trailer: GitCommitTrailer) => boolean)
10
+
11
+ /**
12
+ * Determine whether a commit represents a release or matches a release marker.
13
+ *
14
+ * Resolves string commit identifiers to parsed commit objects, checks if any
15
+ * associated trailer matches the `marker` predicate, and falls back to
16
+ * verifying exact tag matches for the `commit` hash.
17
+ *
18
+ * @param cwd Working directory path for Git commands
19
+ * @param commit Commit object, hash string, or nullish value
20
+ * @param marker Trailer key string or predicate function to evaluate
21
+ * @returns `true` if the commit is a release commit, otherwise `false`
22
+ */
23
+ export async function isReleaseCommit(
24
+ cwd: string,
25
+ commit: GitCommit | string | null | undefined,
26
+ marker: ReleaseMarker = GIT_TRAILER_RELEASE_AGENT
27
+ ): Promise<boolean> {
28
+ if (typeof commit === 'string') {
29
+ try {
30
+ commit = await getParsedGitCommit(
31
+ cwd,
32
+ commit,
33
+ typeof marker === 'string' ? [marker] : []
34
+ )
35
+ } catch {
36
+ commit = null
37
+ }
38
+ }
39
+
40
+ if (!commit) {
41
+ return false
42
+ }
43
+
44
+ const predicate =
45
+ typeof marker === 'string'
46
+ ? (trailer: GitCommitTrailer) => trailer.key === marker && !!trailer.value
47
+ : marker
48
+
49
+ if (commit.trailers.some(predicate)) {
50
+ return true
51
+ }
52
+
53
+ return execGit(cwd, ['describe', '--tags', '--exact-match', commit.hash])
54
+ .then(() => true)
55
+ .catch(() => false)
56
+ }
@@ -0,0 +1,43 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { ReleasePlan } from '#types'
5
+
6
+ export type DependencyGraph = Map<string, Set<ReleasePlan>>
7
+
8
+ /**
9
+ * Build a dependency graph mapping package names to dependent release plans.
10
+ *
11
+ * Each key is a package name and the value is a set of `ReleasePlan`s that
12
+ * list that package as a dependency.
13
+ *
14
+ * @param plans Array of release plans to analyze
15
+ * @returns Dependency graph mapping package name -> set of dependent plans
16
+ */
17
+ export function buildDependencyGraph(
18
+ plans: readonly ReleasePlan[]
19
+ ): DependencyGraph {
20
+ const graph = new Map<string, Set<ReleasePlan>>()
21
+
22
+ const packageNames = new Set(
23
+ plans
24
+ .map((plan) => plan.package.name)
25
+ .filter((name): name is string => !!name)
26
+ )
27
+
28
+ for (const plan of plans) {
29
+ for (const depName of plan.package.dependencies) {
30
+ let set = graph.get(depName)
31
+
32
+ if (!set && packageNames.has(depName)) {
33
+ graph.set(depName, (set = new Set()))
34
+ }
35
+
36
+ if (set) {
37
+ set.add(plan)
38
+ }
39
+ }
40
+ }
41
+
42
+ return graph
43
+ }
@@ -0,0 +1,98 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { DEFAULT_CHANGELOG_FILE } from '#config'
5
+ import {
6
+ generateGitTagName,
7
+ getGitTagMessage,
8
+ readGitFile,
9
+ resolveGitRevision,
10
+ } from '#git'
11
+ import type { Package, Tag } from '#types'
12
+ import { readFile } from 'node:fs/promises'
13
+ import path from 'node:path'
14
+ import { extractLatestVersion } from '../changelog/extractLatestVersion'
15
+ import { verifyPackageTag } from './verifyPackageTag'
16
+
17
+ /**
18
+ * Discover and validate the Git tag for a package.
19
+ *
20
+ * Returns the existing tag if already present on the `pkg` object. Resolves
21
+ * the local changelog file path, extracts the current version, and generates
22
+ * the expected Git tag name. Verifies the tag against the repository and
23
+ * ensures its historical changelog version matches the current local version.
24
+ *
25
+ * @param cwd The current working directory
26
+ * @param pkg The package configuration object
27
+ * @returns The validated `Tag` object or null if validation fails
28
+ */
29
+ export async function discoverPackageTag(
30
+ cwd: string,
31
+ pkg: Package
32
+ ): Promise<Tag | null> {
33
+ if (pkg.tag) {
34
+ return pkg.tag
35
+ }
36
+
37
+ const changelogFile = pkg.changelogFile || DEFAULT_CHANGELOG_FILE
38
+
39
+ const changelogFilePath = path.resolve(cwd, pkg.location, changelogFile)
40
+
41
+ let localChangelogContent: string | null | undefined
42
+
43
+ try {
44
+ localChangelogContent = await readFile(changelogFilePath, 'utf-8')
45
+ } catch {}
46
+
47
+ if (!localChangelogContent) {
48
+ return null
49
+ }
50
+
51
+ const currentVersion = extractLatestVersion(localChangelogContent)
52
+
53
+ if (!currentVersion) {
54
+ return null
55
+ }
56
+
57
+ let expectedTagName: string | null | undefined
58
+
59
+ try {
60
+ expectedTagName = generateGitTagName(pkg.entry, pkg.name, currentVersion)
61
+ } catch {}
62
+
63
+ if (!expectedTagName) {
64
+ return null
65
+ }
66
+
67
+ if (!(await verifyPackageTag(cwd, pkg, expectedTagName))) {
68
+ return null
69
+ }
70
+
71
+ const tagRef = `refs/tags/${expectedTagName}`
72
+
73
+ const historicalChangelogContent = await readGitFile(
74
+ cwd,
75
+ await resolveGitRevision(cwd, tagRef),
76
+ path.relative(cwd, changelogFilePath)
77
+ )
78
+
79
+ if (!historicalChangelogContent) {
80
+ return null
81
+ }
82
+
83
+ const historicalChangelogVersion = extractLatestVersion(
84
+ historicalChangelogContent
85
+ )
86
+
87
+ if (
88
+ !historicalChangelogVersion ||
89
+ historicalChangelogVersion !== currentVersion
90
+ ) {
91
+ return null
92
+ }
93
+
94
+ return {
95
+ name: expectedTagName,
96
+ message: await getGitTagMessage(cwd, expectedTagName),
97
+ }
98
+ }
@@ -0,0 +1,9 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ export * from './buildDependencyGraph'
5
+ export * from './discoverPackageTag'
6
+ export * from './resolvePackageStableTag'
7
+ export * from './resolvePackageTag'
8
+ export * from './sortPackages'
9
+ export * from './verifyPackageTag'
@@ -0,0 +1,88 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { DEFAULT_CHANGELOG_FILE } from '#config'
5
+ import { generateGitTagName, getGitTagMessage } from '#git'
6
+ import type { Package, Tag } from '#types'
7
+ import assert from 'node:assert'
8
+ import { readFile } from 'node:fs/promises'
9
+ import path from 'node:path'
10
+ import semver from 'semver'
11
+ import { iterateChangelogVersions } from '../changelog/iterateChangelogVersions'
12
+ import { verifyPackageTag } from './verifyPackageTag'
13
+
14
+ /**
15
+ * Resolve the latest stable Git tag for a package.
16
+ *
17
+ * Reads changelog release versions for `pkg` and verifies strict descending
18
+ * semver order. Ignores prerelease versions unless transitioning across major
19
+ * or prerelease boundaries, and verifies that the matching Git tag exists.
20
+ *
21
+ * @param cwd Absolute path to the root working directory
22
+ * @param pkg Package configuration object
23
+ * @returns Verified tag metadata object or `null` if no stable tag is resolved
24
+ * @throws If a version is invalid, versions are not in strict descending
25
+ * order, or the corresponding Git tag is missing
26
+ */
27
+ export async function resolvePackageStableTag(
28
+ cwd: string,
29
+ pkg: Package
30
+ ): Promise<Tag | null> {
31
+ const changelogFile = pkg.changelogFile || DEFAULT_CHANGELOG_FILE
32
+
33
+ const changelogFilePath = path.resolve(cwd, pkg.location, changelogFile)
34
+
35
+ let changelogContent: string
36
+
37
+ try {
38
+ changelogContent = await readFile(changelogFilePath, 'utf-8')
39
+ } catch (error: unknown) {
40
+ /* istanbul ignore else */
41
+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') {
42
+ return null
43
+ }
44
+
45
+ /* istanbul ignore next */
46
+ throw error
47
+ }
48
+
49
+ let precedingVersion: semver.SemVer | null = null
50
+
51
+ for (const version of iterateChangelogVersions(changelogContent)) {
52
+ const currentVersion = semver.parse(version)
53
+
54
+ assert(
55
+ currentVersion,
56
+ `Version "${version}" is not a valid semantic version.`
57
+ )
58
+
59
+ if (precedingVersion && semver.gte(currentVersion, precedingVersion)) {
60
+ throw new Error(
61
+ `Version "${version}" must be strictly lower than preceding version "${precedingVersion.raw}".`
62
+ )
63
+ }
64
+
65
+ if (
66
+ !semver.prerelease(currentVersion) &&
67
+ (currentVersion.major >= 1 ||
68
+ (precedingVersion && semver.prerelease(precedingVersion)))
69
+ ) {
70
+ const tagName = generateGitTagName(pkg.entry, pkg.name, version)
71
+
72
+ if (!(await verifyPackageTag(cwd, pkg, tagName))) {
73
+ throw new Error(
74
+ `Git tag "${tagName}" is not associated with package "${pkg.name ?? ''}" in directory "${pkg.location}".`
75
+ )
76
+ }
77
+
78
+ return {
79
+ name: tagName,
80
+ message: await getGitTagMessage(cwd, tagName),
81
+ }
82
+ }
83
+
84
+ precedingVersion = currentVersion
85
+ }
86
+
87
+ return null
88
+ }
@@ -0,0 +1,45 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { generateGitTagName, getGitTagMessage } from '#git'
5
+ import type { Package, Tag } from '#types'
6
+ import { verifyPackageTag } from './verifyPackageTag'
7
+
8
+ /**
9
+ * Resolve the release tag for a single package version.
10
+ *
11
+ * Returns the cached `pkg.tag` immediately if it already exists. Generates an
12
+ * expected tag name from the package metadata and verifies its integrity using
13
+ * `verifyPackageTag`.
14
+ *
15
+ * @param cwd Repository working directory
16
+ * @param pkg Package descriptor containing version and location context
17
+ * @returns A promise resolving to the tag metadata or null when not found
18
+ */
19
+ export async function resolvePackageTag(
20
+ cwd: string,
21
+ pkg: Package
22
+ ): Promise<Tag | null> {
23
+ if (pkg.tag) {
24
+ return pkg.tag
25
+ }
26
+
27
+ let expectedTagName: string | null | undefined
28
+
29
+ try {
30
+ expectedTagName = generateGitTagName(pkg.entry, pkg.name, pkg.version)
31
+ } catch {}
32
+
33
+ if (!expectedTagName) {
34
+ return null
35
+ }
36
+
37
+ if (await verifyPackageTag(cwd, pkg, expectedTagName)) {
38
+ return {
39
+ name: expectedTagName,
40
+ message: await getGitTagMessage(cwd, expectedTagName),
41
+ }
42
+ }
43
+
44
+ return null
45
+ }
@@ -0,0 +1,75 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { Package } from '#types'
5
+
6
+ interface PackageNode {
7
+ package: Package
8
+ level: number
9
+ }
10
+
11
+ /**
12
+ * Sort workspace packages topologically based on their dependency graphs.
13
+ *
14
+ * Deepest dependents are placed first in the resulting array, ensuring that
15
+ * a package always precedes its own dependencies. Ties and circular dependencies
16
+ * are resolved deterministically using an alphabetical sort on the package directory (`dir`).
17
+ *
18
+ * @param packages The workspace packages to sort.
19
+ * @returns A new array of packages sorted by dependency depth and directory path.
20
+ */
21
+ export function sortPackages(packages: readonly Package[]): Package[] {
22
+ const packageNodes: PackageNode[] = []
23
+ const packageMap = new Map<string, PackageNode>()
24
+
25
+ for (const pkg of packages.toSorted((a, b) =>
26
+ a.location.localeCompare(b.location)
27
+ )) {
28
+ const node: PackageNode = {
29
+ package: pkg,
30
+ level: -1,
31
+ }
32
+
33
+ packageNodes.push(node)
34
+
35
+ if (pkg.name) {
36
+ packageMap.set(pkg.name, node)
37
+ }
38
+ }
39
+
40
+ for (const node of packageNodes) {
41
+ visit(node)
42
+ }
43
+
44
+ function visit(
45
+ node: PackageNode,
46
+ level = 0,
47
+ visited = new Set<PackageNode>()
48
+ ): void {
49
+ if (node.level >= level) {
50
+ return
51
+ }
52
+
53
+ if (visited.has(node)) {
54
+ return
55
+ }
56
+
57
+ visited.add(node)
58
+
59
+ for (const depName of node.package.dependencies) {
60
+ const depNode = packageMap.get(depName)
61
+
62
+ if (depNode && depNode !== node) {
63
+ visit(depNode, level + 1, visited)
64
+ }
65
+ }
66
+
67
+ node.level = level
68
+ }
69
+
70
+ const sorted = packageNodes
71
+ .toSorted((a, b) => b.level - a.level)
72
+ .map((node) => node.package)
73
+
74
+ return sorted
75
+ }
@@ -0,0 +1,49 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import {
5
+ ensureGitTag,
6
+ expandGitHistory,
7
+ getParsedGitCommit,
8
+ isGitTagConnected,
9
+ } from '#git'
10
+ import type { GitCommit, Package } from '#types'
11
+ import { isCommitForPackage } from '../analysis/isCommitForPackage'
12
+
13
+ /**
14
+ * Verify a Git tag against package specifications and repository history.
15
+ *
16
+ * Ensures the target tag exists locally before parsing its commit data. Rejects
17
+ * tags that do not target a commit matching the specified `pkg`. Expands the
18
+ * history graph up to the tag reference before verifying structural connectivity.
19
+ *
20
+ * @param cwd Repository working directory path
21
+ * @param pkg Package descriptor containing version and location context
22
+ * @param tagName Name of the Git tag to verify
23
+ * @returns True if the tag is valid and connected; otherwise, false
24
+ */
25
+ export async function verifyPackageTag(
26
+ cwd: string,
27
+ pkg: Package,
28
+ tagName: string
29
+ ): Promise<boolean> {
30
+ await ensureGitTag(cwd, tagName)
31
+
32
+ const tagRef = `refs/tags/${tagName}`
33
+
34
+ let tagCommit: GitCommit
35
+
36
+ try {
37
+ tagCommit = await getParsedGitCommit(cwd, tagRef)
38
+ } catch {
39
+ return false
40
+ }
41
+
42
+ if (!isCommitForPackage(pkg, tagCommit)) {
43
+ return false
44
+ }
45
+
46
+ await expandGitHistory(cwd, { until: tagRef })
47
+
48
+ return isGitTagConnected(cwd, tagName)
49
+ }