soltask 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,28 @@
1
+ import type { JsonObject } from "./util.js";
2
+ export declare const EXIT_OK = 0;
3
+ export declare const EXIT_RUNTIME = 1;
4
+ export declare const EXIT_VALIDATION = 2;
5
+ export declare const EXIT_AUTH = 3;
6
+ export declare const EXIT_CONFLICT = 4;
7
+ export declare const EXIT_WATCH_STOPPED = 5;
8
+ export interface CliErrorOptions {
9
+ exitCode?: number;
10
+ /** The structured body emitted under `--json`; defaults to a generic `cli_error`. */
11
+ payload?: JsonObject;
12
+ /** True when the failure is transient (HTTP 408/429/5xx or non-TLS transport fault) and a caller may retry. */
13
+ retryable?: boolean;
14
+ /** Whole seconds the server asked the caller to wait before retrying, when known. */
15
+ retryAfter?: number | null;
16
+ }
17
+ /** A failure the CLI reports on its own: the message goes to stderr (or JSON to stdout) and the exit code is one of 1..5. */
18
+ export declare class CliError extends Error {
19
+ readonly exitCode: number;
20
+ readonly payload: JsonObject;
21
+ readonly retryable: boolean;
22
+ readonly retryAfter: number | null;
23
+ constructor(message: string, options?: CliErrorOptions);
24
+ }
25
+ /** Maps an HTTP status to the CLI exit code: auth 3, conflict 4, bad input 2, anything else 1. */
26
+ export declare function exitCodeForStatus(status: number): number;
27
+ /** The `--json` error document: the server's own fields first, then the fields every consumer can rely on. */
28
+ export declare function errorToJson(err: CliError): JsonObject;
package/dist/errors.js ADDED
@@ -0,0 +1,40 @@
1
+ export const EXIT_OK = 0;
2
+ export const EXIT_RUNTIME = 1;
3
+ export const EXIT_VALIDATION = 2;
4
+ export const EXIT_AUTH = 3;
5
+ export const EXIT_CONFLICT = 4;
6
+ export const EXIT_WATCH_STOPPED = 5;
7
+ /** A failure the CLI reports on its own: the message goes to stderr (or JSON to stdout) and the exit code is one of 1..5. */
8
+ export class CliError extends Error {
9
+ exitCode;
10
+ payload;
11
+ retryable;
12
+ retryAfter;
13
+ constructor(message, options = {}) {
14
+ super(message);
15
+ this.name = "CliError";
16
+ this.exitCode = options.exitCode ?? EXIT_RUNTIME;
17
+ this.payload = options.payload ?? { ok: false, error: "cli_error", message };
18
+ this.retryable = options.retryable ?? false;
19
+ this.retryAfter = options.retryAfter ?? null;
20
+ }
21
+ }
22
+ /** Maps an HTTP status to the CLI exit code: auth 3, conflict 4, bad input 2, anything else 1. */
23
+ export function exitCodeForStatus(status) {
24
+ if (status === 401 || status === 403) {
25
+ return EXIT_AUTH;
26
+ }
27
+ if (status === 409 || status === 428) {
28
+ return EXIT_CONFLICT;
29
+ }
30
+ if (status === 400 || status === 422) {
31
+ return EXIT_VALIDATION;
32
+ }
33
+ return EXIT_RUNTIME;
34
+ }
35
+ /** The `--json` error document: the server's own fields first, then the fields every consumer can rely on. */
36
+ export function errorToJson(err) {
37
+ const rawCode = err.payload["error"];
38
+ const code = typeof rawCode === "string" && rawCode.trim() !== "" ? rawCode : "cli_error";
39
+ return { ...err.payload, ok: false, error: code, message: err.message, exit_code: err.exitCode };
40
+ }
@@ -0,0 +1,35 @@
1
+ import { type Stats } from "node:fs";
2
+ export declare const O_NOFOLLOW_SAFE: number;
3
+ export declare const O_NONBLOCK_SAFE: number;
4
+ /** `lstat` that treats a missing path as `undefined` and rethrows every other failure. */
5
+ export declare function tryLstat(path: string): Stats | undefined;
6
+ export declare const WINDOWS_DEVICE_NAME: RegExp;
7
+ /** An explicit absolute destination is allowed. A relative destination stays inside its base directory. */
8
+ export declare function resolveOutputPath(base: string, name: string): string;
9
+ /**
10
+ * Checks the destination before a write and reports the existing regular file there, if any.
11
+ *
12
+ * `baseDir` is the directory the person is working in (default: the target's own directory). It and everything above
13
+ * it is trusted as the system resolved it. Every component below it, down to the target itself, must be a plain name
14
+ * (no `..`, reserved device name, trailing dot or space, or characters Windows refuses) and must not be a symlink.
15
+ */
16
+ export declare function checkOutputPath(path: string, baseDir?: string): Stats | undefined;
17
+ /** Reads at most `maxBytes` of UTF-8 text, accepting a byte order mark and normalizing line endings. */
18
+ export declare function readUtf8File(path: string, maxBytes: number): string;
19
+ export interface AtomicWriteOptions {
20
+ /** Permission bits of the new file (ignored on Windows, which has ACLs instead). */
21
+ fileMode: number;
22
+ /** Permission bits for directories this call has to create. */
23
+ dirMode?: number;
24
+ /** Refuse when `path` already is a symbolic link. */
25
+ refuseSymlink?: boolean;
26
+ /** Install the finished file only when the destination is still absent. */
27
+ exclusive?: boolean;
28
+ /** What the file is called in error messages, e.g. "config file". */
29
+ label: string;
30
+ }
31
+ /**
32
+ * Writes `content` to a sibling temp file created exclusively with `fileMode`, then renames it over `path`.
33
+ * A reader never sees a half-written file, and a symlink planted at `path` is refused when requested.
34
+ */
35
+ export declare function writeFileAtomic(path: string, content: string, options: AtomicWriteOptions): void;
package/dist/fsutil.js ADDED
@@ -0,0 +1,243 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, renameSync, unlinkSync, writeSync, } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { CliError, EXIT_CONFLICT, EXIT_VALIDATION } from "./errors.js";
5
+ import { errorCode, errorMessage, oneLine } from "./util.js";
6
+ // Some POSIX open(2) flags are undefined at runtime on Windows even when typed as numbers.
7
+ const fsConstants = constants;
8
+ export const O_NOFOLLOW_SAFE = fsConstants.O_NOFOLLOW ?? 0;
9
+ export const O_NONBLOCK_SAFE = fsConstants.O_NONBLOCK ?? 0;
10
+ /** `lstat` that treats a missing path as `undefined` and rethrows every other failure. */
11
+ export function tryLstat(path) {
12
+ try {
13
+ return lstatSync(path);
14
+ }
15
+ catch (err) {
16
+ if (errorCode(err) === "ENOENT") {
17
+ return undefined;
18
+ }
19
+ throw err;
20
+ }
21
+ }
22
+ export const WINDOWS_DEVICE_NAME = /^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:[ \t]*(?:\.|$))/i;
23
+ /** An explicit absolute destination is allowed. A relative destination stays inside its base directory. */
24
+ export function resolveOutputPath(base, name) {
25
+ if (name === "" || name.includes("\0") || name.endsWith("/") || name.endsWith("\\")) {
26
+ throw new CliError(`Invalid output file path: ${JSON.stringify(name)}`, { exitCode: EXIT_VALIDATION });
27
+ }
28
+ const target = resolve(base, name);
29
+ if (!isAbsolute(name)) {
30
+ const fromBase = relative(base, target);
31
+ if (fromBase === "" || fromBase === ".." || fromBase.startsWith(`..${sep}`) || isAbsolute(fromBase)) {
32
+ throw new CliError(`Output path must stay within ${base}: ${JSON.stringify(name)}`, { exitCode: EXIT_VALIDATION });
33
+ }
34
+ }
35
+ return target;
36
+ }
37
+ function isInside(base, target) {
38
+ const fromBase = relative(base, target);
39
+ return fromBase !== "" && fromBase !== ".." && !fromBase.startsWith(`..${sep}`) && !isAbsolute(fromBase);
40
+ }
41
+ /** The deepest existing ancestor of `path` (the path itself when it exists), or undefined when nothing on the way exists. */
42
+ function nearestExisting(path) {
43
+ let current = path;
44
+ for (;;) {
45
+ if (tryLstat(current) !== undefined) {
46
+ return current;
47
+ }
48
+ const parent = dirname(current);
49
+ if (parent === current) {
50
+ return undefined;
51
+ }
52
+ current = parent;
53
+ }
54
+ }
55
+ /**
56
+ * Checks the destination before a write and reports the existing regular file there, if any.
57
+ *
58
+ * `baseDir` is the directory the person is working in (default: the target's own directory). It and everything above
59
+ * it is trusted as the system resolved it. Every component below it, down to the target itself, must be a plain name
60
+ * (no `..`, reserved device name, trailing dot or space, or characters Windows refuses) and must not be a symlink.
61
+ */
62
+ export function checkOutputPath(path, baseDir) {
63
+ const unsafe = () => new CliError(`Unsafe output path: ${JSON.stringify(path)}`, { exitCode: EXIT_VALIDATION });
64
+ if (path.split(/[\\/]/).includes("..")) {
65
+ throw unsafe();
66
+ }
67
+ const target = resolve(path);
68
+ let base = baseDir === undefined ? dirname(target) : resolve(baseDir);
69
+ if (!isInside(base, target)) {
70
+ base = dirname(target);
71
+ }
72
+ try {
73
+ const anchor = nearestExisting(base);
74
+ if (anchor === undefined) {
75
+ throw new CliError(`Could not inspect output path ${path}: no existing parent directory`);
76
+ }
77
+ const trusted = realpathSync(anchor);
78
+ if (!tryLstat(trusted)?.isDirectory()) {
79
+ throw new CliError(`Output parent is not a directory: ${anchor}`, { exitCode: EXIT_VALIDATION });
80
+ }
81
+ const components = relative(anchor, target).split(sep);
82
+ let current = trusted;
83
+ for (const [index, name] of components.entries()) {
84
+ if (name === "" || WINDOWS_DEVICE_NAME.test(name) || /[<>:"|?*\\]/.test(name) || /[. ]$/.test(name) || oneLine(name) !== name) {
85
+ throw unsafe();
86
+ }
87
+ current = join(current, name);
88
+ const stat = tryLstat(current);
89
+ if (stat?.isSymbolicLink()) {
90
+ throw new CliError(`Refusing to write through a symbolic link: ${join(anchor, ...components.slice(0, index + 1))}`, {
91
+ exitCode: EXIT_VALIDATION,
92
+ });
93
+ }
94
+ if (index === components.length - 1) {
95
+ if (stat === undefined || stat.isFile()) {
96
+ return stat;
97
+ }
98
+ throw new CliError(`Output path is not a regular file: ${target}`, { exitCode: EXIT_VALIDATION });
99
+ }
100
+ if (stat !== undefined && !stat.isDirectory()) {
101
+ throw new CliError(`Output parent is not a directory: ${join(anchor, ...components.slice(0, index + 1))}`, {
102
+ exitCode: EXIT_VALIDATION,
103
+ });
104
+ }
105
+ }
106
+ }
107
+ catch (err) {
108
+ if (err instanceof CliError) {
109
+ throw err;
110
+ }
111
+ throw new CliError(`Could not inspect output path ${path}: ${errorMessage(err)}`);
112
+ }
113
+ return undefined;
114
+ }
115
+ /** Reads at most `maxBytes` of UTF-8 text, accepting a byte order mark and normalizing line endings. */
116
+ export function readUtf8File(path, maxBytes) {
117
+ const tooLarge = () => new CliError(`${path} exceeds the ${maxBytes}-byte limit.`, { exitCode: EXIT_VALIDATION });
118
+ let content;
119
+ try {
120
+ const fd = openSync(path, constants.O_RDONLY | O_NONBLOCK_SAFE);
121
+ try {
122
+ const stat = fstatSync(fd);
123
+ if (!stat.isFile()) {
124
+ throw new CliError(`Expected a regular file: ${path}`, { exitCode: EXIT_VALIDATION });
125
+ }
126
+ if (stat.size > maxBytes) {
127
+ throw tooLarge();
128
+ }
129
+ const buffer = Buffer.allocUnsafe(maxBytes + 1);
130
+ let offset = 0;
131
+ while (offset < buffer.length) {
132
+ const count = readSync(fd, buffer, offset, buffer.length - offset, null);
133
+ if (count === 0) {
134
+ break;
135
+ }
136
+ offset += count;
137
+ }
138
+ if (offset > maxBytes) {
139
+ throw tooLarge();
140
+ }
141
+ content = buffer.subarray(0, offset);
142
+ }
143
+ finally {
144
+ closeSync(fd);
145
+ }
146
+ }
147
+ catch (err) {
148
+ if (err instanceof CliError) {
149
+ throw err;
150
+ }
151
+ throw new CliError(`Could not read ${path}: ${errorMessage(err)}`);
152
+ }
153
+ try {
154
+ return new TextDecoder("utf-8", { fatal: true }).decode(content).replace(/\r\n?/g, "\n");
155
+ }
156
+ catch {
157
+ throw new CliError(`${path} is not valid UTF-8.`, { exitCode: EXIT_VALIDATION });
158
+ }
159
+ }
160
+ /** Error codes that mean "this filesystem cannot make hard links" (FAT, exFAT, some network and FUSE mounts). */
161
+ const NO_HARD_LINKS = new Set(["EPERM", "ENOTSUP", "EOPNOTSUPP", "ENOSYS", "EXDEV", "EMLINK"]);
162
+ function writeAll(fd, bytes, fileMode) {
163
+ let offset = 0;
164
+ while (offset < bytes.length) {
165
+ offset += writeSync(fd, bytes, offset);
166
+ }
167
+ if (process.platform !== "win32") {
168
+ fchmodSync(fd, fileMode);
169
+ }
170
+ fsyncSync(fd);
171
+ }
172
+ /**
173
+ * Creates `path` only if nothing is there: it is installed with a hard link when the filesystem has them, else by
174
+ * creating it directly with `wx` (which also refuses a planted symbolic link). Either way an existing file is never replaced.
175
+ */
176
+ function installExclusive(tmp, path, bytes, fileMode) {
177
+ try {
178
+ linkSync(tmp, path);
179
+ return;
180
+ }
181
+ catch (err) {
182
+ const code = errorCode(err);
183
+ if (code === undefined || !NO_HARD_LINKS.has(code)) {
184
+ throw err;
185
+ }
186
+ }
187
+ const fd = openSync(path, "wx", fileMode);
188
+ try {
189
+ writeAll(fd, bytes, fileMode);
190
+ }
191
+ finally {
192
+ closeSync(fd);
193
+ }
194
+ }
195
+ /**
196
+ * Writes `content` to a sibling temp file created exclusively with `fileMode`, then renames it over `path`.
197
+ * A reader never sees a half-written file, and a symlink planted at `path` is refused when requested.
198
+ */
199
+ export function writeFileAtomic(path, content, options) {
200
+ const dir = dirname(path);
201
+ let tmp;
202
+ try {
203
+ if (options.refuseSymlink === true && tryLstat(path)?.isSymbolicLink() === true) {
204
+ throw new CliError(`Refusing to write through a symbolic link: ${path}`);
205
+ }
206
+ mkdirSync(dir, options.dirMode === undefined ? { recursive: true } : { recursive: true, mode: options.dirMode });
207
+ tmp = join(dir, `.${basename(path)}.${randomBytes(6).toString("hex")}.tmp`);
208
+ const bytes = Buffer.from(content, "utf8");
209
+ const fd = openSync(tmp, "wx", options.fileMode);
210
+ try {
211
+ writeAll(fd, bytes, options.fileMode);
212
+ }
213
+ finally {
214
+ closeSync(fd);
215
+ }
216
+ if (options.exclusive === true) {
217
+ installExclusive(tmp, path, bytes, options.fileMode);
218
+ }
219
+ else {
220
+ renameSync(tmp, path);
221
+ tmp = undefined;
222
+ }
223
+ }
224
+ catch (err) {
225
+ if (err instanceof CliError) {
226
+ throw err;
227
+ }
228
+ if (options.exclusive === true && errorCode(err) === "EEXIST") {
229
+ throw new CliError(`File ${path} already exists; pass --force to overwrite.`, { exitCode: EXIT_CONFLICT });
230
+ }
231
+ throw new CliError(`Could not save ${options.label} ${path}: ${errorMessage(err)}`);
232
+ }
233
+ finally {
234
+ if (tmp !== undefined) {
235
+ try {
236
+ unlinkSync(tmp);
237
+ }
238
+ catch {
239
+ // The temp file is already gone; nothing is left to clean up.
240
+ }
241
+ }
242
+ }
243
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from "./cli.js";
3
+ import { EXIT_RUNTIME } from "./errors.js";
4
+ function fail(reason) {
5
+ const message = reason instanceof Error ? reason.message : String(reason);
6
+ process.stderr.write(`soltask: unexpected error: ${message}\n`);
7
+ process.exit(EXIT_RUNTIME);
8
+ }
9
+ // A closed pipe (`soltask whoami | head`) is the reader's choice, not a failure.
10
+ process.stdout.on("error", (err) => {
11
+ if (err.code === "EPIPE") {
12
+ process.exit(0);
13
+ }
14
+ fail(err);
15
+ });
16
+ process.on("unhandledRejection", fail);
17
+ process.on("uncaughtException", fail);
18
+ process.exitCode = await runCli(process.argv.slice(2));
@@ -0,0 +1,27 @@
1
+ export interface TextSink {
2
+ write(chunk: string): unknown;
3
+ isTTY?: boolean;
4
+ }
5
+ interface Sinks {
6
+ stdout: TextSink;
7
+ stderr: TextSink;
8
+ }
9
+ /** Runs `fn` with `out`, `errOut`, `outRaw`, `emitJson`, and `emitJsonLine` writing to `sinks`, for everything `fn` starts. */
10
+ export declare function withOutputSinks<T>(sinks: Sinks, fn: () => T): T;
11
+ export declare function stdoutIsTty(): boolean;
12
+ /** A line on stdout. */
13
+ export declare function out(text?: string): void;
14
+ /** A line on stderr. */
15
+ export declare function errOut(text?: string): void;
16
+ /** Text exactly as given, no newline added. Control characters are dropped when a terminal is reading. */
17
+ export declare function outRaw(text: string): void;
18
+ /** Pretty-printed JSON document followed by a newline. */
19
+ export declare function emitJson(data: unknown): void;
20
+ /** Single-line JSON record followed by a newline (NDJSON), for realtime streaming output. */
21
+ export declare function emitJsonLine(data: unknown): void;
22
+ export declare function displayText(value: unknown): string;
23
+ /** Left-aligned columns separated by two spaces, a dashed rule under the headers, no trailing blanks. */
24
+ export declare function formatTable(headers: readonly string[], rows: readonly (readonly unknown[])[]): string;
25
+ /** `YYYY-MM-DD HH:MM:SSZ` for epoch seconds; anything else is shown as given, null as a dash. */
26
+ export declare function formatTimestamp(value: unknown): string;
27
+ export {};
package/dist/output.js ADDED
@@ -0,0 +1,74 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { cellText, oneLine, stripControls } from "./util.js";
3
+ // Commands print through the module-level functions below. The streams they print to belong to the run in
4
+ // progress (`withOutputSinks`), carried along its async calls, so concurrent runs never share or clobber them.
5
+ const storage = new AsyncLocalStorage();
6
+ function current() {
7
+ return storage.getStore() ?? { stdout: process.stdout, stderr: process.stderr };
8
+ }
9
+ /** Runs `fn` with `out`, `errOut`, `outRaw`, `emitJson`, and `emitJsonLine` writing to `sinks`, for everything `fn` starts. */
10
+ export function withOutputSinks(sinks, fn) {
11
+ return storage.run(sinks, fn);
12
+ }
13
+ export function stdoutIsTty() {
14
+ return current().stdout.isTTY === true;
15
+ }
16
+ /** A line on stdout. */
17
+ export function out(text = "") {
18
+ current().stdout.write(`${text}\n`);
19
+ }
20
+ /** A line on stderr. */
21
+ export function errOut(text = "") {
22
+ current().stderr.write(`${text}\n`);
23
+ }
24
+ /** Text exactly as given, no newline added. Control characters are dropped when a terminal is reading. */
25
+ export function outRaw(text) {
26
+ current().stdout.write(stdoutIsTty() ? stripControls(text) : text);
27
+ }
28
+ /** Pretty-printed JSON document followed by a newline. */
29
+ export function emitJson(data) {
30
+ current().stdout.write(`${JSON.stringify(data, null, 2)}\n`);
31
+ }
32
+ /** Single-line JSON record followed by a newline (NDJSON), for realtime streaming output. */
33
+ export function emitJsonLine(data) {
34
+ current().stdout.write(`${JSON.stringify(data)}\n`);
35
+ }
36
+ export function displayText(value) {
37
+ return oneLine(cellText(value));
38
+ }
39
+ function width(text) {
40
+ return Array.from(text).length;
41
+ }
42
+ function pad(text, size) {
43
+ return text + " ".repeat(Math.max(0, size - width(text)));
44
+ }
45
+ /** Left-aligned columns separated by two spaces, a dashed rule under the headers, no trailing blanks. */
46
+ export function formatTable(headers, rows) {
47
+ const body = rows.map((row) => row.map(displayText));
48
+ const widths = headers.map((header) => width(header));
49
+ for (const row of body) {
50
+ row.forEach((text, index) => {
51
+ if (index < widths.length) {
52
+ widths[index] = Math.max(widths[index] ?? 0, width(text));
53
+ }
54
+ });
55
+ }
56
+ const render = (cells) => widths
57
+ .map((size, index) => pad(cells[index] ?? "", size))
58
+ .join(" ")
59
+ .trimEnd();
60
+ return [render(headers), render(widths.map((size) => "-".repeat(size))), ...body.map(render)].join("\n");
61
+ }
62
+ /** `YYYY-MM-DD HH:MM:SSZ` for epoch seconds; anything else is shown as given, null as a dash. */
63
+ export function formatTimestamp(value) {
64
+ if (typeof value === "number" && Number.isFinite(value)) {
65
+ const date = new Date(value * 1000);
66
+ if (!Number.isNaN(date.getTime())) {
67
+ return `${date.toISOString().slice(0, 19).replace("T", " ")}Z`;
68
+ }
69
+ }
70
+ if (value === null || value === undefined) {
71
+ return "-";
72
+ }
73
+ return typeof value === "string" ? value : displayText(value);
74
+ }