esbuild-plugin-extract-helpers
Version:
Esbuild plugin to extract cjs helpers (like tslib)
182 lines (179 loc) • 6.43 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/main/ts/index.ts
var ts_exports = {};
__export(ts_exports, {
default: () => extractHelpersPlugin,
extractHelpersPlugin: () => extractHelpersPlugin,
formatFile: () => formatFile,
formatHelpers: () => formatHelpers,
getRelativePath: () => getRelativePath,
onEnd: () => onEnd
});
module.exports = __toCommonJS(ts_exports);
// src/main/ts/plugin.ts
var import_node_path = __toESM(require("node:path"), 1);
var import_promises = __toESM(require("node:fs/promises"), 1);
var import_esbuild_plugin_utils = require("esbuild-plugin-utils");
var extractHelpersPlugin = (options = {}) => {
return {
name: "extract-helpers",
setup(build) {
const {
absWorkingDir = process.cwd(),
outdir,
cwd = outdir || absWorkingDir,
include = /./,
exclude = /^$/,
helper = "esblib.cjs"
} = __spreadValues(__spreadValues({}, build.initialOptions), options);
const opts = {
cwd,
include,
exclude,
helper
};
build.onEnd((result) => __async(this, null, function* () {
return onEnd(result, opts);
}));
}
};
};
var onEnd = (result, opts) => __async(void 0, null, function* () {
const outputFiles = yield (0, import_esbuild_plugin_utils.getOutputFiles)(result.outputFiles, opts.cwd);
const helpers = /* @__PURE__ */ new Map();
const helperRe = /^var (__\w+) = /;
const hook = {
on: "end",
pattern: opts.include,
// eslint-disable-next-line sonarjs/cognitive-complexity
transform(c, p) {
const { lines, header, body } = (0, import_esbuild_plugin_utils.parseContentsLayout)(c.trim());
const headerSize = header ? header.split("\n").length : 0;
const output = [];
const helperPath = getRelativePath(opts.cwd, p, opts.helper);
const capture = () => {
helpers.set(ref, helper);
helper = "";
ref = "";
};
let refs = [];
let helper = "";
let ref = "";
for (const line of lines.slice(headerSize)) {
if (ref) {
helper += line + "\n";
if (line.endsWith(";") && !line.startsWith(" ")) capture();
} else {
const match = helperRe.exec(line);
if (match) {
ref = match[1];
refs.push(ref);
helper = line + "\n";
if (line.endsWith(";")) capture();
} else {
output.push(line);
}
}
}
if (refs.length === 0) return c;
refs = refs.filter((r) => output.some((l) => l.includes(r)));
return formatFile(header, output, refs, helperPath);
}
};
const transformedFiles = (yield Promise.all(outputFiles.map((file) => __async(void 0, null, function* () {
return (0, import_esbuild_plugin_utils.transformFile)(file, [hook], opts.cwd);
})))).filter(Boolean);
yield (0, import_esbuild_plugin_utils.writeFiles)(transformedFiles);
yield import_promises.default.writeFile(import_node_path.default.join(opts.cwd, opts.helper), formatHelpers(helpers), "utf-8");
});
var getRelativePath = (from, to, ref) => {
const link = import_node_path.default.relative(from, import_node_path.default.join(import_node_path.default.dirname(to), ref));
return link.startsWith(".") ? link : "./" + link;
};
var formatHelpers = (helpers) => `
${[...helpers.values()].join("\n")}
module.exports = {
${(0, import_esbuild_plugin_utils.renderList)([...helpers.keys()])}
};
`;
var formatFile = (header, lines, refs, helperPath) => {
const body = lines.join("\n");
const helpers = `const {
${(0, import_esbuild_plugin_utils.renderList)(refs)}
} = require('${helperPath}');
`;
return [
header,
helpers,
body
].filter(Boolean).join("\n");
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
extractHelpersPlugin,
formatFile,
formatHelpers,
getRelativePath,
onEnd
});