Skip to content
Myr

input-sync.js

This file

Path

lib/io/input-sync.js

44 lines · 1.9 KiB · JavaScript

Last changed by

Rename files (#977)ehmickybefore adoption4b2e316

History of this file

Take it

Rename files (#977)ehmickybefore adoption4b2e316

lines 1–44why, one step back
1import {runGeneratorsSync} from '../transform/generator.js';
2import {joinToUint8Array, isUint8Array} from '../utils/uint-array.js';3import {TYPE_TO_MESSAGE} from '../stdio/type.js';45// Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` option6export const addInputOptionsSync = (fileDescriptors, options) => {7 for (const fdNumber of getInputFdNumbers(fileDescriptors)) {8 addInputOptionSync(fileDescriptors, fdNumber, options);9 }10};1112const getInputFdNumbers = fileDescriptors => new Set(Object.entries(fileDescriptors)13 .filter(([, {direction}]) => direction === 'input')14 .map(([fdNumber]) => Number(fdNumber)));1516const addInputOptionSync = (fileDescriptors, fdNumber, options) => {17 const {stdioItems} = fileDescriptors[fdNumber];18 const allStdioItems = stdioItems.filter(({contents}) => contents !== undefined);19 if (allStdioItems.length === 0) {20 return;21 }2223 if (fdNumber !== 0) {24 const [{type, optionName}] = allStdioItems;25 throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`);26 }2728 const allContents = allStdioItems.map(({contents}) => contents);29 const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems));30 options.input = joinToUint8Array(transformedContents);31};3233const applySingleInputGeneratorsSync = (contents, stdioItems) => {34 const newContents = runGeneratorsSync(contents, stdioItems, 'utf8', true);35 validateSerializable(newContents);36 return joinToUint8Array(newContents);37};3839const validateSerializable = newContents => {40 const invalidItem = newContents.find(item => typeof item !== 'string' && !isUint8Array(item));41 if (invalidItem !== undefined) {42 throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`);43 }44};