2026-06-04 16:02:30 +08:00

103 lines
2.8 KiB
JavaScript

const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const dist = path.join(root, "dist");
const appDist = path.join(dist, "sms");
function normalizeText(value) {
return typeof value === "string" ? value.trim() : value ? String(value).trim() : "";
}
const mode = normalizeText(process.argv[2] || process.env.NODE_ENV || "production") || "production";
function assertNoLocalhost(name, value) {
if (!value) return;
if (/^(https?:\/\/)?(localhost|127\.0\.0\.1)(?::|\/|$)/i.test(value)) {
throw new Error(`${name} must not be localhost when building release package`);
}
}
function assertRequired(name, value) {
if (!value) {
throw new Error(`${name} is required`);
}
}
function copyDir(src, dest) {
fs.mkdirSync(dest, { recursive: true });
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
copyDir(srcPath, destPath);
} else if (entry.isFile()) {
fs.copyFileSync(srcPath, destPath);
}
}
}
function writeFile(filePath, content) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content);
}
function parseEnvValue(value) {
const text = normalizeText(value);
if (
(text.startsWith('"') && text.endsWith('"')) ||
(text.startsWith("'") && text.endsWith("'"))
) {
return text.slice(1, -1);
}
return text;
}
function loadEnvFile(fileName) {
const filePath = path.join(root, fileName);
if (!fs.existsSync(filePath)) return {};
const env = {};
const content = fs.readFileSync(filePath, "utf8");
for (const line of content.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const index = trimmed.indexOf("=");
if (index <= 0) continue;
const key = trimmed.slice(0, index).trim();
const value = parseEnvValue(trimmed.slice(index + 1));
env[key] = value;
}
return env;
}
const fileEnv = {
...loadEnvFile(".env"),
...loadEnvFile(`.env.${mode}`),
};
const apiBase = normalizeText(
process.env.api_url ||
fileEnv.api_url ||
"",
).replace(/\/+$/, "");
assertRequired("api_url", apiBase);
if (mode === "production") {
assertNoLocalhost("api_url", apiBase);
}
fs.rmSync(dist, { recursive: true, force: true });
fs.mkdirSync(appDist, { recursive: true });
fs.copyFileSync(path.join(root, "index.html"), path.join(appDist, "index.html"));
copyDir(path.join(root, "src"), path.join(appDist, "src"));
copyDir(path.join(root, "assets"), path.join(appDist, "assets"));
writeFile(
path.join(appDist, "config.js"),
`window.api_url=${JSON.stringify(apiBase)};\n`,
);
console.log(`Built ykt-sms to ${appDist}`);
console.log(`Route: /sms/{id}`);
console.log(`Mode: ${mode}`);
console.log(`API base: ${apiBase}`);