@effected/cli-kit 0.0.0-stage → 0.26.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 (103) hide show
  1. package/Cancelled.js +43 -0
  2. package/CliAudience.js +177 -0
  3. package/CliColor.js +59 -0
  4. package/CliEnv.js +101 -0
  5. package/CliExit.js +64 -0
  6. package/CliFailure.js +287 -0
  7. package/CliFormat.js +124 -0
  8. package/CliInteractive.js +94 -0
  9. package/CliLinks.js +153 -0
  10. package/CliLog.js +367 -0
  11. package/CliLogger.js +91 -0
  12. package/CliMessage.js +79 -0
  13. package/CliPrompt.js +110 -0
  14. package/CliRuntime.js +254 -0
  15. package/CliTest.js +206 -0
  16. package/CliTheme.js +142 -0
  17. package/ConfigIssueRenderer.js +63 -0
  18. package/Doc.js +548 -0
  19. package/Fmt.js +335 -0
  20. package/GithubAnnotation.js +39 -0
  21. package/Glyphs.js +82 -0
  22. package/LICENSE +21 -0
  23. package/NotInteractive.js +41 -0
  24. package/README.md +215 -2
  25. package/Render.js +280 -0
  26. package/SchemaIssueRenderer.js +47 -0
  27. package/Status.js +165 -0
  28. package/TestTerminal.js +101 -0
  29. package/Token.js +68 -0
  30. package/index.d.ts +3951 -0
  31. package/index.js +27 -0
  32. package/internal/ExitRequested.js +21 -0
  33. package/internal/HelpRouting.js +35 -0
  34. package/internal/ansi.js +229 -0
  35. package/internal/autoFormat.js +33 -0
  36. package/internal/canPrompt.js +14 -0
  37. package/internal/counts.js +83 -0
  38. package/internal/diagnostics.js +31 -0
  39. package/internal/displayPath.js +46 -0
  40. package/internal/displayWidth.js +42 -0
  41. package/internal/failureTarget.js +195 -0
  42. package/internal/fallbackAnswer.js +17 -0
  43. package/internal/fileSink.js +61 -0
  44. package/internal/format.js +175 -0
  45. package/internal/inspect.js +40 -0
  46. package/internal/isExitCode.js +11 -0
  47. package/internal/layout.js +249 -0
  48. package/internal/linkScheme.js +29 -0
  49. package/internal/linkTarget.js +49 -0
  50. package/internal/logSafety.js +45 -0
  51. package/internal/renderAnsi.js +51 -0
  52. package/internal/renderDoc.js +322 -0
  53. package/internal/renderGithubLog.js +59 -0
  54. package/internal/renderMarkdown.js +367 -0
  55. package/internal/renderPlain.js +49 -0
  56. package/internal/scanAudience.js +105 -0
  57. package/internal/splitFrame.js +55 -0
  58. package/internal/terminalCapabilities.js +23 -0
  59. package/internal/wizardGate.js +17 -0
  60. package/package.json +90 -5
  61. package/testing.d.ts +246 -0
  62. package/testing.js +4 -0
  63. package/tsdoc-metadata.json +11 -0
  64. package/ui/CliUi.js +507 -0
  65. package/ui/CliUiDetached.js +36 -0
  66. package/ui/CliUiLive.js +436 -0
  67. package/ui/CliUiRouteStream.js +72 -0
  68. package/ui/Confirm.js +244 -0
  69. package/ui/DocView.js +76 -0
  70. package/ui/KeyHelp.js +61 -0
  71. package/ui/KeyTable.js +198 -0
  72. package/ui/MultiSelect.js +259 -0
  73. package/ui/Select.js +229 -0
  74. package/ui/Tabs.js +201 -0
  75. package/ui/TextInput.js +289 -0
  76. package/ui/Toggle.js +31 -0
  77. package/ui/UiKey.js +48 -0
  78. package/ui/UiProvider.js +62 -0
  79. package/ui/UiStreams.js +17 -0
  80. package/ui/UiTheme.js +147 -0
  81. package/ui/Viewport.js +203 -0
  82. package/ui/internal/ErrorBoundary.js +29 -0
  83. package/ui/internal/Holder.js +73 -0
  84. package/ui/internal/ScreenContext.js +51 -0
  85. package/ui/internal/UiProviders.js +38 -0
  86. package/ui/internal/ink.js +121 -0
  87. package/ui/internal/inkChalk.js +47 -0
  88. package/ui/internal/inkConsole.js +150 -0
  89. package/ui/internal/lazyView.js +73 -0
  90. package/ui/internal/lineRouter.js +70 -0
  91. package/ui/internal/lineText.js +18 -0
  92. package/ui/internal/mountPermit.js +15 -0
  93. package/ui/internal/processStreams.js +18 -0
  94. package/ui/internal/renderOptions.js +12 -0
  95. package/ui/testing/CliUiTest.js +792 -0
  96. package/ui/testing/fakeStreams.js +104 -0
  97. package/ui/testing/terminalModel.js +67 -0
  98. package/ui-testing-serializer.d.ts +12 -0
  99. package/ui-testing-serializer.js +32 -0
  100. package/ui-testing.d.ts +558 -0
  101. package/ui-testing.js +3 -0
  102. package/ui.d.ts +1990 -0
  103. package/ui.js +17 -0
package/CliLog.js ADDED
@@ -0,0 +1,367 @@
1
+ import { makeCliLogger } from "./CliLogger.js";
2
+ import { CliTheme } from "./CliTheme.js";
3
+ import { sanitize } from "./Fmt.js";
4
+ import { paintStyle } from "./internal/ansi.js";
5
+ import { Level, passes } from "./internal/diagnostics.js";
6
+ import { makeFileSink } from "./internal/fileSink.js";
7
+ import { TrustedLine, neutralizeJson } from "./internal/logSafety.js";
8
+ import { scanAudience } from "./internal/scanAudience.js";
9
+ import { Cause, Config, Console, Context, Effect, Layer, LogLevel, Logger, Option, Path, References } from "effect";
10
+ import { Audience, CurrentRuntimeEnv, TerminalEnv } from "@effected/env";
11
+ import { CommandNeutralizer } from "@effected/github-commands";
12
+
13
+ // src/CliLog.ts
14
+ /** The most spaces a numeric `indent` writes. */
15
+ const MAX_INDENT = 64;
16
+ /** An indent as written before the glyph: spaces for a number, a string with nothing in it that is not text. */
17
+ const indentOf = (indent) => {
18
+ if (indent === void 0) return "";
19
+ if (typeof indent === "number") return Number.isFinite(indent) && indent > 0 ? " ".repeat(Math.min(MAX_INDENT, Math.floor(indent))) : "";
20
+ return sanitize(indent).replace(/\r\n|\r|\n/g, "");
21
+ };
22
+ /** The accepted spellings of a level, lower-cased, to the level they mean. A `Map`, so no inherited key matches. */
23
+ const LEVELS = /* @__PURE__ */ new Map([
24
+ ["all", "All"],
25
+ ["trace", "Trace"],
26
+ ["debug", "Debug"],
27
+ ["info", "Info"],
28
+ ["warn", "Warn"],
29
+ ["warning", "Warn"],
30
+ ["error", "Error"],
31
+ ["fatal", "Fatal"],
32
+ ["none", "None"]
33
+ ]);
34
+ /** A level's spelling, in any case, to the level it means. */
35
+ const parseLevel = (text) => Option.fromUndefinedOr(LEVELS.get(text.toLowerCase()));
36
+ const LEVEL_STYLES = {
37
+ FATAL: {
38
+ fg: "red",
39
+ bold: true
40
+ },
41
+ ERROR: { fg: "red" },
42
+ WARN: { fg: "yellow" },
43
+ INFO: { fg: "cyan" },
44
+ DEBUG: { fg: "blue" },
45
+ TRACE: { dim: true }
46
+ };
47
+ /** The diagnostics level: the option when given, else the env var, and the raw text when that is not a level. */
48
+ const readLevel = (explicit, envVar) => Effect.gen(function* () {
49
+ if (explicit !== void 0) return {
50
+ level: explicit,
51
+ invalid: void 0
52
+ };
53
+ if (envVar === void 0) return {
54
+ level: "None",
55
+ invalid: void 0
56
+ };
57
+ const raw = yield* Config.option(Config.String(envVar)).pipe(Effect.orElseSucceed(() => Option.none()));
58
+ if (Option.isNone(raw) || raw.value === "") return {
59
+ level: "None",
60
+ invalid: void 0
61
+ };
62
+ const level = parseLevel(raw.value);
63
+ if (Option.isSome(level)) return {
64
+ level: level.value,
65
+ invalid: void 0
66
+ };
67
+ return {
68
+ level: "None",
69
+ invalid: `${envVar}=${raw.value} is not a log level (${[...LEVELS.keys()].join("|")}); ignoring it`
70
+ };
71
+ });
72
+ /**
73
+ * Whether a record's line is neutralized: the `neutralize` option when it is a boolean, else whether the logging
74
+ * fiber's `CurrentRuntimeEnv`, or `fallback` where the fiber has none, says GitHub Actions.
75
+ */
76
+ const actionsDecision = (neutralize, fallback) => (fiber) => {
77
+ if (neutralize !== "auto") return neutralize;
78
+ const inFiber = Context.getOption(fiber.context, CurrentRuntimeEnv);
79
+ const runtime = Option.isSome(inFiber) ? inFiber : fallback;
80
+ return Option.contains(Option.flatMap(runtime, (env) => env.ci), "github-actions");
81
+ };
82
+ /**
83
+ * Diagnostics kept apart from a program's output: a level, a format and a place to write.
84
+ *
85
+ * @remarks
86
+ * Two kinds of line must never be silenced by a diagnostics default: the failure report
87
+ * `CliRuntime.reportFailures` writes through `CliLogger`, and the `CliMessage` lines. This package therefore
88
+ * never makes the diagnostics level a global switch. The diagnostics logger filters on its **own** threshold,
89
+ * {@link CliLog.Level}, and writes to stderr only.
90
+ *
91
+ * `CliLog.layer` **owns the whole logger set**. It builds a `CliLogger` for ordinary log lines and the
92
+ * diagnostics sink itself and replaces whatever was installed, without reading it, so there is no order to get
93
+ * wrong. Use it instead of `CliLogger.layer`, not with it: `CliLogger.layer` alone is the no-diagnostics path,
94
+ * and a `CliLogger.layer` layered on top would replace this layer's set.
95
+ *
96
+ * Effect drops a record below `MinimumLogLevel` before any logger runs, so to let a debug record reach the
97
+ * diagnostics logger `MinimumLogLevel` has to be lowered. `CliLog.layer` does that only when the
98
+ * diagnostics level is below the ambient minimum, and in the same step floors the `CliLogger` it built at the
99
+ * minimum it had, so it never prints a record the diagnostics level alone let through. A failure report is
100
+ * written outside the scope core's `--log-level` flag sets, so `--log-level none` does not silence it either.
101
+ *
102
+ * `format: "auto"`, the default, decides by the audience alone, at build time and at runtime alike: NDJSON for an
103
+ * agent or a CI, the pretty line for a human, whatever stderr's terminal state. A human piping stderr therefore gets
104
+ * plain lines (without escapes unless stderr is a colour terminal); pass `format: "json"` for machine-readable logs.
105
+ *
106
+ * The text a program logs is sanitised before anything is painted in the pretty line (the message, the component and an
107
+ * error's cause lose their escape sequences and control characters), and under GitHub Actions, where
108
+ * `CurrentRuntimeEnv` in the logging fiber's context says so, a line the runner would read as a workflow command is
109
+ * neutralized. An NDJSON record is not safe merely because `JSON.stringify` escapes control characters: the runner's
110
+ * legacy parser reads `##[` anywhere in a line, so under Actions it is written as the JSON escape `#\u0023[`, which
111
+ * decodes to the identical text. The file sink's lines are not read by the runner and are written as they are.
112
+ *
113
+ * `CurrentRuntimeEnv` is read from the logging fiber's context, and where that has none, from the `runtimeEnv` option,
114
+ * else from the layer's own build context (captured if present, never required), so a host that builds the layer over
115
+ * its environment, or names it with `runtimeEnv`, neutralizes every record. A record with none of the three (a program
116
+ * with no `CurrentRuntimeEnv` anywhere) is sanitised but not neutralized, unless the `neutralize` option says otherwise.
117
+ *
118
+ * Core's `--log-level` flag sets `MinimumLogLevel` inside the command. While it is set to something other than
119
+ * the value this layer installed, the diagnostics logger follows the flag instead of its own level: it writes
120
+ * every record that reaches it. The `CliLogger` prints the same record too, so a record at or above the ambient
121
+ * minimum is written twice, once plain and once to the diagnostics sink. Stderr is therefore not pure NDJSON while
122
+ * diagnostics are on: a parser reads the lines that start with `{`.
123
+ *
124
+ * One edge: a `--log-level` value that EQUALS the level this layer installed cannot be told from no flag, so the
125
+ * sink keeps filtering on its own level rather than following the flag. The plain `CliLogger` prints those records
126
+ * regardless.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * import { CliRuntime } from "@effected/cli-kit"
131
+ * import { NodeRuntime, NodeServices } from "@effect/platform-node"
132
+ *
133
+ * // `env.log` makes `main` install `CliLog.layer`: set MYTOOL_LOG_LEVEL=debug to get diagnostics on stderr.
134
+ * NodeRuntime.runMain(
135
+ * CliRuntime.main(program, {
136
+ * platform: NodeServices.layer,
137
+ * env: { audienceEnvVar: "MYTOOL_AUDIENCE", log: { envVar: "MYTOOL_LOG_LEVEL" } },
138
+ * }),
139
+ * )
140
+ * ```
141
+ *
142
+ * @public
143
+ */
144
+ var CliLog = class CliLog {
145
+ constructor() {}
146
+ /**
147
+ * The diagnostics threshold. Defaults to `None`, silent.
148
+ *
149
+ * @remarks
150
+ * `CliLog.layer` sets it from the environment variable. A scope may raise it to narrow the output; it
151
+ * cannot lower it below the level the layer installed, because Effect has already dropped those records.
152
+ */
153
+ static Level = Level;
154
+ /**
155
+ * Read a log level the way `CliLog.layer` reads its environment variable: `Option.some` of the level, or
156
+ * `Option.none()` when the text is not one.
157
+ *
158
+ * @remarks
159
+ * Case-insensitive, and not trimmed. The spellings are `all`, `trace`, `debug`, `info`, `warn` (or `warning`),
160
+ * `error`, `fatal` and `none`. For a host that reads a level from its own flag or config and wants the same answer
161
+ * the layer would give.
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * CliLog.parseLevel("WARNING") // Option.some("Warn")
166
+ * CliLog.parseLevel("loud") // Option.none()
167
+ * ```
168
+ *
169
+ * @param text - the level's spelling
170
+ */
171
+ static parseLevel(text) {
172
+ return parseLevel(text);
173
+ }
174
+ static layer(options = {}) {
175
+ const file = "file" in options ? options.file : void 0;
176
+ const format = options.format ?? "auto";
177
+ return Layer.unwrap(Effect.gen(function* () {
178
+ const audience = format === "auto" ? yield* Audience : void 0;
179
+ const terminal = format === "json" ? void 0 : yield* TerminalEnv;
180
+ const { level, invalid } = yield* readLevel(options.level, options.envVar);
181
+ const ambient = yield* References.MinimumLogLevel;
182
+ const captured = yield* Effect.serviceOption(CurrentRuntimeEnv);
183
+ const fallback = options.runtimeEnv === void 0 ? captured : Option.some(options.runtimeEnv);
184
+ const underActionsIn = actionsDecision(options.neutralize ?? "auto", fallback);
185
+ const color = terminal?.stderr.color ?? "none";
186
+ const isPretty = (record) => {
187
+ if (format !== "auto") return format === "pretty";
188
+ const inForce = Context.getOption(record.fiber.context, Audience);
189
+ return (Option.isSome(inForce) ? inForce.value.kind : audience?.kind) === "human";
190
+ };
191
+ const lowered = LogLevel.isLessThan(level, ambient) ? level : ambient;
192
+ const isLowered = lowered !== ambient;
193
+ const render = (record) => {
194
+ const underActions = underActionsIn(record.fiber);
195
+ if (!isPretty(record)) {
196
+ const json = Logger.formatJson.log(record);
197
+ return underActions ? neutralizeJson(json) : json;
198
+ }
199
+ const annotations = record.fiber.getRef(References.CurrentLogAnnotations);
200
+ const component = annotations.component === void 0 ? "" : ` [${sanitize(String(annotations.component))}]`;
201
+ const message = sanitize(Array.isArray(record.message) ? record.message.map(String).join(" ") : String(record.message));
202
+ const name = record.logLevel.toUpperCase();
203
+ const levelText = paintStyle(LEVEL_STYLES[name] ?? {}, color, name);
204
+ const cause = record.cause.reasons.length > 0 ? `\n${sanitize(Cause.pretty(record.cause))}` : "";
205
+ const line = `${record.date.toISOString().slice(11, 23)} ${levelText}${component} ${message}${cause}`;
206
+ return underActions ? CommandNeutralizer.text(line) : line;
207
+ };
208
+ const sink = Logger.make((record) => {
209
+ if (!passes(record, lowered)) return;
210
+ record.fiber.getRef(Console.Console).error(render(record));
211
+ });
212
+ const floor = (inner) => isLowered ? Logger.make((record) => {
213
+ const current = record.fiber.getRef(References.MinimumLogLevel);
214
+ const threshold = current === lowered ? ambient : current;
215
+ if (LogLevel.isGreaterThanOrEqualTo(record.logLevel, threshold)) inner.log(record);
216
+ }) : inner;
217
+ const cliLogger = floor(makeCliLogger(options.logger, underActionsIn));
218
+ const extras = (options.extraLoggers ?? []).map(floor);
219
+ if (invalid !== void 0) yield* Effect.logWarning(invalid).pipe(Effect.provideService(Logger.CurrentLoggers, /* @__PURE__ */ new Set([cliLogger])));
220
+ return Layer.mergeAll(Layer.succeed(CliLog.Level, level), isLowered ? Layer.succeed(References.MinimumLogLevel, lowered) : Layer.empty, Layer.effect(Logger.CurrentLoggers, Effect.gen(function* () {
221
+ const loggers = [
222
+ ...options.plainLogger === false ? [] : [cliLogger],
223
+ sink,
224
+ ...extras
225
+ ];
226
+ if (file !== void 0) {
227
+ const target = "path" in file ? Option.some(file.path) : yield* Config.option(Config.String(file.envVar)).pipe(Effect.orElseSucceed(() => Option.none()));
228
+ if (Option.isSome(target) && target.value !== "") {
229
+ const location = yield* Path.Path;
230
+ loggers.push(yield* makeFileSink(location.resolve(target.value), lowered, underActionsIn));
231
+ }
232
+ }
233
+ return new Set(loggers);
234
+ })));
235
+ }));
236
+ }
237
+ /**
238
+ * Log a status line: its glyph painted through the theme, then `text`, at a level that follows the status.
239
+ *
240
+ * @remarks
241
+ * The line goes through the logger, so it is a diagnostic like any `Effect.log*` call: filtered by the level in
242
+ * force (`--log-level`, `CliLog.Level`), routed by `CliLogger`'s `stderrFrom` (stderr by default) and neutralized
243
+ * under GitHub Actions. What differs is the glyph: the logger sanitises every line a program logs, which strips a
244
+ * colour a program painted itself, so a glyph on the log channel was always drawn bare. Here the kit paints it and
245
+ * marks the line as its own, so the plain `CliLogger` line keeps the colour, while `text` is still sanitised:
246
+ * escape sequences and control characters in it are removed, as in every line the kit writes.
247
+ *
248
+ * The glyph is painted with stderr's theme (where diagnostics go) through {@link CliTheme.forAudience}, so an agent
249
+ * gets it unpainted, and an `Audience` is read only when provided, so it stays out of the requirements. ASCII glyphs
250
+ * give the status's ASCII form. A diagnostics record carries the line as its message as any record does: the `CliLog`
251
+ * sink's pretty line sanitises it (the glyph is drawn bare there), and NDJSON keeps it, JSON-escaped.
252
+ *
253
+ * The level defaults to the status's rank in `vocab`: `Error` at or above `failure`'s, `Warn` at or above
254
+ * `warning`'s, `Info` below, so a custom status follows its own rank. Pass `level` to choose it, and `indent` (a
255
+ * number of spaces, or a string, sanitised) to start the line inside an indented block: ` ✗ error x: red`.
256
+ *
257
+ * @example
258
+ * ```ts
259
+ * import { CliLog, Status } from "@effected/cli-kit"
260
+ *
261
+ * // ✗ in the failure colour, then the message: on stderr, filtered by the log level.
262
+ * const reportError = (resource: string, message: string) =>
263
+ * CliLog.status(Status.core, "failure", `${resource}: ${message}`)
264
+ * ```
265
+ *
266
+ * @param vocab - the vocabulary the status belongs to
267
+ * @param name - the status
268
+ * @param text - the text after the glyph, sanitised
269
+ * @param options - the level to log at, and the indent before the glyph
270
+ */
271
+ static status = (vocab, name, text, options) => Effect.gen(function* () {
272
+ const audience = yield* Effect.serviceOption(Audience);
273
+ const theme = CliTheme.forAudience((yield* CliTheme).forStream("stderr"), Option.isSome(audience) ? audience.value.kind : void 0);
274
+ const line = `${indentOf(options?.indent)}${theme.status(vocab, name, sanitize(text))}`;
275
+ const core = vocab;
276
+ const rank = vocab.def(name).rank;
277
+ const level = options?.level ?? (rank >= core.def("failure").rank ? "Error" : rank >= core.def("warning").rank ? "Warn" : "Info");
278
+ yield* Effect.logWithLevel(level)(line).pipe(Effect.provideService(TrustedLine, true));
279
+ });
280
+ /**
281
+ * Mark the log records an effect emits as coming from `name`.
282
+ *
283
+ * @remarks
284
+ * Shown as `[name]` in pretty output and as `annotations.component` in NDJSON.
285
+ *
286
+ * @param name - the component
287
+ */
288
+ static component = (name) => (self) => Effect.annotateLogs(self, "component", name);
289
+ };
290
+ /**
291
+ * The audience while the platform builds, from what needs no platform: a flag in `argv` (the rule `CliAudience` reads
292
+ * argv with), else the override variable, else detection from the environment. No terminal is consulted. Silent: the
293
+ * environment layer warns about an invalid override value itself, once.
294
+ */
295
+ const buildTimeAudience = (argv, audienceEnvVar, detected) => {
296
+ const { given, conflict } = scanAudience(argv ?? []);
297
+ const [flagged] = given;
298
+ if (!conflict && flagged !== void 0) return Effect.succeed(flagged);
299
+ return Effect.map(Audience, (audience) => audience.kind).pipe(Effect.provide(Audience.layer(audienceEnvVar === void 0 ? void 0 : { envVar: audienceEnvVar }).pipe(Layer.provide(Layer.succeed(CurrentRuntimeEnv, detected)))), Effect.provideService(Logger.CurrentLoggers, /* @__PURE__ */ new Set()));
300
+ };
301
+ /** What the build-time loggers decide from, read once: the format and the runtime environment to neutralize by. */
302
+ const buildTimeDecision = (options, audienceEnvVar) => Effect.gen(function* () {
303
+ const detected = yield* Effect.provide(CurrentRuntimeEnv, CurrentRuntimeEnv.layer);
304
+ const format = options.format ?? "auto";
305
+ return {
306
+ ndjson: format === "json" || format === "auto" && (yield* buildTimeAudience(options.argv, audienceEnvVar, detected)) !== "human",
307
+ runtimeEnv: options.runtimeEnv ?? detected
308
+ };
309
+ });
310
+ /**
311
+ * The logger the platform is built under by `CliRuntime.main` with `env.log`: the log level and env var apply to
312
+ * what the platform logs while it builds, too.
313
+ *
314
+ * @remarks
315
+ * With `format: "json"`, or `auto` when the build-time audience (`argv`, the override variable, detection) is an
316
+ * agent or a CI, it is the full `CliLog.layer` in NDJSON (that format needs neither the audience nor the terminal,
317
+ * which the platform has not built yet), without the file sink, whose `FileSystem` the platform provides. Otherwise it
318
+ * is the plain `CliLogger`, with `MinimumLogLevel` lowered to the resolved level. Either way it neutralizes under
319
+ * GitHub Actions from the detected environment. The level is resolved silently: the program's own `CliLog.layer` warns
320
+ * about an invalid value, once.
321
+ *
322
+ * @internal
323
+ */
324
+ const platformLogLayer = (options, audienceEnvVar) => Layer.unwrap(Effect.gen(function* () {
325
+ const { level } = yield* readLevel(options.level, options.envVar);
326
+ const ambient = yield* References.MinimumLogLevel;
327
+ const { ndjson, runtimeEnv } = yield* buildTimeDecision(options, audienceEnvVar);
328
+ if (ndjson) return CliLog.layer({
329
+ level,
330
+ format: "json",
331
+ ...options.plainLogger === void 0 ? {} : { plainLogger: options.plainLogger },
332
+ ...options.logger === void 0 ? {} : { logger: options.logger },
333
+ ...options.extraLoggers === void 0 ? {} : { extraLoggers: options.extraLoggers },
334
+ ...options.neutralize === void 0 ? {} : { neutralize: options.neutralize },
335
+ runtimeEnv
336
+ });
337
+ return Layer.merge(Logger.layer([makeCliLogger(options.logger, actionsDecision(options.neutralize ?? "auto", Option.some(runtimeEnv)))]), LogLevel.isLessThan(level, ambient) ? Layer.succeed(References.MinimumLogLevel, level) : Layer.empty);
338
+ }));
339
+ /**
340
+ * The logger `CliRuntime.main` builds the environment layer under: one line per record, in the build-time format.
341
+ *
342
+ * @remarks
343
+ * What the environment layer logs is a configuration error (an invalid audience override, which interpolates the
344
+ * variable's value), so it is never silenced and never written twice: NDJSON alone for an agent or a CI (`json`, or
345
+ * `auto` for that build-time audience), a plain `CliLogger` line otherwise, whatever `plainLogger` and the diagnostics
346
+ * level say, and neutralized under GitHub Actions like the platform's lines. It goes to stderr alone, whatever
347
+ * `stderrFrom` the program's `CliLogger` options raise, and never to `extraLoggers` or the file sink. Only this
348
+ * logger is pinned to stderr: the platform's build-time logger keeps the host's `stderrFrom`. It floors at `Warning` and installs no
349
+ * `MinimumLogLevel`, so `CliLog.layer`'s own build, which shares this context, reads the ambient minimum.
350
+ *
351
+ * @internal
352
+ */
353
+ const envBuildLogLayer = (options, audienceEnvVar) => Layer.unwrap(Effect.gen(function* () {
354
+ const { ndjson, runtimeEnv } = yield* buildTimeDecision(options, audienceEnvVar);
355
+ const underActions = actionsDecision(options.neutralize ?? "auto", Option.some(runtimeEnv));
356
+ if (!ndjson) return Logger.layer([makeCliLogger({
357
+ ...options.logger,
358
+ stderrFrom: "All"
359
+ }, underActions)]);
360
+ return Logger.layer([Logger.make((record) => {
361
+ if (!LogLevel.isGreaterThanOrEqualTo(record.logLevel, "Warn")) return;
362
+ const json = Logger.formatJson.log(record);
363
+ record.fiber.getRef(Console.Console).error(underActions(record.fiber) ? neutralizeJson(json) : json);
364
+ })]);
365
+ }));
366
+
367
+ export { CliLog, envBuildLogLayer, platformLogLayer };
package/CliLogger.js ADDED
@@ -0,0 +1,91 @@
1
+ import { sanitize } from "./Fmt.js";
2
+ import { TrustedLine, sanitizeParts, underActionsIn } from "./internal/logSafety.js";
3
+ import { Console, LogLevel, Logger, References } from "effect";
4
+ import { CommandNeutralizer } from "@effected/github-commands";
5
+
6
+ // src/CliLogger.ts
7
+ const defaultRender = (message) => Array.isArray(message) ? message.map(String).join(" ") : String(message);
8
+ /**
9
+ * A `Logger` that renders CLI output rather than service logs: no timestamp, level or fiber id, with every level
10
+ * going to stderr by default so stdout carries only what the program writes.
11
+ *
12
+ * @remarks
13
+ * Effect's default logger emits `[00:33:56.619] INFO (#2): message`. That is
14
+ * the right shape for a long-running service being scraped and the wrong one
15
+ * for a tool a person is watching: the timestamp, level and fiber id are noise
16
+ * in front of output a human is reading, and they make a formatted block — a
17
+ * permissions table, a summary — unreadable.
18
+ *
19
+ * **A program that never installs a CLI logger looks correct in review and
20
+ * ships timestamps to its users**, so install this one at the program's
21
+ * boundary.
22
+ *
23
+ * It writes through the `Console` reference read off the logging fiber,
24
+ * synchronously, as core's own default logger does: `Logger.make` takes a
25
+ * synchronous callback, and a `Stdio` sink write is an `Effect` a logger cannot
26
+ * `yield*`. `Console.Console` is a `Context.Reference`, so it never appears in
27
+ * `R`, and a test swaps the reference rather than stubbing a global.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { CliLogger } from "@effected/cli-kit"
32
+ * import { Console, Effect } from "effect"
33
+ *
34
+ * const program = Effect.gen(function* () {
35
+ * yield* Effect.log("synced 3 repos") // stderr, no timestamp — a diagnostic
36
+ * yield* Console.log("3 repos synced") // stdout — the program's actual output
37
+ * yield* Effect.logError("one failed") // stderr
38
+ * })
39
+ *
40
+ * program.pipe(Effect.provide(CliLogger.layer()))
41
+ * ```
42
+ *
43
+ * `stderrFrom` defaults to `"All"`: a CLI's stdout is its product, so every
44
+ * log level is a diagnostic unless a consumer narrows the threshold. Write
45
+ * program output with `Console.log`, never `Effect.log`. Pass
46
+ * `stderrFrom: "Error"` for a tool whose output *is* its log lines.
47
+ *
48
+ * @public
49
+ */
50
+ var CliLogger = class CliLogger {
51
+ constructor() {}
52
+ /**
53
+ * The logger itself, for composing into an existing `Logger.layer` set.
54
+ *
55
+ * @remarks
56
+ * Prefer {@link CliLogger.layer}. Reach for this only when you are building
57
+ * the logger set yourself and want this one among several.
58
+ */
59
+ static make = (options = {}) => makeCliLogger(options);
60
+ /**
61
+ * Replace the default logger with this one.
62
+ *
63
+ * @remarks
64
+ * `Logger.layer` **replaces** rather than merges, so nothing is emitted twice.
65
+ *
66
+ * Merge this into the layer you provide to the whole program rather than
67
+ * providing it beneath: merged, it also covers lines emitted during layer
68
+ * construction, which is exactly where a startup failure prints.
69
+ */
70
+ static layer = (options = {}) => Logger.layer([CliLogger.make(options)]);
71
+ };
72
+ /**
73
+ * `CliLogger.make`, with the neutralizing decision as a parameter: `CliLog.layer` passes its own (the fiber's
74
+ * `CurrentRuntimeEnv`, else the one captured at build, or its `neutralize` option), so its plain line and its
75
+ * diagnostics line are neutralized alike.
76
+ *
77
+ * @internal
78
+ */
79
+ const makeCliLogger = (options = {}, underActions = underActionsIn) => {
80
+ const custom = options.render;
81
+ const render = custom ?? defaultRender;
82
+ const stderrFrom = options.stderrFrom ?? "All";
83
+ return Logger.make(({ fiber, logLevel, message }) => {
84
+ const console = fiber.getRef(Console.Console);
85
+ const write = fiber.getRef(References.LogToStderr) || LogLevel.isGreaterThanOrEqualTo(logLevel, stderrFrom) ? console.error : console.log;
86
+ const rendered = fiber.getRef(TrustedLine) ? render(message) : custom === void 0 ? sanitize(render(message)) : render(sanitizeParts(message));
87
+ write(underActions(fiber) ? CommandNeutralizer.text(rendered) : rendered);
88
+ });
89
+ };
90
+
91
+ export { CliLogger, makeCliLogger };
package/CliMessage.js ADDED
@@ -0,0 +1,79 @@
1
+ import { CliTheme } from "./CliTheme.js";
2
+ import { sanitize } from "./Fmt.js";
3
+ import { underGithubActions } from "./internal/autoFormat.js";
4
+ import { Status } from "./Status.js";
5
+ import { Console, Effect } from "effect";
6
+ import { Audience } from "@effected/env";
7
+ import { CommandNeutralizer } from "@effected/github-commands";
8
+
9
+ // src/CliMessage.ts
10
+ /**
11
+ * One-line status messages: a glyph and some text, themed for a person and plain for an agent.
12
+ *
13
+ * @remarks
14
+ * Each line goes through `Console`, `log` for stdout and `error` for stderr, never through the logger, so no
15
+ * log level can silence it. Only the glyph is painted; the text stays plain. An `agent` audience gets the glyph
16
+ * and the text and never colour, even when the theme has colour. `success` and `info` go to stdout, `warning`
17
+ * and `failure` to stderr.
18
+ *
19
+ * The text is whatever the caller supplies, so it is sanitised: escape sequences and control characters are removed
20
+ * (a line break is kept as one, a tab becomes a space), as in a document. Under GitHub Actions, where
21
+ * `CurrentRuntimeEnv` says so, a line the runner would read as a workflow command is neutralized as well. The glyph
22
+ * comes from the vocabulary, sanitised too (`Status.glyph`), so a glyph built from data cannot inject an escape either.
23
+ *
24
+ * @public
25
+ */
26
+ var CliMessage = class CliMessage {
27
+ constructor() {}
28
+ /**
29
+ * Print a status line from a vocabulary.
30
+ *
31
+ * @remarks
32
+ * The stream defaults to stderr when the status ranks at or above `warning` in `vocab`, and stdout
33
+ * otherwise, so a custom status follows its own rank: a `timeout` ranked 85 goes to stderr.
34
+ *
35
+ * @param vocab - the vocabulary the status belongs to
36
+ * @param name - the status
37
+ * @param text - the text after the glyph
38
+ * @param options - the stream override
39
+ */
40
+ static status = (vocab, name, text, options) => Effect.gen(function* () {
41
+ const theme = yield* CliTheme;
42
+ const audience = yield* Audience;
43
+ const def = vocab.def(name);
44
+ const message = sanitize(text);
45
+ const warning = vocab.def("warning").rank;
46
+ const stream = options?.stream ?? (def.rank >= warning ? "stderr" : "stdout");
47
+ const streamTheme = theme.forStream(stream);
48
+ let line;
49
+ line = CliTheme.forAudience(streamTheme, audience.kind).status(vocab, name, message);
50
+ if (yield* underGithubActions) line = CommandNeutralizer.text(line);
51
+ yield* stream === "stderr" ? Console.error(line) : Console.log(line);
52
+ });
53
+ /**
54
+ * A success line, on stdout.
55
+ *
56
+ * @param text - the text after the glyph
57
+ */
58
+ static success = (text) => CliMessage.status(Status.core, "success", text);
59
+ /**
60
+ * An informational line, on stdout.
61
+ *
62
+ * @param text - the text after the glyph
63
+ */
64
+ static info = (text) => CliMessage.status(Status.core, "info", text);
65
+ /**
66
+ * A warning line, on stderr.
67
+ *
68
+ * @param text - the text after the glyph
69
+ */
70
+ static warning = (text) => CliMessage.status(Status.core, "warning", text);
71
+ /**
72
+ * A failure line, on stderr.
73
+ *
74
+ * @param text - the text after the glyph
75
+ */
76
+ static failure = (text) => CliMessage.status(Status.core, "failure", text);
77
+ };
78
+
79
+ export { CliMessage };
package/CliPrompt.js ADDED
@@ -0,0 +1,110 @@
1
+ import { Cancelled } from "./Cancelled.js";
2
+ import { CliInteractive } from "./CliInteractive.js";
3
+ import { answerWithoutPerson } from "./internal/fallbackAnswer.js";
4
+ import { WizardDropped } from "./internal/wizardGate.js";
5
+ import { Context, Effect, Layer, Queue, Terminal } from "effect";
6
+ import { CliConfig, GlobalFlag, Prompt } from "effect/cli";
7
+
8
+ // src/CliPrompt.ts
9
+ /**
10
+ * Prompts that know whether there is a person to ask.
11
+ *
12
+ * @public
13
+ */
14
+ var CliPrompt = class {
15
+ constructor() {}
16
+ /**
17
+ * A fallback for `Flag.withFallbackPrompt` or `Argument.withFallbackPrompt` that only prompts when the run is
18
+ * interactive.
19
+ *
20
+ * @remarks
21
+ * Interactive (`CliInteractive`): the prompt runs and its answer is used. Not interactive: `otherwise` is used
22
+ * when given, and the terminal is never read; without it the parameter fails as missing, exactly as it would
23
+ * with no fallback, so core renders its own message and `CliRuntime.main` exits `64`. Name the parameter with
24
+ * `flag` (the name without dashes, as given to `Flag.String`) or `argument` so that error can be built.
25
+ *
26
+ * Why the prompt runs inside this function rather than being handed back to core: core's
27
+ * `withFallbackPrompt` turns a quit, such as Ctrl-C, into the original missing-parameter error, which would
28
+ * exit `64` as if the flag had been forgotten. Here a quit is `Cancelled` with reason `interrupt`, exit `130`.
29
+ * It is raised as a defect because core's parse step turns every typed failure into a usage error. Core then
30
+ * runs the already-answered `Prompt.succeed` it is handed. Because it travels as a defect, a handler's
31
+ * `Effect.catchTag("Cancelled", ...)` cannot see it, and only `CliRuntime.main` (or
32
+ * `CliRuntime.reportFailures`) renders it as one line with exit `130`; under a bare `runMain` it prints a
33
+ * stack.
34
+ *
35
+ * Core runs `Prompt.run` on the answered prompt it is handed, and an answered prompt never reads the terminal's
36
+ * input (core acquires it only when a prompt needs a key), so piped stdin is left untouched without any gate.
37
+ * `CliPrompt.gateTerminal`, which `CliEnv.layer` installs, covers the prompts this function does not wrap.
38
+ *
39
+ * Core calls a fallback only when its `TerminalCapabilities.canPrompt` is `true`, and its own default decides that
40
+ * from the process's terminal, so in a piped run it would fail the parameter as missing without calling this
41
+ * function and `otherwise` would be lost. `CliInteractive.layer` and `CliInteractive.layerTest` (and so
42
+ * `CliEnv.layer`) hold `canPrompt` at `true` for that reason: the decision is `CliInteractive`'s, made here. A
43
+ * `TerminalCapabilities` with `canPrompt: false` provided inside the program bypasses this fallback again, and a
44
+ * program that sets `CliInteractive` with neither layer keeps core's own gate.
45
+ *
46
+ * @param prompt - the prompt to show
47
+ * @param options - the parameter it stands in for, and the non-interactive default
48
+ */
49
+ static fallback = (prompt, options) => Effect.gen(function* () {
50
+ if (yield* CliInteractive) {
51
+ const answer = yield* Prompt.run(prompt).pipe(Effect.catchTag("QuitError", () => Effect.die(new Cancelled({ reason: "interrupt" }))));
52
+ return Prompt.succeed(answer);
53
+ }
54
+ return yield* answerWithoutPerson(options);
55
+ });
56
+ /**
57
+ * Gates core's `Terminal` on `CliInteractive`, so a run that is not interactive never touches the real one.
58
+ *
59
+ * @remarks
60
+ * A prompt that needs a key reads the terminal's input, and the real Node terminal then attaches a readline to
61
+ * stdin, which drops piped input and puts a TTY stdin into raw mode. Core's `withFallbackPrompt`, a `Prompt.run`
62
+ * in a handler and the command wizard all do so whether or not anyone is there to answer. Not interactive, this
63
+ * terminal's input is an already-ended queue, its `readLine` fails as quit and its `display` writes nothing, so
64
+ * any such prompt is quit at once and the real terminal is never read. Its `columns`, `rows` and `size` always come
65
+ * from the real one, so layout keeps working. Interactive, every call passes through to the real terminal.
66
+ *
67
+ * The decision is made on every call, not when the layer is built, so a scope that narrows `CliInteractive`
68
+ * later, such as an audience flag under `CliAudience.runWith`, gates it too.
69
+ *
70
+ * It requires the real `Terminal`. `CliEnv.layer` installs it, after `TerminalEnv` is built from the real
71
+ * terminal, so consumers do not compose it.
72
+ */
73
+ static gateTerminal = Layer.effect(Terminal.Terminal, Effect.gen(function* () {
74
+ const real = yield* Terminal.Terminal;
75
+ const endedInput = Effect.map(Queue.unbounded(), (queue) => {
76
+ Queue.endUnsafe(queue);
77
+ return queue;
78
+ });
79
+ return Terminal.make({
80
+ columns: real.columns,
81
+ rows: real.rows,
82
+ size: real.size,
83
+ readInput: Effect.flatMap(CliInteractive, (interactive) => interactive ? real.readInput : endedInput),
84
+ readLine: Effect.flatMap(CliInteractive, (interactive) => interactive ? real.readLine : Effect.fail(new Terminal.QuitError({}))),
85
+ display: (text) => Effect.flatMap(CliInteractive, (interactive) => interactive ? real.display(text) : Effect.void)
86
+ });
87
+ }));
88
+ /**
89
+ * Drops core's `--wizard` built-in flag when the run is not interactive.
90
+ *
91
+ * @remarks
92
+ * The wizard prompts, so offering it without a terminal only leads to a dead end. With the flag gone, core
93
+ * treats `--wizard` as an unknown flag, a usage error that exits `64`, and lists it nowhere in `--help`.
94
+ * The layer reads `CliInteractive` and the ambient `CliConfig` when it is built, so provide those first, for
95
+ * example `CliPrompt.gateWizard.pipe(Layer.provide(CliInteractive.layer))`. It filters the ambient `CliConfig`,
96
+ * so a consumer's own `builtIns` survive, and returns it untouched when interactive. An audience flag read
97
+ * later is covered by `CliAudience.runWith`, which drops the wizard too. When this layer removes the flag it records
98
+ * that it did, so `runWith` puts it back only when a flag turns interactivity on where this took it away: a
99
+ * consumer who never had `Wizard` in their `builtIns` keeps it out.
100
+ */
101
+ static gateWizard = Layer.effectContext(Effect.gen(function* () {
102
+ const ambient = yield* CliConfig.CliConfig;
103
+ const unchanged = Context.make(CliConfig.CliConfig, ambient);
104
+ if ((yield* CliInteractive) || !ambient.builtIns.includes(GlobalFlag.Wizard)) return unchanged;
105
+ const dropped = CliConfig.make({ builtIns: ambient.builtIns.filter((flag) => flag !== GlobalFlag.Wizard) });
106
+ return Context.make(CliConfig.CliConfig, dropped).pipe(Context.add(WizardDropped, dropped));
107
+ }));
108
+ };
109
+
110
+ export { CliPrompt };