unplugin-react-inspector
Version:
A plugin to improve the happiness index of react development
327 lines (318 loc) • 11.2 kB
JavaScript
;
var unplugin$1 = require('unplugin');
var MagicString = require('magic-string');
var core = require('@babel/core');
var transformTypescriptPlugin = require('@babel/plugin-transform-typescript');
var path = require('path');
var connect = require('connect');
var http = require('http');
var launchMiddleware = require('launch-editor-middleware');
var getPort = require('@qiuqfang/get-port');
var KEY_DATA = "data-inspector";
var DEFAULT_OPTIONS = {
injectClientEntryFile: "src/main.tsx",
enabled: false
};
// 统一路径分隔符
var normalizePath = function(path) {
return path.replace(/\\/g, "/");
};
var isArray = function(value) {
return Object.prototype.toString.call(value) === "[object Array]";
};
/* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable @typescript-eslint/no-non-null-assertion */ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _async_to_generator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _ts_generator(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([
n,
v
]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while(_)try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [
op[0] & 2,
t.value
];
switch(op[0]){
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [
0
];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [
6,
e
];
y = 0;
} finally{
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
var injectClient = function(param) {
var parseCode = param.parseCode, filePath = param.filePath, port = param.port, enabled = param.enabled, injectClientEntryFile = param.injectClientEntryFile;
if (isArray(injectClientEntryFile)) {
var flag = injectClientEntryFile.some(function(entryFile) {
return filePath.match(entryFile);
});
if (flag) {
var options = {
dataKey: KEY_DATA,
port: port,
enabled: enabled
};
parseCode.prepend("'use client';\nimport { createClient } from \"unplugin-react-inspector/client\";\ncreateClient(".concat(JSON.stringify(options), ");\n"));
}
} else if (filePath.match(injectClientEntryFile)) {
var options1 = {
dataKey: KEY_DATA,
port: port,
enabled: enabled
};
console.log("injectClientEntryFile", options1);
parseCode.prepend("'use client';\nimport { createClient } from \"unplugin-react-inspector/client\";\ncreateClient(".concat(JSON.stringify(options1), ");\n"));
}
return parseCode;
};
var injectInspectorInDom = function(code, filePath, magicCode) {
var relativePath = path.relative(process.cwd(), filePath);
return new Promise(function(resolve) {
var ast = core.parse(code, {
babelrc: false,
comments: true,
plugins: [
[
transformTypescriptPlugin,
{
isTSX: true,
allExtensions: true
}
]
]
});
core.traverse(ast, {
enter: function enter(param) {
var node = param.node;
if (node.type === "JSXElement") {
if (node.openingElement.attributes.some(function(attr) {
return attr.type !== "JSXSpreadAttribute" && attr.name.name === KEY_DATA;
})) return;
var insertPosition = node.openingElement.end - (node.openingElement.selfClosing ? 2 : 1);
var _node_loc_start = node.loc.start, line = _node_loc_start.line, column = _node_loc_start.column;
var content = " ".concat(KEY_DATA, '="').concat(relativePath, ":").concat(line, ":").concat(column, '"');
magicCode.prependLeft(insertPosition, content);
}
}
});
resolve(magicCode.toString());
});
};
function compile(code, filePath, _) {
return _compile.apply(this, arguments);
}
function _compile() {
_compile = _async_to_generator(function(code, filePath, param) {
var port, enabled, injectClientEntryFile, magicCode, result;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
port = param.port, enabled = param.enabled, injectClientEntryFile = param.injectClientEntryFile;
magicCode = new MagicString(code);
magicCode = injectClient({
parseCode: magicCode,
filePath: filePath,
port: port,
enabled: enabled,
injectClientEntryFile: injectClientEntryFile
});
return [
4,
injectInspectorInDom(code, filePath, magicCode)
];
case 1:
result = _state.sent();
return [
2,
result
];
}
});
});
return _compile.apply(this, arguments);
}
var createServer = function(port) {
var app = connect();
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
});
app.use(launchMiddleware());
http.createServer(app).listen(port);
};
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
var unplugin = unplugin$1.createUnplugin(function() {
var ops = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : DEFAULT_OPTIONS;
var defaultPort;
var options = _object_spread({}, DEFAULT_OPTIONS, ops);
if (options.enabled) {
// get port
getPort.getPort().then(function(port) {
console.log("port", port);
defaultPort = port;
// initialize server
createServer(port);
});
}
return {
name: "unplugin-react-inspector",
enforce: "pre",
transformInclude: function transformInclude(id) {
return id.endsWith(".jsx") || id.endsWith(".tsx");
},
transform: function transform(code, id) {
if (!id) return;
// normalize path
var filePath = normalizePath(id);
// filter
var isInspectorOverlay = filterInspectorOverlay(filePath);
if (!isInspectorOverlay && options.enabled) return compile(code, filePath, {
port: defaultPort,
enabled: options.enabled,
injectClientEntryFile: options.injectClientEntryFile
});
return code;
}
};
});
var filterInspectorOverlay = function(filePath) {
return !!filePath.match("unplugin-react-inspector/src/client") || !!filePath.match(".routes");
};
var vitePlugin = unplugin.vite;
var rspackPlugin = unplugin.rspack;
var webpackPlugin = unplugin.webpack; // export const rollupPlugin = unplugin.rollup as unknown;
// export const esbuildPlugin = unplugin.esbuild as unknown;
exports.rspackPlugin = rspackPlugin;
exports.vitePlugin = vitePlugin;
exports.webpackPlugin = webpackPlugin;