@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,310 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Update command handler — updates eser CLI to the latest version.
4
+ *
5
+ * Decision tree:
6
+ * ┌─ ctx.invoker === "binary" (compiled binary)
7
+ * │ → fetch latest release from GitHub API
8
+ * │ → compare versions
9
+ * │ → download + verify SHA256 + replace self
10
+ * │ → Unix: write to temp, rename() over self
11
+ * │ → Windows: write .new.exe, print manual instructions
12
+ * └─ else (Node install)
13
+ * → detectExecutionContext() → run `npm update -g`
14
+ *
15
+ * @module
16
+ */
17
+ import * as span from "@eserstack/streams/span";
18
+ import * as streams from "@eserstack/streams";
19
+ import * as standardsCrossRuntime from "@eserstack/standards/cross-runtime";
20
+ import * as appOpts from "../app-opts.js";
21
+ import * as results from "@eserstack/primitives/results";
22
+ import * as shellExec from "@eserstack/shell/exec";
23
+ import * as install from "./install.js";
24
+ import * as versionCheck from "./version-check.js";
25
+ // Release archives are tens of megabytes; this bounds a stalled download.
26
+ const ARCHIVE_DOWNLOAD_TIMEOUT_MS = 300_000;
27
+ const runtime = standardsCrossRuntime.runtime;
28
+ /**
29
+ * The command that updates a Node install. A function of the app: the same
30
+ * command updates eser, noskills or laroux; only the npm package differs.
31
+ */
32
+ export const updateConfig = (app) => ({
33
+ cmd: "npm",
34
+ args: ["update", "-g", "-f", app.npmPackage ?? app.command],
35
+ });
36
+ /**
37
+ * The checksum SHA256SUMS.txt records for `archiveName`, if any.
38
+ *
39
+ * Matches the second field exactly, the way install.sh's
40
+ * `awk -v want="${ARCHIVE}" '$2 == want { print $1 }'` does. A substring test
41
+ * would happily accept the line for a DIFFERENT artifact whose name merely
42
+ * contains this one -- `<archive>.sig`, `<archive>.sha256` -- and verify the
43
+ * download against a checksum that was never about it.
44
+ */
45
+ export const findExpectedChecksum = (sumsText, archiveName) => {
46
+ for (const line of sumsText.split("\n")) {
47
+ const fields = line.trim().split(/\s+/);
48
+ if (fields.length >= 2 && fields[1] === archiveName) {
49
+ return fields[0];
50
+ }
51
+ }
52
+ return undefined;
53
+ };
54
+ const sha256Hex = async (data) => {
55
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
56
+ return Array.from(new Uint8Array(hashBuffer))
57
+ .map((b) => b.toString(16).padStart(2, "0"))
58
+ .join("");
59
+ };
60
+ /**
61
+ * Verifies a downloaded release archive against the release's SHA256SUMS.txt.
62
+ *
63
+ * Fails CLOSED on every path, matching install.sh: the list being unreachable
64
+ * and the list not naming this archive are refusals, not permission to skip
65
+ * verification. Anyone able to suppress or truncate SHA256SUMS.txt -- a proxy,
66
+ * a captive portal, a partial release upload -- would otherwise get an
67
+ * unverified binary written over the running one.
68
+ */
69
+ export const verifyArchiveChecksum = async (baseUrl, archiveName, archiveData, fetchFn) => {
70
+ const doFetch = fetchFn ?? globalThis.fetch.bind(globalThis);
71
+ const sumsUrl = `${baseUrl}/SHA256SUMS.txt`;
72
+ let sumsResponse;
73
+ try {
74
+ sumsResponse = await doFetch(sumsUrl);
75
+ }
76
+ catch (error) {
77
+ const reason = error instanceof Error ? error.message : String(error);
78
+ return results.fail(`Could not download ${sumsUrl}: ${reason}\n` +
79
+ "Refusing to install a binary that cannot be verified. Check your " +
80
+ "network or proxy and try again.");
81
+ }
82
+ if (!sumsResponse.ok) {
83
+ return results.fail(`Could not download ${sumsUrl}: HTTP ${sumsResponse.status}\n` +
84
+ "Refusing to install a binary that cannot be verified. Check your " +
85
+ "network or proxy and try again.");
86
+ }
87
+ const sumsText = await sumsResponse.text();
88
+ const expectedHash = findExpectedChecksum(sumsText, archiveName);
89
+ if (expectedHash === undefined) {
90
+ return results.fail(`No checksum listed for ${archiveName} in ${sumsUrl}\n` +
91
+ "Refusing to install a binary that cannot be verified. The release " +
92
+ "may be incomplete; report it at " +
93
+ "https://github.com/eser/stack/issues");
94
+ }
95
+ const actualHash = await sha256Hex(archiveData);
96
+ if (actualHash !== expectedHash) {
97
+ return results.fail(`SHA256 checksum verification failed for ${archiveName}\n` +
98
+ ` expected ${expectedHash}\n` +
99
+ ` actual ${actualHash}\n` +
100
+ "Refusing to install. Re-run the update; if it persists, report it at " +
101
+ "https://github.com/eser/stack/issues");
102
+ }
103
+ return results.ok(undefined);
104
+ };
105
+ /** The installer that `missingArchiveMessage` points to. */
106
+ const INSTALL_SCRIPT_URL = "https://raw.githubusercontent.com/eser/stack/main/etc/scripts/install.sh";
107
+ /**
108
+ * The message for a release that has no archive for this binary: the update
109
+ * stops there, and the user gets the two ways to install the current version
110
+ * instead of a download or checksum error. A release can drop an archive when
111
+ * a tool stops shipping as a standalone binary, as laroux does after 4.5.x.
112
+ */
113
+ export const missingArchiveMessage = (app, tag, archiveName, isWindows) => {
114
+ const installScript = isWindows
115
+ ? `& ([scriptblock]::Create((irm ${INSTALL_SCRIPT_URL.replace(/\.sh$/, ".ps1")}))) -Product ${app.command}`
116
+ : `curl -fsSL ${INSTALL_SCRIPT_URL} | sh -s ${app.command}`;
117
+ return (`Release ${tag} has no ${archiveName}, so this ${app.command} binary ` +
118
+ "cannot update itself.\n" +
119
+ "Install the current version with one of:\n" +
120
+ ` npm install -g ${app.npmPackage ?? app.command}\n` +
121
+ ` ${installScript}`);
122
+ };
123
+ // Release archives keep the Rust target triples the v4.5.x binaries look for.
124
+ const RELEASE_TRIPLE_MAP = {
125
+ "linux-amd64": "x86_64-unknown-linux-gnu",
126
+ "linux-arm64": "aarch64-unknown-linux-gnu",
127
+ "darwin-amd64": "x86_64-apple-darwin",
128
+ "darwin-arm64": "aarch64-apple-darwin",
129
+ "windows-amd64": "x86_64-pc-windows-msvc",
130
+ };
131
+ /**
132
+ * Builds the command that unpacks a downloaded release archive into
133
+ * `destDir`. Both paths stay separate arguments, so no shell or PowerShell
134
+ * parser reads them: a Windows path keeps its backslashes, and a quote in a
135
+ * path cannot end a string and start a command.
136
+ *
137
+ * Windows uses the bsdtar that ships in System32 (Windows 10 1803 and later),
138
+ * which reads zip archives. The absolute path matters: a GNU tar from Git for
139
+ * Windows earlier on PATH cannot read zip and takes `C:` for a remote host.
140
+ */
141
+ export const extractArchiveCommand = (archivePath, destDir, target) => {
142
+ if (target.platform === "unix") {
143
+ return { cmd: "tar", args: ["-xzf", archivePath, "-C", destDir] };
144
+ }
145
+ const systemRoot = target.systemRoot?.replace(/[\\/]+$/, "") ?? "";
146
+ const cmd = systemRoot !== "" ? `${systemRoot}\\System32\\tar.exe` : "tar.exe";
147
+ return { cmd, args: ["-xf", archivePath, "-C", destDir] };
148
+ };
149
+ /**
150
+ * Detects the current platform in the format used by our release archives.
151
+ */
152
+ const detectPlatformTarget = () => {
153
+ const os = standardsCrossRuntime.getPlatform(); // "darwin" | "linux" | "windows"
154
+ const arch = standardsCrossRuntime.getArch(); // "amd64" | "arm64"
155
+ const key = `${os}-${arch}`;
156
+ return RELEASE_TRIPLE_MAP[key];
157
+ };
158
+ /**
159
+ * Self-updates a compiled binary from GitHub Releases.
160
+ *
161
+ * Exported for the legacy-update preflight
162
+ * (cmd/legacy-forwarder/legacy_update_test.go), which runs this flow for a
163
+ * v4.5.2 laroux and noskills against a local release.
164
+ */
165
+ export const updateCompiledBinary = async (app, currentVersion) => {
166
+ const out = streams.output({
167
+ renderer: streams.renderers.ansi(),
168
+ sink: streams.sinks.stdout(),
169
+ });
170
+ out.writeln(span.text("Install method: "), span.cyan("compiled binary"));
171
+ out.writeln(span.text("Current version: "), span.cyan(currentVersion), span.text("\n"));
172
+ // Check for updates
173
+ out.writeln(span.text("Checking for updates..."));
174
+ const check = await versionCheck.checkForUpdate(currentVersion);
175
+ if (check === undefined) {
176
+ out.writeln(span.red("Could not check for updates."));
177
+ await out.close();
178
+ return results.fail({ exitCode: 1 });
179
+ }
180
+ if (!check.updateAvailable) {
181
+ out.writeln(span.green(`\nAlready up to date (v${currentVersion}).`));
182
+ await out.close();
183
+ return results.ok(undefined);
184
+ }
185
+ out.writeln(span.text("\nNew version available: "), span.cyan(`v${check.latestVersion}`));
186
+ // Determine platform
187
+ const target = detectPlatformTarget();
188
+ if (target === undefined) {
189
+ const os = standardsCrossRuntime.getPlatform();
190
+ const arch = standardsCrossRuntime.getArch();
191
+ out.writeln(span.red(`\nUnsupported platform: ${os}-${arch}`));
192
+ await out.close();
193
+ return results.fail({ exitCode: 1 });
194
+ }
195
+ const tag = `v${check.latestVersion}`;
196
+ const isWindows = standardsCrossRuntime.getPlatform() === "windows";
197
+ const archiveExt = isWindows ? "zip" : "tar.gz";
198
+ const archiveName = `${app.command}-${tag}-${target}.${archiveExt}`;
199
+ const baseUrl = `https://github.com/eser/stack/releases/download/${tag}`;
200
+ // Download archive
201
+ out.writeln(span.dim(`Downloading ${archiveName}...`));
202
+ const archiveResponse = await fetch(`${baseUrl}/${archiveName}`, {
203
+ signal: AbortSignal.timeout(ARCHIVE_DOWNLOAD_TIMEOUT_MS),
204
+ });
205
+ if (archiveResponse.status === 404) {
206
+ // Fails closed with a way forward: the release has no archive for this
207
+ // binary, which is not a network problem a retry would fix.
208
+ await archiveResponse.body?.cancel();
209
+ out.writeln(span.red(`\n${missingArchiveMessage(app, tag, archiveName, isWindows)}`));
210
+ await out.close();
211
+ return results.fail({ exitCode: 1 });
212
+ }
213
+ if (!archiveResponse.ok) {
214
+ out.writeln(span.red(`\nFailed to download: HTTP ${archiveResponse.status}`));
215
+ await out.close();
216
+ return results.fail({ exitCode: 1 });
217
+ }
218
+ // Download SHA256SUMS.txt and verify. Verification is mandatory: see
219
+ // verifyArchiveChecksum for why every failure path is a refusal.
220
+ const archiveBytes = new Uint8Array(await archiveResponse.arrayBuffer());
221
+ const verification = await verifyArchiveChecksum(baseUrl, archiveName, archiveBytes);
222
+ if (results.isFail(verification)) {
223
+ out.writeln(span.red(`\n${verification.error}`));
224
+ await out.close();
225
+ return results.fail({ exitCode: 1 });
226
+ }
227
+ out.writeln(span.dim("Checksum verified."));
228
+ // Extract to temp directory
229
+ const tempDir = await runtime.fs.makeTempDir({ prefix: "eser-update-" });
230
+ try {
231
+ // The bytes written are the ones the checksum was verified against.
232
+ const archivePath = runtime.path.join(tempDir, archiveName);
233
+ await runtime.fs.writeFile(archivePath, archiveBytes);
234
+ const extract = extractArchiveCommand(archivePath, tempDir, isWindows
235
+ ? { platform: "windows", systemRoot: runtime.env.get("SystemRoot") }
236
+ : { platform: "unix" });
237
+ await new shellExec.CommandBuilder(extract.cmd, [...extract.args]).spawn();
238
+ // The archive holds the binary under the app's command name, as
239
+ // `eser dev compile` (pkg/ajan/codebasefx) packs it.
240
+ const newBinaryPath = runtime.path.join(tempDir, isWindows ? `${app.command}.exe` : app.command);
241
+ const currentBinaryPath = runtime.process.execPath();
242
+ if (isWindows) {
243
+ // Windows: can't replace a running binary. Write .new.exe next to current.
244
+ const newPath = currentBinaryPath.replace(/\.exe$/i, ".new.exe");
245
+ await runtime.fs.copyFile(newBinaryPath, newPath);
246
+ out.writeln(span.green(`\nDownloaded v${check.latestVersion}!`));
247
+ out.writeln(span.text("\nTo complete the update, close this terminal and rename:\n "), span.cyan(newPath), span.text("\nto:\n "), span.cyan(currentBinaryPath));
248
+ }
249
+ else {
250
+ // Unix: write to temp, then rename over self
251
+ const tempBinaryPath = `${currentBinaryPath}.new`;
252
+ await runtime.fs.copyFile(newBinaryPath, tempBinaryPath);
253
+ await runtime.fs.chmod(tempBinaryPath, 0o755);
254
+ await runtime.fs.rename(tempBinaryPath, currentBinaryPath);
255
+ out.writeln(span.green(`\nUpdated to v${check.latestVersion}!`));
256
+ }
257
+ }
258
+ catch (error) {
259
+ if (install.isPermissionDenied(error)) {
260
+ out.writeln(span.red(`\nPermission denied. Try running with sudo:\n sudo ${app.command} update`));
261
+ await out.close();
262
+ return results.fail({ exitCode: 1 });
263
+ }
264
+ await out.close();
265
+ throw error;
266
+ }
267
+ finally {
268
+ try {
269
+ await runtime.fs.remove(tempDir, { recursive: true });
270
+ }
271
+ catch {
272
+ // Best effort cleanup
273
+ }
274
+ }
275
+ await out.close();
276
+ return results.ok(undefined);
277
+ };
278
+ /**
279
+ * Updates eser CLI using the appropriate method for the current install type.
280
+ */
281
+ export const updateHandler = async (_ctx, app) => {
282
+ const execContext = await standardsCrossRuntime.detectExecutionContext(appOpts.appOpts(app));
283
+ // Compiled binary: self-update from GitHub Releases
284
+ if (execContext.invoker === "binary") {
285
+ return await updateCompiledBinary(app, _ctx.root.versionString ?? "0.0.0");
286
+ }
287
+ const out = streams.output({
288
+ renderer: streams.renderers.ansi(),
289
+ sink: streams.sinks.stdout(),
290
+ });
291
+ // Node install: use npm
292
+ out.writeln(span.text("Detected runtime: "), span.cyan(execContext.runtime));
293
+ const { cmd, args } = updateConfig(app);
294
+ out.writeln(span.dim(`Running: ${cmd} ${args.join(" ")}`));
295
+ out.writeln();
296
+ const result = await shellExec.exec `${cmd} ${args}`
297
+ .stdout("inherit")
298
+ .stderr("inherit")
299
+ .noThrow()
300
+ .spawn();
301
+ if (!result.success) {
302
+ out.writeln(span.red("\nUpdate failed."));
303
+ await out.close();
304
+ return results.fail({ exitCode: result.code });
305
+ }
306
+ out.writeln(span.green("\nUpdate complete!"));
307
+ out.writeln(span.text("The "), span.cyan(app.command), span.text(" command has been updated to the latest version."));
308
+ await out.close();
309
+ return results.ok(undefined);
310
+ };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Result of an update check.
3
+ */
4
+ export type UpdateCheckResult = {
5
+ latestVersion: string;
6
+ currentVersion: string;
7
+ updateAvailable: boolean;
8
+ };
9
+ /**
10
+ * Checks for an available update by comparing the current version
11
+ * against the latest GitHub release.
12
+ *
13
+ * Results are cached for 24 hours in ~/.cache/eser/latest-version.json.
14
+ * Returns undefined if the check fails for any reason (no network, etc.).
15
+ */
16
+ export declare const checkForUpdate: (currentVersionArg: string) => Promise<UpdateCheckResult | undefined>;
@@ -0,0 +1,176 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Version check utilities - shared by version and doctor handlers.
4
+ *
5
+ * Checks for CLI updates by comparing the current version against the
6
+ * latest GitHub release, with 24-hour caching in ~/.cache/eser/.
7
+ *
8
+ * @module
9
+ */
10
+ import * as standardsCrossRuntime from "@eserstack/standards/cross-runtime";
11
+ import * as versions from "@eserstack/standards/versions";
12
+ const runtime = standardsCrossRuntime.runtime;
13
+ // Deliberately shared across binaries, not per-app.
14
+ //
15
+ // eser, noskills and laroux are built from one repo, released at one version by
16
+ // one pipeline, and this check asks that repo's releases endpoint. The answer is
17
+ // identical for all three, so sharing the cache means one fetch serves whichever
18
+ // binary you happen to run next — and a per-app cache would multiply the network
19
+ // call this file exists to avoid.
20
+ const CACHE_DIR = ".cache/eser";
21
+ const CACHE_FILE = "latest-version.json";
22
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
23
+ /**
24
+ * How long to wait after a FAILED or timed-out attempt before trying again.
25
+ *
26
+ * Short enough that a genuinely available update is still noticed the same day,
27
+ * long enough that a machine which cannot reach api.github.com -- offline, or
28
+ * behind a proxy that blackholes it -- stops paying UPDATE_CHECK_TIMEOUT_MS on
29
+ * every single command.
30
+ */
31
+ const ATTEMPT_BACKOFF_MS = 60 * 60 * 1000; // 1 hour
32
+ const RELEASES_URL = "https://api.github.com/repos/eser/stack/releases/latest";
33
+ const getCachePath = () => {
34
+ const home = standardsCrossRuntime.getHomedir();
35
+ return runtime.path.join(home, CACHE_DIR, CACHE_FILE);
36
+ };
37
+ const getCacheDir = () => {
38
+ const home = standardsCrossRuntime.getHomedir();
39
+ return runtime.path.join(home, CACHE_DIR);
40
+ };
41
+ const readCache = async () => {
42
+ try {
43
+ const cachePath = getCachePath();
44
+ const exists = await runtime.fs.exists(cachePath);
45
+ if (!exists) {
46
+ return undefined;
47
+ }
48
+ const content = await runtime.fs.readTextFile(cachePath);
49
+ const cached = JSON.parse(content);
50
+ if (typeof cached.latestVersion !== "string" ||
51
+ typeof cached.checkedAt !== "number") {
52
+ return undefined;
53
+ }
54
+ return cached;
55
+ }
56
+ catch {
57
+ return undefined;
58
+ }
59
+ };
60
+ const writeCache = async (latestVersion, attemptedAt) => {
61
+ try {
62
+ const cacheDir = getCacheDir();
63
+ await runtime.fs.ensureDir(cacheDir);
64
+ const cachePath = getCachePath();
65
+ const data = {
66
+ latestVersion,
67
+ checkedAt: Date.now(),
68
+ attemptedAt: attemptedAt ?? Date.now(),
69
+ };
70
+ await runtime.fs.writeTextFile(cachePath, JSON.stringify(data));
71
+ }
72
+ catch {
73
+ // Skip caching if directory creation or write fails
74
+ }
75
+ };
76
+ /**
77
+ * Records that a fetch is about to start, keeping whatever version we already
78
+ * knew.
79
+ *
80
+ * This is what stops the check costing 200ms on EVERY invocation. The caller
81
+ * races checkForUpdate against UPDATE_CHECK_TIMEOUT_MS and then exits the
82
+ * process outright, so a fetch slower than that -- which TLS to api.github.com
83
+ * always is -- is killed before it can write anything. Nothing was recorded,
84
+ * so the next run tried again, lost again, and paid the full timeout again,
85
+ * forever. Marking the attempt BEFORE the fetch is the only write guaranteed to
86
+ * survive.
87
+ */
88
+ const markAttempt = async (knownVersion) => {
89
+ try {
90
+ await runtime.fs.ensureDir(getCacheDir());
91
+ const data = {
92
+ latestVersion: knownVersion ?? "",
93
+ // Deliberately old, so a marker never masquerades as a fresh answer.
94
+ checkedAt: 0,
95
+ attemptedAt: Date.now(),
96
+ };
97
+ await runtime.fs.writeTextFile(getCachePath(), JSON.stringify(data));
98
+ }
99
+ catch {
100
+ // Best effort — a missing marker only costs another attempt.
101
+ }
102
+ };
103
+ // The check runs on ordinary CLI invocations; a slow network must not hold
104
+ // the command up.
105
+ const VERSION_CHECK_TIMEOUT_MS = 5_000;
106
+ const fetchLatestVersion = async () => {
107
+ try {
108
+ const response = await fetch(RELEASES_URL, {
109
+ headers: { Accept: "application/vnd.github.v3+json" },
110
+ signal: AbortSignal.timeout(VERSION_CHECK_TIMEOUT_MS),
111
+ });
112
+ if (!response.ok) {
113
+ return undefined;
114
+ }
115
+ const data = (await response.json());
116
+ const tagName = data.tag_name;
117
+ if (typeof tagName !== "string") {
118
+ return undefined;
119
+ }
120
+ // Strip leading 'v' if present
121
+ return tagName.startsWith("v") ? tagName.slice(1) : tagName;
122
+ }
123
+ catch {
124
+ return undefined;
125
+ }
126
+ };
127
+ /**
128
+ * Checks for an available update by comparing the current version
129
+ * against the latest GitHub release.
130
+ *
131
+ * Results are cached for 24 hours in ~/.cache/eser/latest-version.json.
132
+ * Returns undefined if the check fails for any reason (no network, etc.).
133
+ */
134
+ export const checkForUpdate = async (currentVersionArg) => {
135
+ try {
136
+ const currentVersion = currentVersionArg;
137
+ // Try reading from cache first
138
+ const cached = await readCache();
139
+ if (cached !== undefined) {
140
+ const age = Date.now() - cached.checkedAt;
141
+ if (age < CACHE_TTL_MS) {
142
+ return {
143
+ latestVersion: cached.latestVersion,
144
+ currentVersion,
145
+ updateAvailable: versions.compareTextVersions(currentVersion, cached.latestVersion),
146
+ };
147
+ }
148
+ }
149
+ // Back off after a recent attempt that produced nothing.
150
+ //
151
+ // Without this the timeout is paid on every invocation forever: the caller
152
+ // kills the process at UPDATE_CHECK_TIMEOUT_MS, so a slow fetch never gets
153
+ // to record anything, and the next run repeats it.
154
+ if (cached?.attemptedAt !== undefined &&
155
+ Date.now() - cached.attemptedAt < ATTEMPT_BACKOFF_MS) {
156
+ return undefined;
157
+ }
158
+ // Recorded BEFORE the fetch, because this is the only write that is certain
159
+ // to happen while the process is still alive.
160
+ await markAttempt(cached?.latestVersion);
161
+ const latestVersion = await fetchLatestVersion();
162
+ if (latestVersion === undefined) {
163
+ return undefined;
164
+ }
165
+ // Update cache (fire-and-forget, errors are swallowed)
166
+ await writeCache(latestVersion);
167
+ return {
168
+ latestVersion,
169
+ currentVersion,
170
+ updateAvailable: versions.compareTextVersions(currentVersion, latestVersion),
171
+ };
172
+ }
173
+ catch {
174
+ return undefined;
175
+ }
176
+ };
@@ -0,0 +1,3 @@
1
+ import type { CliApp } from "../app.ts";
2
+ import type * as shellArgs from "@eserstack/shell/args";
3
+ export declare const versionHandler: (ctx: shellArgs.CommandContext, app: CliApp) => Promise<shellArgs.CliResult<void>>;
@@ -0,0 +1,45 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Version command handler - displays CLI version and checks for updates.
4
+ *
5
+ * When invoked with --bare, prints only the raw version string (no extras).
6
+ * This is relied upon by Homebrew's test block.
7
+ *
8
+ * @module
9
+ */
10
+ import * as span from "@eserstack/streams/span";
11
+ import * as streams from "@eserstack/streams";
12
+ import * as results from "@eserstack/primitives/results";
13
+ import * as versionCheck from "./version-check.js";
14
+ const UPDATE_CHECK_TIMEOUT_MS = 200;
15
+ export const versionHandler = async (ctx, app) => {
16
+ const out = streams.output({
17
+ renderer: streams.renderers.ansi(),
18
+ sink: streams.sinks.stdout(),
19
+ });
20
+ // --bare: print raw version only (Homebrew compatibility)
21
+ if (ctx.flags["bare"] === true) {
22
+ out.writeln(span.text(ctx.root.versionString ?? "unknown"));
23
+ await out.close();
24
+ return results.ok(undefined);
25
+ }
26
+ out.writeln(span.text(`${app.command} ${ctx.root.versionString ?? "unknown"}`));
27
+ // Race the update check against a short timeout so the command stays snappy
28
+ try {
29
+ const timeoutPromise = new Promise((resolve) => {
30
+ setTimeout(() => resolve(undefined), UPDATE_CHECK_TIMEOUT_MS);
31
+ });
32
+ const result = await Promise.race([
33
+ versionCheck.checkForUpdate(ctx.root.versionString ?? "0.0.0"),
34
+ timeoutPromise,
35
+ ]);
36
+ if (result !== undefined && result.updateAvailable) {
37
+ out.writeln(span.dim(` Update available: v${result.latestVersion} — run '${app.command} update'`));
38
+ }
39
+ }
40
+ catch {
41
+ // Silently ignore — update check is best-effort
42
+ }
43
+ await out.close();
44
+ return results.ok(undefined);
45
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The `system` command tree, shared by every binary this workspace ships.
3
+ *
4
+ * A factory rather than a module-level constant, because `eser`, `noskills` and
5
+ * `laroux` each need the same tree describing THEMSELVES: `noskills system
6
+ * install` must install noskills, and its help must say so. One implementation,
7
+ * parameterised by {@link CliApp} — not three copies.
8
+ *
9
+ * @module
10
+ */
11
+ import * as shellArgs from "@eserstack/shell/args";
12
+ import type { CliApp } from "./app.ts";
13
+ /**
14
+ * Builds the `system` tree for one binary.
15
+ *
16
+ * The app descriptor is bound into each handler here, so the handlers stay
17
+ * plain functions of (ctx, app) and nothing has to reach for a global.
18
+ */
19
+ export declare const createSystemCommand: (app: CliApp) => shellArgs.Command;
@@ -0,0 +1,52 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * The `system` command tree, shared by every binary this workspace ships.
4
+ *
5
+ * A factory rather than a module-level constant, because `eser`, `noskills` and
6
+ * `laroux` each need the same tree describing THEMSELVES: `noskills system
7
+ * install` must install noskills, and its help must say so. One implementation,
8
+ * parameterised by {@link CliApp} — not three copies.
9
+ *
10
+ * @module
11
+ */
12
+ import * as shellArgs from "@eserstack/shell/args";
13
+ import * as handlers from "./handlers/mod.js";
14
+ /**
15
+ * Builds the `system` tree for one binary.
16
+ *
17
+ * The app descriptor is bound into each handler here, so the handlers stay
18
+ * plain functions of (ctx, app) and nothing has to reach for a global.
19
+ */
20
+ export const createSystemCommand = (app) => new shellArgs.Command("system")
21
+ .description("Commands related with this CLI")
22
+ .command(new shellArgs.Command("install")
23
+ .description(`Install ${app.command} globally`)
24
+ .run((ctx) => handlers.installHandler(ctx, app)))
25
+ .command(new shellArgs.Command("uninstall")
26
+ .description(`Uninstall ${app.command} globally`)
27
+ .run((ctx) => handlers.uninstallHandler(ctx, app)))
28
+ .command(new shellArgs.Command("update")
29
+ .description(`Update ${app.command} to the latest version`)
30
+ .run((ctx) => handlers.updateHandler(ctx, app)))
31
+ .command(new shellArgs.Command("completions")
32
+ .description("Generate shell completion scripts")
33
+ .flag({
34
+ name: "shell",
35
+ type: "string",
36
+ description: "Shell type: bash, zsh, or fish",
37
+ })
38
+ .run((ctx) => handlers.completionsHandler(ctx, app)))
39
+ .command(new shellArgs.Command("version")
40
+ .description("Show version and check for updates")
41
+ .flag({
42
+ name: "bare",
43
+ type: "boolean",
44
+ description: "Print version number only",
45
+ })
46
+ .run((ctx) => handlers.versionHandler(ctx, app)))
47
+ .command(new shellArgs.Command("doctor")
48
+ .description("Run diagnostic checks")
49
+ .run((ctx) => handlers.doctorHandler(ctx, app)))
50
+ .command(new shellArgs.Command("info")
51
+ .description("Show runtime and execution context diagnostics")
52
+ .run((ctx) => handlers.infoHandler(ctx, app)));
@@ -0,0 +1,28 @@
1
+ /**
2
+ * `codebase commitmsg` — Generate a commit message from git diff using AI.
3
+ *
4
+ * @module
5
+ */
6
+ import * as results from "@eserstack/primitives/results";
7
+ import type * as shellArgs from "@eserstack/shell/args";
8
+ import * as ai from "@eserstack/ai/mod";
9
+ import type * as workflows from "@eserstack/workflows/mod";
10
+ export declare const main: (_args?: readonly string[]) => Promise<shellArgs.CliResult<void>>;
11
+ export declare const generateCommitMessage: (diff: string, providerName?: string) => Promise<results.Result<string, Error>>;
12
+ /** Builds the generation request that asks for a commit line for `diff`. */
13
+ export declare const buildCommitMessageRequest: (diff: string) => ai.GenerateTextOptions;
14
+ /**
15
+ * Reads the commit line out of a model reply. A refusal fails instead of
16
+ * becoming the commit message: its text explains why the model declined, and
17
+ * the conventional-commit fallback below would otherwise pass it through.
18
+ */
19
+ export declare const readCommitMessage: (result: ai.GenerateTextResult) => results.Result<string, Error>;
20
+ /**
21
+ * Pull the conventional-commit line out of a model response. Agent-style
22
+ * providers (claude-code) often wrap the answer in reasoning ("Let me craft…")
23
+ * or emit several candidate lines; we want the single commit line, preferring
24
+ * the last conforming one (the model's final answer), and fall back to the first
25
+ * non-empty line if none match.
26
+ */
27
+ export declare const extractCommitLine: (text: string) => string;
28
+ export declare const workflowTool: workflows.WorkflowTool;