Refactor normalizeOptions function; streamline query parameter extraction and improve boolean conversion logic for better clarity and performance
This commit is contained in:
@@ -25,55 +25,42 @@ const AMZ_DEFAULTS = {
|
||||
* - ipv6=false => удалить IPv6 из allowed-ips (и вообще не добавлять ipv6-части)
|
||||
**********************/
|
||||
function normalizeOptions(rawOptions) {
|
||||
// $options может быть объектом или строкой или чем-то странным.
|
||||
const opts = rawOptions ?? {};
|
||||
let q = "";
|
||||
|
||||
if (typeof opts === "string") {
|
||||
q = opts;
|
||||
} else if (typeof opts === "object") {
|
||||
// часто движки кладут query в одном из полей
|
||||
q =
|
||||
opts.query ||
|
||||
opts.params ||
|
||||
opts.search ||
|
||||
opts.hash ||
|
||||
opts.raw ||
|
||||
"";
|
||||
}
|
||||
// rawOptions может быть
|
||||
// 1) {}
|
||||
// 2) { meta: { url: "..." } }
|
||||
// 3) { url: "..." }
|
||||
const urlStr =
|
||||
(rawOptions && rawOptions.meta && rawOptions.meta.url) ||
|
||||
rawOptions.url ||
|
||||
"";
|
||||
|
||||
// Ищем part после #
|
||||
const hashIdx = urlStr.indexOf("#");
|
||||
const qstr = hashIdx >= 0 ? urlStr.slice(hashIdx + 1) : "";
|
||||
|
||||
// Если q выглядит как "dns=false&ipv6=false"
|
||||
const params = {};
|
||||
if (typeof q === "string" && q.includes("=")) {
|
||||
for (const part of q.split("&")) {
|
||||
const [k, v] = part.split("=");
|
||||
if (!k) continue;
|
||||
params[String(k).trim()] = (v ?? "").trim();
|
||||
}
|
||||
for (const part of qstr.split("&")) {
|
||||
const [k, v] = part.split("=");
|
||||
if (!k) continue;
|
||||
params[k.trim().toLowerCase()] = (v ?? "").trim();
|
||||
}
|
||||
|
||||
// Фоллбек: если $options уже содержит ключи dns/ipv6
|
||||
const get = (key) => {
|
||||
if (params[key] !== undefined) return params[key];
|
||||
if (opts[key] !== undefined) return opts[key];
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const asBool = (v, defaultVal = true) => {
|
||||
if (v === undefined || v === null || v === "") return defaultVal;
|
||||
if (typeof v === "boolean") return v;
|
||||
const s = String(v).toLowerCase().trim();
|
||||
if (["1", "true", "yes", "y", "on"].includes(s)) return true;
|
||||
if (["0", "false", "no", "n", "off"].includes(s)) return false;
|
||||
return defaultVal;
|
||||
const asBool = (v, def) => {
|
||||
if (v === undefined || v === "") return def;
|
||||
const s = String(v).toLowerCase();
|
||||
if (["1","true","yes","on"].includes(s)) return true;
|
||||
if (["0","false","no","off"].includes(s)) return false;
|
||||
return def;
|
||||
};
|
||||
|
||||
return {
|
||||
dns: asBool(get("dns"), true),
|
||||
ipv6: asBool(get("ipv6"), true),
|
||||
dns: asBool(params.dns, true),
|
||||
ipv6: asBool(params.ipv6, true),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**********************
|
||||
* Parsing WG INI blocks
|
||||
**********************/
|
||||
|
||||
Reference in New Issue
Block a user