printable-shell-command 1.1.5 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,8 +2,8 @@ import type { ChildProcess as NodeChildProcess, SpawnOptions as NodeSpawnOptions
2
2
  import { styleText } from "node:util";
3
3
  import type { SpawnOptions as BunSpawnOptions, Subprocess as BunSubprocess } from "bun";
4
4
  type SingleArgument = string;
5
- type FlagArgumentPair = [string, string];
6
- type ArgsEntry = SingleArgument | FlagArgumentPair;
5
+ type FlagArgumentGroup = string[];
6
+ type ArgsEntry = SingleArgument | FlagArgumentGroup;
7
7
  type Args = ArgsEntry[];
8
8
  export interface PrintOptions {
9
9
  /** Defaults to "" */
@@ -20,6 +20,8 @@ export interface PrintOptions {
20
20
  quoting?: "auto" | "extra-safe";
21
21
  /** Line wrapping to use between arguments. Defaults to `"by-entry"`. */
22
22
  argumentLineWrapping?: "by-entry" | "nested-by-entry" | "by-argument" | "inline";
23
+ /** Include the first arg (or first arg group) on the same line as the command, regardless of the `argumentLineWrapping` setting. */
24
+ skipLineWrapBeforeFirstArg?: true | false;
23
25
  /**
24
26
  * Style text using `node`'s [`styleText(…)`](https://nodejs.org/api/util.html#utilstyletextformat-text-options)
25
27
  *
@@ -111,6 +113,7 @@ export declare class PrintableShellCommand {
111
113
  spawnNodeInherit(options?: Omit<NodeSpawnOptions, "stdio">): NodeChildProcess & {
112
114
  success: Promise<void>;
113
115
  };
116
+ spawnNodeStdout(options?: Omit<NodeSpawnOptions, "stdio">): Response;
114
117
  /** Equivalent to:
115
118
  *
116
119
  * ```
@@ -1,4 +1,5 @@
1
1
  // src/index.ts
2
+ import { Readable } from "node:stream";
2
3
  import { styleText } from "node:util";
3
4
  var DEFAULT_MAIN_INDENTATION = "";
4
5
  var DEFAULT_ARG_INDENTATION = " ";
@@ -8,6 +9,14 @@ var LINE_WRAP_LINE_END = " \\\n";
8
9
  function isString(s) {
9
10
  return typeof s === "string";
10
11
  }
12
+ function isStringArray(entries) {
13
+ for (const entry of entries) {
14
+ if (!isString(entry)) {
15
+ return false;
16
+ }
17
+ }
18
+ return true;
19
+ }
11
20
  var SPECIAL_SHELL_CHARACTERS = /* @__PURE__ */ new Set([
12
21
  " ",
13
22
  '"',
@@ -52,7 +61,7 @@ var PrintableShellCommand = class {
52
61
  if (typeof argEntry === "string") {
53
62
  continue;
54
63
  }
55
- if (Array.isArray(argEntry) && argEntry.length === 2 && isString(argEntry[0]) && isString(argEntry[1])) {
64
+ if (Array.isArray(argEntry) && isStringArray(argEntry)) {
56
65
  continue;
57
66
  }
58
67
  throw new Error(`Invalid arg entry at index: ${i}`);
@@ -166,14 +175,10 @@ var PrintableShellCommand = class {
166
175
  throw new Error("Invalid argument line wrapping argument.");
167
176
  }
168
177
  }
169
- #entrySeparator(options) {
178
+ #intraEntrySeparator(options) {
170
179
  switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {
171
- case "by-entry": {
172
- return LINE_WRAP_LINE_END + this.#argIndentation(options);
173
- }
174
- case "nested-by-entry": {
175
- return LINE_WRAP_LINE_END + this.#argIndentation(options);
176
- }
180
+ case "by-entry":
181
+ case "nested-by-entry":
177
182
  case "by-argument": {
178
183
  return LINE_WRAP_LINE_END + this.#argIndentation(options);
179
184
  }
@@ -184,24 +189,29 @@ var PrintableShellCommand = class {
184
189
  throw new Error("Invalid argument line wrapping argument.");
185
190
  }
186
191
  }
192
+ #separatorAfterCommand(options, numFollowingEntries) {
193
+ if (numFollowingEntries === 0) {
194
+ return "";
195
+ }
196
+ if (options.skipLineWrapBeforeFirstArg ?? false) {
197
+ return INLINE_SEPARATOR;
198
+ }
199
+ return this.#intraEntrySeparator(options);
200
+ }
187
201
  getPrintableCommand(options) {
188
202
  options ??= {};
189
203
  const serializedEntries = [];
190
- serializedEntries.push(
191
- this.#mainIndentation(options) + this.#escapeArg(this.commandName, true, options)
192
- );
193
204
  for (let i = 0; i < this.args.length; i++) {
194
205
  const argsEntry = this.args[i];
195
206
  if (isString(argsEntry)) {
196
207
  serializedEntries.push(this.#escapeArg(argsEntry, false, options));
197
208
  } else {
198
- const [part1, part2] = argsEntry;
199
209
  serializedEntries.push(
200
- this.#escapeArg(part1, false, options) + this.#argPairSeparator(options) + this.#escapeArg(part2, false, options)
210
+ argsEntry.map((part) => this.#escapeArg(part, false, options)).join(this.#argPairSeparator(options))
201
211
  );
202
212
  }
203
213
  }
204
- let text = serializedEntries.join(this.#entrySeparator(options));
214
+ let text = this.#mainIndentation(options) + this.#escapeArg(this.commandName, true, options) + this.#separatorAfterCommand(options, serializedEntries.length) + serializedEntries.join(this.#intraEntrySeparator(options));
205
215
  if (options?.styleTextFormat) {
206
216
  text = styleText(options.styleTextFormat, text);
207
217
  }
@@ -245,6 +255,16 @@ var PrintableShellCommand = class {
245
255
  }
246
256
  return this.spawnNode({ ...options, stdio: "inherit" });
247
257
  }
258
+ spawnNodeStdout(options) {
259
+ if (options && "stdio" in options) {
260
+ throw new Error("Unexpected `stdio` field.");
261
+ }
262
+ const subprocess = this.spawnNode({
263
+ ...options,
264
+ stdio: ["ignore", "pipe", "inherit"]
265
+ });
266
+ return new Response(Readable.toWeb(subprocess.stdout));
267
+ }
248
268
  /** Equivalent to:
249
269
  *
250
270
  * ```
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/index.ts"],
4
- "sourcesContent": ["import type {\n ChildProcess as NodeChildProcess,\n SpawnOptions as NodeSpawnOptions,\n SpawnOptionsWithoutStdio as NodeSpawnOptionsWithoutStdio,\n SpawnOptionsWithStdioTuple as NodeSpawnOptionsWithStdioTuple,\n StdioNull as NodeStdioNull,\n StdioPipe as NodeStdioPipe,\n} from \"node:child_process\";\nimport { styleText } from \"node:util\";\nimport type {\n SpawnOptions as BunSpawnOptions,\n Subprocess as BunSubprocess,\n} from \"bun\";\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\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// TODO: allow `.toString()`ables?\ntype SingleArgument = string;\ntype FlagArgumentPair = [string, string];\ntype ArgsEntry = SingleArgument | FlagArgumentPair;\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 /**\n * Style text using `node`'s [`styleText(\u2026)`](https://nodejs.org/api/util.html#utilstyletextformat-text-options)\n *\n * Example usage:\n *\n * ```\n * new PrintableShellCommand(\"echo\", [\"hi\"]).print({\n * styleTextFormat: [\"gray\", \"bold\"],\n * });\n * */\n styleTextFormat?: Parameters<typeof styleText>[0];\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\nexport class PrintableShellCommand {\n #commandName: string;\n constructor(\n commandName: string,\n private args: Args = [],\n ) {\n if (!isString(commandName)) {\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 (\n Array.isArray(argEntry) &&\n argEntry.length === 2 &&\n isString(argEntry[0]) &&\n isString(argEntry[1])\n ) {\n continue;\n }\n throw new Error(`Invalid arg entry at index: ${i}`);\n }\n }\n\n get commandName(): string {\n return 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()];\n }\n\n /**\n * Convenient alias for `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()];\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 `toCommandWithFlatArgs()`.\n */\n public forNode(): [string, string[]] {\n return this.toCommandWithFlatArgs();\n }\n\n #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\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 #entrySeparator(options: PrintOptions): string {\n switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {\n case \"by-entry\": {\n return LINE_WRAP_LINE_END + this.#argIndentation(options);\n }\n case \"nested-by-entry\": {\n return LINE_WRAP_LINE_END + this.#argIndentation(options);\n }\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 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 serializedEntries.push(\n this.#mainIndentation(options) +\n this.#escapeArg(this.commandName, true, options),\n );\n\n for (let i = 0; i < this.args.length; i++) {\n const argsEntry = this.args[i];\n\n if (isString(argsEntry)) {\n serializedEntries.push(this.#escapeArg(argsEntry, false, options));\n } else {\n const [part1, part2] = argsEntry;\n serializedEntries.push(\n this.#escapeArg(part1, false, options) +\n this.#argPairSeparator(options) +\n this.#escapeArg(part2, false, options),\n );\n }\n }\n\n let text = serializedEntries.join(this.#entrySeparator(options));\n if (options?.styleTextFormat) {\n text = styleText(options.styleTextFormat, text);\n }\n return text;\n }\n\n public print(options?: PrintOptions): PrintableShellCommand {\n console.log(this.getPrintableCommand(options));\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 spawnNode<\n Stdin extends NodeStdioNull | NodeStdioPipe,\n Stdout extends NodeStdioNull | NodeStdioPipe,\n Stderr extends NodeStdioNull | NodeStdioPipe,\n >(\n options?:\n | NodeSpawnOptions\n | NodeSpawnOptionsWithoutStdio\n | NodeSpawnOptionsWithStdioTuple<Stdin, Stdout, Stderr>,\n ): // TODO: figure out how to return `ChildProcessByStdio<\u2026>` without duplicating fragile boilerplate.\n NodeChildProcess & { success: Promise<void> } {\n const { spawn } = process.getBuiltinModule(\"node:child_process\");\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(), options) as NodeChildProcess & {\n success: Promise<void>;\n };\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 return subprocess;\n }\n\n /** A wrapper for `.spawnNode(\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 public spawnNodeInherit(\n options?: Omit<NodeSpawnOptions, \"stdio\">,\n ): NodeChildProcess & { success: Promise<void> } {\n if (options && \"stdio\" in options) {\n throw new Error(\"Unexpected `stdio` field.\");\n }\n return this.spawnNode({ ...options, stdio: \"inherit\" });\n }\n\n /** Equivalent to:\n *\n * ```\n * await this.print().spawnNodeInherit(\u2026).success;\n * ```\n */\n public async shellOutNode(\n options?: Omit<NodeSpawnOptions, \"stdio\">,\n ): Promise<void> {\n await this.print().spawnNodeInherit(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 public 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?: Omit<BunSpawnOptions.OptionsObject<In, Out, Err>, \"cmd\">,\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 subprocess = spawn({\n ...options,\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 /**\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 public spawnBunInherit(\n options?: Omit<\n Omit<\n BunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n \"cmd\"\n >,\n \"stdio\"\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.spawnBun({\n ...options,\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n });\n }\n\n /** Equivalent to:\n *\n * ```\n * new Response(this.spawnBun(\u2026).stdout);\n * ```\n */\n public spawnBunStdout(\n options?: Omit<\n Omit<\n BunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n \"cmd\"\n >,\n \"stdio\"\n >,\n ): Response {\n // biome-ignore lint/suspicious/noExplicitAny: Avoid breaking the lib check when used without `@types/bun`.\n return new Response((this.spawnBun(options) as any).stdout);\n }\n\n /** Equivalent to:\n *\n * ```\n * await this.print().spawnBunInherit(\u2026).success;\n * ```\n */\n public async shellOutBun(\n options?: Omit<\n Omit<\n BunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n \"cmd\"\n >,\n \"stdio\"\n >,\n ): Promise<void> {\n await this.print().spawnBunInherit(options).success;\n }\n}\n"],
5
- "mappings": ";AAQA,SAAS,iBAAiB;AAM1B,IAAM,2BAA2B;AACjC,IAAM,0BAA0B;AAChC,IAAM,iCAAiC;AAEvC,IAAM,mBAAmB;AACzB,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M;AAAA,MACvB,GAAG;AAAA,MACH,KAAK,KAAK,OAAO;AAAA,IACnB,CAAC;AACD,WAAO,eAAe,YAAY,WAAW;AAAA,MAC3C,MAAM;AACJ,eAAO,IAAI;AAAA,UAAc,CAAC,SAAS,WACjC,KAAK,OACF,KAAK,CAAC,aAAqB;AAC1B,gBAAI,aAAa,GAAG;AAClB,sBAAQ;AAAA,YACV,OAAO;AACL;AAAA,gBACE,IAAI;AAAA,kBACF,2CAA2C,QAAQ;AAAA,gBACrD;AAAA,cACF;AAAA,YACF;AAAA,UACF,CAAC,EACA,MAAM,MAAM;AAAA,QACjB;AAAA,MACF;AAAA,MACA,YAAY;AAAA,IACd,CAAC;AACD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,gBACL,SASA;AACA,QAAI,WAAW,WAAW,SAAS;AACjC,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AACA,WAAO,KAAK,SAAS;AAAA,MACnB,GAAG;AAAA,MACH,OAAO,CAAC,WAAW,WAAW,SAAS;AAAA,IACzC,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,eACL,SAOU;AAEV,WAAO,IAAI,SAAU,KAAK,SAAS,OAAO,EAAU,MAAM;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAa,YACX,SAOe;AACf,UAAM,KAAK,MAAM,EAAE,gBAAgB,OAAO,EAAE;AAAA,EAC9C;AACF;",
4
+ "sourcesContent": ["import type {\n ChildProcess as NodeChildProcess,\n SpawnOptions as NodeSpawnOptions,\n SpawnOptionsWithoutStdio as NodeSpawnOptionsWithoutStdio,\n SpawnOptionsWithStdioTuple as NodeSpawnOptionsWithStdioTuple,\n StdioNull as NodeStdioNull,\n StdioPipe as NodeStdioPipe,\n} from \"node:child_process\";\nimport { Readable } from \"node:stream\";\nimport { styleText } from \"node:util\";\nimport type {\n SpawnOptions as BunSpawnOptions,\n Subprocess as BunSubprocess,\n} from \"bun\";\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\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// biome-ignore lint/suspicious/noExplicitAny: This is the correct type nere.\nfunction isStringArray(entries: any[]): entries is string[] {\n for (const entry of entries) {\n if (!isString(entry)) {\n return false;\n }\n }\n return true;\n}\n\n// TODO: allow `.toString()`ables?\ntype SingleArgument = string;\ntype FlagArgumentGroup = string[];\ntype ArgsEntry = SingleArgument | FlagArgumentGroup;\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 [`styleText(\u2026)`](https://nodejs.org/api/util.html#utilstyletextformat-text-options)\n *\n * Example usage:\n *\n * ```\n * new PrintableShellCommand(\"echo\", [\"hi\"]).print({\n * styleTextFormat: [\"gray\", \"bold\"],\n * });\n * */\n styleTextFormat?: Parameters<typeof styleText>[0];\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\nexport class PrintableShellCommand {\n #commandName: string;\n constructor(\n commandName: string,\n private args: Args = [],\n ) {\n if (!isString(commandName)) {\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 (Array.isArray(argEntry) && isStringArray(argEntry)) {\n continue;\n }\n throw new Error(`Invalid arg entry at index: ${i}`);\n }\n }\n\n get commandName(): string {\n return 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()];\n }\n\n /**\n * Convenient alias for `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()];\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 `toCommandWithFlatArgs()`.\n */\n public forNode(): [string, string[]] {\n return this.toCommandWithFlatArgs();\n }\n\n #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\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 = this.args[i];\n\n if (isString(argsEntry)) {\n serializedEntries.push(this.#escapeArg(argsEntry, false, options));\n } else {\n serializedEntries.push(\n argsEntry\n .map((part) => this.#escapeArg(part, false, options))\n .join(this.#argPairSeparator(options)),\n );\n }\n }\n\n let text =\n this.#mainIndentation(options) +\n this.#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 public print(options?: PrintOptions): PrintableShellCommand {\n console.log(this.getPrintableCommand(options));\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 spawnNode<\n Stdin extends NodeStdioNull | NodeStdioPipe,\n Stdout extends NodeStdioNull | NodeStdioPipe,\n Stderr extends NodeStdioNull | NodeStdioPipe,\n >(\n options?:\n | NodeSpawnOptions\n | NodeSpawnOptionsWithoutStdio\n | NodeSpawnOptionsWithStdioTuple<Stdin, Stdout, Stderr>,\n ): // TODO: figure out how to return `ChildProcessByStdio<\u2026>` without duplicating fragile boilerplate.\n NodeChildProcess & { success: Promise<void> } {\n const { spawn } = process.getBuiltinModule(\"node:child_process\");\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(), options) as NodeChildProcess & {\n success: Promise<void>;\n };\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 return subprocess;\n }\n\n /** A wrapper for `.spawnNode(\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 public spawnNodeInherit(\n options?: Omit<NodeSpawnOptions, \"stdio\">,\n ): NodeChildProcess & { success: Promise<void> } {\n if (options && \"stdio\" in options) {\n throw new Error(\"Unexpected `stdio` field.\");\n }\n return this.spawnNode({ ...options, stdio: \"inherit\" });\n }\n\n public spawnNodeStdout(options?: Omit<NodeSpawnOptions, \"stdio\">): Response {\n if (options && \"stdio\" in options) {\n throw new Error(\"Unexpected `stdio` field.\");\n }\n const subprocess = this.spawnNode({\n ...options,\n stdio: [\"ignore\", \"pipe\", \"inherit\"],\n });\n\n // biome-ignore lint/style/noNonNullAssertion: dude\n return new Response(Readable.toWeb(subprocess.stdout!));\n }\n\n /** Equivalent to:\n *\n * ```\n * await this.print().spawnNodeInherit(\u2026).success;\n * ```\n */\n public async shellOutNode(\n options?: Omit<NodeSpawnOptions, \"stdio\">,\n ): Promise<void> {\n await this.print().spawnNodeInherit(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 public 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?: Omit<BunSpawnOptions.OptionsObject<In, Out, Err>, \"cmd\">,\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 subprocess = spawn({\n ...options,\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 /**\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 public spawnBunInherit(\n options?: Omit<\n Omit<\n BunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n \"cmd\"\n >,\n \"stdio\"\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.spawnBun({\n ...options,\n stdio: [\"inherit\", \"inherit\", \"inherit\"],\n });\n }\n\n /** Equivalent to:\n *\n * ```\n * new Response(this.spawnBun(\u2026).stdout);\n * ```\n */\n public spawnBunStdout(\n options?: Omit<\n Omit<\n BunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n \"cmd\"\n >,\n \"stdio\"\n >,\n ): Response {\n // biome-ignore lint/suspicious/noExplicitAny: Avoid breaking the lib check when used without `@types/bun`.\n return new Response((this.spawnBun(options) as any).stdout);\n }\n\n /** Equivalent to:\n *\n * ```\n * await this.print().spawnBunInherit(\u2026).success;\n * ```\n */\n public async shellOutBun(\n options?: Omit<\n Omit<\n BunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n \"cmd\"\n >,\n \"stdio\"\n >,\n ): Promise<void> {\n await this.print().spawnBunInherit(options).success;\n }\n}\n"],
5
+ "mappings": ";AAQA,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAM1B,IAAM,2BAA2B;AACjC,IAAM,0BAA0B;AAChC,IAAM,iCAAiC;AAEvC,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAG3B,SAAS,SAAS,GAAqB;AACrC,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,cAAc,SAAqC;AAC1D,aAAW,SAAS,SAAS;AAC3B,QAAI,CAAC,SAAS,KAAK,GAAG;AACpB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AA2CA,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;AAE5D,IAAM,wBAAN,MAA4B;AAAA,EAEjC,YACE,aACQ,OAA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AClB,sBAAQ;AAAA,YACV,OAAO;AACL;AAAA,gBACE,IAAI;AAAA,kBACF,2CAA2C,QAAQ;AAAA,gBACrD;AAAA,cACF;AAAA,YACF;AAAA,UACF,CAAC,EACA,MAAM,MAAM;AAAA,QACjB;AAAA,MACF;AAAA,MACA,YAAY;AAAA,IACd,CAAC;AACD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,gBACL,SASA;AACA,QAAI,WAAW,WAAW,SAAS;AACjC,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC7C;AACA,WAAO,KAAK,SAAS;AAAA,MACnB,GAAG;AAAA,MACH,OAAO,CAAC,WAAW,WAAW,SAAS;AAAA,IACzC,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,eACL,SAOU;AAEV,WAAO,IAAI,SAAU,KAAK,SAAS,OAAO,EAAU,MAAM;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAa,YACX,SAOe;AACf,UAAM,KAAK,MAAM,EAAE,gBAAgB,OAAO,EAAE;AAAA,EAC9C;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "printable-shell-command",
3
- "version": "1.1.5",
3
+ "version": "1.2.1",
4
4
  "main": "./src/index.ts",
5
5
  "devDependencies": {
6
6
  "@biomejs/biome": "^2.1.4",
7
7
  "@cubing/dev-config": "^0.3.6",
8
8
  "@types/bun": "^1.2.20",
9
9
  "@types/node": "^24.2.0",
10
- "esbuild": "^0.25.5"
10
+ "esbuild": "^0.25.5",
11
+ "typescript": "^5.9.3"
11
12
  },
12
13
  "optionalDependencies": {
13
14
  "@types/bun": "^1.2.20",
package/src/index.ts CHANGED
@@ -6,6 +6,7 @@ import type {
6
6
  StdioNull as NodeStdioNull,
7
7
  StdioPipe as NodeStdioPipe,
8
8
  } from "node:child_process";
9
+ import { Readable } from "node:stream";
9
10
  import { styleText } from "node:util";
10
11
  import type {
11
12
  SpawnOptions as BunSpawnOptions,
@@ -23,11 +24,20 @@ const LINE_WRAP_LINE_END = " \\\n";
23
24
  function isString(s: any): s is string {
24
25
  return typeof s === "string";
25
26
  }
27
+ // biome-ignore lint/suspicious/noExplicitAny: This is the correct type nere.
28
+ function isStringArray(entries: any[]): entries is string[] {
29
+ for (const entry of entries) {
30
+ if (!isString(entry)) {
31
+ return false;
32
+ }
33
+ }
34
+ return true;
35
+ }
26
36
 
27
37
  // TODO: allow `.toString()`ables?
28
38
  type SingleArgument = string;
29
- type FlagArgumentPair = [string, string];
30
- type ArgsEntry = SingleArgument | FlagArgumentPair;
39
+ type FlagArgumentGroup = string[];
40
+ type ArgsEntry = SingleArgument | FlagArgumentGroup;
31
41
  type Args = ArgsEntry[];
32
42
 
33
43
  export interface PrintOptions {
@@ -49,6 +59,8 @@ export interface PrintOptions {
49
59
  | "nested-by-entry"
50
60
  | "by-argument"
51
61
  | "inline";
62
+ /** Include the first arg (or first arg group) on the same line as the command, regardless of the `argumentLineWrapping` setting. */
63
+ skipLineWrapBeforeFirstArg?: true | false;
52
64
  /**
53
65
  * Style text using `node`'s [`styleText(…)`](https://nodejs.org/api/util.html#utilstyletextformat-text-options)
54
66
  *
@@ -113,12 +125,7 @@ export class PrintableShellCommand {
113
125
  if (typeof argEntry === "string") {
114
126
  continue;
115
127
  }
116
- if (
117
- Array.isArray(argEntry) &&
118
- argEntry.length === 2 &&
119
- isString(argEntry[0]) &&
120
- isString(argEntry[1])
121
- ) {
128
+ if (Array.isArray(argEntry) && isStringArray(argEntry)) {
122
129
  continue;
123
130
  }
124
131
  throw new Error(`Invalid arg entry at index: ${i}`);
@@ -256,14 +263,10 @@ export class PrintableShellCommand {
256
263
  }
257
264
  }
258
265
 
259
- #entrySeparator(options: PrintOptions): string {
266
+ #intraEntrySeparator(options: PrintOptions): string {
260
267
  switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {
261
- case "by-entry": {
262
- return LINE_WRAP_LINE_END + this.#argIndentation(options);
263
- }
264
- case "nested-by-entry": {
265
- return LINE_WRAP_LINE_END + this.#argIndentation(options);
266
- }
268
+ case "by-entry":
269
+ case "nested-by-entry":
267
270
  case "by-argument": {
268
271
  return LINE_WRAP_LINE_END + this.#argIndentation(options);
269
272
  }
@@ -275,32 +278,43 @@ export class PrintableShellCommand {
275
278
  }
276
279
  }
277
280
 
281
+ #separatorAfterCommand(
282
+ options: PrintOptions,
283
+ numFollowingEntries: number,
284
+ ): string {
285
+ if (numFollowingEntries === 0) {
286
+ return "";
287
+ }
288
+ if (options.skipLineWrapBeforeFirstArg ?? false) {
289
+ return INLINE_SEPARATOR;
290
+ }
291
+ return this.#intraEntrySeparator(options);
292
+ }
293
+
278
294
  public getPrintableCommand(options?: PrintOptions): string {
279
295
  // TODO: Why in the world does TypeScript not give the `options` arg the type of `PrintOptions | undefined`???
280
296
  options ??= {};
281
297
  const serializedEntries: string[] = [];
282
298
 
283
- serializedEntries.push(
284
- this.#mainIndentation(options) +
285
- this.#escapeArg(this.commandName, true, options),
286
- );
287
-
288
299
  for (let i = 0; i < this.args.length; i++) {
289
300
  const argsEntry = this.args[i];
290
301
 
291
302
  if (isString(argsEntry)) {
292
303
  serializedEntries.push(this.#escapeArg(argsEntry, false, options));
293
304
  } else {
294
- const [part1, part2] = argsEntry;
295
305
  serializedEntries.push(
296
- this.#escapeArg(part1, false, options) +
297
- this.#argPairSeparator(options) +
298
- this.#escapeArg(part2, false, options),
306
+ argsEntry
307
+ .map((part) => this.#escapeArg(part, false, options))
308
+ .join(this.#argPairSeparator(options)),
299
309
  );
300
310
  }
301
311
  }
302
312
 
303
- let text = serializedEntries.join(this.#entrySeparator(options));
313
+ let text =
314
+ this.#mainIndentation(options) +
315
+ this.#escapeArg(this.commandName, true, options) +
316
+ this.#separatorAfterCommand(options, serializedEntries.length) +
317
+ serializedEntries.join(this.#intraEntrySeparator(options));
304
318
  if (options?.styleTextFormat) {
305
319
  text = styleText(options.styleTextFormat, text);
306
320
  }
@@ -363,6 +377,19 @@ export class PrintableShellCommand {
363
377
  return this.spawnNode({ ...options, stdio: "inherit" });
364
378
  }
365
379
 
380
+ public spawnNodeStdout(options?: Omit<NodeSpawnOptions, "stdio">): Response {
381
+ if (options && "stdio" in options) {
382
+ throw new Error("Unexpected `stdio` field.");
383
+ }
384
+ const subprocess = this.spawnNode({
385
+ ...options,
386
+ stdio: ["ignore", "pipe", "inherit"],
387
+ });
388
+
389
+ // biome-ignore lint/style/noNonNullAssertion: dude
390
+ return new Response(Readable.toWeb(subprocess.stdout!));
391
+ }
392
+
366
393
  /** Equivalent to:
367
394
  *
368
395
  * ```