/* istanbul ignore file */ import type { Stream } from "node:stream"; import { URL } from "node:url"; import { createReadStream, pathExists, stat } from "fs-extra"; import fetch from "node-fetch"; import { type Type, extendType, number } from "../src"; export const Integer: Type = extendType(number, { async from(n) { if (Math.round(n) !== n) { throw new Error("This is a floating-point number"); } return n; }, }); function stdin() { return (global as any).mockStdin || process.stdin; } export const ReadStream: Type = { description: "A file path or a URL to make a GET request to", displayName: "file", async from(str) { if (str.startsWith("http://") || str.startsWith("https://")) { const parsedUrl = new URL(str); if (parsedUrl.protocol?.startsWith("http")) { const response = await fetch(str); const statusGroup = Math.floor(response.status / 100); if (statusGroup !== 2) { throw new Error( `Got status ${response.statusText} ${response.status} reading URL`, ); } return response.body; } } if (str === "-") { return stdin(); } if (!(await pathExists(str))) { throw new Error(`Can't find file in path ${str}`); } const fileStat = await stat(str); if (!fileStat.isFile()) { throw new Error("Path is not a file."); } return createReadStream(str); }, }; export function readStreamToString(s: Stream): Promise { return new Promise((resolve, reject) => { let str = ""; s.on("data", (x) => { str += x.toString(); }); s.on("error", (e) => reject(e)); s.on("end", () => resolve(str)); }); } export const CommaSeparatedString: Type = { description: "comma seperated string", async from(s) { return s.split(/, ?/); }, };