@eserstack/codebase 0.0.0-stage → 5.0.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 (175) hide show
  1. package/README.md +301 -2
  2. package/dist/changelog-gen.d.ts +105 -0
  3. package/dist/changelog-gen.js +498 -0
  4. package/dist/changelog-text.d.ts +39 -0
  5. package/dist/changelog-text.js +82 -0
  6. package/dist/cli-support.d.ts +140 -0
  7. package/dist/cli-support.js +244 -0
  8. package/dist/cli-system/app-opts.d.ts +15 -0
  9. package/dist/cli-system/app-opts.js +13 -0
  10. package/dist/cli-system/app.d.ts +29 -0
  11. package/dist/cli-system/app.js +12 -0
  12. package/dist/cli-system/handlers/completions-setup.d.ts +14 -0
  13. package/dist/cli-system/handlers/completions-setup.js +139 -0
  14. package/dist/cli-system/handlers/completions.d.ts +3 -0
  15. package/dist/cli-system/handlers/completions.js +79 -0
  16. package/dist/cli-system/handlers/doctor.d.ts +8 -0
  17. package/dist/cli-system/handlers/doctor.js +146 -0
  18. package/dist/cli-system/handlers/info.d.ts +3 -0
  19. package/dist/cli-system/handlers/info.js +69 -0
  20. package/dist/cli-system/handlers/install.d.ts +8 -0
  21. package/dist/cli-system/handlers/install.js +137 -0
  22. package/dist/cli-system/handlers/mod.d.ts +12 -0
  23. package/dist/cli-system/handlers/mod.js +13 -0
  24. package/dist/cli-system/handlers/uninstall.d.ts +3 -0
  25. package/dist/cli-system/handlers/uninstall.js +60 -0
  26. package/dist/cli-system/handlers/update.d.ts +76 -0
  27. package/dist/cli-system/handlers/update.js +310 -0
  28. package/dist/cli-system/handlers/version-check.d.ts +16 -0
  29. package/dist/cli-system/handlers/version-check.js +176 -0
  30. package/dist/cli-system/handlers/version.d.ts +3 -0
  31. package/dist/cli-system/handlers/version.js +45 -0
  32. package/dist/cli-system/mod.d.ts +19 -0
  33. package/dist/cli-system/mod.js +52 -0
  34. package/dist/commitmsg.d.ts +28 -0
  35. package/dist/commitmsg.js +232 -0
  36. package/dist/directive-analysis.d.ts +75 -0
  37. package/dist/directive-analysis.js +223 -0
  38. package/dist/ffi-client.d.ts +11 -0
  39. package/dist/ffi-client.js +12 -0
  40. package/dist/file-tool.d.ts +96 -0
  41. package/dist/file-tool.js +274 -0
  42. package/dist/file-tools-shared.d.ts +81 -0
  43. package/dist/file-tools-shared.js +276 -0
  44. package/dist/gh-contributors.d.ts +89 -0
  45. package/dist/gh-contributors.js +205 -0
  46. package/dist/gh.d.ts +3 -0
  47. package/dist/gh.js +64 -0
  48. package/dist/git-listing.d.ts +27 -0
  49. package/dist/git-listing.js +69 -0
  50. package/dist/git.d.ts +172 -0
  51. package/dist/git.js +277 -0
  52. package/dist/install.d.ts +34 -0
  53. package/dist/install.js +421 -0
  54. package/dist/main.d.ts +22 -0
  55. package/dist/main.js +14 -0
  56. package/dist/mod.d.ts +25 -0
  57. package/dist/mod.js +8 -0
  58. package/dist/module.d.ts +10 -0
  59. package/dist/module.js +221 -0
  60. package/dist/native-functions.d.ts +1088 -0
  61. package/dist/native-functions.js +2 -0
  62. package/dist/npm-externals.d.ts +27 -0
  63. package/dist/npm-externals.js +34 -0
  64. package/dist/npm-workspace-specifiers.d.ts +6 -0
  65. package/dist/npm-workspace-specifiers.js +45 -0
  66. package/dist/package/loader.d.ts +34 -0
  67. package/dist/package/loader.js +203 -0
  68. package/dist/package/mod.d.ts +36 -0
  69. package/dist/package/mod.js +5 -0
  70. package/dist/package/types.d.ts +142 -0
  71. package/dist/package/types.js +32 -0
  72. package/dist/package/workspace.d.ts +33 -0
  73. package/dist/package/workspace.js +158 -0
  74. package/dist/package/writer.d.ts +52 -0
  75. package/dist/package/writer.js +278 -0
  76. package/dist/package.json +275 -0
  77. package/dist/release-notes.d.ts +90 -0
  78. package/dist/release-notes.js +236 -0
  79. package/dist/release-tag.d.ts +46 -0
  80. package/dist/release-tag.js +95 -0
  81. package/dist/release.d.ts +145 -0
  82. package/dist/release.js +584 -0
  83. package/dist/source-mask.d.ts +3 -0
  84. package/dist/source-mask.js +185 -0
  85. package/dist/validate-bom.d.ts +5 -0
  86. package/dist/validate-bom.js +43 -0
  87. package/dist/validate-case-conflict.d.ts +5 -0
  88. package/dist/validate-case-conflict.js +43 -0
  89. package/dist/validate-circular-deps.d.ts +11 -0
  90. package/dist/validate-circular-deps.js +53 -0
  91. package/dist/validate-code-conventions.d.ts +22 -0
  92. package/dist/validate-code-conventions.js +166 -0
  93. package/dist/validate-commit-msg.d.ts +50 -0
  94. package/dist/validate-commit-msg.js +182 -0
  95. package/dist/validate-docs.d.ts +20 -0
  96. package/dist/validate-docs.js +78 -0
  97. package/dist/validate-eof.d.ts +5 -0
  98. package/dist/validate-eof.js +61 -0
  99. package/dist/validate-error-coverage.d.ts +28 -0
  100. package/dist/validate-error-coverage.js +93 -0
  101. package/dist/validate-export-names.d.ts +17 -0
  102. package/dist/validate-export-names.js +56 -0
  103. package/dist/validate-filenames.d.ts +5 -0
  104. package/dist/validate-filenames.js +151 -0
  105. package/dist/validate-json.d.ts +5 -0
  106. package/dist/validate-json.js +71 -0
  107. package/dist/validate-large-files.d.ts +5 -0
  108. package/dist/validate-large-files.js +41 -0
  109. package/dist/validate-laroux-boundaries.d.ts +19 -0
  110. package/dist/validate-laroux-boundaries.js +59 -0
  111. package/dist/validate-licenses.d.ts +5 -0
  112. package/dist/validate-licenses.js +137 -0
  113. package/dist/validate-line-endings.d.ts +5 -0
  114. package/dist/validate-line-endings.js +47 -0
  115. package/dist/validate-merge-conflict.d.ts +5 -0
  116. package/dist/validate-merge-conflict.js +46 -0
  117. package/dist/validate-mod-exports.d.ts +16 -0
  118. package/dist/validate-mod-exports.js +56 -0
  119. package/dist/validate-naming-and-todos.d.ts +5 -0
  120. package/dist/validate-naming-and-todos.js +70 -0
  121. package/dist/validate-runtime-js-apis.d.ts +5 -0
  122. package/dist/validate-runtime-js-apis.js +78 -0
  123. package/dist/validate-secrets.d.ts +5 -0
  124. package/dist/validate-secrets.js +82 -0
  125. package/dist/validate-self-imports.d.ts +5 -0
  126. package/dist/validate-self-imports.js +78 -0
  127. package/dist/validate-server-loc.d.ts +32 -0
  128. package/dist/validate-server-loc.js +94 -0
  129. package/dist/validate-shebangs.d.ts +5 -0
  130. package/dist/validate-shebangs.js +33 -0
  131. package/dist/validate-stream.d.ts +25 -0
  132. package/dist/validate-stream.js +62 -0
  133. package/dist/validate-submodules.d.ts +5 -0
  134. package/dist/validate-submodules.js +43 -0
  135. package/dist/validate-symlinks.d.ts +5 -0
  136. package/dist/validate-symlinks.js +46 -0
  137. package/dist/validate-toml.d.ts +5 -0
  138. package/dist/validate-toml.js +40 -0
  139. package/dist/validate-trailing-whitespace.d.ts +5 -0
  140. package/dist/validate-trailing-whitespace.js +49 -0
  141. package/dist/validate-yaml.d.ts +5 -0
  142. package/dist/validate-yaml.js +40 -0
  143. package/dist/validation/config.d.ts +17 -0
  144. package/dist/validation/config.js +30 -0
  145. package/dist/validation/mod.d.ts +71 -0
  146. package/dist/validation/mod.js +479 -0
  147. package/dist/validation/registry.d.ts +57 -0
  148. package/dist/validation/registry.js +256 -0
  149. package/dist/validation/types.d.ts +101 -0
  150. package/dist/validation/types.js +2 -0
  151. package/dist/validation/validators/circular-deps.d.ts +7 -0
  152. package/dist/validation/validators/circular-deps.js +31 -0
  153. package/dist/validation/validators/docs.d.ts +7 -0
  154. package/dist/validation/validators/docs.js +38 -0
  155. package/dist/validation/validators/error-coverage.d.ts +2 -0
  156. package/dist/validation/validators/error-coverage.js +46 -0
  157. package/dist/validation/validators/export-names.d.ts +7 -0
  158. package/dist/validation/validators/export-names.js +31 -0
  159. package/dist/validation/validators/laroux-boundaries.d.ts +2 -0
  160. package/dist/validation/validators/laroux-boundaries.js +29 -0
  161. package/dist/validation/validators/mod-exports.d.ts +7 -0
  162. package/dist/validation/validators/mod-exports.js +32 -0
  163. package/dist/validation/validators/mod.d.ts +11 -0
  164. package/dist/validation/validators/mod.js +12 -0
  165. package/dist/validation/validators/server-loc.d.ts +2 -0
  166. package/dist/validation/validators/server-loc.js +48 -0
  167. package/dist/versions.d.ts +166 -0
  168. package/dist/versions.js +349 -0
  169. package/dist/violation-baseline.d.ts +58 -0
  170. package/dist/violation-baseline.js +144 -0
  171. package/dist/walk-stream.d.ts +24 -0
  172. package/dist/walk-stream.js +55 -0
  173. package/dist/workspace-discovery.d.ts +60 -0
  174. package/dist/workspace-discovery.js +130 -0
  175. package/package.json +222 -3
@@ -0,0 +1,584 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Release orchestration — bump version, generate changelog, commit, push, tag.
4
+ *
5
+ * The release pipeline is tag-triggered: pushing `v<version>` is what makes CI
6
+ * validate and publish. Every command here is therefore defined by what it does
7
+ * to that tag.
8
+ *
9
+ * Provides three commands:
10
+ * - **release** — full release flow (bump, changelog, commit, push, push tag)
11
+ * - **rerelease** — delete and re-push the current version tag at HEAD, which
12
+ * re-fires the pipeline for a version that is already committed
13
+ * - **unrelease** — delete the current version tag and its GitHub Release,
14
+ * leaving the version-bump commit in history
15
+ *
16
+ * Library usage:
17
+ * ```typescript
18
+ * import * as release from "@eserstack/codebase/release";
19
+ *
20
+ * const result = await release.release({ type: "patch" });
21
+ * console.log(result.tag); // "v4.1.4"
22
+ * ```
23
+ *
24
+ * CLI usage:
25
+ * eser codebase release <patch|minor|major|same> [--dry-run] [--yes]
26
+ * eser codebase rerelease [--dry-run] [--yes]
27
+ * eser codebase unrelease [--yes]
28
+ *
29
+ * Only the release flow runs when this file is executed directly
30
+ * (`node ./release.ts patch`); rerelease and unrelease are
31
+ * separate entry points, not flags on it.
32
+ *
33
+ * @module
34
+ */
35
+ import * as primitives from "@eserstack/primitives";
36
+ import * as standards from "@eserstack/standards";
37
+ import * as functions from "@eserstack/functions";
38
+ import * as shellExec from "@eserstack/shell/exec";
39
+ import * as tui from "@eserstack/shell/tui";
40
+ import * as versions from "./versions.js";
41
+ import * as cliSupport from "./cli-support.js";
42
+ // =============================================================================
43
+ // Git helpers
44
+ // =============================================================================
45
+ /** Check if the working tree is clean. */
46
+ const gitIsClean = async () => {
47
+ const text = await shellExec.exec `git status --porcelain`.noThrow().text();
48
+ return text.length === 0;
49
+ };
50
+ /** List unpushed commits (empty array means up to date). */
51
+ const gitUnpushedCommits = async () => {
52
+ const text = await shellExec.exec `git log @{u}..HEAD --oneline`
53
+ .noThrow()
54
+ .text();
55
+ return text.length > 0 ? text.split("\n") : [];
56
+ };
57
+ /**
58
+ * Stage specific files and create a commit.
59
+ *
60
+ * Each pathspec is reported by name when it fails. `git add` exits 128 on a
61
+ * pathspec matching no tracked file, and this runs after the version bump has
62
+ * already been written, so the bare "exit code 128: git" it used to surface
63
+ * left a half-released tree with no indication of which entry was at fault.
64
+ */
65
+ const gitAddAndCommit = async (message, files) => {
66
+ for (const file of files) {
67
+ // One pathspec at a time: concurrent `git add` runs contend for
68
+ // .git/index.lock, and the first failure must stop the loop.
69
+ // oxlint-disable-next-line no-await-in-loop
70
+ const result = await shellExec.exec `git add ${file}`.noThrow().spawn();
71
+ if (result.code !== 0) {
72
+ throw new Error(`git add ${file} failed (exit ${result.code}). The pathspec matches ` +
73
+ `no tracked file — check whether it is gitignored or the layout moved.`);
74
+ }
75
+ }
76
+ await shellExec.exec `git commit -m ${message}`.spawn();
77
+ };
78
+ /** Push current branch to origin. */
79
+ const gitPushHead = async () => {
80
+ await shellExec.exec `git push origin HEAD`.spawn();
81
+ };
82
+ /** Delete a tag locally and remotely (best-effort, does not throw). */
83
+ const gitDeleteTag = async (tag) => {
84
+ await shellExec.exec `git tag -d ${tag}`.noThrow().spawn();
85
+ const refspec = `:refs/tags/${tag}`;
86
+ await shellExec.exec `git push origin ${refspec}`.noThrow().spawn();
87
+ };
88
+ /**
89
+ * Delete the GitHub Release for a tag. Best-effort: returns whether it worked.
90
+ *
91
+ * No `--repo` (gh infers it from origin) and no `--cleanup-tag` (the caller
92
+ * deletes the tag itself). The try/catch covers gh being absent entirely: a
93
+ * missing binary makes the spawn reject rather than exit non-zero, and losing
94
+ * the tag deletion over an uninstalled CLI would be the worse outcome.
95
+ */
96
+ const deleteGitHubRelease = async (tag) => {
97
+ try {
98
+ const result = await shellExec.exec `gh release delete ${tag} --yes`
99
+ .noThrow()
100
+ .spawn();
101
+ return result.code === 0;
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ };
107
+ // =============================================================================
108
+ // Prompt helper
109
+ // =============================================================================
110
+ /**
111
+ * Ask a yes/no question via the TUI confirm widget.
112
+ * Falls back to a simple process-based prompt if TUI is unavailable.
113
+ */
114
+ const confirmPrompt = async (question) => {
115
+ const { ctx } = cliSupport.getCliContext();
116
+ const answer = await tui.confirm(ctx, { message: question });
117
+ return answer === true;
118
+ };
119
+ // =============================================================================
120
+ // Pure logic — release
121
+ // =============================================================================
122
+ const defaultReleaseDeps = {
123
+ generateChangelog: async (options) => {
124
+ const changelogModule = await import("./changelog-gen.js");
125
+ return await changelogModule.generateChangelog(options);
126
+ },
127
+ };
128
+ /**
129
+ * Perform a full release: bump version, generate changelog, commit, push, and
130
+ * push the `v<version>` tag that starts the release pipeline.
131
+ *
132
+ * The tag push is the last step and the only one CI reacts to, so a release
133
+ * that stops before it publishes nothing — both push failures below name the
134
+ * command that finishes the job.
135
+ *
136
+ * @param options - Release options
137
+ * @returns Result describing what happened
138
+ * @throws If working tree is dirty, or unpushed commits exist (without --yes)
139
+ */
140
+ export const release = async (options, deps = defaultReleaseDeps) => {
141
+ const { type, dryRun = false } = options;
142
+ // 1. Validate clean tree
143
+ if (!(await gitIsClean())) {
144
+ throw new Error("Working tree is dirty. Commit or stash changes first.");
145
+ }
146
+ // 2. Check for unpushed commits
147
+ const unpushed = await gitUnpushedCommits();
148
+ if (unpushed.length > 0 && options.yes !== true) {
149
+ throw new Error(`You have ${unpushed.length} unpushed commit(s):\n${unpushed.join("\n")}\n\nPush first, or re-run with --yes to continue anyway.`);
150
+ }
151
+ // 3. Read previous version
152
+ const previousVersion = (await versions.readVersionFile()) ?? "0.0.0";
153
+ // 4. Bump version (unless type is "same")
154
+ //
155
+ // Keep the version versions() computed rather than re-reading VERSION after
156
+ // the call. Under --dry-run nothing is written, so a re-read returns the OLD
157
+ // version and the preview reports "4.1.58 -> 4.1.58" -- telling the user the
158
+ // release is a no-op when it is not. targetVersion is computed before any
159
+ // write, so it is correct in both modes.
160
+ let bumpedVersion;
161
+ if (type !== "same") {
162
+ // Import versions dynamically to avoid circular deps at module scope
163
+ const versionsModule = await import("./versions.js");
164
+ const bump = await versionsModule.versions(type, { dryRun });
165
+ bumpedVersion = bump.targetVersion;
166
+ }
167
+ // 5. Resolve the new version
168
+ const version = bumpedVersion ?? (await versions.readVersionFile()) ?? previousVersion;
169
+ const tag = `v${version}`;
170
+ // 6. Generate changelog
171
+ //
172
+ // The version is passed explicitly for the same reason it is kept from
173
+ // versions() above: under --dry-run the VERSION file still holds the old
174
+ // version, so a changelog that re-read it would head the entry with it.
175
+ //
176
+ // A failure stops the release. It means the native library did not load or
177
+ // git or the file write failed; going on would tag a release with no section,
178
+ // which the release gate rejects only after the tag is pushed.
179
+ let changelogGenerated;
180
+ try {
181
+ const generated = await deps.generateChangelog({ dryRun, version });
182
+ changelogGenerated = generated.entryCount > 0;
183
+ }
184
+ catch (err) {
185
+ throw new Error("Changelog generation failed, so nothing was committed, pushed or " +
186
+ "tagged. Any version bump this run made is still in the working tree." +
187
+ cliSupport.commandFailureDetail(err), { cause: err });
188
+ }
189
+ // 7-11. Format, stage, commit, push, tag
190
+ let committed = false;
191
+ let pushed = false;
192
+ let tagPushed = false;
193
+ if (!dryRun) {
194
+ // Format changelog with the workspace's pinned oxfmt. `node --run` puts
195
+ // node_modules/.bin on PATH without the dependency check `pnpm exec` runs.
196
+ await shellExec.exec `node --run fmt -- CHANGELOG.md`.noThrow().spawn();
197
+ // Stage and commit
198
+ //
199
+ // Every pathspec here must be able to match a TRACKED file: `git add` exits
200
+ // 128 on one that matches nothing, and gitAddAndCommit does not tolerate
201
+ // that, so a dead entry aborts the release after the version bump has
202
+ // already been written to disk.
203
+ //
204
+ // Note `*` spans `/` in a git pathspec, so `pkg/*/package.json` does reach
205
+ // the scoped packages.
206
+ const filesToStage = [
207
+ "VERSION",
208
+ "CHANGELOG.md",
209
+ "pkg/*/package.json",
210
+ "package.json",
211
+ ];
212
+ const commitMessage = `chore(codebase): release ${tag}`;
213
+ await gitAddAndCommit(commitMessage, filesToStage);
214
+ committed = true;
215
+ // Push the commit.
216
+ //
217
+ // Both pushes run after the bump is already written and committed, so a
218
+ // bare git error would leave the operator holding a half-released tree.
219
+ // Each message therefore states the exact command that resumes the release.
220
+ try {
221
+ await gitPushHead();
222
+ }
223
+ catch (err) {
224
+ throw new Error("Release commit created but push failed. Fix the push, then run: " +
225
+ `git push origin HEAD && eser codebase gh release-tag${cliSupport.commandFailureDetail(err)}`, { cause: err });
226
+ }
227
+ pushed = true;
228
+ // Push the tag — this is what starts the release pipeline.
229
+ //
230
+ // pushReleaseTag re-reads the VERSION file, which on disk already holds the
231
+ // new version, so it derives the same tag computed above. Dynamic import
232
+ // matches the versions/changelog calls above.
233
+ try {
234
+ const releaseTagModule = await import("./release-tag.js");
235
+ await releaseTagModule.pushReleaseTag({});
236
+ }
237
+ catch (err) {
238
+ throw new Error(`Commit pushed but tag push failed. Run "eser codebase rerelease" to ` +
239
+ `create and push ${tag}.${cliSupport.commandFailureDetail(err)}`, { cause: err });
240
+ }
241
+ tagPushed = true;
242
+ }
243
+ // Under --dry-run the tag is only computed, never previewed through
244
+ // pushReleaseTag({ dryRun: true }): that reads the VERSION file, which no
245
+ // write has touched yet, so it would report the OLD version's tag — the same
246
+ // stale-read trap as the bumpedVersion comment above.
247
+ return {
248
+ version,
249
+ previousVersion,
250
+ tag,
251
+ changelogGenerated,
252
+ committed,
253
+ pushed,
254
+ tagPushed,
255
+ dryRun,
256
+ };
257
+ };
258
+ // =============================================================================
259
+ // Pure logic — rerelease
260
+ // =============================================================================
261
+ /**
262
+ * Delete the current version tag and re-push it at HEAD, re-firing the release
263
+ * pipeline for a version that is already committed.
264
+ *
265
+ * This is the repair path for a release whose tag push failed or whose pipeline
266
+ * run needs repeating; it adds no commit and changes no version.
267
+ *
268
+ * Pre-checks: tree must be clean, no unpushed commits.
269
+ *
270
+ * @param options - Rerelease options
271
+ * @returns Result describing what happened
272
+ * @throws If working tree is dirty or unpushed commits exist
273
+ */
274
+ export const rerelease = async (options = {}) => {
275
+ const { dryRun = false } = options;
276
+ // Validate clean tree
277
+ if (!(await gitIsClean())) {
278
+ throw new Error("Working tree is dirty. Commit and push first.");
279
+ }
280
+ // Check for unpushed commits
281
+ const unpushed = await gitUnpushedCommits();
282
+ if (unpushed.length > 0) {
283
+ throw new Error(`You have unpushed commits. Push first, then rerelease.\n${unpushed.join("\n")}`);
284
+ }
285
+ // Read current version
286
+ const version = await versions.readVersionFile();
287
+ if (version === undefined || !/^\d+\.\d+\.\d+$/.test(version)) {
288
+ throw new Error(`Invalid or missing version in VERSION file: "${version}"`);
289
+ }
290
+ const tag = `v${version}`;
291
+ if (!dryRun) {
292
+ // The delete is noThrow, so this repairs both the never-tagged case and a
293
+ // tag stranded locally by a failed push. No guard is needed against tagging
294
+ // the wrong commit: the tree is clean, so HEAD's VERSION is the file read
295
+ // above, and the tag can only land on a commit carrying that version.
296
+ await gitDeleteTag(tag);
297
+ // The delete already removed the remote tag. If the re-push fails here the
298
+ // version has NO tag at all, which is worse than where we started, so name
299
+ // the command that finishes the job.
300
+ try {
301
+ const releaseTagModule = await import("./release-tag.js");
302
+ await releaseTagModule.pushReleaseTag({});
303
+ }
304
+ catch (err) {
305
+ throw new Error(`${tag} was deleted but could not be recreated — the version now has ` +
306
+ `no tag. Run "eser codebase gh release-tag" to push it.${cliSupport.commandFailureDetail(err)}`, { cause: err });
307
+ }
308
+ }
309
+ return { version, tag, dryRun };
310
+ };
311
+ // =============================================================================
312
+ // Pure logic — unrelease
313
+ // =============================================================================
314
+ /**
315
+ * Delete the current version tag (local + remote) and its GitHub Release.
316
+ *
317
+ * The version-bump commit is deliberately left in history — rewriting a pushed
318
+ * commit is not something a cleanup command should do behind the operator's
319
+ * back. `eser codebase rerelease` re-pushes the tag afterwards, which is the
320
+ * command for "the version is already committed, the tag needs to exist again".
321
+ *
322
+ * @param options - Unrelease options
323
+ * @returns Result describing what happened
324
+ */
325
+ export const unrelease = async (options = {}) => {
326
+ // Read current version
327
+ const version = await versions.readVersionFile();
328
+ if (version === undefined || !/^\d+\.\d+\.\d+$/.test(version)) {
329
+ throw new Error(`Invalid or missing version in VERSION file: "${version}"`);
330
+ }
331
+ const tag = `v${version}`;
332
+ if (options.yes !== true) {
333
+ throw new Error(`This will delete tag ${tag} (local + remote) and its GitHub Release. Re-run with --yes to confirm.`);
334
+ }
335
+ // Release first, tag second: gh resolves a release by its tag, so deleting
336
+ // the tag first would leave the Release unreachable and stranded.
337
+ const releaseDeleted = await deleteGitHubRelease(tag);
338
+ await gitDeleteTag(tag);
339
+ return { version, tag, deleted: true, releaseDeleted };
340
+ };
341
+ // =============================================================================
342
+ // Handlers
343
+ // =============================================================================
344
+ /** Handler: wraps release as a Task via fromPromise. */
345
+ export const releaseHandler = (input) => functions.task.fromPromise(() => release(input));
346
+ /** Handler: wraps rerelease as a Task via fromPromise. */
347
+ export const rereleaseHandler = (input) => functions.task.fromPromise(() => rerelease(input));
348
+ /** Handler: wraps unrelease as a Task via fromPromise. */
349
+ export const unreleaseHandler = (input) => functions.task.fromPromise(() => unrelease(input));
350
+ // =============================================================================
351
+ // CLI Adapters
352
+ // =============================================================================
353
+ /** Adapter: CliEvent -> ReleaseOptions */
354
+ const releaseCliAdapter = (event) => {
355
+ const typeArg = event.args[0];
356
+ const validTypes = ["patch", "minor", "major", "same"];
357
+ if (typeArg === undefined || !validTypes.includes(typeArg)) {
358
+ return primitives.results.fail(functions.handler.adaptError(`Usage: eser codebase release <patch|minor|major|same> [--dry-run] [--yes]`));
359
+ }
360
+ return primitives.results.ok({
361
+ type: typeArg,
362
+ dryRun: event.flags["dry-run"] === true,
363
+ yes: event.flags["yes"] === true,
364
+ });
365
+ };
366
+ /** Adapter: CliEvent -> RereleaseOptions */
367
+ const rereleaseCliAdapter = (event) => primitives.results.ok({
368
+ dryRun: event.flags["dry-run"] === true,
369
+ yes: event.flags["yes"] === true,
370
+ });
371
+ /** Adapter: CliEvent -> UnreleaseOptions */
372
+ const unreleaseCliAdapter = (event) => primitives.results.ok({
373
+ yes: event.flags["yes"] === true,
374
+ });
375
+ // =============================================================================
376
+ // CLI ResponseMappers
377
+ // =============================================================================
378
+ /** ResponseMapper: formats ReleaseResult for CLI output. */
379
+ const releaseResponseMapper = (result) => {
380
+ const { ctx } = cliSupport.getCliContext();
381
+ if (primitives.results.isFail(result)) {
382
+ const err = result.error;
383
+ const message = err instanceof Error
384
+ ? err.message
385
+ : (err.message ?? String(err));
386
+ tui.log.error(ctx, message);
387
+ return primitives.results.fail({ exitCode: 1 });
388
+ }
389
+ const { value } = result;
390
+ if (value.dryRun) {
391
+ tui.log.warn(ctx, "[DRY RUN] Release preview:");
392
+ tui.log.info(ctx, ` Version: ${value.previousVersion} -> ${value.version}`);
393
+ tui.log.info(ctx, ` Changelog: ${value.changelogGenerated ? "generated" : "no user-facing changes"}`);
394
+ tui.log.info(ctx, ` Tag: v${value.version} (would be created and pushed — starts the release pipeline)`);
395
+ tui.log.info(ctx, " No changes were made.");
396
+ }
397
+ else {
398
+ tui.log.success(ctx, `Released v${value.version}`);
399
+ tui.log.info(ctx, ` Version: ${value.previousVersion} -> ${value.version}`);
400
+ tui.log.info(ctx, ` Changelog: ${value.changelogGenerated ? "updated" : "no user-facing changes"}`);
401
+ // The old "Committed: true / Pushed: true" booleans are gone: this branch
402
+ // is only reached when every step succeeded, so they could never print
403
+ // anything but true.
404
+ tui.log.info(ctx, " Commit: pushed to origin");
405
+ tui.log.info(ctx, ` Tag: ${value.tag} pushed — release pipeline started.`);
406
+ tui.log.info(ctx, " Watch: https://github.com/eser/stack/actions");
407
+ }
408
+ return primitives.results.ok(undefined);
409
+ };
410
+ /** ResponseMapper: formats RereleaseResult for CLI output. */
411
+ const rereleaseResponseMapper = (result) => {
412
+ const { ctx } = cliSupport.getCliContext();
413
+ if (primitives.results.isFail(result)) {
414
+ const err = result.error;
415
+ const message = err instanceof Error
416
+ ? err.message
417
+ : (err.message ?? String(err));
418
+ tui.log.error(ctx, message);
419
+ return primitives.results.fail({ exitCode: 1 });
420
+ }
421
+ const { value } = result;
422
+ if (value.dryRun) {
423
+ tui.log.warn(ctx, `[DRY RUN] Would delete and recreate tag ${value.tag} at HEAD (re-fires the release pipeline)`);
424
+ }
425
+ else {
426
+ tui.log.success(ctx, `Re-created tag ${value.tag} at HEAD`);
427
+ tui.log.info(ctx, "Tag push re-fired the release pipeline.");
428
+ tui.log.info(ctx, "Watch: https://github.com/eser/stack/actions");
429
+ }
430
+ return primitives.results.ok(undefined);
431
+ };
432
+ /** ResponseMapper: formats UnreleaseResult for CLI output. */
433
+ const unreleaseResponseMapper = (result) => {
434
+ const { ctx } = cliSupport.getCliContext();
435
+ if (primitives.results.isFail(result)) {
436
+ const err = result.error;
437
+ const message = err instanceof Error
438
+ ? err.message
439
+ : (err.message ?? String(err));
440
+ tui.log.error(ctx, message);
441
+ return primitives.results.fail({ exitCode: 1 });
442
+ }
443
+ const { value } = result;
444
+ if (value.deleted) {
445
+ tui.log.success(ctx, `Deleted tag ${value.tag} (local + remote).`);
446
+ }
447
+ if (value.releaseDeleted) {
448
+ tui.log.success(ctx, `Deleted GitHub Release ${value.tag}.`);
449
+ }
450
+ else {
451
+ tui.log.warn(ctx, `GitHub Release not deleted (no release for ${value.tag}, or gh CLI unavailable).`);
452
+ }
453
+ tui.log.info(ctx, `The release commit remains in history. Run "eser codebase rerelease" to ` +
454
+ `re-push the tag once the version is publishable again — but only if ` +
455
+ `nothing was published: npm refuses a re-published version.`);
456
+ return primitives.results.ok(undefined);
457
+ };
458
+ // =============================================================================
459
+ // CLI Triggers
460
+ // =============================================================================
461
+ /** Runnable CLI trigger for release. */
462
+ export const handleReleaseCli = functions.handler.createTrigger({
463
+ handler: releaseHandler,
464
+ adaptInput: releaseCliAdapter,
465
+ adaptOutput: releaseResponseMapper,
466
+ });
467
+ /** Runnable CLI trigger for rerelease. */
468
+ export const handleRereleaseCli = functions.handler.createTrigger({
469
+ handler: rereleaseHandler,
470
+ adaptInput: rereleaseCliAdapter,
471
+ adaptOutput: rereleaseResponseMapper,
472
+ });
473
+ /** Runnable CLI trigger for unrelease. */
474
+ export const handleUnreleaseCli = functions.handler.createTrigger({
475
+ handler: unreleaseHandler,
476
+ adaptInput: unreleaseCliAdapter,
477
+ adaptOutput: unreleaseResponseMapper,
478
+ });
479
+ // =============================================================================
480
+ // CLI Entry Points
481
+ // =============================================================================
482
+ const DRY_RUN_AND_YES = {
483
+ "dry-run": { type: "boolean", short: "n" },
484
+ yes: { type: "boolean", short: "y" },
485
+ };
486
+ /** Parse the release arguments: the bump type, `--dry-run` (`-n`), `--yes` (`-y`). */
487
+ export const parseReleaseArgs = (cliArgs) => cliSupport.parseCliEvent("release", cliArgs, DRY_RUN_AND_YES);
488
+ /** Parse the rerelease arguments: `--dry-run` (`-n`), `--yes` (`-y`). */
489
+ export const parseRereleaseArgs = (cliArgs) => cliSupport.parseCliEvent("rerelease", cliArgs, DRY_RUN_AND_YES);
490
+ /** Parse the unrelease arguments: `--yes` (`-y`). */
491
+ export const parseUnreleaseArgs = (cliArgs) => cliSupport.parseCliEvent("unrelease", cliArgs, {
492
+ yes: { type: "boolean", short: "y" },
493
+ });
494
+ /** The event with `--yes` set, after the user confirmed at the prompt. */
495
+ const confirmed = (event) => ({
496
+ ...event,
497
+ flags: { ...event.flags, yes: true },
498
+ });
499
+ /** CLI entry point for release (default export via main). */
500
+ export const main = async (cliArgs) => {
501
+ const event = parseReleaseArgs(cliArgs);
502
+ // Interactive confirmation for release (when not --yes and not --dry-run)
503
+ const typeArg = event.args[0];
504
+ const dryRun = event.flags["dry-run"] === true;
505
+ const yes = event.flags["yes"] === true;
506
+ if (typeArg !== undefined &&
507
+ !dryRun &&
508
+ !yes &&
509
+ ["patch", "minor", "major", "same"].includes(typeArg)) {
510
+ // Preview version
511
+ const previousVersion = (await versions.readVersionFile()) ?? "0.0.0";
512
+ // Name the tag in the prompt — it is the step that actually publishes. The
513
+ // bump goes through FFI and can fail on a machine without the native lib,
514
+ // and a wrong number here would misdescribe what is about to be pushed, so
515
+ // fall back to number-free wording rather than guessing.
516
+ // bumpVersion returns the Go FormatSemver shape, which is ALWAYS
517
+ // v-prefixed ("v4.3.1"), while readVersionFile returns the bare VERSION
518
+ // file contents ("4.3.0"). Normalising here is what keeps the prompt from
519
+ // reading "push tag vv4.3.1" on every bump.
520
+ let nextVersion;
521
+ try {
522
+ const bumped = typeArg === "same"
523
+ ? previousVersion
524
+ : await versions.bumpVersion(previousVersion, typeArg);
525
+ nextVersion = bumped.replace(/^v/, "");
526
+ }
527
+ catch {
528
+ nextVersion = undefined;
529
+ }
530
+ const { ctx, output: out } = cliSupport.getCliContext();
531
+ tui.log.info(ctx, `Current version: ${previousVersion}`);
532
+ tui.log.info(ctx, `Bump type: ${typeArg}`);
533
+ tui.log.info(ctx, nextVersion !== undefined
534
+ ? `This will bump the version, generate the changelog, commit, push, and push tag v${nextVersion} — the tag push starts the release pipeline.`
535
+ : "This will bump the version, generate the changelog, commit, push, and push the release tag — the tag push starts the release pipeline.");
536
+ await out.flush();
537
+ const proceed = await confirmPrompt("Proceed?");
538
+ if (!proceed) {
539
+ tui.log.warn(ctx, "Aborted.");
540
+ return primitives.results.ok(undefined);
541
+ }
542
+ // User confirmed — add --yes so the handler doesn't throw on unpushed commits prompt
543
+ return await handleReleaseCli(confirmed(event));
544
+ }
545
+ return await handleReleaseCli(event);
546
+ };
547
+ /** CLI entry point for rerelease. */
548
+ export const rereleaseMain = async (cliArgs) => {
549
+ const event = parseRereleaseArgs(cliArgs);
550
+ const dryRun = event.flags["dry-run"] === true;
551
+ const yes = event.flags["yes"] === true;
552
+ if (!dryRun && !yes) {
553
+ const version = (await versions.readVersionFile()) ?? "0.0.0";
554
+ const proceed = await confirmPrompt(`Delete and recreate tag v${version} at HEAD? This re-fires the release pipeline.`);
555
+ if (!proceed) {
556
+ tui.log.warn(cliSupport.getCliContext().ctx, "Aborted.");
557
+ return primitives.results.ok(undefined);
558
+ }
559
+ return await handleRereleaseCli(confirmed(event));
560
+ }
561
+ return await handleRereleaseCli(event);
562
+ };
563
+ /** CLI entry point for unrelease. */
564
+ export const unreleaseMain = async (cliArgs) => {
565
+ const event = parseUnreleaseArgs(cliArgs);
566
+ if (event.flags["yes"] !== true) {
567
+ const version = (await versions.readVersionFile()) ?? "0.0.0";
568
+ const proceed = await confirmPrompt(`Delete tag v${version} and its GitHub Release? The release commit stays in history.`);
569
+ if (!proceed) {
570
+ tui.log.warn(cliSupport.getCliContext().ctx, "Aborted.");
571
+ return primitives.results.ok(undefined);
572
+ }
573
+ // unrelease() still throws without this; the prompt is the interactive
574
+ // path, the throw stays as the backstop for non-interactive callers.
575
+ return await handleUnreleaseCli(confirmed(event));
576
+ }
577
+ return await handleUnreleaseCli(event);
578
+ };
579
+ if (import.meta.main) {
580
+ // Entry point: the await only runs when this file is executed directly.
581
+ // oxlint-disable-next-line node/no-top-level-await
582
+ const result = await main(standards.crossRuntime.runtime.process.args);
583
+ cliSupport.runCliMain(result, cliSupport.getCliContext().output);
584
+ }
@@ -0,0 +1,3 @@
1
+ export declare const codeMask: (content: string) => Uint8Array;
2
+ /** The 1-based line number of a character index in `content`. */
3
+ export declare const lineOf: (content: string, index: number) => number;