htmelt
Version:
Bundle your HTML assets with Esbuild and LightningCSS. Custom plugins, HMR platform, and more.
122 lines (120 loc) • 2.85 kB
JavaScript
// src/utils.mts
import {
findElements,
getAttribute,
getTagName
} from "@htmelt/plugin";
import cac from "cac";
import * as fs from "fs";
import * as net from "net";
import * as os from "os";
import * as path from "path";
function parseFlags(cli = cac()) {
const {
args: pre,
options: { "--": post, ...flags }
} = cli.parse();
flags.pre = pre;
flags.post = post;
return flags;
}
function createDir(file) {
fs.mkdirSync(path.dirname(file), { recursive: true });
}
function relative2(from, to) {
let result = path.relative(path.dirname(from), to);
if (!result.startsWith(".")) {
result = "./" + result;
}
return result;
}
function findExternalScripts(rootNode) {
return findElements(
rootNode,
(e) => getTagName(e) === "script" && !!getAttribute(e, "src")
);
}
function findFreeTcpPort() {
return new Promise((resolve2) => {
const srv = net.createServer();
srv.listen(0, "127.0.0.1", () => {
const freeTcpPort = srv.address().port;
srv.close(() => resolve2(freeTcpPort));
});
});
}
function resolveDevMapSources(map, root, resolveDir) {
let isOutOfRoot;
if (path.relative(root, resolveDir).startsWith("..")) {
isOutOfRoot = () => true;
} else {
const outOfRootPrefix = path.relative(resolveDir, path.dirname(root));
isOutOfRoot = (source) => source.startsWith(outOfRootPrefix);
}
map.sources = map.sources.map((source) => {
if (!source.includes(":") && isOutOfRoot(source)) {
return "/@fs" + path.resolve(resolveDir, source);
}
return source;
});
}
function setsEqual(a, b) {
if (a.size !== b.size) {
return false;
}
for (const item of a) {
if (!b.has(item)) {
return false;
}
}
return true;
}
function removePathSuffix(str) {
const suffixStart = str.indexOf("?");
if (suffixStart === -1) {
return str;
}
return str.slice(0, suffixStart);
}
function findDirectoryUp(fromDir, targetFiles, stopDirs) {
const homeDir = os.homedir();
const cwd = process.cwd();
let dir = fromDir;
while (true) {
if (dir === "/" || dir === homeDir || cwd.startsWith(dir + "/") || stopDirs?.has(dir)) {
return null;
}
const files = fs.readdirSync(dir);
if (files.some((file) => targetFiles.includes(file))) {
break;
}
dir = path.dirname(dir);
}
return dir;
}
var CaseInsensitiveMap = class extends Map {
get(key) {
return super.get(key.toLowerCase());
}
set(key, value) {
return super.set(key.toLowerCase(), value);
}
has(key) {
return super.has(key.toLowerCase());
}
delete(key) {
return super.delete(key.toLowerCase());
}
};
export {
parseFlags,
createDir,
relative2 as relative,
findExternalScripts,
findFreeTcpPort,
resolveDevMapSources,
setsEqual,
removePathSuffix,
findDirectoryUp,
CaseInsensitiveMap
};