dom-to-code
Version:
navigate to the code through the dom
101 lines (97 loc) • 3.19 kB
JavaScript
import { createFilter } from '@rollup/pluginutils';
import { createUnplugin } from 'unplugin';
import { r as resolveOption, t as transform } from './dom-to-code.6ebba5a3.mjs';
import launch from 'launch-editor';
import { O as OPEN_CODE_API } from './dom-to-code.2c4d4e6b.mjs';
import { pathResolve } from '../shared-utils.mjs';
const launchEditorMiddleware = (req, res, next) => {
if (req.url.startsWith(OPEN_CODE_API)) {
const filePath = typeof req.query.filePath === "string" ? req.query.filePath : "";
if (!filePath) {
res.statusCode = 500;
res.end('launch-editor-middleware: required query param "filePath" is missing.');
} else {
launch(filePath, () => console.log(
"To specify an editor, specify the EDITOR env variable"
));
res.end();
}
} else {
next();
}
};
const launchEditorMiddlewareForVite = (req, res, next) => {
if (req.url?.startsWith(OPEN_CODE_API)) {
const url = new URL(req.url, "http://domain.inspector");
const query = Object.fromEntries(url.searchParams.entries());
const filePath = typeof query.filePath === "string" ? query.filePath : "";
if (!filePath) {
res.statusCode = 500;
res.end('launch-editor-middleware: required query param "filePath" is missing.');
} else {
launch(filePath, () => console.log(
"To specify an editor, specify the EDITOR env variable"
));
res.end();
}
} else {
next();
}
};
const unplugin = createUnplugin((userOptions = {}, meta) => {
const options = resolveOption(userOptions);
const filter = createFilter(options.include, options.exclude);
return {
name: "unplugin-dom-to-code",
enforce: "pre",
transformInclude(id) {
if (meta.framework === "webpack")
return false;
return filter(id);
},
transform(code, id) {
try {
return transform(code, id, options);
} catch (e) {
this.error(e);
}
},
vite: {
configureServer(server) {
server.middlewares.use(launchEditorMiddlewareForVite);
}
},
webpack(compiler) {
const isWebpack5 = Number(compiler.webpack?.version?.[0]) >= 5 || false;
compiler.options.module.rules.push({
test: options.include,
use: [
{
loader: pathResolve("./webpack-loader.cjs"),
options: {
...options
}
}
]
});
if (!compiler.options.devServer)
compiler.options.devServer = {};
const { devServer } = compiler.options;
if (isWebpack5) {
const originSetup = devServer.setupMiddlewares;
devServer.setupMiddlewares = (middlewares, devServer2) => {
const result = originSetup ? originSetup(middlewares, devServer2) : middlewares;
result.unshift(launchEditorMiddleware);
return result;
};
} else {
const originBefore = devServer.before;
devServer.before = (app, server, compiler2) => {
app.use(launchEditorMiddleware);
originBefore?.(app, server, compiler2);
};
}
}
};
});
export { launchEditorMiddleware as l, unplugin as u };