UNPKG

fusox

Version:

Command line wrapper for fuse-box

129 lines (102 loc) 2.65 kB
const {existsSync} = require('fs') const portfinder = require('portfinder') module.exports = { parseBoolean, parseTruthy, parseFlag, parseNumber, findExistingFile, getTransparentCorsSnippet, printHeader, getFreePorts, getFreePort, getVersion } function parseBoolean (str) { if (str === true || str === false) { return str } if (str === 'true') { return true } return false } function parseTruthy (str) { return !! parseFlag(str) } function parseFlag (str, valueForTrue = true, valueForFalse = false) { if (str === true || str === 'true') { return valueForTrue } if (str === false || str === 'false') { return valueForFalse } return str } function parseNumber (str) { return parseInt(str) } function findExistingFile (...paths) { return paths.find((path) => path && existsSync(path)) } function getTransparentCorsSnippet (host, port, mode) { return ` ;(function () { var host = '${host}' var port = '${port}' var mode = '${mode}' if ( ! host) return var message = 'All ajax and fetch requests are redirected trough a local CORS proxy at http://' + host + ':' + port + ', do not use in production!' if (mode === 'production') { console.error(message) } else { console.debug(message) } ;(function (open) { XMLHttpRequest.prototype.open = function(...args) { args[1] = 'http://' + host + ':' + port + '/' + args[1] open.call(this, ...args) } })(XMLHttpRequest.prototype.open) ;(function (fetch) { window.fetch = function (...args) { args[0] = 'http://' + host + ':' + port + '/' + args[0] return fetch.call(this, ...args) } })(fetch) })(); ` } function printHeader (...args) { console.log('-----------------------------------------------------------------') console.log(...args) console.log('-----------------------------------------------------------------') } function getFreePorts (preferredPort = 3000, count = 1) { let ports = [] const gatherPorts = (preferredPort) => { return getFreePort(preferredPort) .then((port) => { ports.push(port) if (ports.length < count) { return gatherPorts(port + 1) } return ports }) } return gatherPorts(preferredPort) } function getFreePort (preferredPort = 3000) { return new Promise((resolve) => { portfinder.basePort = preferredPort portfinder.getPort((err, port) => { if (err) { throw new Error('Could not figure out free port') } resolve(port) }) }) } function getVersion () { return require('../package').version }