@reelout/core 0.7.0 → 0.9.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.
@@ -5,126 +5,272 @@ import { RELEASE_HOOK_NAMES } from '#config'
5
5
  import { HookManager, type HookHandler } from '#plugin'
6
6
  import type { ReleaseContext, ReleaseHookName, ReleasePlugin } from '#types'
7
7
  import { colors } from 'consola/utils'
8
- import { generateReleaseReport, printReleaseReport } from './report'
8
+ import {
9
+ appendReleaseReportSummary,
10
+ generateReleaseReport,
11
+ printReleaseReport,
12
+ printReleaseReportAnnotation,
13
+ } from './report'
14
+
15
+ /** Failure of a `finalize` handler, collected for the post-report warning. */
16
+ interface FinalizeFailure {
17
+ plugin: string
18
+ error: unknown
19
+ }
20
+
21
+ interface PluginHookRegistration {
22
+ /** Hook name the plugin handler registers under. */
23
+ hookName: ReleaseHookName
24
+ /** Plugin owning the hook entry. */
25
+ plugin: ReleasePlugin
26
+ /**
27
+ * Handle a thrown handler error instead of rethrowing it.
28
+ *
29
+ * When provided, the wrapper passes a thrown error to this callback and
30
+ * continues the middleware chain, so later handlers still run.
31
+ */
32
+ onHandlerError?: (error: unknown) => void
33
+ }
34
+
35
+ /**
36
+ * Register a plugin's hook handler on the workflow hook manager.
37
+ *
38
+ * Normalizes the plugin's hook entry into a handler and priority, wraps the
39
+ * handler in shared timing and logging middleware, and registers it under
40
+ * the registration's hook name. When `onHandlerError` is provided, a thrown
41
+ * handler error is passed to it and the middleware chain continues so later
42
+ * handlers still run; without it the wrapper attributes the failure to the
43
+ * current hook and plugin on `context.outcome` before rethrowing.
44
+ *
45
+ * @param manager Hook manager receiving the wrapped handler
46
+ * @param registration Plugin hook registration carrying the error strategy
47
+ */
48
+ function registerPluginHook(
49
+ manager: HookManager<Record<ReleaseHookName, HookHandler<ReleaseContext>>>,
50
+ registration: PluginHookRegistration
51
+ ): void {
52
+ const { hookName, plugin } = registration
53
+
54
+ let hook = plugin[hookName]
55
+
56
+ if (typeof hook === 'function') {
57
+ hook = { handler: hook }
58
+ }
59
+
60
+ const handler = hook?.handler
61
+ const priority = hook?.priority
62
+
63
+ if (!handler) return
64
+
65
+ const isSilent = import.meta.env.MODE === 'test'
66
+
67
+ manager.on(
68
+ hookName,
69
+ async (context, next) => {
70
+ const current = {
71
+ hook: hookName,
72
+ plugin: plugin.name,
73
+ }
74
+
75
+ const label = `${colors.gray(`[${current.hook}]`)} ${current.plugin}`
76
+ let startedLogging = false
77
+ let hasError = false
78
+
79
+ if (!isSilent) {
80
+ startedLogging = true
81
+ context.logger.start(label)
82
+ }
83
+
84
+ const currentFrame = { startTime: performance.now() }
85
+ const nextFrame = { duration: 0 }
86
+
87
+ const runNext = async () => {
88
+ const startTime = performance.now()
89
+
90
+ try {
91
+ return await next(context)
92
+ } finally {
93
+ nextFrame.duration = performance.now() - startTime
94
+ }
95
+ }
96
+
97
+ try {
98
+ return await handler.call(plugin, context, runNext)
99
+ } catch (err) {
100
+ hasError = true
101
+
102
+ if (registration.onHandlerError) {
103
+ registration.onHandlerError(err)
104
+ return await runNext()
105
+ }
106
+
107
+ context.outcome ??= {
108
+ status: 'failure',
109
+ error: err,
110
+ phase: current,
111
+ }
112
+
113
+ throw err
114
+ } finally {
115
+ if (startedLogging) {
116
+ const duration =
117
+ performance.now() - currentFrame.startTime - nextFrame.duration
118
+ const color = duration >= 5000 ? colors.yellow : colors.cyan
119
+ const message = [
120
+ label,
121
+ color(`${(duration / 1000).toFixed(2)}s`),
122
+ ].join(' ')
123
+
124
+ if (hasError) {
125
+ context.logger.error(message)
126
+ } else {
127
+ context.logger.success(message)
128
+ }
129
+ }
130
+ }
131
+ },
132
+ priority
133
+ )
134
+ }
135
+
136
+ /**
137
+ * Throw a cancellation error when the context abort signal has fired.
138
+ *
139
+ * Wraps the underlying `AbortError` so the workflow reports a readable
140
+ * cancellation instead of a bare DOM exception.
141
+ *
142
+ * @param context Release execution context carrying the optional abort signal
143
+ * @throws If the context abort signal has already fired
144
+ */
145
+ function throwIfCancelled(context: ReleaseContext): void {
146
+ const signal = context.signal
147
+
148
+ if (!signal?.aborted) return
149
+
150
+ try {
151
+ signal.throwIfAborted()
152
+ } catch (err) {
153
+ throw new Error('Release cancelled.', { cause: err })
154
+ }
155
+ }
9
156
 
10
157
  /**
11
158
  * Execute the complete release workflow across all configured plugins.
12
159
  *
13
160
  * Runs each lifecycle phase sequentially, dispatching plugin hooks in onion
14
- * order based on declared priority. Logs hook execution timing for non-silent
15
- * runs and prints a release report upon completion or failure.
161
+ * order based on declared priority, and checks the abort signal before each
162
+ * phase. Emits the `finalize` hook on every terminal outcome so plugins can
163
+ * send notifications and clean up: when a phase hook throws, plugin rollbacks
164
+ * run while the error unwinds, then every `finalize` handler runs with the
165
+ * failure recorded on `context.outcome`. When a `finalize` handler throws,
166
+ * the remaining handlers still run: on a failed workflow each failure is
167
+ * logged as a warning after the report, while on a successful workflow the
168
+ * first failure fails the release. Failures in `finalize` never mask the
169
+ * original workflow error.
16
170
  *
17
171
  * @param context Release execution context containing runtime options and logger
18
172
  * @param plugins List of release plugins to execute
19
- * @returns Promise that resolves when all workflow phases complete
20
- * @throws If any lifecycle hook execution fails
173
+ * @returns Promise that resolves when all phases and `finalize` handlers
174
+ * complete
175
+ * @throws If a lifecycle hook fails, the workflow is cancelled, or a finalize
176
+ * handler fails on an otherwise successful workflow
21
177
  */
22
178
  export async function executeReleaseWorkflow(
23
179
  context: ReleaseContext,
24
180
  plugins: readonly ReleasePlugin[]
25
181
  ): Promise<void> {
26
- const isSilent = import.meta.env.MODE === 'test'
182
+ const phaseHookNames = RELEASE_HOOK_NAMES.filter(
183
+ (name) => name !== 'finalize'
184
+ )
27
185
 
28
- try {
29
- context.status = null
30
- context.error = null
186
+ context.outcome = null
31
187
 
32
- const manager = new HookManager<
33
- Record<ReleaseHookName, HookHandler<ReleaseContext>>
34
- >()
188
+ const manager = new HookManager<
189
+ Record<ReleaseHookName, HookHandler<ReleaseContext>>
190
+ >()
35
191
 
36
- for (const hookName of RELEASE_HOOK_NAMES) {
37
- for (const plugin of plugins) {
38
- let hook = plugin[hookName]
192
+ for (const hookName of phaseHookNames) {
193
+ for (const plugin of plugins) {
194
+ registerPluginHook(manager, { hookName, plugin })
195
+ }
196
+ }
39
197
 
40
- if (typeof hook === 'function') {
41
- hook = { handler: hook }
42
- }
198
+ const dispatch = async (
199
+ index: number,
200
+ context: ReleaseContext
201
+ ): Promise<void> => {
202
+ const hook = phaseHookNames[index]
43
203
 
44
- const handler = hook?.handler
45
- const priority = hook?.priority
46
-
47
- if (handler) {
48
- manager.on(
49
- hookName,
50
- async (context, next) => {
51
- const current = (context.phase = {
52
- hook: hookName,
53
- plugin: plugin.name,
54
- })
55
-
56
- const label = `${colors.gray(`[${current.hook}]`)} ${current.plugin}`
57
- let startedLogging = false
58
- let hasError = false
59
-
60
- if (!isSilent) {
61
- startedLogging = true
62
- context.logger.start(label)
63
- }
64
-
65
- const currentFrame = { startTime: performance.now() }
66
- const nextFrame = { duration: 0 }
67
-
68
- try {
69
- return await handler.call(plugin, context, async () => {
70
- const startTime = performance.now()
71
-
72
- try {
73
- return await next(context)
74
- } finally {
75
- nextFrame.duration = performance.now() - startTime
76
- }
77
- })
78
- } catch (err) {
79
- hasError = true
80
- throw err
81
- } finally {
82
- if (startedLogging) {
83
- const duration =
84
- performance.now() -
85
- currentFrame.startTime -
86
- nextFrame.duration
87
- const color = duration >= 5000 ? colors.yellow : colors.cyan
88
- const message = [
89
- label,
90
- color(`${(duration / 1000).toFixed(2)}s`),
91
- ].join(' ')
92
-
93
- if (hasError) {
94
- context.logger.error(message)
95
- } else {
96
- context.logger.success(message)
97
- }
98
- }
99
- }
100
- },
101
- priority
102
- )
103
- }
104
- }
204
+ if (!hook) return
205
+
206
+ throwIfCancelled(context)
207
+
208
+ return await manager.emit(hook, context, (context) =>
209
+ dispatch(index + 1, context)
210
+ )
211
+ }
212
+
213
+ try {
214
+ await dispatch(0, context)
215
+
216
+ context.outcome = {
217
+ status: 'success',
218
+ error: null,
219
+ phase: null,
105
220
  }
221
+ } catch (err) {
222
+ context.outcome ??= {
223
+ status: 'failure',
224
+ error: err,
225
+ phase: null,
226
+ }
227
+ }
228
+
229
+ const finalizeFailures: FinalizeFailure[] = []
106
230
 
107
- const dispatch = async (
108
- index: number,
109
- context: ReleaseContext
110
- ): Promise<void> => {
111
- const hook = RELEASE_HOOK_NAMES[index]
231
+ for (const plugin of plugins) {
232
+ registerPluginHook(manager, {
233
+ hookName: 'finalize',
234
+ plugin,
235
+ onHandlerError: (error) =>
236
+ finalizeFailures.push({ plugin: plugin.name, error }),
237
+ })
238
+ }
239
+
240
+ await manager.emit('finalize', context)
112
241
 
113
- if (!hook) return
242
+ const [firstFinalizeFailure] = finalizeFailures
114
243
 
115
- return await manager.emit(hook, context, (context) =>
116
- dispatch(index + 1, context)
117
- )
244
+ if (context.outcome.status === 'success' && firstFinalizeFailure) {
245
+ context.outcome = {
246
+ status: 'failure',
247
+ error: firstFinalizeFailure.error,
248
+ phase: {
249
+ hook: 'finalize',
250
+ plugin: firstFinalizeFailure.plugin,
251
+ },
118
252
  }
253
+ }
119
254
 
120
- await dispatch(0, context)
255
+ const report = generateReleaseReport(context)
121
256
 
122
- context.status = 'success'
123
- } catch (err) {
124
- context.status = 'failure'
125
- context.error = err
126
- throw err
127
- } finally {
128
- printReleaseReport(context.logger, generateReleaseReport(context))
257
+ printReleaseReport(context.logger, report)
258
+ appendReleaseReportSummary(context.logger, context.env, report)
259
+ printReleaseReportAnnotation(context.env, context.stdout, report)
260
+
261
+ for (const failure of finalizeFailures) {
262
+ if (failure.error === context.outcome.error) continue
263
+
264
+ context.logger.warn(
265
+ `Plugin "${failure.plugin}" could not finalize: ${
266
+ failure.error instanceof Error
267
+ ? failure.error.message
268
+ : String(failure.error)
269
+ }`
270
+ )
271
+ }
272
+
273
+ if (context.outcome.status === 'failure') {
274
+ throw context.outcome.error
129
275
  }
130
276
  }
@@ -0,0 +1,115 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { ReleaseReport } from '#types'
5
+ import { isGitHubActions } from '#util'
6
+ import type { ConsolaInstance } from 'consola/core'
7
+ import { appendFileSync } from 'node:fs'
8
+ import { resolveOutcomeErrorMessage } from './resolveErrorMessage'
9
+
10
+ const STATUS_LABELS = {
11
+ success: 'Success',
12
+ failure: 'Failure',
13
+ } as const
14
+
15
+ type ReportPlan = ReleaseReport['plans'][number]
16
+
17
+ /**
18
+ * Append a Markdown release report to the GitHub Actions job summary.
19
+ *
20
+ * Detects a GitHub Actions runner through the `GITHUB_ACTIONS` environment
21
+ * variable and appends the rendered `report` to the file referenced by
22
+ * `GITHUB_STEP_SUMMARY`, so GitHub displays it on the run summary page. Does
23
+ * nothing outside GitHub Actions or when no summary file is configured, and
24
+ * logs a warning instead of throwing when the summary file cannot be written.
25
+ *
26
+ * @param logger Logger instance for reporting summary write failures
27
+ * @param env Readonly process environment variables object
28
+ * @param report Release report containing outcome and package details
29
+ */
30
+ export function appendReleaseReportSummary(
31
+ logger: ConsolaInstance,
32
+ env: Readonly<NodeJS.ProcessEnv>,
33
+ report: ReleaseReport
34
+ ): void {
35
+ if (!isGitHubActions(env)) return
36
+
37
+ const filePath = env.GITHUB_STEP_SUMMARY
38
+
39
+ if (!filePath) return
40
+
41
+ try {
42
+ appendFileSync(filePath, `\n${formatReleaseReportSummary(report)}`)
43
+ } catch (error) {
44
+ logger.warn(
45
+ `GitHub Actions job summary could not be written to "${filePath}": ${error instanceof Error ? error.message : error}`
46
+ )
47
+ }
48
+ }
49
+
50
+ const formatPackageLabel = (plan: ReportPlan): string => {
51
+ if (plan.package.name) return `\`${plan.package.name}\``
52
+
53
+ return `\`${plan.package.location}\``
54
+ }
55
+
56
+ const formatReleaseReportSummary = (report: ReleaseReport): string => {
57
+ const lines: string[] = ['## ReelOut Release Report', '']
58
+
59
+ if (report.outcome) {
60
+ lines.push(`**Status:** ${STATUS_LABELS[report.outcome.status]}`, '')
61
+ }
62
+
63
+ if (report.outcome?.status === 'failure') {
64
+ const message = resolveOutcomeErrorMessage(report.outcome)
65
+
66
+ lines.push(...message.split('\n').map((line) => `> ${line}`), '')
67
+
68
+ return lines.join('\n')
69
+ }
70
+
71
+ if (report.plans.length === 0) {
72
+ lines.push('No packages are scheduled for release.', '')
73
+
74
+ return lines.join('\n')
75
+ }
76
+
77
+ const plans = report.plans.toSorted((a, b) =>
78
+ (a.package.name || '').localeCompare(b.package.name || '')
79
+ )
80
+
81
+ lines.push('| Package | Version | Type | Tag |', '| --- | --- | --- | --- |')
82
+
83
+ for (const plan of plans) {
84
+ const version = `\`${plan.release.version}\` ← \`${plan.package.version}\``
85
+
86
+ lines.push(
87
+ [
88
+ `| ${formatPackageLabel(plan)}`,
89
+ version,
90
+ plan.release.type,
91
+ plan.release.tag ? `\`${plan.release.tag}\`` : '',
92
+ ].join(' | ') + ' |'
93
+ )
94
+ }
95
+
96
+ lines.push('')
97
+
98
+ for (const plan of plans) {
99
+ const changelog = plan.release.changelog?.trim()
100
+
101
+ if (!changelog) continue
102
+
103
+ lines.push(
104
+ '<details>',
105
+ `<summary>${formatPackageLabel(plan)} ${plan.release.version}</summary>`,
106
+ '',
107
+ changelog,
108
+ '',
109
+ '</details>',
110
+ ''
111
+ )
112
+ }
113
+
114
+ return lines.join('\n')
115
+ }
@@ -8,21 +8,15 @@ import { compact } from '#util'
8
8
  * Generate a structured release report from the current workflow state.
9
9
  *
10
10
  * Extracts state information from `context` and organizes it into a report
11
- * containing workflow status, release plans, and package metadata. Omits
12
- * unversioned release plans from the finalized output.
11
+ * containing the terminal release outcome, release plans, and package
12
+ * metadata. Omits unversioned release plans from the finalized output.
13
13
  *
14
14
  * @param context Release execution context containing workflow state and plans
15
15
  * @returns Structured release report object containing workflow results
16
16
  */
17
17
  export function generateReleaseReport(context: ReleaseContext): ReleaseReport {
18
18
  return {
19
- status: context.status,
20
- phase: context.phase,
21
- error: Error.isError(context.error)
22
- ? context.error.message
23
- : typeof context.error === 'string'
24
- ? context.error
25
- : null,
19
+ outcome: context.outcome,
26
20
  packages: context.packages.map((pkg) => ({
27
21
  location: pkg.location,
28
22
  name: pkg.name,
@@ -1,5 +1,7 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  // Copyright (c) 2026 Fai
3
3
 
4
+ export * from './appendReleaseReportSummary'
4
5
  export * from './generateReleaseReport'
5
6
  export * from './printReleaseReport'
7
+ export * from './printReleaseReportAnnotation'
@@ -5,38 +5,36 @@ import type { ReleaseReport } from '#types'
5
5
  import type { ConsolaInstance } from 'consola/core'
6
6
  import { colors } from 'consola/utils'
7
7
  import path from 'node:path'
8
+ import { resolveOutcomeErrorMessage } from './resolveErrorMessage'
8
9
 
9
10
  /**
10
11
  * Print a formatted release report to the logger.
11
12
  *
12
- * Logs workflow `status` and details for planned package releases. Displays
13
- * package names, directories, and version changes on success, or outputs the
14
- * error message on failure.
13
+ * Logs the terminal outcome status and details for planned package releases.
14
+ * Displays package names, directories, and version changes on success, or
15
+ * outputs the error message on failure.
15
16
  *
16
17
  * @param logger Logger instance for outputting messages
17
- * @param report Release report containing status and package details
18
+ * @param report Release report containing outcome and package details
18
19
  */
19
20
  export function printReleaseReport(
20
21
  logger: ConsolaInstance,
21
22
  report: ReleaseReport
22
23
  ): void {
23
- if (report.status) {
24
+ if (report.outcome) {
24
25
  const statusLabel = {
25
26
  success: colors.green('SUCCESS'),
26
27
  failure: colors.red('FAILURE'),
27
- }[report.status]
28
+ }[report.outcome.status]
28
29
 
29
30
  logger.info(`Status: ${statusLabel}`)
30
31
  }
31
32
 
32
- if (report.status === 'failure') {
33
+ if (report.outcome?.status === 'failure') {
33
34
  return logger.error(
34
35
  [
35
36
  'Release complete:',
36
- colors.red(
37
- report.error ||
38
- 'An unexpected error occurred during the release process.'
39
- ),
37
+ colors.red(resolveOutcomeErrorMessage(report.outcome)),
40
38
  ].join(' ')
41
39
  )
42
40
  }
@@ -0,0 +1,36 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { ReleaseReport } from '#types'
5
+ import { isGitHubActions } from '#util'
6
+ import { resolveOutcomeErrorMessage } from './resolveErrorMessage'
7
+
8
+ /**
9
+ * Print a GitHub Actions error annotation for a failed release.
10
+ *
11
+ * Detects a GitHub Actions runner through the `GITHUB_ACTIONS` environment
12
+ * variable and writes a `::error` workflow command carrying the failure
13
+ * reason to `stdout`, so GitHub surfaces the failure as an annotation on the
14
+ * run page. Does nothing outside GitHub Actions or when the release did not
15
+ * fail.
16
+ *
17
+ * @param env Readonly process environment variables object
18
+ * @param stdout Writable stream receiving the annotation command
19
+ * @param report Release report containing outcome and failure details
20
+ */
21
+ export function printReleaseReportAnnotation(
22
+ env: Readonly<NodeJS.ProcessEnv>,
23
+ stdout: NodeJS.WritableStream,
24
+ report: ReleaseReport
25
+ ): void {
26
+ if (!isGitHubActions(env) || report.outcome?.status !== 'failure') return
27
+
28
+ const message = formatAnnotationMessage(
29
+ resolveOutcomeErrorMessage(report.outcome)
30
+ )
31
+
32
+ stdout.write(`::error title=Release failed::${message}\n`)
33
+ }
34
+
35
+ const formatAnnotationMessage = (message: string): string =>
36
+ message.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A')
@@ -0,0 +1,36 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { ReleaseOutcome } from '#types'
5
+
6
+ /**
7
+ * Resolve a displayable message from an unknown error value.
8
+ *
9
+ * Normalizes `Error` instances to their `message` and passes string values
10
+ * through unchanged. Returns `null` for any other shape so callers can fall
11
+ * back to a generic message.
12
+ *
13
+ * @param error Unknown error value carried on a release outcome
14
+ * @returns The resolved error message, or `null` when none can be resolved
15
+ */
16
+ export function resolveErrorMessage(error: unknown): string | null {
17
+ if (Error.isError(error)) return error.message
18
+
19
+ return typeof error === 'string' ? error : null
20
+ }
21
+
22
+ const FALLBACK_ERROR_MESSAGE =
23
+ 'An unexpected error occurred during the release process.'
24
+
25
+ /**
26
+ * Resolve a displayable failure message from a release outcome.
27
+ *
28
+ * Normalizes the outcome error to its message and falls back to a generic
29
+ * message when the error carries no displayable content.
30
+ *
31
+ * @param outcome Failure outcome whose error is rendered
32
+ * @returns The resolved error message, or the fallback message
33
+ */
34
+ export function resolveOutcomeErrorMessage(outcome: ReleaseOutcome): string {
35
+ return resolveErrorMessage(outcome.error) || FALLBACK_ERROR_MESSAGE
36
+ }