handle-sync.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import {readFileSync} from 'node:fs';
  2. import {bufferToUint8Array} from '../utils/uint-array.js';
  3. import {handleStdio} from './handle.js';
  4. import {TYPE_TO_MESSAGE} from './type.js';
  5. // Normalize `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode
  6. export const handleStdioSync = (options, verboseInfo) => handleStdio(addPropertiesSync, options, verboseInfo, true);
  7. const forbiddenIfSync = ({type, optionName}) => {
  8. throwInvalidSyncValue(optionName, TYPE_TO_MESSAGE[type]);
  9. };
  10. const forbiddenNativeIfSync = ({optionName, value}) => {
  11. if (value === 'ipc' || value === 'overlapped') {
  12. throwInvalidSyncValue(optionName, `"${value}"`);
  13. }
  14. return {};
  15. };
  16. const throwInvalidSyncValue = (optionName, value) => {
  17. throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);
  18. };
  19. // Create streams used internally for redirecting when using specific values for the `std*` options, in sync mode.
  20. // For example, `stdin: {file}` reads the file synchronously, then passes it as the `input` option.
  21. const addProperties = {
  22. generator() {},
  23. asyncGenerator: forbiddenIfSync,
  24. webStream: forbiddenIfSync,
  25. nodeStream: forbiddenIfSync,
  26. webTransform: forbiddenIfSync,
  27. duplex: forbiddenIfSync,
  28. asyncIterable: forbiddenIfSync,
  29. native: forbiddenNativeIfSync,
  30. };
  31. const addPropertiesSync = {
  32. input: {
  33. ...addProperties,
  34. fileUrl: ({value}) => ({contents: [bufferToUint8Array(readFileSync(value))]}),
  35. filePath: ({value: {file}}) => ({contents: [bufferToUint8Array(readFileSync(file))]}),
  36. fileNumber: forbiddenIfSync,
  37. iterable: ({value}) => ({contents: [...value]}),
  38. string: ({value}) => ({contents: [value]}),
  39. uint8Array: ({value}) => ({contents: [value]}),
  40. },
  41. output: {
  42. ...addProperties,
  43. fileUrl: ({value}) => ({path: value}),
  44. filePath: ({value: {file, append}}) => ({path: file, append}),
  45. fileNumber: ({value}) => ({path: value}),
  46. iterable: forbiddenIfSync,
  47. string: forbiddenIfSync,
  48. uint8Array: forbiddenIfSync,
  49. },
  50. };