printable-shell-command 3.0.2 → 4.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.
@@ -2,9 +2,7 @@ import type { ChildProcessByStdio, SpawnOptions as NodeSpawnOptions } from "node
2
2
  import { Readable, Writable } from "node:stream";
3
3
  import type { WriteStream } from "node:tty";
4
4
  import { styleText } from "node:util";
5
- import type { SpawnOptions as BunSpawnOptions, Subprocess as BunSubprocess, SpawnOptions } from "bun";
6
5
  import { Path } from "path-class";
7
- import type { SetFieldType } from "type-fest";
8
6
  import type { NodeWithCwd, spawnType, WithSuccess } from "./spawn";
9
7
  type StyleTextFormat = Parameters<typeof styleText>[0];
10
8
  type SingleArgument = string | Path;
@@ -51,10 +49,6 @@ export interface StreamPrintOptions extends PrintOptions {
51
49
  autoStyle?: "tty" | "never";
52
50
  stream?: WriteStream | Writable;
53
51
  }
54
- type BunCwd = SpawnOptions.OptionsObject<any, any, any>["cwd"] | Path;
55
- type BunWithCwd<T extends {
56
- cwd?: SpawnOptions.OptionsObject<any, any, any>["cwd"] | Path;
57
- }> = SetFieldType<T, "cwd", BunCwd | undefined>;
58
52
  export type StdinSource = {
59
53
  text: string;
60
54
  } | {
@@ -69,34 +63,6 @@ export declare class PrintableShellCommand {
69
63
  private args;
70
64
  constructor(commandName: string | Path, args?: Args);
71
65
  get commandName(): string;
72
- /** For use with `bun`.
73
- *
74
- * Usage example:
75
- *
76
- * ```
77
- * import { PrintableShellCommand } from "printable-shell-command";
78
- * import { spawn } from "bun";
79
- *
80
- * const command = new PrintableShellCommand( … );
81
- * await spawn(command.toFlatCommand()).exited;
82
- * ```
83
- */
84
- toFlatCommand(): string[];
85
- /**
86
- * Convenient alias for {@link PrintableShellCommand.toFlatCommand | `.toFlatCommand()`}.
87
- *
88
- * Usage example:
89
- *
90
- * ```
91
- * import { PrintableShellCommand } from "printable-shell-command";
92
- * import { spawn } from "bun";
93
- *
94
- * const command = new PrintableShellCommand( … );
95
- * await spawn(command.forBun()).exited;
96
- * ```
97
- *
98
- * */
99
- forBun(): string[];
100
66
  /**
101
67
  * For use with `node:child_process`
102
68
  *
@@ -112,22 +78,6 @@ export declare class PrintableShellCommand {
112
78
  *
113
79
  */
114
80
  toCommandWithFlatArgs(): [string, string[]];
115
- /**
116
- * For use with `node:child_process`
117
- *
118
- * Usage example:
119
- *
120
- * ```
121
- * import { PrintableShellCommand } from "printable-shell-command";
122
- * import { spawn } from "node:child_process";
123
- *
124
- * const command = new PrintableShellCommand( … );
125
- * const child_process = spawn(...command.forNode()); // Note the `...`
126
- * ```
127
- *
128
- * Convenient alias for {@link PrintableShellCommand.toCommandWithFlatArgs | `toCommandWithFlatArgs()`}.
129
- */
130
- forNode(): [string, string[]];
131
81
  getPrintableCommand(options?: PrintOptions): string;
132
82
  /**
133
83
  * Print the shell command to {@link stderr} (default) or a specified stream.
@@ -209,33 +159,6 @@ export declare class PrintableShellCommand {
209
159
  * ```
210
160
  */
211
161
  shellOut(options?: NodeWithCwd<Omit<NodeSpawnOptions, "stdio">>): Promise<void>;
212
- bun: {
213
- /** Equivalent to:
214
- *
215
- * ```
216
- * await this.print().bun.spawnBunInherit(…).success;
217
- * ```
218
- */
219
- spawnBun: <const In extends BunSpawnOptions.Writable = "ignore", const Out extends BunSpawnOptions.Readable = "pipe", const Err extends BunSpawnOptions.Readable = "inherit">(options?: BunWithCwd<Omit<BunSpawnOptions.OptionsObject<In, Out, Err>, "cmd">>) => BunSubprocess<In, Out, Err> & {
220
- success: Promise<void>;
221
- };
222
- /**
223
- * A wrapper for `.spawnBunInherit(…)` that sets stdio to `"inherit"` (common
224
- * for invoking commands from scripts whose output and interaction should be
225
- * surfaced to the user).
226
- */
227
- spawnBunInherit: (options?: BunWithCwd<Omit<BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">, "cmd" | "stdio">>) => BunSubprocess<"inherit", "inherit", "inherit"> & {
228
- success: Promise<void>;
229
- };
230
- /** Equivalent to:
231
- *
232
- * ```
233
- * new Response(this.bun.spawnBun(…).stdout);
234
- * ```
235
- */
236
- spawnBunStdout: (options?: BunWithCwd<Omit<BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">, "cmd" | "stdio">>) => Response;
237
- shellOutBun: (options?: BunWithCwd<Omit<BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">, "cmd" | "stdio">>) => Promise<void>;
238
- };
239
162
  }
240
163
  export declare function escapeArg(arg: string, isMainCommand: boolean, options: PrintOptions): string;
241
164
  export {};
@@ -84,38 +84,6 @@ var PrintableShellCommand = class {
84
84
  get commandName() {
85
85
  return stringifyIfPath(this.#commandName);
86
86
  }
87
- /** For use with `bun`.
88
- *
89
- * Usage example:
90
- *
91
- * ```
92
- * import { PrintableShellCommand } from "printable-shell-command";
93
- * import { spawn } from "bun";
94
- *
95
- * const command = new PrintableShellCommand( … );
96
- * await spawn(command.toFlatCommand()).exited;
97
- * ```
98
- */
99
- toFlatCommand() {
100
- return [this.commandName, ...this.args.flat().map(stringifyIfPath)];
101
- }
102
- /**
103
- * Convenient alias for {@link PrintableShellCommand.toFlatCommand | `.toFlatCommand()`}.
104
- *
105
- * Usage example:
106
- *
107
- * ```
108
- * import { PrintableShellCommand } from "printable-shell-command";
109
- * import { spawn } from "bun";
110
- *
111
- * const command = new PrintableShellCommand( … );
112
- * await spawn(command.forBun()).exited;
113
- * ```
114
- *
115
- * */
116
- forBun() {
117
- return this.toFlatCommand();
118
- }
119
87
  /**
120
88
  * For use with `node:child_process`
121
89
  *
@@ -133,24 +101,6 @@ var PrintableShellCommand = class {
133
101
  toCommandWithFlatArgs() {
134
102
  return [this.commandName, this.args.flat().map(stringifyIfPath)];
135
103
  }
136
- /**
137
- * For use with `node:child_process`
138
- *
139
- * Usage example:
140
- *
141
- * ```
142
- * import { PrintableShellCommand } from "printable-shell-command";
143
- * import { spawn } from "node:child_process";
144
- *
145
- * const command = new PrintableShellCommand( … );
146
- * const child_process = spawn(...command.forNode()); // Note the `...`
147
- * ```
148
- *
149
- * Convenient alias for {@link PrintableShellCommand.toCommandWithFlatArgs | `toCommandWithFlatArgs()`}.
150
- */
151
- forNode() {
152
- return this.toCommandWithFlatArgs();
153
- }
154
104
  #mainIndentation(options) {
155
105
  return options?.mainIndentation ?? DEFAULT_MAIN_INDENTATION;
156
106
  }
@@ -270,7 +220,7 @@ var PrintableShellCommand = class {
270
220
  }
271
221
  options.stdio[0] = "pipe";
272
222
  }
273
- const subprocess = spawn(...this.forNode(), {
223
+ const subprocess = spawn(...this.toCommandWithFlatArgs(), {
274
224
  ...options,
275
225
  cwd
276
226
  });
@@ -458,78 +408,6 @@ var PrintableShellCommand = class {
458
408
  async shellOut(options) {
459
409
  await this.print().spawnTransparently(options).success;
460
410
  }
461
- /**
462
- * The returned subprocess includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313
463
- */
464
- #spawnBun(options) {
465
- if (options && "cmd" in options) {
466
- throw new Error("Unexpected `cmd` field.");
467
- }
468
- const { spawn } = process.getBuiltinModule("bun");
469
- const cwd = stringifyIfPath(options?.cwd);
470
- const subprocess = spawn({
471
- ...options,
472
- cwd,
473
- cmd: this.forBun()
474
- });
475
- Object.defineProperty(subprocess, "success", {
476
- get() {
477
- return new Promise(
478
- (resolve, reject) => this.exited.then((exitCode) => {
479
- if (exitCode === 0) {
480
- resolve();
481
- } else {
482
- reject(
483
- new Error(
484
- `Command failed with non-zero exit code: ${exitCode}`
485
- )
486
- );
487
- }
488
- }).catch(reject)
489
- );
490
- },
491
- enumerable: false
492
- });
493
- return subprocess;
494
- }
495
- #spawnBunInherit(options) {
496
- if (options && "stdio" in options) {
497
- throw new Error("Unexpected `stdio` field.");
498
- }
499
- return this.bun.spawnBun({
500
- ...options,
501
- stdio: ["inherit", "inherit", "inherit"]
502
- });
503
- }
504
- #spawnBunStdout(options) {
505
- return new Response(this.bun.spawnBun(options).stdout);
506
- }
507
- async #shellOutBun(options) {
508
- await this.print().bun.spawnBunInherit(options).success;
509
- }
510
- bun = {
511
- /** Equivalent to:
512
- *
513
- * ```
514
- * await this.print().bun.spawnBunInherit(…).success;
515
- * ```
516
- */
517
- spawnBun: this.#spawnBun.bind(this),
518
- /**
519
- * A wrapper for `.spawnBunInherit(…)` that sets stdio to `"inherit"` (common
520
- * for invoking commands from scripts whose output and interaction should be
521
- * surfaced to the user).
522
- */
523
- spawnBunInherit: this.#spawnBunInherit.bind(this),
524
- /** Equivalent to:
525
- *
526
- * ```
527
- * new Response(this.bun.spawnBun(…).stdout);
528
- * ```
529
- */
530
- spawnBunStdout: this.#spawnBunStdout.bind(this),
531
- shellOutBun: this.#shellOutBun.bind(this)
532
- };
533
411
  };
534
412
  function escapeArg(arg, isMainCommand, options) {
535
413
  const argCharacters = new Set(arg);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/index.ts"],
4
- "sourcesContent": ["import assert from \"node:assert\";\nimport type {\n ChildProcessByStdio,\n ChildProcess as NodeChildProcess,\n SpawnOptions as NodeSpawnOptions,\n} from \"node:child_process\";\nimport { createReadStream } from \"node:fs\";\nimport { stderr } from \"node:process\";\nimport { Readable, Writable } from \"node:stream\";\nimport type { WriteStream } from \"node:tty\";\nimport { styleText } from \"node:util\";\nimport type {\n SpawnOptions as BunSpawnOptions,\n Subprocess as BunSubprocess,\n SpawnOptions,\n} from \"bun\";\nimport { Path, stringifyIfPath } from \"path-class\";\nimport type { SetFieldType } from \"type-fest\";\nimport type {\n NodeWithCwd,\n spawnType,\n WithStderrResponse,\n WithStdoutResponse,\n WithSuccess,\n} from \"./spawn\";\n\n// TODO: does this import work?\n/**\n * @import { stdout } from \"node:process\"\n */\n\nconst DEFAULT_MAIN_INDENTATION = \"\";\nconst DEFAULT_ARG_INDENTATION = \" \";\nconst DEFAULT_ARGUMENT_LINE_WRAPPING = \"by-entry\";\n\nconst INLINE_SEPARATOR = \" \";\nconst LINE_WRAP_LINE_END = \" \\\\\\n\";\n\ntype StyleTextFormat = Parameters<typeof styleText>[0];\n\nconst TTY_AUTO_STYLE: StyleTextFormat = [\"gray\", \"bold\"];\n\n// biome-ignore lint/suspicious/noExplicitAny: This is the correct type nere.\nfunction isString(s: any): s is string {\n return typeof s === \"string\";\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: This is the correct type here.\nfunction isValidArgsEntryArray(entries: any[]): entries is SingleArgument[] {\n for (const entry of entries) {\n if (isString(entry)) {\n continue;\n }\n if (entry instanceof Path) {\n continue;\n }\n return false;\n }\n return true;\n}\n\n// TODO: allow `.toString()`ables?\ntype SingleArgument = string | Path;\ntype ArgsEntry = SingleArgument | SingleArgument[];\ntype Args = ArgsEntry[];\n\nexport interface PrintOptions {\n /** Defaults to \"\" */\n mainIndentation?: string;\n /** Defaults to \" \" */\n argIndentation?: string;\n /**\n * - `\"auto\"`: Quote only arguments that need it for safety. This tries to be\n * portable and safe across shells, but true safety and portability is hard\n * to guarantee.\n * - `\"extra-safe\"`: Quote all arguments, even ones that don't need it. This is\n * more likely to be safe under all circumstances.\n */\n quoting?: \"auto\" | \"extra-safe\";\n /** Line wrapping to use between arguments. Defaults to `\"by-entry\"`. */\n argumentLineWrapping?:\n | \"by-entry\"\n | \"nested-by-entry\"\n | \"by-argument\"\n | \"inline\";\n /** Include the first arg (or first arg group) on the same line as the command, regardless of the `argumentLineWrapping` setting. */\n skipLineWrapBeforeFirstArg?: true | false;\n /**\n * Style text using `node`'s {@link styleText | `styleText(\u2026)`}.\n *\n * Example usage:\n *\n * ```\n * new PrintableShellCommand(\"echo\", [\"hi\"]).print({\n * styleTextFormat: [\"green\", \"underline\"],\n * });\n * */\n styleTextFormat?: StyleTextFormat;\n}\n\nexport interface StreamPrintOptions extends PrintOptions {\n /**\n * Auto-style the text when:\n *\n * - the output stream is detected to be a TTY\n * - `styleTextFormat` is not specified.\n *\n * The current auto style is: `[\"gray\", \"bold\"]`\n */\n autoStyle?: \"tty\" | \"never\";\n // This would be a `WritableStream` (open web standard), but `WriteStream` allows us to query `.isTTY`.\n stream?: WriteStream | Writable;\n}\n\n// https://mywiki.wooledge.org/BashGuide/SpecialCharacters\nconst SPECIAL_SHELL_CHARACTERS = new Set([\n \" \",\n '\"',\n \"'\",\n \"`\",\n \"|\",\n \"$\",\n \"*\",\n \"?\",\n \">\",\n \"<\",\n \"(\",\n \")\",\n \"[\",\n \"]\",\n \"{\",\n \"}\",\n \"&\",\n \"\\\\\",\n \";\",\n \"#\",\n]);\n\n// https://mywiki.wooledge.org/BashGuide/SpecialCharacters\nconst SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND =\n // biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)\n (SPECIAL_SHELL_CHARACTERS as unknown as any).union(new Set([\"=\"]));\n\n// biome-ignore lint/suspicious/noExplicitAny: Just matching\ntype BunCwd = SpawnOptions.OptionsObject<any, any, any>[\"cwd\"] | Path;\ntype BunWithCwd<\n // biome-ignore lint/suspicious/noExplicitAny: Just matching\n T extends { cwd?: SpawnOptions.OptionsObject<any, any, any>[\"cwd\"] | Path },\n> = SetFieldType<T, \"cwd\", BunCwd | undefined>;\n\n// TODO: Is there an idiomatic ways to check that all potential fields of\n// `StdinSource` satisfy `(typeof STDIN_SOURCE_KEYS)[number]`, without adding\n// extra indirection for type wrangling?\nconst STDIN_SOURCE_KEYS = [\"text\", \"json\", \"path\", \"stream\"] as const;\nexport type StdinSource =\n | { text: string }\n // biome-ignore lint/suspicious/noExplicitAny: `any` is the correct type for JSON data.\n | { json: any }\n | { path: string | Path }\n | { stream: Readable | ReadableStream };\n\nexport class PrintableShellCommand {\n #commandName: string | Path;\n constructor(\n commandName: string | Path,\n private args: Args = [],\n ) {\n if (!isString(commandName) && !(commandName instanceof Path)) {\n // biome-ignore lint/suspicious/noExplicitAny: We want to print this, no matter what it is.\n throw new Error(\"Command name is not a string:\", commandName as any);\n }\n this.#commandName = commandName;\n if (typeof args === \"undefined\") {\n return;\n }\n if (!Array.isArray(args)) {\n throw new Error(\"Command arguments are not an array\");\n }\n for (let i = 0; i < args.length; i++) {\n const argEntry = args[i];\n if (typeof argEntry === \"string\") {\n continue;\n }\n if (argEntry instanceof Path) {\n continue;\n }\n if (Array.isArray(argEntry) && isValidArgsEntryArray(argEntry)) {\n continue;\n }\n throw new Error(`Invalid arg entry at index: ${i}`);\n }\n }\n\n get commandName(): string {\n return stringifyIfPath(this.#commandName);\n }\n\n /** For use with `bun`.\n *\n * Usage example:\n *\n * ```\n * import { PrintableShellCommand } from \"printable-shell-command\";\n * import { spawn } from \"bun\";\n *\n * const command = new PrintableShellCommand( \u2026 );\n * await spawn(command.toFlatCommand()).exited;\n * ```\n */\n public toFlatCommand(): string[] {\n return [this.commandName, ...this.args.flat().map(stringifyIfPath)];\n }\n\n /**\n * Convenient alias for {@link PrintableShellCommand.toFlatCommand | `.toFlatCommand()`}.\n *\n * Usage example:\n *\n * ```\n * import { PrintableShellCommand } from \"printable-shell-command\";\n * import { spawn } from \"bun\";\n *\n * const command = new PrintableShellCommand( \u2026 );\n * await spawn(command.forBun()).exited;\n * ```\n *\n * */\n public forBun(): string[] {\n return this.toFlatCommand();\n }\n\n /**\n * For use with `node:child_process`\n *\n * Usage example:\n *\n * ```\n * import { PrintableShellCommand } from \"printable-shell-command\";\n * import { spawn } from \"node:child_process\";\n *\n * const command = new PrintableShellCommand( \u2026 );\n * const child_process = spawn(...command.toCommandWithFlatArgs()); // Note the `...`\n * ```\n *\n */\n public toCommandWithFlatArgs(): [string, string[]] {\n return [this.commandName, this.args.flat().map(stringifyIfPath)];\n }\n\n /**\n * For use with `node:child_process`\n *\n * Usage example:\n *\n * ```\n * import { PrintableShellCommand } from \"printable-shell-command\";\n * import { spawn } from \"node:child_process\";\n *\n * const command = new PrintableShellCommand( \u2026 );\n * const child_process = spawn(...command.forNode()); // Note the `...`\n * ```\n *\n * Convenient alias for {@link PrintableShellCommand.toCommandWithFlatArgs | `toCommandWithFlatArgs()`}.\n */\n public forNode(): [string, string[]] {\n return this.toCommandWithFlatArgs();\n }\n\n #mainIndentation(options: PrintOptions): string {\n return options?.mainIndentation ?? DEFAULT_MAIN_INDENTATION;\n }\n\n #argIndentation(options: PrintOptions): string {\n return (\n this.#mainIndentation(options) +\n (options?.argIndentation ?? DEFAULT_ARG_INDENTATION)\n );\n }\n\n #lineWrapSeparator(options: PrintOptions): string {\n return LINE_WRAP_LINE_END + this.#argIndentation(options);\n }\n\n #argPairSeparator(options: PrintOptions): string {\n switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {\n case \"by-entry\": {\n return INLINE_SEPARATOR;\n }\n case \"nested-by-entry\": {\n return this.#lineWrapSeparator(options) + this.#argIndentation(options);\n }\n case \"by-argument\": {\n return this.#lineWrapSeparator(options);\n }\n case \"inline\": {\n return INLINE_SEPARATOR;\n }\n default:\n throw new Error(\"Invalid argument line wrapping argument.\");\n }\n }\n\n #intraEntrySeparator(options: PrintOptions): string {\n switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {\n case \"by-entry\":\n case \"nested-by-entry\":\n case \"by-argument\": {\n return LINE_WRAP_LINE_END + this.#argIndentation(options);\n }\n case \"inline\": {\n return INLINE_SEPARATOR;\n }\n default:\n throw new Error(\"Invalid argument line wrapping argument.\");\n }\n }\n\n #separatorAfterCommand(\n options: PrintOptions,\n numFollowingEntries: number,\n ): string {\n if (numFollowingEntries === 0) {\n return \"\";\n }\n if (options.skipLineWrapBeforeFirstArg ?? false) {\n return INLINE_SEPARATOR;\n }\n return this.#intraEntrySeparator(options);\n }\n\n public getPrintableCommand(options?: PrintOptions): string {\n // TODO: Why in the world does TypeScript not give the `options` arg the type of `PrintOptions | undefined`???\n options ??= {};\n const serializedEntries: string[] = [];\n\n for (let i = 0; i < this.args.length; i++) {\n const argsEntry = stringifyIfPath(this.args[i]);\n\n if (isString(argsEntry)) {\n serializedEntries.push(escapeArg(argsEntry, false, options));\n } else {\n serializedEntries.push(\n argsEntry\n .map((part) => escapeArg(stringifyIfPath(part), false, options))\n .join(this.#argPairSeparator(options)),\n );\n }\n }\n\n let text =\n this.#mainIndentation(options) +\n escapeArg(this.commandName, true, options) +\n this.#separatorAfterCommand(options, serializedEntries.length) +\n serializedEntries.join(this.#intraEntrySeparator(options));\n if (options?.styleTextFormat) {\n text = styleText(options.styleTextFormat, text);\n }\n return text;\n }\n\n /**\n * Print the shell command to {@link stderr} (default) or a specified stream.\n *\n * By default, this will be auto-styled (as bold gray) when `.isTTY` is true\n * for the stream. `.isTTY` is populated for the {@link stderr} and\n * {@link stdout} objects. Pass `\"autoStyle\": \"never\"` or an explicit\n * `styleTextFormat` to disable this.\n *\n */\n public print(options?: StreamPrintOptions): PrintableShellCommand {\n const stream = options?.stream ?? stderr;\n // Note: we only need to modify top-level fields, so `structuredClone(\u2026)`\n // would be overkill and can only cause performance issues.\n const optionsCopy = { ...options };\n optionsCopy.styleTextFormat ??=\n options?.autoStyle !== \"never\" &&\n (stream as { isTTY?: boolean }).isTTY === true\n ? TTY_AUTO_STYLE\n : undefined;\n const writable =\n stream instanceof Writable ? stream : Writable.fromWeb(stream);\n writable.write(this.getPrintableCommand(optionsCopy));\n writable.write(\"\\n\");\n return this;\n }\n\n #stdinSource: StdinSource | undefined;\n /**\n * Send data to `stdin` of the subprocess.\n *\n * Note that this will overwrite:\n *\n * - Any previous value set using {@link PrintableShellCommand.stdin | `.stdin(\u2026)`}.\n * - Any value set for `stdin` using the `\"stdio\"` field of {@link PrintableShellCommand.spawn | `.spawn(\u2026)`}.\n */\n stdin(source: StdinSource): PrintableShellCommand {\n const [key, ...moreKeys] = Object.keys(source);\n assert.equal(moreKeys.length, 0);\n // TODO: validate values?\n assert((STDIN_SOURCE_KEYS as unknown as string[]).includes(key));\n\n this.#stdinSource = source;\n return this;\n }\n\n /**\n * The returned child process includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313\n */\n public spawn: typeof spawnType = ((\n options?: Parameters<typeof spawnType>[0],\n ) => {\n const { spawn } = process.getBuiltinModule(\"node:child_process\");\n const cwd = stringifyIfPath(options?.cwd);\n if (this.#stdinSource) {\n options ??= {};\n if (typeof options.stdio === \"undefined\") {\n options.stdio = \"pipe\";\n }\n if (typeof options.stdio === \"string\") {\n options.stdio = new Array(3).fill(options.stdio);\n }\n options.stdio[0] = \"pipe\";\n }\n // biome-ignore lint/suspicious/noTsIgnore: We don't want linting to depend on *broken* type checking.\n // @ts-ignore: The TypeScript checker has trouble reconciling the optional (i.e. potentially `undefined`) `options` with the third argument.\n const subprocess = spawn(...this.forNode(), {\n ...(options as object),\n cwd,\n }) as NodeChildProcess & {\n success: Promise<void>;\n };\n // TODO: define properties on prototypes instead.\n Object.defineProperty(subprocess, \"success\", {\n get() {\n return new Promise<void>((resolve, reject) =>\n this.addListener(\n \"exit\",\n (exitCode: number /* we only use the first arg */) => {\n if (exitCode === 0) {\n resolve();\n } else {\n reject(`Command failed with non-zero exit code: ${exitCode}`);\n }\n },\n ),\n );\n },\n enumerable: false,\n });\n if (subprocess.stdout) {\n // TODO: dedupe\n const s = subprocess as unknown as Readable &\n WithStdoutResponse &\n WithSuccess;\n s.stdout.response = () =>\n new Response(Readable.from(this.#generator(s.stdout, s.success)));\n s.stdout.text = () => s.stdout.response().text();\n const thisCached = this; // TODO: make this type-check using `.bind(\u2026)`\n s.stdout.text0 = async function* () {\n yield* thisCached.#split0(thisCached.#generator(s.stdout, s.success));\n };\n s.stdout.json = <T>() => s.stdout.response().json() as Promise<T>;\n }\n if (subprocess.stderr) {\n // TODO: dedupe\n const s = subprocess as unknown as Readable &\n WithStderrResponse &\n WithSuccess;\n s.stderr.response = () =>\n new Response(Readable.from(this.#generator(s.stderr, s.success)));\n s.stderr.text = () => s.stderr.response().text();\n const thisCached = this; // TODO: make this type-check using `.bind(\u2026)`\n s.stderr.text0 = async function* () {\n yield* thisCached.#split0(thisCached.#generator(s.stderr, s.success));\n };\n s.stderr.json = <T>() => s.stderr.response().json() as Promise<T>;\n }\n if (this.#stdinSource) {\n const { stdin } = subprocess;\n assert(stdin);\n if (\"text\" in this.#stdinSource) {\n stdin.write(this.#stdinSource.text);\n stdin.end();\n } else if (\"json\" in this.#stdinSource) {\n stdin.write(JSON.stringify(this.#stdinSource.json));\n stdin.end();\n } else if (\"path\" in this.#stdinSource) {\n createReadStream(stringifyIfPath(this.#stdinSource.path)).pipe(stdin);\n } else if (\"stream\" in this.#stdinSource) {\n const stream = (() => {\n const { stream } = this.#stdinSource;\n return stream instanceof Readable ? stream : Readable.fromWeb(stream);\n })();\n stream.pipe(stdin);\n } else {\n throw new Error(\"Invalid `.stdin(\u2026)` source?\");\n }\n }\n return subprocess;\n // biome-ignore lint/suspicious/noExplicitAny: Type wrangling\n }) as any;\n\n /** A wrapper for `.spawn(\u2026)` that sets stdio to `\"inherit\"` (common for\n * invoking commands from scripts whose output and interaction should be\n * surfaced to the user).\n *\n * If there is no other interaction with the shell from the calling process,\n * then it acts \"transparent\" and allows user to interact with the subprocess\n * in its stead.\n */\n public spawnTransparently(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): ChildProcessByStdio<null, null, null> & WithSuccess {\n if (options && \"stdio\" in options) {\n throw new Error(\"Unexpected `stdio` field.\");\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Type wrangling.\n return this.spawn({ ...options, stdio: \"inherit\" }) as any;\n }\n\n /**\n * A wrapper for {@link PrintableShellCommand.spawn | `.spawn(\u2026)`} that:\n *\n * - sets `detached` to `true`,\n * - sets stdio to `\"inherit\"`,\n * - calls `.unref()`, and\n * - does not wait for the process to exit.\n *\n * This is similar to starting a command in the background and disowning it (in a shell).\n *\n */\n public spawnDetached(\n options?: NodeWithCwd<Omit<Omit<NodeSpawnOptions, \"stdio\">, \"detached\">>,\n ): void {\n if (options) {\n for (const field of [\"stdio\", \"detached\"]) {\n if (field in options) {\n throw new Error(`Unexpected \\`${field}\\` field.`);\n }\n }\n }\n const childProcess = this.spawn({\n stdio: \"ignore\",\n ...options,\n detached: true,\n });\n childProcess.unref();\n }\n\n #generator(\n readable: Readable,\n successPromise: Promise<void>,\n ): AsyncGenerator<string> {\n // TODO: we'd make this a `ReadableStream`, but `ReadableStream.from(\u2026)` is\n // not implemented in `bun`: https://github.com/oven-sh/bun/issues/3700\n return (async function* () {\n for await (const chunk of readable) {\n yield chunk;\n }\n await successPromise;\n })();\n }\n\n #stdoutSpawnGenerator(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): AsyncGenerator<string> {\n if (options && \"stdio\" in options) {\n throw new Error(\"Unexpected `stdio` field.\");\n }\n const subprocess = this.spawn({\n ...options,\n stdio: [\"ignore\", \"pipe\", \"inherit\"],\n });\n return this.#generator(subprocess.stdout, subprocess.success);\n }\n\n public stdout(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): Response {\n // TODO: Use `ReadableStream.from(\u2026)` once `bun` implements it: https://github.com/oven-sh/bun/pull/21269\n return new Response(Readable.from(this.#stdoutSpawnGenerator(options)));\n }\n\n async *#split0(generator: AsyncGenerator<string>): AsyncGenerator<string> {\n let pending = \"\";\n for await (const chunk of generator) {\n pending += chunk;\n const newChunks = pending.split(\"\\x00\");\n pending = newChunks.splice(-1)[0];\n yield* newChunks;\n }\n if (pending !== \"\") {\n throw new Error(\n \"Missing a trailing NUL character at the end of a NUL-delimited stream.\",\n );\n }\n }\n\n /**\n * Convenience function for:\n *\n * .stdout(options).text()\n *\n * This can make some simple invocations easier to read and/or fit on a single line.\n */\n public text(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): Promise<string> {\n return this.stdout(options).text();\n }\n\n /**\n * Convenience function for:\n *\n * .stdout(options).json()\n *\n * This can make some simple invocations easier to read and/or fit on a single line.\n */\n public json<T>(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): Promise<T> {\n return this.stdout(options).json() as Promise<T>;\n }\n\n /**\n * Parse `stdout` into a generator of string values using a NULL delimiter.\n *\n * A trailing NULL delimiter from `stdout` is required and removed.\n */\n public async *text0(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): AsyncGenerator<string> {\n yield* this.#split0(this.#stdoutSpawnGenerator(options));\n }\n\n /**\n * Parse `stdout` into a generator of JSON values using a NULL delimiter.\n *\n * A trailing NULL delimiter from `stdout` is required and removed.\n */\n public async *json0(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): // biome-ignore lint/suspicious/noExplicitAny: `any` is the correct type for JSON\n AsyncGenerator<any> {\n for await (const part of this.#split0(\n this.#stdoutSpawnGenerator(options),\n )) {\n yield JSON.parse(part);\n }\n }\n\n /** Equivalent to:\n *\n * ```\n * await this.print().spawnTransparently(\u2026).success;\n * ```\n */\n public async shellOut(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): Promise<void> {\n await this.print().spawnTransparently(options).success;\n }\n\n /**\n * The returned subprocess includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313\n */\n #spawnBun<\n const In extends BunSpawnOptions.Writable = \"ignore\",\n const Out extends BunSpawnOptions.Readable = \"pipe\",\n const Err extends BunSpawnOptions.Readable = \"inherit\",\n >(\n options?: BunWithCwd<\n Omit<BunSpawnOptions.OptionsObject<In, Out, Err>, \"cmd\">\n >,\n ): BunSubprocess<In, Out, Err> & { success: Promise<void> } {\n if (options && \"cmd\" in options) {\n throw new Error(\"Unexpected `cmd` field.\");\n }\n const { spawn } = process.getBuiltinModule(\"bun\") as typeof import(\"bun\");\n const cwd = stringifyIfPath(options?.cwd);\n const subprocess = spawn({\n ...options,\n cwd,\n cmd: this.forBun(),\n }) as BunSubprocess<In, Out, Err> & { success: Promise<void> };\n Object.defineProperty(subprocess, \"success\", {\n get() {\n return new Promise<void>((resolve, reject) =>\n this.exited\n .then((exitCode: number) => {\n if (exitCode === 0) {\n resolve();\n } else {\n reject(\n new Error(\n `Command failed with non-zero exit code: ${exitCode}`,\n ),\n );\n }\n })\n .catch(reject),\n );\n },\n enumerable: false,\n });\n return subprocess;\n }\n\n #spawnBunInherit(\n options?: BunWithCwd<\n Omit<\n BunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n \"cmd\" | \"stdio\"\n >\n >,\n ): BunSubprocess<\"inherit\", \"inherit\", \"inherit\"> & {\n success: Promise<void>;\n } {\n if (options && \"stdio\" in options) {\n throw new Error(\"Unexpected `stdio` field.\");\n }\n return this.bun.spawnBun({\n ...options,\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n });\n }\n\n #spawnBunStdout(\n options?: BunWithCwd<\n Omit<\n BunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n \"cmd\" | \"stdio\"\n >\n >,\n ): Response {\n // biome-ignore lint/suspicious/noExplicitAny: Avoid breaking the lib check when used without `@types/bun`.\n return new Response((this.bun.spawnBun(options) as any).stdout);\n }\n\n async #shellOutBun(\n options?: BunWithCwd<\n Omit<\n BunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n \"cmd\" | \"stdio\"\n >\n >,\n ): Promise<void> {\n await this.print().bun.spawnBunInherit(options).success;\n }\n\n bun = {\n /** Equivalent to:\n *\n * ```\n * await this.print().bun.spawnBunInherit(\u2026).success;\n * ```\n */\n spawnBun: this.#spawnBun.bind(this),\n /**\n * A wrapper for `.spawnBunInherit(\u2026)` that sets stdio to `\"inherit\"` (common\n * for invoking commands from scripts whose output and interaction should be\n * surfaced to the user).\n */\n spawnBunInherit: this.#spawnBunInherit.bind(this),\n /** Equivalent to:\n *\n * ```\n * new Response(this.bun.spawnBun(\u2026).stdout);\n * ```\n */\n spawnBunStdout: this.#spawnBunStdout.bind(this),\n shellOutBun: this.#shellOutBun.bind(this),\n };\n}\n\nexport function escapeArg(\n arg: string,\n isMainCommand: boolean,\n options: PrintOptions,\n): string {\n const argCharacters = new Set(arg);\n const specialShellCharacters = isMainCommand\n ? SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND\n : SPECIAL_SHELL_CHARACTERS;\n if (\n options?.quoting === \"extra-safe\" ||\n // biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)\n (argCharacters as unknown as any).intersection(specialShellCharacters)\n .size > 0\n ) {\n // Use single quote to reduce the need to escape (and therefore reduce the chance for bugs/security issues).\n const escaped = arg.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"\\\\'\");\n return `'${escaped}'`;\n }\n return arg;\n}\n"],
5
- "mappings": ";AAAA,OAAO,YAAY;AAMnB,SAAS,wBAAwB;AACjC,SAAS,cAAc;AACvB,SAAS,UAAU,gBAAgB;AAEnC,SAAS,iBAAiB;AAM1B,SAAS,MAAM,uBAAuB;AAetC,IAAM,2BAA2B;AACjC,IAAM,0BAA0B;AAChC,IAAM,iCAAiC;AAEvC,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAI3B,IAAM,iBAAkC,CAAC,QAAQ,MAAM;AAGvD,SAAS,SAAS,GAAqB;AACrC,SAAO,OAAO,MAAM;AACtB;AAGA,SAAS,sBAAsB,SAA6C;AAC1E,aAAW,SAAS,SAAS;AAC3B,QAAI,SAAS,KAAK,GAAG;AACnB;AAAA,IACF;AACA,QAAI,iBAAiB,MAAM;AACzB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAwDA,IAAM,2BAA2B,oBAAI,IAAI;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGD,IAAM;AAAA;AAAA,EAEH,yBAA4C,MAAM,oBAAI,IAAI,CAAC,GAAG,CAAC,CAAC;AAAA;AAYnE,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EA,UAAM,UAAU,IAAI,WAAW,MAAM,MAAM,EAAE,WAAW,KAAK,KAAK;AAClE,WAAO,IAAI,OAAO;AAAA,EACpB;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import assert from \"node:assert\";\nimport type {\n ChildProcessByStdio,\n ChildProcess as NodeChildProcess,\n SpawnOptions as NodeSpawnOptions,\n} from \"node:child_process\";\nimport { createReadStream } from \"node:fs\";\nimport { stderr } from \"node:process\";\nimport { Readable, Writable } from \"node:stream\";\nimport type { WriteStream } from \"node:tty\";\nimport { styleText } from \"node:util\";\nimport { Path, stringifyIfPath } from \"path-class\";\nimport type {\n NodeWithCwd,\n spawnType,\n WithStderrResponse,\n WithStdoutResponse,\n WithSuccess,\n} from \"./spawn\";\n\n// TODO: does this import work?\n/**\n * @import { stdout } from \"node:process\"\n */\n\nconst DEFAULT_MAIN_INDENTATION = \"\";\nconst DEFAULT_ARG_INDENTATION = \" \";\nconst DEFAULT_ARGUMENT_LINE_WRAPPING = \"by-entry\";\n\nconst INLINE_SEPARATOR = \" \";\nconst LINE_WRAP_LINE_END = \" \\\\\\n\";\n\ntype StyleTextFormat = Parameters<typeof styleText>[0];\n\nconst TTY_AUTO_STYLE: StyleTextFormat = [\"gray\", \"bold\"];\n\n// biome-ignore lint/suspicious/noExplicitAny: This is the correct type nere.\nfunction isString(s: any): s is string {\n return typeof s === \"string\";\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: This is the correct type here.\nfunction isValidArgsEntryArray(entries: any[]): entries is SingleArgument[] {\n for (const entry of entries) {\n if (isString(entry)) {\n continue;\n }\n if (entry instanceof Path) {\n continue;\n }\n return false;\n }\n return true;\n}\n\n// TODO: allow `.toString()`ables?\ntype SingleArgument = string | Path;\ntype ArgsEntry = SingleArgument | SingleArgument[];\ntype Args = ArgsEntry[];\n\nexport interface PrintOptions {\n /** Defaults to \"\" */\n mainIndentation?: string;\n /** Defaults to \" \" */\n argIndentation?: string;\n /**\n * - `\"auto\"`: Quote only arguments that need it for safety. This tries to be\n * portable and safe across shells, but true safety and portability is hard\n * to guarantee.\n * - `\"extra-safe\"`: Quote all arguments, even ones that don't need it. This is\n * more likely to be safe under all circumstances.\n */\n quoting?: \"auto\" | \"extra-safe\";\n /** Line wrapping to use between arguments. Defaults to `\"by-entry\"`. */\n argumentLineWrapping?:\n | \"by-entry\"\n | \"nested-by-entry\"\n | \"by-argument\"\n | \"inline\";\n /** Include the first arg (or first arg group) on the same line as the command, regardless of the `argumentLineWrapping` setting. */\n skipLineWrapBeforeFirstArg?: true | false;\n /**\n * Style text using `node`'s {@link styleText | `styleText(\u2026)`}.\n *\n * Example usage:\n *\n * ```\n * new PrintableShellCommand(\"echo\", [\"hi\"]).print({\n * styleTextFormat: [\"green\", \"underline\"],\n * });\n * */\n styleTextFormat?: StyleTextFormat;\n}\n\nexport interface StreamPrintOptions extends PrintOptions {\n /**\n * Auto-style the text when:\n *\n * - the output stream is detected to be a TTY\n * - `styleTextFormat` is not specified.\n *\n * The current auto style is: `[\"gray\", \"bold\"]`\n */\n autoStyle?: \"tty\" | \"never\";\n // This would be a `WritableStream` (open web standard), but `WriteStream` allows us to query `.isTTY`.\n stream?: WriteStream | Writable;\n}\n\n// https://mywiki.wooledge.org/BashGuide/SpecialCharacters\nconst SPECIAL_SHELL_CHARACTERS = new Set([\n \" \",\n '\"',\n \"'\",\n \"`\",\n \"|\",\n \"$\",\n \"*\",\n \"?\",\n \">\",\n \"<\",\n \"(\",\n \")\",\n \"[\",\n \"]\",\n \"{\",\n \"}\",\n \"&\",\n \"\\\\\",\n \";\",\n \"#\",\n]);\n\n// https://mywiki.wooledge.org/BashGuide/SpecialCharacters\nconst SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND =\n // biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)\n (SPECIAL_SHELL_CHARACTERS as unknown as any).union(new Set([\"=\"]));\n\n// TODO: Is there an idiomatic ways to check that all potential fields of\n// `StdinSource` satisfy `(typeof STDIN_SOURCE_KEYS)[number]`, without adding\n// extra indirection for type wrangling?\nconst STDIN_SOURCE_KEYS = [\"text\", \"json\", \"path\", \"stream\"] as const;\nexport type StdinSource =\n | { text: string }\n // biome-ignore lint/suspicious/noExplicitAny: `any` is the correct type for JSON data.\n | { json: any }\n | { path: string | Path }\n | { stream: Readable | ReadableStream };\n\nexport class PrintableShellCommand {\n #commandName: string | Path;\n constructor(\n commandName: string | Path,\n private args: Args = [],\n ) {\n if (!isString(commandName) && !(commandName instanceof Path)) {\n // biome-ignore lint/suspicious/noExplicitAny: We want to print this, no matter what it is.\n throw new Error(\"Command name is not a string:\", commandName as any);\n }\n this.#commandName = commandName;\n if (typeof args === \"undefined\") {\n return;\n }\n if (!Array.isArray(args)) {\n throw new Error(\"Command arguments are not an array\");\n }\n for (let i = 0; i < args.length; i++) {\n const argEntry = args[i];\n if (typeof argEntry === \"string\") {\n continue;\n }\n if (argEntry instanceof Path) {\n continue;\n }\n if (Array.isArray(argEntry) && isValidArgsEntryArray(argEntry)) {\n continue;\n }\n throw new Error(`Invalid arg entry at index: ${i}`);\n }\n }\n\n get commandName(): string {\n return stringifyIfPath(this.#commandName);\n }\n\n /**\n * For use with `node:child_process`\n *\n * Usage example:\n *\n * ```\n * import { PrintableShellCommand } from \"printable-shell-command\";\n * import { spawn } from \"node:child_process\";\n *\n * const command = new PrintableShellCommand( \u2026 );\n * const child_process = spawn(...command.toCommandWithFlatArgs()); // Note the `...`\n * ```\n *\n */\n public toCommandWithFlatArgs(): [string, string[]] {\n return [this.commandName, this.args.flat().map(stringifyIfPath)];\n }\n\n #mainIndentation(options: PrintOptions): string {\n return options?.mainIndentation ?? DEFAULT_MAIN_INDENTATION;\n }\n\n #argIndentation(options: PrintOptions): string {\n return (\n this.#mainIndentation(options) +\n (options?.argIndentation ?? DEFAULT_ARG_INDENTATION)\n );\n }\n\n #lineWrapSeparator(options: PrintOptions): string {\n return LINE_WRAP_LINE_END + this.#argIndentation(options);\n }\n\n #argPairSeparator(options: PrintOptions): string {\n switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {\n case \"by-entry\": {\n return INLINE_SEPARATOR;\n }\n case \"nested-by-entry\": {\n return this.#lineWrapSeparator(options) + this.#argIndentation(options);\n }\n case \"by-argument\": {\n return this.#lineWrapSeparator(options);\n }\n case \"inline\": {\n return INLINE_SEPARATOR;\n }\n default:\n throw new Error(\"Invalid argument line wrapping argument.\");\n }\n }\n\n #intraEntrySeparator(options: PrintOptions): string {\n switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {\n case \"by-entry\":\n case \"nested-by-entry\":\n case \"by-argument\": {\n return LINE_WRAP_LINE_END + this.#argIndentation(options);\n }\n case \"inline\": {\n return INLINE_SEPARATOR;\n }\n default:\n throw new Error(\"Invalid argument line wrapping argument.\");\n }\n }\n\n #separatorAfterCommand(\n options: PrintOptions,\n numFollowingEntries: number,\n ): string {\n if (numFollowingEntries === 0) {\n return \"\";\n }\n if (options.skipLineWrapBeforeFirstArg ?? false) {\n return INLINE_SEPARATOR;\n }\n return this.#intraEntrySeparator(options);\n }\n\n public getPrintableCommand(options?: PrintOptions): string {\n // TODO: Why in the world does TypeScript not give the `options` arg the type of `PrintOptions | undefined`???\n options ??= {};\n const serializedEntries: string[] = [];\n\n for (let i = 0; i < this.args.length; i++) {\n const argsEntry = stringifyIfPath(this.args[i]);\n\n if (isString(argsEntry)) {\n serializedEntries.push(escapeArg(argsEntry, false, options));\n } else {\n serializedEntries.push(\n argsEntry\n .map((part) => escapeArg(stringifyIfPath(part), false, options))\n .join(this.#argPairSeparator(options)),\n );\n }\n }\n\n let text =\n this.#mainIndentation(options) +\n escapeArg(this.commandName, true, options) +\n this.#separatorAfterCommand(options, serializedEntries.length) +\n serializedEntries.join(this.#intraEntrySeparator(options));\n if (options?.styleTextFormat) {\n text = styleText(options.styleTextFormat, text);\n }\n return text;\n }\n\n /**\n * Print the shell command to {@link stderr} (default) or a specified stream.\n *\n * By default, this will be auto-styled (as bold gray) when `.isTTY` is true\n * for the stream. `.isTTY` is populated for the {@link stderr} and\n * {@link stdout} objects. Pass `\"autoStyle\": \"never\"` or an explicit\n * `styleTextFormat` to disable this.\n *\n */\n public print(options?: StreamPrintOptions): PrintableShellCommand {\n const stream = options?.stream ?? stderr;\n // Note: we only need to modify top-level fields, so `structuredClone(\u2026)`\n // would be overkill and can only cause performance issues.\n const optionsCopy = { ...options };\n optionsCopy.styleTextFormat ??=\n options?.autoStyle !== \"never\" &&\n (stream as { isTTY?: boolean }).isTTY === true\n ? TTY_AUTO_STYLE\n : undefined;\n const writable =\n stream instanceof Writable ? stream : Writable.fromWeb(stream);\n writable.write(this.getPrintableCommand(optionsCopy));\n writable.write(\"\\n\");\n return this;\n }\n\n #stdinSource: StdinSource | undefined;\n /**\n * Send data to `stdin` of the subprocess.\n *\n * Note that this will overwrite:\n *\n * - Any previous value set using {@link PrintableShellCommand.stdin | `.stdin(\u2026)`}.\n * - Any value set for `stdin` using the `\"stdio\"` field of {@link PrintableShellCommand.spawn | `.spawn(\u2026)`}.\n */\n stdin(source: StdinSource): PrintableShellCommand {\n const [key, ...moreKeys] = Object.keys(source);\n assert.equal(moreKeys.length, 0);\n // TODO: validate values?\n assert((STDIN_SOURCE_KEYS as unknown as string[]).includes(key));\n\n this.#stdinSource = source;\n return this;\n }\n\n /**\n * The returned child process includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313\n */\n public spawn: typeof spawnType = ((\n options?: Parameters<typeof spawnType>[0],\n ) => {\n const { spawn } = process.getBuiltinModule(\"node:child_process\");\n const cwd = stringifyIfPath(options?.cwd);\n if (this.#stdinSource) {\n options ??= {};\n if (typeof options.stdio === \"undefined\") {\n options.stdio = \"pipe\";\n }\n if (typeof options.stdio === \"string\") {\n options.stdio = new Array(3).fill(options.stdio);\n }\n options.stdio[0] = \"pipe\";\n }\n // biome-ignore lint/suspicious/noTsIgnore: We don't want linting to depend on *broken* type checking.\n // @ts-ignore: The TypeScript checker has trouble reconciling the optional (i.e. potentially `undefined`) `options` with the third argument.\n const subprocess = spawn(...this.toCommandWithFlatArgs(), {\n ...(options as object),\n cwd,\n }) as NodeChildProcess & {\n success: Promise<void>;\n };\n // TODO: define properties on prototypes instead.\n Object.defineProperty(subprocess, \"success\", {\n get() {\n return new Promise<void>((resolve, reject) =>\n this.addListener(\n \"exit\",\n (exitCode: number /* we only use the first arg */) => {\n if (exitCode === 0) {\n resolve();\n } else {\n reject(`Command failed with non-zero exit code: ${exitCode}`);\n }\n },\n ),\n );\n },\n enumerable: false,\n });\n if (subprocess.stdout) {\n // TODO: dedupe\n const s = subprocess as unknown as Readable &\n WithStdoutResponse &\n WithSuccess;\n s.stdout.response = () =>\n new Response(Readable.from(this.#generator(s.stdout, s.success)));\n s.stdout.text = () => s.stdout.response().text();\n const thisCached = this; // TODO: make this type-check using `.bind(\u2026)`\n s.stdout.text0 = async function* () {\n yield* thisCached.#split0(thisCached.#generator(s.stdout, s.success));\n };\n s.stdout.json = <T>() => s.stdout.response().json() as Promise<T>;\n }\n if (subprocess.stderr) {\n // TODO: dedupe\n const s = subprocess as unknown as Readable &\n WithStderrResponse &\n WithSuccess;\n s.stderr.response = () =>\n new Response(Readable.from(this.#generator(s.stderr, s.success)));\n s.stderr.text = () => s.stderr.response().text();\n const thisCached = this; // TODO: make this type-check using `.bind(\u2026)`\n s.stderr.text0 = async function* () {\n yield* thisCached.#split0(thisCached.#generator(s.stderr, s.success));\n };\n s.stderr.json = <T>() => s.stderr.response().json() as Promise<T>;\n }\n if (this.#stdinSource) {\n const { stdin } = subprocess;\n assert(stdin);\n if (\"text\" in this.#stdinSource) {\n stdin.write(this.#stdinSource.text);\n stdin.end();\n } else if (\"json\" in this.#stdinSource) {\n stdin.write(JSON.stringify(this.#stdinSource.json));\n stdin.end();\n } else if (\"path\" in this.#stdinSource) {\n createReadStream(stringifyIfPath(this.#stdinSource.path)).pipe(stdin);\n } else if (\"stream\" in this.#stdinSource) {\n const stream = (() => {\n const { stream } = this.#stdinSource;\n return stream instanceof Readable ? stream : Readable.fromWeb(stream);\n })();\n stream.pipe(stdin);\n } else {\n throw new Error(\"Invalid `.stdin(\u2026)` source?\");\n }\n }\n return subprocess;\n // biome-ignore lint/suspicious/noExplicitAny: Type wrangling\n }) as any;\n\n /** A wrapper for `.spawn(\u2026)` that sets stdio to `\"inherit\"` (common for\n * invoking commands from scripts whose output and interaction should be\n * surfaced to the user).\n *\n * If there is no other interaction with the shell from the calling process,\n * then it acts \"transparent\" and allows user to interact with the subprocess\n * in its stead.\n */\n public spawnTransparently(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): ChildProcessByStdio<null, null, null> & WithSuccess {\n if (options && \"stdio\" in options) {\n throw new Error(\"Unexpected `stdio` field.\");\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Type wrangling.\n return this.spawn({ ...options, stdio: \"inherit\" }) as any;\n }\n\n /**\n * A wrapper for {@link PrintableShellCommand.spawn | `.spawn(\u2026)`} that:\n *\n * - sets `detached` to `true`,\n * - sets stdio to `\"inherit\"`,\n * - calls `.unref()`, and\n * - does not wait for the process to exit.\n *\n * This is similar to starting a command in the background and disowning it (in a shell).\n *\n */\n public spawnDetached(\n options?: NodeWithCwd<Omit<Omit<NodeSpawnOptions, \"stdio\">, \"detached\">>,\n ): void {\n if (options) {\n for (const field of [\"stdio\", \"detached\"]) {\n if (field in options) {\n throw new Error(`Unexpected \\`${field}\\` field.`);\n }\n }\n }\n const childProcess = this.spawn({\n stdio: \"ignore\",\n ...options,\n detached: true,\n });\n childProcess.unref();\n }\n\n #generator(\n readable: Readable,\n successPromise: Promise<void>,\n ): AsyncGenerator<string> {\n // TODO: we'd make this a `ReadableStream`, but `ReadableStream.from(\u2026)` is\n // not implemented in `bun`: https://github.com/oven-sh/bun/issues/3700\n return (async function* () {\n for await (const chunk of readable) {\n yield chunk;\n }\n await successPromise;\n })();\n }\n\n #stdoutSpawnGenerator(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): AsyncGenerator<string> {\n if (options && \"stdio\" in options) {\n throw new Error(\"Unexpected `stdio` field.\");\n }\n const subprocess = this.spawn({\n ...options,\n stdio: [\"ignore\", \"pipe\", \"inherit\"],\n });\n return this.#generator(subprocess.stdout, subprocess.success);\n }\n\n public stdout(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): Response {\n // TODO: Use `ReadableStream.from(\u2026)` once `bun` implements it: https://github.com/oven-sh/bun/pull/21269\n return new Response(Readable.from(this.#stdoutSpawnGenerator(options)));\n }\n\n async *#split0(generator: AsyncGenerator<string>): AsyncGenerator<string> {\n let pending = \"\";\n for await (const chunk of generator) {\n pending += chunk;\n const newChunks = pending.split(\"\\x00\");\n pending = newChunks.splice(-1)[0];\n yield* newChunks;\n }\n if (pending !== \"\") {\n throw new Error(\n \"Missing a trailing NUL character at the end of a NUL-delimited stream.\",\n );\n }\n }\n\n /**\n * Convenience function for:\n *\n * .stdout(options).text()\n *\n * This can make some simple invocations easier to read and/or fit on a single line.\n */\n public text(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): Promise<string> {\n return this.stdout(options).text();\n }\n\n /**\n * Convenience function for:\n *\n * .stdout(options).json()\n *\n * This can make some simple invocations easier to read and/or fit on a single line.\n */\n public json<T>(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): Promise<T> {\n return this.stdout(options).json() as Promise<T>;\n }\n\n /**\n * Parse `stdout` into a generator of string values using a NULL delimiter.\n *\n * A trailing NULL delimiter from `stdout` is required and removed.\n */\n public async *text0(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): AsyncGenerator<string> {\n yield* this.#split0(this.#stdoutSpawnGenerator(options));\n }\n\n /**\n * Parse `stdout` into a generator of JSON values using a NULL delimiter.\n *\n * A trailing NULL delimiter from `stdout` is required and removed.\n */\n public async *json0(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): // biome-ignore lint/suspicious/noExplicitAny: `any` is the correct type for JSON\n AsyncGenerator<any> {\n for await (const part of this.#split0(\n this.#stdoutSpawnGenerator(options),\n )) {\n yield JSON.parse(part);\n }\n }\n\n /** Equivalent to:\n *\n * ```\n * await this.print().spawnTransparently(\u2026).success;\n * ```\n */\n public async shellOut(\n options?: NodeWithCwd<Omit<NodeSpawnOptions, \"stdio\">>,\n ): Promise<void> {\n await this.print().spawnTransparently(options).success;\n }\n}\n\nexport function escapeArg(\n arg: string,\n isMainCommand: boolean,\n options: PrintOptions,\n): string {\n const argCharacters = new Set(arg);\n const specialShellCharacters = isMainCommand\n ? SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND\n : SPECIAL_SHELL_CHARACTERS;\n if (\n options?.quoting === \"extra-safe\" ||\n // biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)\n (argCharacters as unknown as any).intersection(specialShellCharacters)\n .size > 0\n ) {\n // Use single quote to reduce the need to escape (and therefore reduce the chance for bugs/security issues).\n const escaped = arg.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"\\\\'\");\n return `'${escaped}'`;\n }\n return arg;\n}\n"],
5
+ "mappings": ";AAAA,OAAO,YAAY;AAMnB,SAAS,wBAAwB;AACjC,SAAS,cAAc;AACvB,SAAS,UAAU,gBAAgB;AAEnC,SAAS,iBAAiB;AAC1B,SAAS,MAAM,uBAAuB;AActC,IAAM,2BAA2B;AACjC,IAAM,0BAA0B;AAChC,IAAM,iCAAiC;AAEvC,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAI3B,IAAM,iBAAkC,CAAC,QAAQ,MAAM;AAGvD,SAAS,SAAS,GAAqB;AACrC,SAAO,OAAO,MAAM;AACtB;AAGA,SAAS,sBAAsB,SAA6C;AAC1E,aAAW,SAAS,SAAS;AAC3B,QAAI,SAAS,KAAK,G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essWithoutNullStreams, ProcessEnvOptions, SpawnOptions, SpawnOptionsWithoutStdio, SpawnOptionsWithStdioTuple, StdioNull, StdioPipe } from "node:child_process";
2
2
  import type { Readable, Writable } from "node:stream";
3
3
  import type { Path } from "path-class";
4
- import type { SetFieldType } from "type-fest";
5
4
  export type NodeCwd = ProcessEnvOptions["cwd"] | Path;
6
5
  export type NodeWithCwd<T extends {
7
6
  cwd?: ProcessEnvOptions["cwd"];
8
- }> = SetFieldType<T, "cwd", NodeCwd | undefined>;
7
+ }> = Omit<T, "cwd"> & {
8
+ cwd?: NodeCwd;
9
+ };
9
10
  export interface WithSuccess {
10
11
  success: Promise<void>;
11
12
  }
package/package.json CHANGED
@@ -1,34 +1,43 @@
1
1
  {
2
- "name": "printable-shell-command",
3
- "version": "3.0.2",
4
- "devDependencies": {
5
- "@biomejs/biome": "^2.1.4",
6
- "@cubing/dev-config": "^0.3.6",
7
- "@types/bun": "^1.2.20",
8
- "@types/node": "^24.2.0",
9
- "esbuild": "^0.25.5",
10
- "typescript": "^5.9.3"
11
- },
12
- "peerDependencies": {
13
- "@types/bun": "^1.2.20",
14
- "@types/node": "^24.2.0"
15
- },
16
- "exports": {
17
- ".": {
18
- "types": "./dist/lib/printable-shell-command/index.d.ts",
19
- "import": "./dist/lib/printable-shell-command/index.js"
20
- }
21
- },
22
- "files": [
23
- "./dist/",
24
- "./src/"
25
- ],
26
- "type": "module",
27
- "scripts": {
28
- "prepublishOnly": "make prepublishOnly"
29
- },
30
- "dependencies": {
31
- "path-class": ">=0.10.3",
32
- "type-fest": ">=5.1.0"
33
- }
2
+ "name": "printable-shell-command",
3
+ "version": "4.0.0",
4
+ "description": "A helper class to construct shell commands in a way that allows printing them.",
5
+ "author": {
6
+ "name": "Lucas Garron",
7
+ "email": "code@garron.net",
8
+ "url": "https://garron.net/"
9
+ },
10
+ "license": "MPL-2.0",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/lgarron/printable-shell-command.git"
14
+ },
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/lib/printable-shell-command/index.d.ts",
19
+ "import": "./dist/lib/printable-shell-command/index.js"
20
+ }
21
+ },
22
+ "dependencies": {
23
+ "path-class": ">=0.10.3"
24
+ },
25
+ "devDependencies": {
26
+ "@biomejs/biome": "^2.1.4",
27
+ "@cubing/dev-config": ">=0.7.2",
28
+ "@types/node": ">=24.2.0",
29
+ "esbuild": "^0.25.5",
30
+ "printable-shell-command": "^3.0.3",
31
+ "typescript": "^5.9.3"
32
+ },
33
+ "peerDependencies": {
34
+ "@types/node": ">=24.2.0"
35
+ },
36
+ "files": [
37
+ "./dist/",
38
+ "./src/"
39
+ ],
40
+ "scripts": {
41
+ "prepublishOnly": "make prepublishOnly"
42
+ }
34
43
  }
package/src/index.ts CHANGED
@@ -9,13 +9,7 @@ import { stderr } from "node:process";
9
9
  import { Readable, Writable } from "node:stream";
10
10
  import type { WriteStream } from "node:tty";
11
11
  import { styleText } from "node:util";
12
- import type {
13
- SpawnOptions as BunSpawnOptions,
14
- Subprocess as BunSubprocess,
15
- SpawnOptions,
16
- } from "bun";
17
12
  import { Path, stringifyIfPath } from "path-class";
18
- import type { SetFieldType } from "type-fest";
19
13
  import type {
20
14
  NodeWithCwd,
21
15
  spawnType,
@@ -141,13 +135,6 @@ const SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND =
141
135
  // biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)
142
136
  (SPECIAL_SHELL_CHARACTERS as unknown as any).union(new Set(["="]));
143
137
 
144
- // biome-ignore lint/suspicious/noExplicitAny: Just matching
145
- type BunCwd = SpawnOptions.OptionsObject<any, any, any>["cwd"] | Path;
146
- type BunWithCwd<
147
- // biome-ignore lint/suspicious/noExplicitAny: Just matching
148
- T extends { cwd?: SpawnOptions.OptionsObject<any, any, any>["cwd"] | Path },
149
- > = SetFieldType<T, "cwd", BunCwd | undefined>;
150
-
151
138
  // TODO: Is there an idiomatic ways to check that all potential fields of
152
139
  // `StdinSource` satisfy `(typeof STDIN_SOURCE_KEYS)[number]`, without adding
153
140
  // extra indirection for type wrangling?
@@ -195,40 +182,6 @@ export class PrintableShellCommand {
195
182
  return stringifyIfPath(this.#commandName);
196
183
  }
197
184
 
198
- /** For use with `bun`.
199
- *
200
- * Usage example:
201
- *
202
- * ```
203
- * import { PrintableShellCommand } from "printable-shell-command";
204
- * import { spawn } from "bun";
205
- *
206
- * const command = new PrintableShellCommand( … );
207
- * await spawn(command.toFlatCommand()).exited;
208
- * ```
209
- */
210
- public toFlatCommand(): string[] {
211
- return [this.commandName, ...this.args.flat().map(stringifyIfPath)];
212
- }
213
-
214
- /**
215
- * Convenient alias for {@link PrintableShellCommand.toFlatCommand | `.toFlatCommand()`}.
216
- *
217
- * Usage example:
218
- *
219
- * ```
220
- * import { PrintableShellCommand } from "printable-shell-command";
221
- * import { spawn } from "bun";
222
- *
223
- * const command = new PrintableShellCommand( … );
224
- * await spawn(command.forBun()).exited;
225
- * ```
226
- *
227
- * */
228
- public forBun(): string[] {
229
- return this.toFlatCommand();
230
- }
231
-
232
185
  /**
233
186
  * For use with `node:child_process`
234
187
  *
@@ -247,25 +200,6 @@ export class PrintableShellCommand {
247
200
  return [this.commandName, this.args.flat().map(stringifyIfPath)];
248
201
  }
249
202
 
250
- /**
251
- * For use with `node:child_process`
252
- *
253
- * Usage example:
254
- *
255
- * ```
256
- * import { PrintableShellCommand } from "printable-shell-command";
257
- * import { spawn } from "node:child_process";
258
- *
259
- * const command = new PrintableShellCommand( … );
260
- * const child_process = spawn(...command.forNode()); // Note the `...`
261
- * ```
262
- *
263
- * Convenient alias for {@link PrintableShellCommand.toCommandWithFlatArgs | `toCommandWithFlatArgs()`}.
264
- */
265
- public forNode(): [string, string[]] {
266
- return this.toCommandWithFlatArgs();
267
- }
268
-
269
203
  #mainIndentation(options: PrintOptions): string {
270
204
  return options?.mainIndentation ?? DEFAULT_MAIN_INDENTATION;
271
205
  }
@@ -423,7 +357,7 @@ export class PrintableShellCommand {
423
357
  }
424
358
  // biome-ignore lint/suspicious/noTsIgnore: We don't want linting to depend on *broken* type checking.
425
359
  // @ts-ignore: The TypeScript checker has trouble reconciling the optional (i.e. potentially `undefined`) `options` with the third argument.
426
- const subprocess = spawn(...this.forNode(), {
360
+ const subprocess = spawn(...this.toCommandWithFlatArgs(), {
427
361
  ...(options as object),
428
362
  cwd,
429
363
  }) as NodeChildProcess & {
@@ -661,117 +595,6 @@ export class PrintableShellCommand {
661
595
  ): Promise<void> {
662
596
  await this.print().spawnTransparently(options).success;
663
597
  }
664
-
665
- /**
666
- * The returned subprocess includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313
667
- */
668
- #spawnBun<
669
- const In extends BunSpawnOptions.Writable = "ignore",
670
- const Out extends BunSpawnOptions.Readable = "pipe",
671
- const Err extends BunSpawnOptions.Readable = "inherit",
672
- >(
673
- options?: BunWithCwd<
674
- Omit<BunSpawnOptions.OptionsObject<In, Out, Err>, "cmd">
675
- >,
676
- ): BunSubprocess<In, Out, Err> & { success: Promise<void> } {
677
- if (options && "cmd" in options) {
678
- throw new Error("Unexpected `cmd` field.");
679
- }
680
- const { spawn } = process.getBuiltinModule("bun") as typeof import("bun");
681
- const cwd = stringifyIfPath(options?.cwd);
682
- const subprocess = spawn({
683
- ...options,
684
- cwd,
685
- cmd: this.forBun(),
686
- }) as BunSubprocess<In, Out, Err> & { success: Promise<void> };
687
- Object.defineProperty(subprocess, "success", {
688
- get() {
689
- return new Promise<void>((resolve, reject) =>
690
- this.exited
691
- .then((exitCode: number) => {
692
- if (exitCode === 0) {
693
- resolve();
694
- } else {
695
- reject(
696
- new Error(
697
- `Command failed with non-zero exit code: ${exitCode}`,
698
- ),
699
- );
700
- }
701
- })
702
- .catch(reject),
703
- );
704
- },
705
- enumerable: false,
706
- });
707
- return subprocess;
708
- }
709
-
710
- #spawnBunInherit(
711
- options?: BunWithCwd<
712
- Omit<
713
- BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">,
714
- "cmd" | "stdio"
715
- >
716
- >,
717
- ): BunSubprocess<"inherit", "inherit", "inherit"> & {
718
- success: Promise<void>;
719
- } {
720
- if (options && "stdio" in options) {
721
- throw new Error("Unexpected `stdio` field.");
722
- }
723
- return this.bun.spawnBun({
724
- ...options,
725
- stdio: ["inherit", "inherit", "inherit"],
726
- });
727
- }
728
-
729
- #spawnBunStdout(
730
- options?: BunWithCwd<
731
- Omit<
732
- BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">,
733
- "cmd" | "stdio"
734
- >
735
- >,
736
- ): Response {
737
- // biome-ignore lint/suspicious/noExplicitAny: Avoid breaking the lib check when used without `@types/bun`.
738
- return new Response((this.bun.spawnBun(options) as any).stdout);
739
- }
740
-
741
- async #shellOutBun(
742
- options?: BunWithCwd<
743
- Omit<
744
- BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">,
745
- "cmd" | "stdio"
746
- >
747
- >,
748
- ): Promise<void> {
749
- await this.print().bun.spawnBunInherit(options).success;
750
- }
751
-
752
- bun = {
753
- /** Equivalent to:
754
- *
755
- * ```
756
- * await this.print().bun.spawnBunInherit(…).success;
757
- * ```
758
- */
759
- spawnBun: this.#spawnBun.bind(this),
760
- /**
761
- * A wrapper for `.spawnBunInherit(…)` that sets stdio to `"inherit"` (common
762
- * for invoking commands from scripts whose output and interaction should be
763
- * surfaced to the user).
764
- */
765
- spawnBunInherit: this.#spawnBunInherit.bind(this),
766
- /** Equivalent to:
767
- *
768
- * ```
769
- * new Response(this.bun.spawnBun(…).stdout);
770
- * ```
771
- */
772
- spawnBunStdout: this.#spawnBunStdout.bind(this),
773
- shellOutBun: this.#shellOutBun.bind(this),
774
- };
775
598
  }
776
599
 
777
600
  export function escapeArg(
package/src/spawn.ts CHANGED
@@ -11,11 +11,12 @@ import type {
11
11
  } from "node:child_process";
12
12
  import type { Readable, Writable } from "node:stream";
13
13
  import type { Path } from "path-class";
14
- import type { SetFieldType } from "type-fest";
15
14
 
16
15
  export type NodeCwd = ProcessEnvOptions["cwd"] | Path;
17
- export type NodeWithCwd<T extends { cwd?: ProcessEnvOptions["cwd"] }> =
18
- SetFieldType<T, "cwd", NodeCwd | undefined>;
16
+ export type NodeWithCwd<T extends { cwd?: ProcessEnvOptions["cwd"] }> = Omit<
17
+ T,
18
+ "cwd"
19
+ > & { cwd?: NodeCwd };
19
20
 
20
21
  export interface WithSuccess {
21
22
  success: Promise<void>;