esbuild-pilet-plugin
Version:
Plugin for transforming pilets.
159 lines (154 loc) • 6.31 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
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);
// src/index.ts
var index_exports = {};
__export(index_exports, {
piletPlugin: () => piletPlugin
});
module.exports = __toCommonJS(index_exports);
var import_core = require("@babel/core");
var import_fs = require("fs");
var import_path = require("path");
// src/importmap-plugin.ts
var import_types = require("@babel/types");
function babelPlugin(importmap) {
return {
visitor: {
ImportDeclaration(path) {
path.traverse({
Literal(path2) {
if (path2.node.type === "StringLiteral") {
const name = path2.node.value;
const entry = importmap.find((m) => m.name === name);
if (entry) {
path2.replaceWith((0, import_types.stringLiteral)(entry.requireId || entry.id));
}
}
}
});
}
}
};
}
// src/banner-plugin.ts
var import_template = __toESM(require("@babel/template"));
function babelPlugin2(name, importmap, requireRef, schema, cssFiles) {
const debug = process.env.NODE_ENV === "development";
return {
visitor: {
Program(path) {
const deps = importmap.reduce((obj, dep) => {
obj[dep.id] = dep.ref;
return obj;
}, {});
if (schema === "v2") {
path.addComment("leading", `@pilet v:2(${requireRef},${JSON.stringify(deps)})`, true);
if (cssFiles.length > 0) {
const bundleUrl = `function(){try{throw new Error}catch(t){const e=(""+t.stack).match(/(https?|file|ftp|chrome-extension|moz-extension):\\/\\/[^)\\n]+/g);if(e)return e[0].replace(/^((?:https?|file|ftp|chrome-extension|moz-extension):\\/\\/.+)\\/[^\\/]+$/,"$1")+"/"}return"/"}`;
const stylesheet = [
`var d=document`,
`var __bundleUrl__=(${bundleUrl})()`,
`${JSON.stringify(cssFiles)}.forEach(cf=>{`,
`var u=__bundleUrl__+cf`,
`var e=d.createElement("link")`,
`e.setAttribute('data-origin', ${JSON.stringify(name)})`,
`e.type="text/css"`,
`e.rel="stylesheet"`,
`e.href=${debug ? 'u+"?_="+Math.random()' : "u"}`,
`d.head.appendChild(e)`,
`})`
].join(";\n");
path.node.body.push(import_template.default.ast(`(function(){${stylesheet}})()`));
}
} else if (schema === "v3") {
path.addComment("leading", `@pilet v:3(${requireRef},${JSON.stringify(deps)})`, true);
if (cssFiles.length > 0) {
path.node.body.push(import_template.default.ast(`export const styles = ${JSON.stringify(cssFiles)};`));
}
}
}
}
};
}
// src/index.ts
var piletPlugin = (options) => ({
name: "pilet-plugin",
setup(build) {
build.initialOptions.metafile = true;
build.onEnd(async (result) => {
const root = process.cwd();
if (result.metafile) {
const { outputs } = result.metafile;
const { entryPoints } = build.initialOptions;
const [name] = Object.keys(entryPoints);
const entryModule = (0, import_path.resolve)(root, entryPoints[name]);
const cssFiles = Object.keys(outputs).filter((m) => m.endsWith(".css")).map((m) => (0, import_path.basename)(m));
await Promise.all(
Object.keys(outputs).filter((m) => m.endsWith(".js")).map(async (file) => {
const { entryPoint } = outputs[file];
const isEntryModule = entryPoint && (0, import_path.resolve)(root, entryPoint) === entryModule;
const path = (0, import_path.resolve)(root, file);
const smname = `${file}.map`;
const smpath = (0, import_path.resolve)(root, smname);
const sourceMaps = smname in outputs;
const inputSourceMap = sourceMaps ? JSON.parse(await import_fs.promises.readFile(smpath, "utf8")) : void 0;
const plugins = [babelPlugin(options.importmap)];
if (isEntryModule) {
plugins.push(
babelPlugin2(options.name, options.importmap, options.requireRef, options.schema, cssFiles)
);
}
const { code, map } = await (0, import_core.transformFileAsync)(path, {
sourceMaps,
inputSourceMap,
comments: isEntryModule,
plugins,
presets: [
[
"@babel/preset-env",
{
modules: "systemjs"
}
]
]
});
if (map) {
await import_fs.promises.writeFile(smpath, JSON.stringify(map), "utf8");
}
await import_fs.promises.writeFile(path, code, "utf8");
})
);
}
});
}
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
piletPlugin
});
//# sourceMappingURL=index.cjs.map