Fix the `encoding` option and line splitting in transforms
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 4a0a121 · Browse files · 14 files·+394 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+394 added−40 removed
- tests:+301 added−12 removed
- other:+93 added−28 removed
Provenance
- Commit
6adb3c3- Tree
4cad54a- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
4a0a121
14 files changed+394 added−40 removed
modified:docs/api.md+2 added
986 unmodified lines987 - [`'hex'`](https://en.wikipedia.org/wiki/Hexadecimal), [`'base64'`](https://en.wikipedia.org/wiki/Base64), [`'base64url'`](https://en.wikipedia.org/wiki/Base64#RFC_4648), [`'latin1'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings) or [`'ascii'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings): encodes the binary output as a string.988 989 The output is available with [`result.stdout`](#resultstdout), [`result.stderr`](#resultstderr) and [`result.stdio`](#resultstdio).990 991+String input passed with the [`input`](#optionsinput) or [`stdin`](#optionsstdin) option is always encoded with UTF-8, whatever this option is. With a text encoding, [`stdin` transforms](transform.md) also decode their input with UTF-8.992+993 [More info.](binary.md)994 995 ### options.lines996 367 unmodified linesmodified:docs/binary.md+3 added
59 unmodified lines606162636465666768697012 unmodified lines59 unmodified lines
await execa({stdout: {transform, binary: true}})`zip -r - input.txt`;```
> [!NOTE]> With the [`binary`](api.md#transformoptionsbinary) transform option, a `string` a transform yields is always converted to bytes using UTF-8, since the transform deals with raw bytes. Therefore, if the [`encoding`](api.md#optionsencoding) option is a different text encoding like `'utf16le'`, those bytes are then decoded with that encoding, which corrupts the text. Either `yield` an `Uint8Array` instead, or do not use the `binary` transform option.
## Streams
[Streams produced](streams.md#converting-a-subprocess-to-a-stream) by [`subprocess.readable()`](api.md#subprocessreadablereadableoptions) and [`subprocess.duplex()`](api.md#subprocessduplexduplexoptions) are binary by default, which means they iterate over arbitrary [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) chunks. However, if the [`binary`](api.md#readableoptionsbinary) option is `false`, they iterate over line strings instead, and the stream is [in object mode](https://nodejs.org/api/stream.html#object-mode).
12 unmodified linesmodified:lib/arguments/encoding-option.js+10 added
17 unmodified lines18192021222324252627282930313233343526 unmodified lines17 unmodified linesconst TEXT_ENCODINGS = new Set(['utf8', 'utf16le']);export const BINARY_ENCODINGS = new Set(['buffer', 'hex', 'base64', 'base64url', 'latin1', 'ascii']);const ENCODINGS = TEXT_ENCODINGS.union(BINARY_ENCODINGS);
/*Encoding to use when converting a transform's string to bytes.Text encodings describe how text is represented as bytes, so those must be used, otherwise the string would be decoded with a different encoding than the one it was encoded with, which corrupts it.Binary encodings instead describe how bytes are serialized as text, so the string's UTF-8 bytes are used. The same applies with the `binary` transform option, since the transform then deals with raw bytes.*/export const getStringEncoding = (binary, encoding) => binary || !TEXT_ENCODINGS.has(encoding) ? 'utf8' : encoding;
// Text encodings only apply to the subprocess' output. Its input is always text encoded with UTF-8, so input transforms decode and encode strings with UTF-8 too, whichever text encoding the `encoding` option uses.export const getInputEncoding = encoding => TEXT_ENCODINGS.has(encoding) ? 'utf8' : encoding;
const getCorrectEncoding = encoding => { if (encoding === null) { return 'buffer'; }26 unmodified linesmodified:lib/io/input-sync.js+5 added-3 removed
1234567817 unmodified lines2627282929303132333334343536373839406 unmodified linesimport {runGeneratorsSync} from '../transform/generator.js';import {joinToUint8Array, isUint8Array} from '../utils/uint-array.js';import {TYPE_TO_MESSAGE} from '../stdio/type.js';import {getInputEncoding} from '../arguments/encoding-option.js';
// Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` optionexport const addInputOptionsSync = (fileDescriptors, options) => { for (const fdNumber of getInputFdNumbers(fileDescriptors)) {17 unmodified lines throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`); }
const allContents = allStdioItems.map(({contents}) => contents); const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems)); const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems, options.encoding)); options.input = joinToUint8Array(transformedContents);};
const applySingleInputGeneratorsSync = (contents, stdioItems) => { const newContents = runGeneratorsSync(contents, stdioItems, 'utf8', true);const applySingleInputGeneratorsSync = (contents, stdioItems, encoding) => { // Input transforms use UTF-8 with text encodings, since those only apply to the output const newContents = runGeneratorsSync(contents, stdioItems, getInputEncoding(encoding), true); validateSerializable(newContents); return joinToUint8Array(newContents);};
6 unmodified linesmodified:lib/stdio/handle-async.js+6 added
1 import {createReadStream, createWriteStream} from 'node:fs';2 import {Buffer} from 'node:buffer';3 import {Readable, Writable, Duplex} from 'node:stream';4 import {generatorToStream} from '../transform/generator.js';5+import {getInputEncoding} from '../arguments/encoding-option.js';6 import {handleStdio} from './handle.js';7 import {TYPE_TO_MESSAGE} from './type.js';8 9 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode18 unmodified lines28 duplex: ({value: {transform}}) => ({stream: transform}),29 native() {},30 };31 32+// Input transforms use UTF-8 with text encodings, since those only apply to the output33+const generatorToInputStream = (stdioItem, {encoding}) => generatorToStream(stdioItem, {encoding: getInputEncoding(encoding)});34+35 const addPropertiesAsync = {36 input: {37 ...addProperties,38+ generator: generatorToInputStream,39+ asyncGenerator: generatorToInputStream,40 fileUrl: ({value}) => ({stream: createReadStream(value)}),41 filePath: ({value: {file}}) => ({stream: createReadStream(file)}),42 webStream: ({value}) => ({stream: Readable.fromWeb(value)}),43 iterable: ({value}) => ({stream: Readable.from(value)}),15 unmodified linesmodified:lib/transform/encoding-transform.js+15 added
1 import {Buffer} from 'node:buffer';2 import {StringDecoder} from 'node:string_decoder';3+import {getStringEncoding} from '../arguments/encoding-option.js';4 import {isUint8Array, bufferToUint8Array} from '../utils/uint-array.js';5 6 /*7 When using binary encodings, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.41 unmodified lines49 if (lastChunk !== '') {50 yield lastChunk;51 }52 };53+54+/*55+Once the user's transform has run, its string chunks are converted to bytes: by `Transform.push()` with the asynchronous methods, and by `joinToString()` with the synchronous ones. Both use UTF-8, yet the result is then decoded with the `encoding` option, which would corrupt the text when that option is a different text encoding.56+Therefore, those chunks are converted using the `encoding` option beforehand.57+With the `binary` transform option, they are converted with UTF-8 even when the `encoding` option is another text encoding. Otherwise, with synchronous methods, the next transform would receive the string itself, while with asynchronous methods it receives those UTF-8 bytes decoded with the `encoding` option.58+When the `encoding` option is UTF-8, strings round-trip unchanged, so there is nothing to do.59+*/60+export const getStringToBytesGenerator = (binary, encoding, skipped) => skipped || encoding === 'utf8'61+ ? undefined62+ : {transform: stringToBytesGenerator.bind(undefined, getStringEncoding(binary, encoding))};63+64+const stringToBytesGenerator = function * (stringEncoding, chunk) {65+ yield typeof chunk === 'string' ? bufferToUint8Array(Buffer.from(chunk, stringEncoding)) : chunk;66+};modified:lib/transform/generator.js+13 added-2 removed
1 import {Transform, getDefaultHighWaterMark} from 'node:stream';2+import {getStringEncoding} from '../arguments/encoding-option.js';3 import {isAsyncGenerator} from '../stdio/type.js';4 import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';5 import {getValidateTransformInput, getValidateTransformReturn} from './validate.js';5-import {getEncodingTransformGenerator} from './encoding-transform.js';6+import {getEncodingTransformGenerator, getStringToBytesGenerator} from './encoding-transform.js';7 import {8 pushChunks,9 transformChunk,10 finalChunks,26 unmodified lines37 `Duplex.from(generator)` cannot be used because it does not allow setting the `objectMode` and `highWaterMark`.38 */39 export const generatorToStream = ({40 value,40- value: {transform, final, writableObjectMode, readableObjectMode},41+ value: {42+ transform,43+ final,44+ binary,45+ writableObjectMode,46+ readableObjectMode,47+ },48 optionName,49 }, {encoding}) => {50 const state = {};51 const generators = addInternalGenerators(value, encoding, optionName);14 unmodified lines66 writableObjectMode,67 writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode),68 readableObjectMode,69 readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode),70+ // A string written to the stream is converted to bytes with this encoding, which `getEncodingTransformGenerator()` then decodes with the `encoding` option71+ defaultEncoding: getStringEncoding(binary, encoding),72 transform(chunk, encoding, done) {73 transformMethod([chunk, generators, 0], this, done);74 },75 flush(done) {34 unmodified lines110 binary,111 preserveNewlines,112 readableObjectMode,113 state,114+ encoding,115 }),116+ getStringToBytesGenerator(binary, encoding, readableObjectMode),117 ].filter(Boolean);118 };modified:lib/transform/split.js+37 added-23 removed
1+import {getStringEncoding} from '../arguments/encoding-option.js';2+3 // Split chunks line-wise for generators passed to the `std*` options4 export const getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped5 ? undefined6 : initializeSplitLines(preserveNewlines, state);30 unmodified lines37 if (chunk[end] !== '\n') {38 continue;39 }40 39- const newlineLength = getNewlineLength(chunk, end, preserveNewlines, state);40- let line = chunk.slice(start + 1, end + 1 - newlineLength);41+ // The `\r` of a `\r\n` sequence is stripped further below, once `previousChunks` has been prepended.42+ // Otherwise, a `\r\n` sequence split across two chunks would not be detected.43+ let line = chunk.slice(start + 1, preserveNewlines ? end + 1 : end);44 45 if (previousChunks.length > 0) {46 line = concatString(previousChunks, line);47 previousChunks = '';48 }49 47- yield line;50+ yield preserveNewlines ? line : stripCarriageReturn(line, state);51 start = end;52 }53 54 if (start !== chunk.length - 1) {2 unmodified lines57 58 state.previousChunks = previousChunks;59 };60 58-const getNewlineLength = (chunk, end, preserveNewlines, state) => {59- if (preserveNewlines) {60- return 0;61- }62-63- state.isWindowsNewline = end !== 0 && chunk[end - 1] === '\r';64- return state.isWindowsNewline ? 2 : 1;61+const stripCarriageReturn = (line, state) => {62+ state.isWindowsNewline = line.endsWith('\r');63+ return state.isWindowsNewline ? line.slice(0, -1) : line;64 };65 66 const linesFinal = function * ({previousChunks}) {67 if (previousChunks.length > 0) {2 unmodified lines70 };71 72 // Unless `preserveNewlines: true` is used, we strip the newline of each line.73 // This re-adds them after the user `transform` code has run.74+// The re-added newline must be encoded with the `encoding` option when the chunk is bytes: a UTF-8 newline would misalign `utf16le` bytes.75-export const getAppendNewlineGenerator = ({binary, preserveNewlines, readableObjectMode, state}) => binary || preserveNewlines || readableObjectMode75+export const getAppendNewlineGenerator = ({binary, preserveNewlines, readableObjectMode, state, encoding}) => binary || preserveNewlines || readableObjectMode76 ? undefined77- : {transform: appendNewlineGenerator.bind(undefined, state)};77+ : {transform: appendNewlineGenerator.bind(undefined, state, getStringEncoding(binary, encoding))};78 79-const appendNewlineGenerator = function * ({isWindowsNewline = false}, chunk) {80- const {unixNewline, windowsNewline, LF, concatBytes} = typeof chunk === 'string' ? linesStringInfo : linesUint8ArrayInfo;79+const appendNewlineGenerator = function * ({isWindowsNewline = false}, stringEncoding, chunk) {80+ const {unixNewline, windowsNewline, concat} = typeof chunk === 'string'81+ ? linesStringInfo82+ : LINES_BYTES_INFO[stringEncoding];83 82- if (chunk.at(-1) === LF) {84+ if (endsWithNewline(chunk, unixNewline)) {85 yield chunk;86 return;87 }88 89 const newline = isWindowsNewline ? windowsNewline : unixNewline;88- yield concatBytes(chunk, newline);90+ yield concat(chunk, newline);91 };92 93+const endsWithNewline = (chunk, unixNewline) => typeof chunk === 'string'94+ ? chunk.endsWith(unixNewline)95+ : chunk.length >= unixNewline.length96+ && chunk.subarray(-unixNewline.length).every((byte, index) => byte === unixNewline[index]);97+98 const concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`;99 100 const linesStringInfo = {101 windowsNewline: '\r\n',102 unixNewline: '\n',96- LF: '\n',97- concatBytes: concatString,103+ concat: concatString,104 };105 106 const concatUint8Array = (firstChunk, secondChunk) => {107 const chunk = new Uint8Array(firstChunk.length + secondChunk.length);1 unmodified line109 chunk.set(secondChunk, firstChunk.length);110 return chunk;111 };112 107-const linesUint8ArrayInfo = {108- windowsNewline: new Uint8Array([0x0D, 0x0A]),109- unixNewline: new Uint8Array([0x0A]),110- LF: 0x0A,111- concatBytes: concatUint8Array,113+// Only indexed with text encodings, since the `binary` option and binary encodings disable this generator114+const LINES_BYTES_INFO = {115+ __proto__: null,116+ utf8: {117+ windowsNewline: new Uint8Array([0x0D, 0x0A]),118+ unixNewline: new Uint8Array([0x0A]),119+ concat: concatUint8Array,120+ },121+ utf16le: {122+ windowsNewline: new Uint8Array([0x0D, 0x00, 0x0A, 0x00]),123+ unixNewline: new Uint8Array([0x0A, 0x00]),124+ concat: concatUint8Array,125+ },126 };modified:test/helpers/lines.js-2 removed
18 unmodified lines19 export const simpleFullUtf16Inverted = simpleFullBuffer.toString('utf16le');20 const simpleFullUtf16Buffer = Buffer.from(simpleFull, 'utf16le');21 export const simpleFullUtf16Uint8Array = new Uint8Array(simpleFullUtf16Buffer);22 export const simpleFullEnd = `${simpleFull}\n`;23-const simpleFullEndBuffer = Buffer.from(simpleFullEnd);23 export const simpleFullEndChunks = [simpleFullEnd];25-export const simpleFullEndUtf16Inverted = simpleFullEndBuffer.toString('utf16le');24 export const simpleLines = ['aaa\n', 'bbb\n', 'ccc'];25 export const simpleFullEndLines = ['aaa\n', 'bbb\n', 'ccc\n'];26 export const noNewlinesFull = 'aaabbbccc';27 export const noNewlinesChunks = ['aaa', 'bbb', 'ccc'];16 unmodified linesmodified:test/io/input-option.js+57 added
1+import {Buffer} from 'node:buffer';2 import {Writable} from 'node:stream';3 import test from 'ava';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10 unmodified lines16 foobarArrayBuffer,17 foobarUint16Array,18 foobarDataView,19 } from '../helpers/input.js';20+import {noopGenerator} from '../helpers/generator.js';21 22 setFixtureDirectory();23 24 const testInput = async (t, input, execaMethod) => {43 unmodified lines68 test('input option cannot be 0 - sync', testInvalidInput, 0, execaSync);69 test('input option cannot be false - sync', testInvalidInput, false, execaSync);70 test('input option cannot be null - sync', testInvalidInput, null, execaSync);71 test('input option cannot be a non-Readable stream - sync', testInvalidInput, new Writable(), execaSync);72+73+/*74+String input is encoded with the `encoding` option, so it round-trips with subprocesses echoing it back.75+This must not depend on whether a `stdin` transform happens to be present.76+*/77+const nonAsciiString = '🦄🦄';78+79+const testStringEncoding = async (t, options, execaMethod) => {80+ const {stdout} = await execaMethod('stdin.js', {...options, input: nonAsciiString, encoding: 'utf16le'});81+ t.is(stdout, nonAsciiString);82+};83+84+test('input option string is encoded with encoding "utf16le" without transforms', testStringEncoding, {}, execa);85+test('input option string is encoded with encoding "utf16le" without transforms - sync', testStringEncoding, {}, execaSync);86+test('input option string is encoded with encoding "utf16le" with transforms', testStringEncoding, {stdin: noopGenerator()}, execa);87+test('input option string is encoded with encoding "utf16le" with transforms - sync', testStringEncoding, {stdin: noopGenerator()}, execaSync);88+89+/*90+Sources other than the `input` option also pass strings to the subprocess, which must be encoded with the `encoding` option too.91+*/92+const testIterableInputEncoding = async (t, execaMethod) => {93+ const {stdout} = await execaMethod('stdin.js', {94+ stdin: [[`${nonAsciiString}aaa\n`], [`${nonAsciiString}bbb\n`]],95+ encoding: 'utf16le',96+ stripFinalNewline: false,97+ });98+ t.is(stdout, `${nonAsciiString}aaa\n${nonAsciiString}bbb\n`);99+};100+101+test('Iterable string input is encoded with encoding "utf16le"', testIterableInputEncoding, execa);102+test('Iterable string input is encoded with encoding "utf16le" - sync', testIterableInputEncoding, execaSync);103+104+const testAsyncIterableInputEncoding = async t => {105+ const chunks = async function * () {106+ yield nonAsciiString;107+ };108+109+ const {stdout} = await execa('stdin.js', {stdin: [chunks()], encoding: 'utf16le'});110+ t.is(stdout, nonAsciiString);111+};112+113+test('Async iterable string input is encoded with encoding "utf16le"', testAsyncIterableInputEncoding);114+115+/*116+The `encoding` option does not change how string input is encoded when it is a binary encoding: those describe how output bytes are serialized, so input keeps using UTF-8.117+*/118+const testBinaryEncodingInput = async (t, encoding, execaMethod) => {119+ const {stdout} = await execaMethod('stdin.js', {input: nonAsciiString, encoding});120+ t.is(stdout, Buffer.from(nonAsciiString).toString(encoding));121+};122+123+test('String input stays UTF-8 with encoding "latin1"', testBinaryEncodingInput, 'latin1', execa);124+test('String input stays UTF-8 with encoding "latin1" - sync', testBinaryEncodingInput, 'latin1', execaSync);125+test('String input stays UTF-8 with encoding "hex"', testBinaryEncodingInput, 'hex', execa);126+test('String input stays UTF-8 with encoding "hex" - sync', testBinaryEncodingInput, 'hex', execaSync);modified:test/transform/encoding-transform.js+132 added-1 removed
5 unmodified lines6 import {7 foobarString,8 foobarUint8Array,9 foobarBuffer,10+ foobarUtf16Uint8Array,11 foobarObject,12 } from '../helpers/input.js';12-import {noopGenerator, getOutputGenerator} from '../helpers/generator.js';13+import {noopGenerator, getOutputGenerator, uppercaseGenerator} from '../helpers/generator.js';14 15 setFixtureDirectory();16 17 const getTypeofGenerator = lines => (objectMode, binary) => ({74 unmodified lines92 test('First generator argument can be objects with objectMode, sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, undefined);93 test('First generator argument can be objects with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, false);94 test('First generator argument can be objects with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, true);95 96+/*97+The `encoding` option also determines how binary `stdin` input is decoded before being passed to a transform.98+Unlike the tests above, this checks the chunk's value, not only its type.99+This must be the same with both asynchronous and synchronous methods.100+*/101+const getChunkGenerator = chunks => ({102+ * transform(chunk) {103+ chunks.push(chunk);104+ yield chunk;105+ },106+});107+108+const testStdinEncodingValue = async (t, encoding) => {109+ const chunks = [];110+ const subprocess = execa('stdin.js', {stdin: getChunkGenerator(chunks), encoding});111+ subprocess.stdin.end(foobarUtf16Uint8Array);112+ await subprocess;113+ t.deepEqual(chunks, [Buffer.from(foobarUtf16Uint8Array).toString(encoding)]);114+};115+116+test('First generator argument is decoded with encoding "utf8"', testStdinEncodingValue, 'utf8');117+test('First generator argument is decoded with encoding "utf16le"', testStdinEncodingValue, 'utf16le');118+119+const testStdinEncodingValueSync = (t, encoding) => {120+ const chunks = [];121+ execaSync('stdin.js', {stdin: [[foobarUtf16Uint8Array], getChunkGenerator(chunks)], encoding});122+ t.deepEqual(chunks, [Buffer.from(foobarUtf16Uint8Array).toString(encoding)]);123+};124+125+test('First generator argument is decoded with encoding "utf8", sync', testStdinEncodingValueSync, 'utf8');126+test('First generator argument is decoded with encoding "utf16le", sync', testStdinEncodingValueSync, 'utf16le');127+128 const testEncodingIgnored = async (t, encoding) => {129 const input = Buffer.from(foobarString).toString(encoding);130 const subprocess = execa('stdin.js', {stdin: noopGenerator(true)});131 subprocess.stdin.end(input, encoding);75 unmodified lines207 test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3, execa);208 test('The first generator with result.stdout does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 1, execaSync);209 test('The first generator with result.stderr does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 2, execaSync);210 test('The first generator with result.stdio[*] does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 3, execaSync);211+212+// When the `encoding` option is binary, the whole pipeline is byte-oriented: a transform yielding a213+// string has it encoded as UTF-8, then those bytes are serialized using the `encoding` option.214+// This is the only coherent rule, since a yielded string like 'foobar' is neither valid hex nor valid base64.215+// A non-ASCII string is used, so UTF-8 and the binary encoding differ.216+const nonAsciiString = 'ré😀';217+const nonAsciiBuffer = Buffer.from(nonAsciiString, 'utf8');218+219+const testYieldStringBinaryEncoding = async (t, encoding, execaMethod) => {220+ const {stdout} = await execaMethod('noop.js', {221+ stdout: getOutputGenerator(nonAsciiString)(false, true),222+ encoding,223+ });224+ t.is(stdout, nonAsciiBuffer.toString(encoding));225+};226+227+test('Transforms yielding a string are UTF-8 encoded, latin1', testYieldStringBinaryEncoding, 'latin1', execa);228+test('Transforms yielding a string are UTF-8 encoded, latin1, sync', testYieldStringBinaryEncoding, 'latin1', execaSync);229+test('Transforms yielding a string are UTF-8 encoded, hex', testYieldStringBinaryEncoding, 'hex', execa);230+test('Transforms yielding a string are UTF-8 encoded, hex, sync', testYieldStringBinaryEncoding, 'hex', execaSync);231+test('Transforms yielding a string are UTF-8 encoded, base64', testYieldStringBinaryEncoding, 'base64', execa);232+test('Transforms yielding a string are UTF-8 encoded, base64, sync', testYieldStringBinaryEncoding, 'base64', execaSync);233+234+// A transform yielding the bytes it received must round-trip them unchanged235+const testYieldBytesBinaryEncoding = async (t, execaMethod) => {236+ const {stdout} = await execaMethod('noop-fd.js', ['1', nonAsciiString], {237+ stdout: noopGenerator(false, true),238+ encoding: 'latin1',239+ });240+ t.is(stdout, nonAsciiBuffer.toString('latin1'));241+};242+243+test('Transforms yielding Uint8Array keep the bytes unchanged', testYieldBytesBinaryEncoding, execa);244+test('Transforms yielding Uint8Array keep the bytes unchanged, sync', testYieldBytesBinaryEncoding, execaSync);245+246+/*247+With a text encoding, a transform receives text decoded with it, so a string it yields must be encoded back with it.248+Otherwise that string would be encoded as UTF-8, then decoded with the `encoding` option, which corrupts it.249+*/250+const nonAsciiUtf16Uint8Array = new Uint8Array(Buffer.from(nonAsciiString, 'utf16le'));251+252+const testYieldStringTextEncoding = async (t, transform, expectedOutput, execaMethod) => {253+ const {stdout} = await execaMethod('noop.js', {254+ stdout: [getOutputGenerator(nonAsciiUtf16Uint8Array)(false, true), transform],255+ encoding: 'utf16le',256+ });257+ t.is(stdout, expectedOutput);258+};259+260+test('Transforms yielding a string are encoded with encoding "utf16le"', testYieldStringTextEncoding, noopGenerator(), nonAsciiString, execa);261+test('Transforms yielding a string are encoded with encoding "utf16le", sync', testYieldStringTextEncoding, noopGenerator(), nonAsciiString, execaSync);262+test('Transforms modifying a string are encoded with encoding "utf16le"', testYieldStringTextEncoding, uppercaseGenerator(), nonAsciiString.toUpperCase(), execa);263+test('Transforms modifying a string are encoded with encoding "utf16le", sync', testYieldStringTextEncoding, uppercaseGenerator(), nonAsciiString.toUpperCase(), execaSync);264+test('Transforms yielding a Uint8Array keep the bytes unchanged with encoding "utf16le"', testYieldStringTextEncoding, getOutputGenerator(nonAsciiUtf16Uint8Array)(false, true), nonAsciiString, execa);265+test('Transforms yielding a Uint8Array keep the bytes unchanged with encoding "utf16le", sync', testYieldStringTextEncoding, getOutputGenerator(nonAsciiUtf16Uint8Array)(false, true), nonAsciiString, execaSync);266+267+// A `stdin` transform also receives text decoded with the `encoding` option, so the same applies in that direction268+const testYieldStringTextEncodingInput = async (t, execaMethod) => {269+ const {stdout} = await execaMethod('stdin.js', {270+ stdin: [[nonAsciiUtf16Uint8Array], noopGenerator()],271+ encoding: 'utf16le',272+ });273+ t.is(stdout, nonAsciiString);274+};275+276+test('Transforms yielding a string are encoded with encoding "utf16le", stdin', testYieldStringTextEncodingInput, execa);277+test('Transforms yielding a string are encoded with encoding "utf16le", stdin, sync', testYieldStringTextEncodingInput, execaSync);278+279+// When the `stdin` value is a string, the transform receives it as text, so it must not be encoded as UTF-8 either280+const testStringInputTextEncoding = async (t, execaMethod) => {281+ const {stdout} = await execaMethod('stdin.js', {282+ stdin: [[nonAsciiString], noopGenerator()],283+ encoding: 'utf16le',284+ });285+ t.is(stdout, nonAsciiString);286+};287+288+test('String input is encoded with encoding "utf16le", stdin', testStringInputTextEncoding, execa);289+test('String input is encoded with encoding "utf16le", stdin, sync', testStringInputTextEncoding, execaSync);290+291+// A transform may also yield `Uint8Array`s with a text encoding. The newline re-added after each stripped line must then be encoded with that same encoding, otherwise the bytes become misaligned.292+const utf16leYieldGenerator = {293+ * transform(line) {294+ yield Buffer.from(line, 'utf16le');295+ },296+};297+298+const testYieldUtf16LeLines = async (t, execaMethod) => {299+ const {stdout} = await execaMethod('stdin.js', {300+ stdin: [['aaa\nbbb\nccc\n'], utf16leYieldGenerator],301+ encoding: 'utf16le',302+ stripFinalNewline: false,303+ });304+ t.is(stdout, 'aaa\nbbb\nccc\n');305+};306+307+test('Transforms yielding Uint8Array re-add newlines with encoding "utf16le"', testYieldUtf16LeLines, execa);308+test('Transforms yielding Uint8Array re-add newlines with encoding "utf16le", sync', testYieldUtf16LeLines, execaSync);modified:test/transform/split-binary.js+8 added-9 removed
8 unmodified lines9 simpleFullUtf16Inverted,10 simpleFullUtf16Uint8Array,11 simpleChunksUint8Array,12 simpleFullEnd,13- simpleFullEndUtf16Inverted,13 simpleFullHex,14 simpleLines,15 noNewlinesChunks,16 } from '../helpers/lines.js';18 unmodified lines35 test('Does not split lines when "binary" is true', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execa);36 test('Splits lines when "binary" is false', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);37 test('Splits lines when "binary" is undefined', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);38 test('Does not split lines when "binary" is true, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execa);40-test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);41-test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);39+test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFull, false, true, 'utf16le', execa);40+test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFull, false, true, 'utf16le', execa);41 test('Does not split lines when "binary" is true, encoding "buffer"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);42 test('Does not split lines when "binary" is undefined, encoding "buffer"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);43 test('Does not split lines when "binary" is false, encoding "buffer"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);44 test('Does not split lines when "binary" is true, encoding "hex"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);5 unmodified lines50 test('Does not split lines when "binary" is true, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execa);51 test('Splits lines when "binary" is false, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);52 test('Splits lines when "binary" is undefined, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);53 test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execa);55-test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);56-test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);54+test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEnd, false, false, 'utf16le', execa);55+test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEnd, false, false, 'utf16le', execa);56 test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);57 test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);58 test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);59 test('Does not split lines when "binary" is true, objectMode, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execa);5 unmodified lines65 test('Does not split lines when "binary" is true, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execaSync);66 test('Splits lines when "binary" is false, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);67 test('Splits lines when "binary" is undefined, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);68 test('Does not split lines when "binary" is true, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);70-test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);71-test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);69+test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFull, false, true, 'utf16le', execaSync);70+test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFull, false, true, 'utf16le', execaSync);71 test('Does not split lines when "binary" is true, encoding "buffer", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);72 test('Does not split lines when "binary" is undefined, encoding "buffer", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);73 test('Does not split lines when "binary" is false, encoding "buffer", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);74 test('Does not split lines when "binary" is true, encoding "hex", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);5 unmodified lines80 test('Does not split lines when "binary" is true, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execaSync);81 test('Splits lines when "binary" is false, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);82 test('Splits lines when "binary" is undefined, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);83 test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execaSync);85-test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);86-test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);84+test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEnd, false, false, 'utf16le', execaSync);85+test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEnd, false, false, 'utf16le', execaSync);86 test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);87 test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);88 test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);89 test('Does not split lines when "binary" is true, objectMode, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execaSync);5 unmodified linesmodified:test/transform/split-newline.js+104 added
1+import process from 'node:process';2+import {Buffer} from 'node:buffer';3 import test from 'ava';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {getOutputsGenerator, noopGenerator, noopAsyncGenerator} from '../helpers/generator.js';29 unmodified lines36 37 test('Can mix Unix and Windows newlines', testMixNewlines, noopGenerator, execa);38 test('Can mix Unix and Windows newlines, sync', testMixNewlines, noopGenerator, execaSync);39 test('Can mix Unix and Windows newlines, async', testMixNewlines, noopAsyncGenerator, execa);40+41+// A `\r\n` sequence can be split across two chunks, since chunk boundaries are arbitrary.42+// `noop-progressive.js` writes each character as a separate chunk, then a final newline.43+test('Detects Windows newlines split across chunks', async t => {44+ const {stdout} = await execa('noop-progressive.js', ['aaa\r'], {lines: true});45+ t.deepEqual(stdout, ['aaa']);46+});47+48+test('Keeps Windows newlines split across chunks', async t => {49+ const {stdout} = await execa('noop-progressive.js', ['aaa\r'], {lines: true, stripFinalNewline: false});50+ t.deepEqual(stdout, ['aaa\r\n']);51+});52+53+test('Detects multiple Windows newlines split across chunks', async t => {54+ const {stdout} = await execa('noop-progressive.js', ['aaa\r\nbbb\r'], {lines: true});55+ t.deepEqual(stdout, ['aaa', 'bbb']);56+});57+58+test('Keeps lone carriage returns split across chunks', async t => {59+ const {stdout} = await execa('noop-progressive.js', ['aaa\rbbb'], {lines: true});60+ t.deepEqual(stdout, ['aaa\rbbb']);61+});62+63+/*64+The newline re-added after each stripped line must be encoded with the `encoding` option when the transform yields bytes, both for `\n` and `\r\n`, and whether the input comes from the subprocess or from the `stdin` option.65+*/66+const utf16Input = 'aaa\nbbb\nccc\n';67+const utf16WindowsInput = 'aaa\r\nbbb\r\n';68+69+const utf16YieldGenerator = {70+ * transform(line) {71+ yield Buffer.from(line, 'utf16le');72+ },73+};74+75+// The transform yields bytes which already end with a newline: it must not be appended twice76+const utf16YieldNewlineGenerator = {77+ * transform(line) {78+ yield Buffer.from(`${line}\n`, 'utf16le');79+ },80+};81+82+const testUtf16LeInputNewlines = async (t, input, generator, execaMethod) => {83+ const {stdout} = await execaMethod('stdin.js', {84+ stdin: [[input], generator],85+ encoding: 'utf16le',86+ stripFinalNewline: false,87+ });88+ t.is(stdout, input);89+};90+91+test('Newlines re-added to bytes use encoding "utf16le"', testUtf16LeInputNewlines, utf16Input, utf16YieldGenerator, execa);92+test('Newlines re-added to bytes use encoding "utf16le", sync', testUtf16LeInputNewlines, utf16Input, utf16YieldGenerator, execaSync);93+test('Windows newlines re-added to bytes use encoding "utf16le"', testUtf16LeInputNewlines, utf16WindowsInput, utf16YieldGenerator, execa);94+test('Windows newlines re-added to bytes use encoding "utf16le", sync', testUtf16LeInputNewlines, utf16WindowsInput, utf16YieldGenerator, execaSync);95+test('Bytes already ending with a newline are not appended to, utf16le', testUtf16LeInputNewlines, utf16Input, utf16YieldNewlineGenerator, execa);96+test('Bytes already ending with a newline are not appended to, utf16le, sync', testUtf16LeInputNewlines, utf16Input, utf16YieldNewlineGenerator, execaSync);97+98+// The subprocess' own output goes through the same newline re-adding logic99+const testUtf16LeOutputNewlines = async (t, execaMethod) => {100+ const {stdout} = await execaMethod(process.execPath, ['-e', `process.stdout.write(${JSON.stringify(utf16Input)}, 'utf16le')`], {101+ stdout: utf16YieldGenerator,102+ encoding: 'utf16le',103+ stripFinalNewline: false,104+ });105+ t.is(stdout, utf16Input);106+};107+108+test('Newlines re-added to bytes use encoding "utf16le", subprocess output', testUtf16LeOutputNewlines, execa);109+test('Newlines re-added to bytes use encoding "utf16le", subprocess output, sync', testUtf16LeOutputNewlines, execaSync);110+111+// Control: UTF-8 bytes keep using UTF-8 newlines112+const utf8YieldGenerator = {113+ * transform(line) {114+ yield Buffer.from(line, 'utf8');115+ },116+};117+118+const testUtf8InputNewlines = async (t, execaMethod) => {119+ const {stdout} = await execaMethod('stdin.js', {120+ stdin: [[utf16Input], utf8YieldGenerator],121+ stripFinalNewline: false,122+ });123+ t.is(stdout, utf16Input);124+};125+126+test('Newlines re-added to bytes use UTF-8 by default', testUtf8InputNewlines, execa);127+test('Newlines re-added to bytes use UTF-8 by default, sync', testUtf8InputNewlines, execaSync);128+129+// With the `binary` transform option, the transform deals with raw bytes: they are left untouched130+const testBinaryUtf16Le = async (t, execaMethod) => {131+ const bytes = new Uint8Array(Buffer.from(utf16Input, 'utf16le'));132+ const {stdout} = await execaMethod('stdin.js', {133+ stdin: [[bytes], noopGenerator(false, true)],134+ encoding: 'utf16le',135+ stripFinalNewline: false,136+ });137+ t.is(stdout, utf16Input);138+};139+140+test('"binary: true" leaves utf16le bytes untouched', testBinaryUtf16Le, execa);141+test('"binary: true" leaves utf16le bytes untouched, sync', testBinaryUtf16Le, execaSync);modified:types/arguments/options.d.ts+2 added
157 unmodified lines158 - [`'hex'`](https://en.wikipedia.org/wiki/Hexadecimal), [`'base64'`](https://en.wikipedia.org/wiki/Base64), [`'base64url'`](https://en.wikipedia.org/wiki/Base64#RFC_4648), [`'latin1'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings) or [`'ascii'`](https://nodejs.org/api/buffer.html#buffers-and-character-encodings): encodes the binary output as a string.159 160 The output is available with `result.stdout`, `result.stderr` and `result.stdio`.161 162+ String input passed with the `input` or `stdin` option is always encoded with UTF-8, whatever this option is. With a text encoding, `stdin` transforms also decode their input with UTF-8.163+164 @default 'utf8'165 */166 readonly encoding?: Encoding;167 260 unmodified lines