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.
87 lines (84 loc) • 2.73 kB
JavaScript
import path from 'path';
import { exec } from 'child_process';
import fs from '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.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.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);
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;
export { index_default as default, vitePluginOpenInEditor as openInEditor };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map