vite-plugin-open-in-editor
Version:
Vite plugin to open files directly in any editor (Cursor, VSCode, etc) from Alt+Click or Qwik dev tools.
97 lines (90 loc) • 3.07 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var path = require('path');
var child_process = require('child_process');
var fs = require('fs');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var path__default = /*#__PURE__*/_interopDefault(path);
var fs__default = /*#__PURE__*/_interopDefault(fs);
// src/parser.ts
function parseFileParam(fileParam) {
fileParam = decodeURIComponent(fileParam);
const lastColon = fileParam.lastIndexOf(":");
const secondLastColon = fileParam.lastIndexOf(":", lastColon - 1);
let column = "1";
let line = "1";
let rawPath = fileParam;
if (secondLastColon !== -1) {
column = fileParam.substring(lastColon + 1);
line = fileParam.substring(secondLastColon + 1, lastColon);
rawPath = fileParam.substring(0, secondLastColon);
}
rawPath = rawPath.replace(/\/+/g, "/");
rawPath = rawPath.replace(/\/src\/src\//, "/src/");
rawPath = rawPath.replace(/^\/?([a-zA-Z]):/, "$1:");
const normalizedPath = path__default.default.normalize(rawPath);
return { normalizedPath, line, column };
}
function openFile({
parsedFile,
editorBin = "cursor",
log = false
}) {
return new Promise((resolve, reject) => {
const { normalizedPath, line, column } = parsedFile;
if (!fs__default.default.existsSync(normalizedPath)) {
return reject(new Error(`File not found: ${normalizedPath}`));
}
let command;
if (editorBin === "code" || editorBin === "vscode") {
command = `code -g "${normalizedPath}:${line}:${column}"`;
} else {
command = `${editorBin} --goto "${normalizedPath}:${line}:${column}"`;
}
if (log) console.log("Executing:", command);
child_process.exec(command, (err) => {
if (err) {
return reject(err);
}
resolve();
});
});
}
// src/index.ts
function vitePluginOpenInEditor(options = {}) {
const { editorBin = "cursor", log = false } = options;
return {
name: "vite-plugin-open-in-editor",
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
var _a;
if ((_a = req.url) == null ? void 0 : _a.startsWith("/__open-in-editor")) {
const url = new URL(req.url, "http://localhost");
const fileParam = url.searchParams.get("file");
if (!fileParam) {
res.writeHead(400);
res.end("Missing file parameter");
return;
}
try {
const parsedFile = parseFileParam(fileParam);
await openFile({ parsedFile, editorBin, log });
res.writeHead(200);
res.end("Opened successfully");
} catch (err) {
console.error(err);
res.writeHead(500);
res.end(err.message);
}
return;
}
next();
});
}
};
}
var index_default = vitePluginOpenInEditor;
exports.default = index_default;
exports.openInEditor = vitePluginOpenInEditor;
//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map