@releasekit/release 0.3.0 → 0.4.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.
package/README.md CHANGED
@@ -1,6 +1,10 @@
1
1
  # @releasekit/release
2
2
 
3
- Unified release pipeline: version, changelog, and publish in a single command.
3
+ [![@releasekit/release](https://img.shields.io/badge/@releasekit-release-9feaf9?labelColor=1a1a1a&style=plastic)](https://www.npmjs.com/package/@releasekit/release)
4
+ [![Version](https://img.shields.io/npm/v/@releasekit/release?color=28a745&labelColor=1a1a1a)](https://www.npmjs.com/package/@releasekit/release)
5
+ [![Downloads](https://img.shields.io/npm/dw/@releasekit/release?color=6f42c1&labelColor=1a1a1a)](https://www.npmjs.com/package/@releasekit/release)
6
+
7
+ **Unified release pipeline: version, changelog, and publish in a single command.**
4
8
 
5
9
  ## Features
6
10
 
@@ -71,6 +75,18 @@ If no releasable changes are found after step 1, the command exits with code 0 a
71
75
  | `-q, --quiet` | Suppress non-error output | `false` |
72
76
  | `--project-dir <path>` | Project directory | cwd |
73
77
 
78
+ ### `releasekit init`
79
+
80
+ Create a default `releasekit.config.json` in the current directory.
81
+
82
+ ```bash
83
+ releasekit init [--force]
84
+ ```
85
+
86
+ Detects monorepo layout and sets `changelog.mode` accordingly. Adds `access: "public"` only for scoped packages (`@scope/name`), which npm defaults to restricted.
87
+
88
+ Use `--force` to overwrite an existing config file.
89
+
74
90
  ### `releasekit preview`
75
91
 
76
92
  Posts a release preview comment on a pull request showing what would be released if merged.
@@ -275,6 +291,11 @@ jobs:
275
291
 
276
292
  A template is also available at [`templates/workflows/release-preview.yml`](../../templates/workflows/release-preview.yml).
277
293
 
294
+ ## Documentation
295
+
296
+ **Getting Started**
297
+ - [CI Setup](./docs/ci-setup.md) — GitHub Actions workflows (push, label, OIDC, PR preview, prerelease)
298
+
278
299
  ## License
279
300
 
280
301
  MIT
@@ -0,0 +1,438 @@
1
+ import {
2
+ info,
3
+ loadCIConfig,
4
+ loadConfig,
5
+ runRelease,
6
+ success,
7
+ warn
8
+ } from "./chunk-YZHGXRG6.js";
9
+
10
+ // src/preview-context.ts
11
+ import * as fs from "fs";
12
+ function resolvePreviewContext(opts) {
13
+ const token = process.env.GITHUB_TOKEN;
14
+ if (!token) {
15
+ throw new Error("GITHUB_TOKEN environment variable is required");
16
+ }
17
+ const prNumber = resolvePRNumber(opts.pr);
18
+ const { owner, repo } = resolveRepo(opts.repo);
19
+ return { prNumber, owner, repo, token };
20
+ }
21
+ function resolvePRNumber(cliValue) {
22
+ if (cliValue) {
23
+ const num = Number.parseInt(cliValue, 10);
24
+ if (Number.isNaN(num) || num <= 0) {
25
+ throw new Error(`Invalid PR number: ${cliValue}`);
26
+ }
27
+ return num;
28
+ }
29
+ const eventPath = process.env.GITHUB_EVENT_PATH;
30
+ if (eventPath && fs.existsSync(eventPath)) {
31
+ try {
32
+ const event = JSON.parse(fs.readFileSync(eventPath, "utf-8"));
33
+ if (event.pull_request?.number) {
34
+ return event.pull_request.number;
35
+ }
36
+ } catch {
37
+ }
38
+ }
39
+ throw new Error("Could not determine PR number. Use --pr <number> or run in a GitHub Actions pull_request workflow.");
40
+ }
41
+ function resolveRepo(cliValue) {
42
+ const repoStr = cliValue ?? process.env.GITHUB_REPOSITORY;
43
+ if (!repoStr) {
44
+ throw new Error("Could not determine repository. Use --repo <owner/repo> or run in a GitHub Actions workflow.");
45
+ }
46
+ const parts = repoStr.split("/");
47
+ if (parts.length !== 2 || !parts[0] || !parts[1]) {
48
+ throw new Error(`Invalid repository format: ${repoStr}. Expected "owner/repo".`);
49
+ }
50
+ return { owner: parts[0], repo: parts[1] };
51
+ }
52
+
53
+ // src/preview-detect.ts
54
+ import * as fs2 from "fs";
55
+ import * as path from "path";
56
+ function detectPrerelease(packagePaths, projectDir) {
57
+ const paths = packagePaths.length > 0 ? packagePaths.map((p) => path.join(projectDir, p, "package.json")) : [path.join(projectDir, "package.json")];
58
+ for (const pkgPath of paths) {
59
+ if (!fs2.existsSync(pkgPath)) continue;
60
+ try {
61
+ const pkg = JSON.parse(fs2.readFileSync(pkgPath, "utf-8"));
62
+ const result = parsePrerelease(pkg.version);
63
+ if (result.isPrerelease) return result;
64
+ } catch {
65
+ }
66
+ }
67
+ return { isPrerelease: false };
68
+ }
69
+ function parsePrerelease(version) {
70
+ if (!version) return { isPrerelease: false };
71
+ const match = version.match(/-([a-zA-Z0-9][a-zA-Z0-9-]*)(?:\.\d+)*(?:\+[^\s]+)?$/);
72
+ if (match) {
73
+ return { isPrerelease: true, identifier: match[1] };
74
+ }
75
+ return { isPrerelease: false };
76
+ }
77
+
78
+ // src/preview-format.ts
79
+ var MARKER = "<!-- releasekit-preview -->";
80
+ var FOOTER = "*Updated automatically by [ReleaseKit](https://github.com/goosewobbler/releasekit)*";
81
+ var TYPE_LABELS = {
82
+ added: "Added",
83
+ changed: "Changed",
84
+ fixed: "Fixed",
85
+ security: "Security",
86
+ docs: "Documentation",
87
+ chore: "Chores",
88
+ test: "Tests",
89
+ feat: "Features",
90
+ fix: "Bug Fixes",
91
+ perf: "Performance",
92
+ refactor: "Refactoring",
93
+ style: "Styles",
94
+ build: "Build",
95
+ ci: "CI",
96
+ revert: "Reverts"
97
+ };
98
+ function getNoChangesMessage(strategy) {
99
+ switch (strategy) {
100
+ case "manual":
101
+ return "Run the release workflow manually if a release is needed.";
102
+ case "direct":
103
+ return "Merging this PR will not trigger a release.";
104
+ case "standing-pr":
105
+ return "Merging this PR will not affect the release PR.";
106
+ case "scheduled":
107
+ return "These changes will not be included in the next scheduled release.";
108
+ default:
109
+ return "";
110
+ }
111
+ }
112
+ function getIntroMessage(strategy, standingPrNumber) {
113
+ switch (strategy) {
114
+ case "direct":
115
+ return "This PR will trigger the following release when merged:";
116
+ case "standing-pr":
117
+ return standingPrNumber ? `These changes will be added to the release PR (#${standingPrNumber}) when merged:` : "Merging this PR will create a new release PR with the following changes:";
118
+ case "scheduled":
119
+ return "These changes will be included in the next scheduled release:";
120
+ default:
121
+ return "If released, this PR would include:";
122
+ }
123
+ }
124
+ function getLabelBanner(labelContext) {
125
+ if (!labelContext) return [];
126
+ if (labelContext.trigger === "commit") {
127
+ if (labelContext.skip) {
128
+ return ["> **Warning:** This PR is marked to skip release.", ""];
129
+ }
130
+ if (labelContext.bumpLabel === "major") {
131
+ return ["> **Important:** This PR is labeled for a **major** release.", ""];
132
+ }
133
+ }
134
+ if (labelContext.trigger === "label") {
135
+ if (labelContext.noBumpLabel) {
136
+ const labels = labelContext.labels;
137
+ const labelExamples = labels ? `\`${labels.patch}\`, \`${labels.minor}\`, or \`${labels.major}\`` : "a release label (e.g., `release:patch`, `release:minor`, `release:major`)";
138
+ return ["> No release label detected.", `> **Note:** Add ${labelExamples} to trigger a release.`, ""];
139
+ }
140
+ if (labelContext.bumpLabel) {
141
+ return [`> This PR is labeled for a **${labelContext.bumpLabel}** release.`, ""];
142
+ }
143
+ }
144
+ return [];
145
+ }
146
+ function formatPreviewComment(result, options) {
147
+ const strategy = options?.strategy ?? "direct";
148
+ const labelContext = options?.labelContext;
149
+ const lines = [MARKER, ""];
150
+ const banner = getLabelBanner(labelContext);
151
+ if (!result) {
152
+ lines.push("<details>", "<summary><b>Release Preview</b> \u2014 no release</summary>", "");
153
+ lines.push(...banner);
154
+ if (!labelContext?.noBumpLabel) {
155
+ lines.push(`> **Note:** No releasable changes detected. ${getNoChangesMessage(strategy)}`);
156
+ }
157
+ lines.push("", "---", FOOTER, "</details>");
158
+ return lines.join("\n");
159
+ }
160
+ const { versionOutput } = result;
161
+ const pkgCount = versionOutput.updates.length;
162
+ const pkgSummary = pkgCount === 1 ? `${versionOutput.updates[0]?.packageName} ${versionOutput.updates[0]?.newVersion}` : `${pkgCount} packages`;
163
+ lines.push("<details>", `<summary><b>Release Preview</b> \u2014 ${pkgSummary}</summary>`, "");
164
+ lines.push(...banner);
165
+ lines.push(getIntroMessage(strategy, options?.standingPrNumber), "");
166
+ lines.push("### Packages", "");
167
+ lines.push("| Package | Version |", "|---------|---------|");
168
+ for (const update of versionOutput.updates) {
169
+ lines.push(`| \`${update.packageName}\` | ${update.newVersion} |`);
170
+ }
171
+ lines.push("");
172
+ const sharedEntries = versionOutput.sharedEntries?.length ? versionOutput.sharedEntries : void 0;
173
+ const hasPackageChangelogs = versionOutput.changelogs.some((cl) => cl.entries.length > 0);
174
+ if (sharedEntries || hasPackageChangelogs) {
175
+ lines.push("### Changelog", "");
176
+ if (sharedEntries) {
177
+ lines.push("<details>", "<summary><b>Project-wide changes</b></summary>", "");
178
+ lines.push(...renderEntries(sharedEntries));
179
+ lines.push("</details>", "");
180
+ }
181
+ for (const changelog of versionOutput.changelogs) {
182
+ if (changelog.entries.length > 0) {
183
+ lines.push(...formatPackageChangelog(changelog));
184
+ }
185
+ }
186
+ }
187
+ if (versionOutput.tags.length > 0) {
188
+ lines.push("### Tags", "");
189
+ for (const tag of versionOutput.tags) {
190
+ lines.push(`- \`${tag}\``);
191
+ }
192
+ lines.push("");
193
+ }
194
+ lines.push("---", FOOTER, "</details>");
195
+ return lines.join("\n");
196
+ }
197
+ function renderEntries(entries) {
198
+ const lines = [];
199
+ const grouped = /* @__PURE__ */ new Map();
200
+ for (const entry of entries) {
201
+ if (!grouped.has(entry.type)) grouped.set(entry.type, []);
202
+ grouped.get(entry.type)?.push(entry);
203
+ }
204
+ const renderedTypes = /* @__PURE__ */ new Set();
205
+ for (const type of Object.keys(TYPE_LABELS)) {
206
+ const group = grouped.get(type);
207
+ if (group && group.length > 0) {
208
+ lines.push(...formatEntryGroup(type, group));
209
+ renderedTypes.add(type);
210
+ }
211
+ }
212
+ for (const [type, group] of grouped) {
213
+ if (!renderedTypes.has(type) && group.length > 0) {
214
+ lines.push(...formatEntryGroup(type, group));
215
+ }
216
+ }
217
+ return lines;
218
+ }
219
+ function formatPackageChangelog(changelog) {
220
+ const lines = [];
221
+ const prevVersion = changelog.previousVersion ?? "N/A";
222
+ const summary = `<b>${changelog.packageName}</b> ${prevVersion} \u2192 ${changelog.version}`;
223
+ lines.push("<details>", `<summary>${summary}</summary>`, "");
224
+ lines.push(...renderEntries(changelog.entries));
225
+ lines.push("</details>", "");
226
+ return lines;
227
+ }
228
+ function formatEntryGroup(type, entries) {
229
+ const label = TYPE_LABELS[type] ?? capitalize(type);
230
+ const lines = [`#### ${label}`, ""];
231
+ for (const entry of entries) {
232
+ let line = `- ${entry.description}`;
233
+ if (entry.scope) {
234
+ line += ` (\`${entry.scope}\`)`;
235
+ }
236
+ if (entry.issueIds && entry.issueIds.length > 0) {
237
+ line += ` ${entry.issueIds.join(", ")}`;
238
+ }
239
+ lines.push(line);
240
+ }
241
+ lines.push("");
242
+ return lines;
243
+ }
244
+ function capitalize(str) {
245
+ return str.charAt(0).toUpperCase() + str.slice(1);
246
+ }
247
+
248
+ // src/preview-github.ts
249
+ import { Octokit } from "@octokit/rest";
250
+ function createOctokit(token) {
251
+ return new Octokit({ auth: token });
252
+ }
253
+ async function findPreviewComment(octokit, owner, repo, prNumber) {
254
+ const iterator = octokit.paginate.iterator(octokit.rest.issues.listComments, {
255
+ owner,
256
+ repo,
257
+ issue_number: prNumber,
258
+ per_page: 100
259
+ });
260
+ for await (const response of iterator) {
261
+ for (const comment of response.data) {
262
+ if (comment.body?.startsWith(MARKER)) {
263
+ return comment.id;
264
+ }
265
+ }
266
+ }
267
+ return null;
268
+ }
269
+ async function fetchPRLabels(octokit, owner, repo, prNumber) {
270
+ const { data } = await octokit.rest.issues.get({
271
+ owner,
272
+ repo,
273
+ issue_number: prNumber
274
+ });
275
+ return (data.labels ?? []).map((label) => typeof label === "string" ? label : label.name ?? "");
276
+ }
277
+ async function postOrUpdateComment(octokit, owner, repo, prNumber, body) {
278
+ const existingId = await findPreviewComment(octokit, owner, repo, prNumber);
279
+ if (existingId) {
280
+ await octokit.rest.issues.updateComment({
281
+ owner,
282
+ repo,
283
+ comment_id: existingId,
284
+ body
285
+ });
286
+ } else {
287
+ await octokit.rest.issues.createComment({
288
+ owner,
289
+ repo,
290
+ issue_number: prNumber,
291
+ body
292
+ });
293
+ }
294
+ }
295
+
296
+ // src/preview.ts
297
+ var DEFAULT_LABELS = {
298
+ stable: "release:stable",
299
+ prerelease: "release:prerelease",
300
+ skip: "release:skip",
301
+ major: "release:major",
302
+ minor: "release:minor",
303
+ patch: "release:patch"
304
+ };
305
+ async function runPreview(options) {
306
+ const ciConfig = loadCIConfig({ cwd: options.projectDir, configPath: options.config });
307
+ if (ciConfig?.prPreview === false) {
308
+ info("PR preview is disabled in config (ci.prPreview: false)");
309
+ return;
310
+ }
311
+ let context;
312
+ let octokit;
313
+ if (!options.dryRun) {
314
+ try {
315
+ context = resolvePreviewContext({ pr: options.pr, repo: options.repo });
316
+ octokit = createOctokit(context.token);
317
+ } catch (error) {
318
+ warn(`Cannot post PR comment: ${error instanceof Error ? error.message : String(error)}`);
319
+ }
320
+ }
321
+ const { options: effectiveOptions, labelContext } = await applyLabelOverrides(options, ciConfig, context, octokit);
322
+ const strategy = ciConfig?.releaseStrategy ?? "direct";
323
+ let result = null;
324
+ if (!labelContext.noBumpLabel) {
325
+ const releaseConfig = loadConfig({ cwd: effectiveOptions.projectDir, configPath: effectiveOptions.config });
326
+ const prereleaseFlag = resolvePrerelease(
327
+ effectiveOptions,
328
+ releaseConfig.version?.packages ?? [],
329
+ effectiveOptions.projectDir
330
+ );
331
+ info("Analyzing release...");
332
+ result = await runRelease({
333
+ config: effectiveOptions.config,
334
+ dryRun: true,
335
+ sync: false,
336
+ bump: effectiveOptions.bump,
337
+ prerelease: prereleaseFlag,
338
+ skipNotes: true,
339
+ skipPublish: true,
340
+ skipGit: true,
341
+ skipGithubRelease: true,
342
+ skipVerification: true,
343
+ json: false,
344
+ verbose: false,
345
+ quiet: true,
346
+ projectDir: effectiveOptions.projectDir
347
+ });
348
+ } else {
349
+ info("No release label detected \u2014 skipping version analysis");
350
+ }
351
+ const commentBody = formatPreviewComment(result, { strategy, labelContext });
352
+ if (!context || !octokit) {
353
+ console.log(commentBody);
354
+ return;
355
+ }
356
+ info(`Posting preview comment on PR #${context.prNumber}...`);
357
+ await postOrUpdateComment(octokit, context.owner, context.repo, context.prNumber, commentBody);
358
+ success(`Preview comment posted on PR #${context.prNumber}`);
359
+ }
360
+ function resolvePrerelease(options, packagePaths, projectDir) {
361
+ if (options.stable) {
362
+ return void 0;
363
+ }
364
+ if (options.prerelease !== void 0) {
365
+ return options.prerelease;
366
+ }
367
+ const detected = detectPrerelease(packagePaths, projectDir);
368
+ if (detected.isPrerelease) {
369
+ info(`Detected prerelease version (identifier: ${detected.identifier})`);
370
+ return detected.identifier;
371
+ }
372
+ return void 0;
373
+ }
374
+ async function applyLabelOverrides(options, ciConfig, context, existingOctokit) {
375
+ const trigger = ciConfig?.releaseTrigger ?? "label";
376
+ const labels = ciConfig?.labels ?? DEFAULT_LABELS;
377
+ const defaultLabelContext = { trigger, skip: false, noBumpLabel: false };
378
+ if (!context) {
379
+ return {
380
+ options,
381
+ labelContext: { ...defaultLabelContext, noBumpLabel: trigger === "label" && !options.bump, labels }
382
+ };
383
+ }
384
+ let prLabels;
385
+ const octokitToUse = existingOctokit ?? createOctokit(context.token);
386
+ try {
387
+ prLabels = await fetchPRLabels(octokitToUse, context.owner, context.repo, context.prNumber);
388
+ } catch {
389
+ warn("Could not fetch PR labels \u2014 skipping label-driven overrides");
390
+ return {
391
+ options,
392
+ labelContext: { ...defaultLabelContext, noBumpLabel: trigger === "label", labels }
393
+ };
394
+ }
395
+ const result = { ...options };
396
+ const labelContext = { trigger, skip: false, noBumpLabel: false, labels };
397
+ if (trigger === "commit") {
398
+ if (prLabels.includes(labels.skip)) {
399
+ info(`PR label "${labels.skip}" detected \u2014 release will be skipped`);
400
+ labelContext.skip = true;
401
+ }
402
+ if (!labelContext.skip && prLabels.includes(labels.major)) {
403
+ info(`PR label "${labels.major}" detected \u2014 forcing major release`);
404
+ labelContext.bumpLabel = "major";
405
+ result.bump = "major";
406
+ }
407
+ } else {
408
+ if (prLabels.includes(labels.major)) {
409
+ info(`PR label "${labels.major}" detected \u2014 major release`);
410
+ labelContext.bumpLabel = "major";
411
+ result.bump = "major";
412
+ } else if (prLabels.includes(labels.minor)) {
413
+ info(`PR label "${labels.minor}" detected \u2014 minor release`);
414
+ labelContext.bumpLabel = "minor";
415
+ result.bump = "minor";
416
+ } else if (prLabels.includes(labels.patch)) {
417
+ info(`PR label "${labels.patch}" detected \u2014 patch release`);
418
+ labelContext.bumpLabel = "patch";
419
+ result.bump = "patch";
420
+ } else {
421
+ labelContext.noBumpLabel = true;
422
+ }
423
+ }
424
+ if (!options.stable && options.prerelease === void 0) {
425
+ if (prLabels.includes(labels.stable)) {
426
+ info(`PR label "${labels.stable}" detected \u2014 using stable release preview`);
427
+ result.stable = true;
428
+ } else if (prLabels.includes(labels.prerelease)) {
429
+ info(`PR label "${labels.prerelease}" detected \u2014 using prerelease preview`);
430
+ result.prerelease = true;
431
+ }
432
+ }
433
+ return { options: result, labelContext: { ...labelContext, labels } };
434
+ }
435
+
436
+ export {
437
+ runPreview
438
+ };
@@ -0,0 +1,46 @@
1
+ import {
2
+ EXIT_CODES,
3
+ runRelease
4
+ } from "./chunk-YZHGXRG6.js";
5
+
6
+ // src/release-command.ts
7
+ import { Command, Option } from "commander";
8
+ function createReleaseCommand() {
9
+ return new Command("release").description("Run the full release pipeline").option("-c, --config <path>", "Path to config file").option("-d, --dry-run", "Preview all steps without side effects", false).option("-b, --bump <type>", "Force bump type (patch|minor|major)").option("-p, --prerelease [identifier]", "Create prerelease version").option("-s, --sync", "Use synchronized versioning across all packages", false).option("-t, --target <packages>", "Target specific packages (comma-separated)").option("--branch <name>", "Override the git branch used for push").addOption(new Option("--npm-auth <method>", "NPM auth method").choices(["auto", "oidc", "token"]).default("auto")).option("--skip-notes", "Skip changelog generation", false).option("--skip-publish", "Skip registry publishing and git operations", false).option("--skip-git", "Skip git commit/tag/push", false).option("--skip-github-release", "Skip GitHub release creation", false).option("--skip-verification", "Skip post-publish verification", false).option("-j, --json", "Output results as JSON", false).option("-v, --verbose", "Verbose logging", false).option("-q, --quiet", "Suppress non-error output", false).option("--project-dir <path>", "Project directory", process.cwd()).action(async (opts) => {
10
+ const options = {
11
+ config: opts.config,
12
+ dryRun: opts.dryRun,
13
+ bump: opts.bump,
14
+ prerelease: opts.prerelease,
15
+ sync: opts.sync,
16
+ target: opts.target,
17
+ branch: opts.branch,
18
+ npmAuth: opts.npmAuth,
19
+ skipNotes: opts.skipNotes,
20
+ skipPublish: opts.skipPublish,
21
+ skipGit: opts.skipGit,
22
+ skipGithubRelease: opts.skipGithubRelease,
23
+ skipVerification: opts.skipVerification,
24
+ json: opts.json,
25
+ verbose: opts.verbose,
26
+ quiet: opts.quiet,
27
+ projectDir: opts.projectDir
28
+ };
29
+ try {
30
+ const result = await runRelease(options);
31
+ if (options.json && result) {
32
+ console.log(JSON.stringify(result, null, 2));
33
+ }
34
+ if (!result) {
35
+ process.exit(0);
36
+ }
37
+ } catch (error) {
38
+ console.error(error instanceof Error ? error.message : String(error));
39
+ process.exit(EXIT_CODES.GENERAL_ERROR);
40
+ }
41
+ });
42
+ }
43
+
44
+ export {
45
+ createReleaseCommand
46
+ };