beesbuild
Version:
构建工具链
70 lines (69 loc) • 1.72 kB
JavaScript
import { promises as fsp } from "node:fs";
import MagicString from "magic-string";
import { resolve } from "pathe";
const SHEBANG_RE = /^#![^\n]*/;
function shebangPlugin(options = {}) {
const shebangs = /* @__PURE__ */ new Map();
return {
name: "cli-shebang",
// @ts-ignore temp workaround
_options: options,
transform(code, mod) {
let shebang;
code = code.replace(SHEBANG_RE, (match) => {
shebang = match;
return "";
});
if (!shebang) {
return null;
}
shebangs.set(mod, shebang);
return { code, map: null };
},
renderChunk(code, chunk, { sourcemap }) {
if (options.preserve === false) {
return null;
}
const shebang = shebangs.get(chunk.facadeModuleId);
if (!shebang) {
return null;
}
const s = new MagicString(code);
s.prepend(`${shebang}
`);
return {
code: s.toString(),
map: sourcemap ? s.generateMap({ hires: true }) : null
};
},
async writeBundle(options2, bundle) {
var _a;
for (const [fileName, output] of Object.entries(bundle)) {
if (output.type !== "chunk") {
continue;
}
if ((_a = output.code) == null ? void 0 : _a.match(SHEBANG_RE)) {
const outFile = resolve(options2.dir, fileName);
await makeExecutable(outFile);
}
}
}
};
}
async function makeExecutable(filePath) {
await fsp.chmod(
filePath,
493
/* rwx r-x r-x */
).catch(() => {
});
}
function getShebang(code, append = "\n") {
const m = code.match(SHEBANG_RE);
return m ? m + append : "";
}
export {
getShebang,
makeExecutable,
shebangPlugin
};