react-cosmos
Version:
CLI for running React Cosmos inside webpack-powered apps
87 lines (70 loc) • 2.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.openFile = openFile;
var _launchEditor = _interopRequireDefault(require("@skidding/launch-editor"));
var _fs = _interopRequireDefault(require("fs"));
var _open = _interopRequireDefault(require("open"));
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function openFile(_ref) {
var cosmosConfig = _ref.cosmosConfig,
expressApp = _ref.expressApp;
expressApp.get('/_open', function (req, res) {
var _getReqQuery = getReqQuery(req),
filePath = _getReqQuery.filePath,
line = _getReqQuery.line,
column = _getReqQuery.column;
if (!filePath) {
res.status(400).send("File path missing");
return;
}
var absFilePath = resolveFilePath(cosmosConfig, filePath);
if (!_fs.default.existsSync(absFilePath)) {
res.status(404).send("File not found at path: ".concat(absFilePath));
return;
}
new Promise(function (resolve, reject) {
var file = "".concat(absFilePath, ":").concat(line, ":").concat(column);
(0, _launchEditor.default)(file, function (fileName, errorMsg) {
return reject(errorMsg);
}); // If launchEditor doesn't report error within 500ms we assume it worked
setTimeout(resolve, 500);
}) // Fall back to open in case launchEditor fails. launchEditor only works
// when the editor app is already open, but is favorable because it can
// open a code file on a specific line & column.
.catch(function (err) {
return (0, _open.default)(absFilePath);
}).catch(function (err) {
return res.status(500).send('Failed to open file');
}).then(function () {
return res.send();
});
});
}
function getReqQuery(req) {
var _req$query = req.query,
filePath = _req$query.filePath,
line = _req$query.line,
column = _req$query.column;
if (typeof filePath !== 'string') throw new Error('filePath missing');
return {
filePath: filePath,
line: typeof line === 'string' ? parseInt(line, 10) : 1,
column: typeof column === 'string' ? parseInt(column, 10) : 1
};
}
function resolveFilePath(cosmosConfig, filePath) {
// This heuristic is needed because the open file endpoint is used for
// multiple applications, which provide different file path types:
// 1. Edit fixture button: Sends path relative to Cosmos rootDir
// 2. react-error-overlay runtime error: Sends absolute path
// 3. react-error-overlay compile error: Sends path relative to CWD
if (_path.default.isAbsolute(filePath)) {
return filePath;
}
var cosmosRelPath = _path.default.join(cosmosConfig.rootDir, filePath);
var cwdRelPath = _path.default.join(process.cwd(), filePath);
return _fs.default.existsSync(cosmosRelPath) ? cosmosRelPath : cwdRelPath;
}