mihomo-kit/luci/graph.js
2026-10-29 20:52:06 +03:00

1042 lines
41 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// A mihomo config as a left-to-right graph (LuCI "mihomo-kit → Граф", tools/graph.html):
// rules (top to bottom = match order) -> groups -> subscriptions and servers -> their
// dialer-proxy chains; dashed: what a subscription is downloaded through. The live state
// of the mihomo API (/proxies: what each group uses now, /connections: where the traffic
// goes) is drawn on top. model() and layout() are plain functions (node: tools/test-graph.js).
// Browser: a global "mkGraph"; node: module.exports.
(function (root, factory) {
var api = factory();
if (typeof module === 'object' && module.exports)
module.exports = api;
else
root.mkGraph = api;
})(this, function () {
'use strict';
// --- model -----------------------------------------------------------------
// outbounds mihomo has without a config entry: a node of their own per group or proxy
// using one (rank right after it), not one node every edge crosses the page to; a rule
// to one has no node at all
var BUILTIN = { 'DIRECT': 1, 'REJECT': 1, 'REJECT-DROP': 1, 'PASS': 1, 'COMPATIBLE': 1, 'GLOBAL': 1 };
var LOGIC = { 'AND': 1, 'OR': 1, 'NOT': 1, 'SUB-RULE': 1 };
// edges that place nodes left to right; fetch / file are drawn over the layout
var RANKED = { route: 1, member: 1, use: 1, dialer: 1 };
// "AND,((DOMAIN,a),(NETWORK,UDP)),X" -> parts split on commas outside parentheses
function splitTop(s) {
var out = [], depth = 0, cur = '';
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
if (c == '(')
depth++;
else if (c == ')')
depth--;
if (c == ',' && depth == 0) {
out.push(cur.trim());
cur = '';
} else
cur += c;
}
out.push(cur.trim());
return out;
}
// the way mihomo reads a rule line: TYPE,payload,target[,params]; MATCH,target
function parseRule(line, i) {
line = String(line);
var type = line.split(',')[0].trim().toUpperCase();
var t = LOGIC[type] ? splitTop(line) : line.split(',').map(function(x) { return x.trim(); });
if (type == 'MATCH')
return { i: i, type: type, payload: '', target: t[1], params: [], text: line };
return { i: i, type: type, payload: t[1] || '', target: t[2], params: t.slice(3), text: line };
}
// "RULE-SET" / "RuleSet" (the API's name) -> "ruleset"
function ruleKey(type, payload) {
return String(type).replace(/-/g, '').toLowerCase() + '|' + (payload || '');
}
// filter regex for an edge label: "(?i)🇷🇺|\\bru\\b|russia" -> "🇷🇺|ru|russia"
function prettyRe(re) {
return String(re).replace(/^\(\?i\)/, '').replace(/\\b/g, '').replace(/\\(.)/g, '$1');
}
function cut(s, n) {
s = String(s);
return s.length > n ? s.slice(0, n - 1) + '…' : s;
}
// subscription URL without its secret part: https://host/…
function maskUrl(u) {
var m = /^([a-z0-9+.-]+:\/\/[^\/?#]+)(.*)$/i.exec(String(u || ''));
return m ? m[1] + (m[2] && m[2] != '/' ? '/…' : '') : String(u || '');
}
function useLabel(g) {
var l = [];
if (g.filter)
l.push('∋ ' + prettyRe(g.filter));
if (g['exclude-filter'])
l.push('∌ ' + prettyRe(g['exclude-filter']));
if (g['exclude-type'])
l.push('− ' + g['exclude-type']);
return l.join(' ');
}
function proxySub(p) {
var s = p.type || '?';
if (p.server)
s += ' · ' + p.server;
else if (p['interface-name'])
s += ' · ' + p['interface-name'];
else if (p.hostname)
s += ' · ' + p.hostname;
return s;
}
// model(cfg) -> { nodes: {id: node}, list: [node], edges: [edge], ... }
// node { id, kind: rule|group|provider|proxy|builtin|missing, label, sub, data }
// edge { from, to, kind: route|member|use|dialer|fetch|file, label }
// ids: r:<n> rules, g:<name> groups, p:<name> proxies, v:<name> providers,
// b:<name>@<user id> built-in outbounds
function model(cfg) {
cfg = cfg || {};
var m = { nodes: {}, list: [], edges: [], byPair: {}, ruleIndex: {}, warnings: [] };
var groups = {}, proxies = {}, providers = cfg['proxy-providers'] || {};
var ruleProviders = cfg['rule-providers'] || {};
(cfg['proxy-groups'] || []).forEach(function(g) { if (g && g.name != null) groups[g.name] = g; });
(cfg.proxies || []).forEach(function(p) { if (p && p.name != null) proxies[p.name] = p; });
m.groups = groups;
m.proxies = proxies;
m.providers = providers;
var node = function(id, kind, label, sub, data) {
if (!m.nodes[id]) {
m.nodes[id] = { id: id, kind: kind, label: String(label), sub: sub || '', data: data || {} };
m.list.push(m.nodes[id]);
}
return m.nodes[id];
};
var edge = function(from, to, kind, label) {
var e = { from: from, to: to, kind: kind, label: label || '' };
m.edges.push(e);
m.byPair[from + '\n' + to] = m.byPair[from + '\n' + to] || e;
return e;
};
// a group or proxy by name, as mihomo resolves it (groups and proxies share names)
var ref = function(name, user) {
name = String(name);
if (groups[name])
return 'g:' + name;
if (proxies[name])
return 'p:' + name;
var id = 'b:' + name + '@' + user;
if (BUILTIN[name])
node(id, 'builtin', name);
else {
node(id, 'missing', name, 'нет в конфиге');
m.warnings.push(name + ': нет такой группы или прокси (' + user + ')');
}
return id;
};
m.ref = ref;
// rules: one node per run of the same type and target
var rules = (cfg.rules || []).map(parseRule), blocks = [];
rules.forEach(function(r) {
var b = blocks[blocks.length - 1];
if (b && b.type == r.type && b.target == r.target)
b.items.push(r);
else
blocks.push({ type: r.type, target: r.target, items: [ r ] });
});
blocks.forEach(function(b, n) {
var first = b.items[0], last = b.items[b.items.length - 1];
var label = b.items.length == 1 ? b.type + (first.payload ? ' ' + cut(first.payload, 26) : '')
: b.type + ' ×' + b.items.length;
if (b.type == 'RULE-SET' && b.items.length <= 2)
label = 'RULE-SET ' + b.items.map(function(r) { return r.payload; }).join(', ');
var id = 'r:' + n;
node(id, 'rule', label, '#' + (first.i + 1) + (b.items.length > 1 ? '–' + (last.i + 1) : '') + ' → ' + b.target,
{ items: b.items, ruleProviders: b.items.filter(function(r) { return r.type == 'RULE-SET'; })
.map(function(r) { return { name: r.payload, def: ruleProviders[r.payload] || null }; }) });
b.items.forEach(function(r) { m.ruleIndex[ruleKey(r.type, r.payload)] = id; });
// DIRECT / REJECT: the way ends at the rule (its line says where), no node of its own
if (BUILTIN[b.target] && !groups[b.target] && !proxies[b.target])
m.nodes[id].data.end = b.target;
else
edge(id, ref(b.target, id), 'route');
});
(cfg['proxy-groups'] || []).forEach(function(g) {
if (!g || g.name == null)
return;
var id = 'g:' + g.name;
node(id, 'group', g.name, g.type || '', { def: g });
(g.proxies || []).forEach(function(p) { edge(id, ref(p, id), 'member'); });
var use = (g.use || []).slice();
if (g['include-all'] || g['include-all-providers'])
Object.keys(providers).forEach(function(v) { if (use.indexOf(v) < 0) use.push(v); });
use.forEach(function(v) {
if (!providers[v])
m.warnings.push(g.name + ': нет провайдера ' + v);
node('v:' + v, 'provider', v, '', { def: providers[v] || {} });
edge(id, 'v:' + v, 'use', useLabel(g));
});
if (g['include-all'] || g['include-all-proxies'])
Object.keys(proxies).forEach(function(p) { edge(id, 'p:' + p, 'member', useLabel(g)); });
});
var paths = {};
Object.keys(providers).forEach(function(v) {
var d = providers[v] || {};
if (d.type == 'http' && d.path)
paths[d.path] = v;
});
Object.keys(providers).forEach(function(v) {
var d = providers[v] || {}, id = 'v:' + v;
var sub = d.type == 'http' ? maskUrl(d.url) : d.type == 'file' ? 'файл ' + (d.path || '') : d.type || '';
node(id, 'provider', v, sub, { def: d }).sub = sub;
var dialer = d.override && d.override['dialer-proxy'];
if (dialer)
edge(id, ref(dialer, id), 'dialer', 'через');
if (d.type == 'http' && d.proxy)
edge(id, ref(d.proxy, id), 'fetch', 'качается через');
// [MY] nodes: a file provider reading what another one downloads
if (d.type == 'file' && paths[d.path] && paths[d.path] != v)
edge(id, 'v:' + paths[d.path], 'file', 'тот же файл');
});
(cfg.proxies || []).forEach(function(p) {
if (!p || p.name == null)
return;
var id = 'p:' + p.name;
node(id, 'proxy', p.name, proxySub(p), { def: p });
if (p['dialer-proxy'])
edge(id, ref(p['dialer-proxy'], id), 'dialer', 'через');
});
return m;
}
// --- layout ----------------------------------------------------------------
// isotonic regression (pool adjacent violators): positions as close as possible to
// want[], in the same order, at least sep[i] apart (sep[i] between i and i+1)
function pack(want, sep) {
var n = want.length, off = [ 0 ], i;
for (i = 1; i < n; i++)
off[i] = off[i - 1] + sep[i - 1];
var blocks = [];
for (i = 0; i < n; i++) {
blocks.push({ sum: want[i] - off[i], n: 1, from: i });
while (blocks.length > 1) {
var b = blocks[blocks.length - 1], a = blocks[blocks.length - 2];
if (a.sum / a.n <= b.sum / b.n)
break;
a.sum += b.sum;
a.n += b.n;
blocks.pop();
}
}
var out = [];
blocks.forEach(function(b) {
for (var k = 0; k < b.n; k++)
out[b.from + k] = b.sum / b.n + off[b.from + k];
});
return out;
}
// layout(m, measure) -> { nodes: {id: {x, y, w, h}}, edges: [{e, pts}], width, height }
// Sugiyama-style: ranks by the longest path from the rules, dummy nodes on long edges,
// barycenter sweeps for the order, then y as close to the neighbours as the order allows.
function layout(m, measure) {
measure = measure || function(s, px) { return String(s).length * px * 0.6; };
var NODE_H = 36, GAP_Y = 8, GAP_X = 90, DUMMY_H = 6;
var out = {}, succ = {}, pred = {};
m.list.forEach(function(n) { succ[n.id] = []; pred[n.id] = []; });
m.edges.forEach(function(e) {
if (!RANKED[e.kind] || !succ[e.from] || !succ[e.to] || e.from == e.to)
return;
succ[e.from].push(e.to);
pred[e.to].push(e.from);
});
// rank: rules 0; else 1 + the deepest predecessor (back edges of a cycle ignored)
var rank = {}, state = {};
var visit = function(id) {
if (state[id] == 2)
return rank[id];
if (state[id] == 1)
return -1;
state[id] = 1;
var r = m.nodes[id].kind == 'rule' ? 0 : 1;
if (m.nodes[id].kind != 'rule')
pred[id].forEach(function(p) { var pr = visit(p); if (pr >= 0) r = Math.max(r, pr + 1); });
state[id] = 2;
rank[id] = r;
return r;
};
m.list.forEach(function(n) { visit(n.id); });
// a node no rule leads to (BOOT-AUTO, unused groups) sits just left of what it uses
var pull = true;
while (pull) {
pull = false;
m.list.forEach(function(n) {
if (pred[n.id].length || n.kind == 'rule' || !succ[n.id].length)
return;
var r = Math.min.apply(null, succ[n.id].map(function(s) { return rank[s]; })) - 1;
if (r > rank[n.id]) {
rank[n.id] = r;
pull = true;
}
});
}
// layers with dummies; segs: per ranked edge the chain of ids it passes
var maxRank = 0, layers = [], chain = [];
m.list.forEach(function(n) { maxRank = Math.max(maxRank, rank[n.id]); });
for (var r = 0; r <= maxRank; r++)
layers.push([]);
var info = {};
m.list.forEach(function(n) {
info[n.id] = { id: n.id, rank: rank[n.id], up: [], down: [], h: NODE_H, node: n };
});
// first seen from the rules, top to bottom: a sensible starting order
var seen = {}, queue = m.list.filter(function(n) { return n.kind == 'rule'; }).map(function(n) { return n.id; });
var order = [];
while (queue.length) {
var id = queue.shift();
if (seen[id])
continue;
seen[id] = 1;
order.push(id);
succ[id].forEach(function(s) { if (!seen[s]) queue.push(s); });
}
m.list.forEach(function(n) { if (!seen[n.id]) order.push(n.id); });
order.forEach(function(id) { layers[info[id].rank].push(info[id]); });
var dn = 0;
m.edges.forEach(function(e, k) {
if (!RANKED[e.kind] || !info[e.from] || !info[e.to] || e.from == e.to)
return;
var a = info[e.from], b = info[e.to];
if (b.rank <= a.rank) {
chain[k] = [ a, b ];
return;
}
var c = [ a ], prev = a;
for (var rr = a.rank + 1; rr < b.rank; rr++) {
var d = { id: '~' + (dn++), rank: rr, up: [ prev ], down: [], h: DUMMY_H, dummy: true };
prev.down.push(d);
layers[rr].push(d);
c.push(d);
prev = d;
}
prev.down.push(b);
b.up.push(prev);
c.push(b);
chain[k] = c;
});
var pos = function(layer) { layer.forEach(function(v, i) { v.ord = i; }); };
layers.forEach(pos);
var bary = function(v, dir) {
var ns = dir == 'up' ? v.up : v.down;
if (!ns.length)
return v.ord;
return ns.reduce(function(s, u) { return s + u.ord; }, 0) / ns.length;
};
var sweep = function(r, dir) {
var l = layers[r];
l.forEach(function(v) { v.bc = bary(v, dir); });
l.sort(function(a, b) { return a.bc - b.bc || a.ord - b.ord; });
pos(l);
};
for (var it = 0; it < 6; it++) {
for (r = 1; r <= maxRank; r++)
sweep(r, 'up');
for (r = maxRank - 1; r >= 1; r--)
sweep(r, 'down');
}
for (r = 1; r <= maxRank; r++)
sweep(r, 'up');
// x: columns as wide as their widest node
var x = 0;
layers.forEach(function(l) {
var w = 60;
l.forEach(function(v) {
if (v.dummy) {
v.w = 0;
return;
}
// groups: room for the live "→ node · 42 мс"
v.w = Math.ceil(Math.max(measure(v.node.label, 12) + 22, measure(v.node.sub, 10.5) + 22,
v.node.kind == 'group' ? 150 : 64));
w = Math.max(w, v.w);
});
l.forEach(function(v) { v.x = x + (v.dummy ? w / 2 : 0); });
x += Math.min(w, 340) + GAP_X;
});
// y: rules stacked in match order, the rest close to their neighbours
var center = function(v) { return v.y + v.h / 2; };
var place = function(l, want) {
var sep = [];
for (var i = 0; i + 1 < l.length; i++)
sep.push(l[i].h / 2 + l[i + 1].h / 2 + GAP_Y);
var c = pack(want, sep);
l.forEach(function(v, i) { v.y = c[i] - v.h / 2; });
};
var y = 0;
layers[0].forEach(function(v) { v.y = y; y += v.h + GAP_Y; });
var near = function(v, sides) {
var ns = [];
sides.forEach(function(s) { ns = ns.concat(v[s]); });
ns = ns.filter(function(u) { return u.y != null; });
return ns.length ? ns.reduce(function(s, u) { return s + center(u); }, 0) / ns.length : null;
};
var settle = function(r, sides) {
var l = layers[r], last = 0;
var want = l.map(function(v) {
var c = near(v, sides);
if (c == null)
c = v.y != null ? center(v) : last;
last = c;
return c;
});
place(l, want);
};
for (r = 1; r <= maxRank; r++)
settle(r, [ 'up' ]);
for (it = 0; it < 3; it++) {
for (r = maxRank - 1; r >= 1; r--)
settle(r, [ 'up', 'down' ]);
for (r = 1; r <= maxRank; r++)
settle(r, [ 'up', 'down' ]);
}
var minY = Infinity, maxY = -Infinity, maxX = 0;
layers.forEach(function(l) {
l.forEach(function(v) {
minY = Math.min(minY, v.y);
maxY = Math.max(maxY, v.y + v.h);
maxX = Math.max(maxX, v.x + v.w);
});
});
layers.forEach(function(l) { l.forEach(function(v) { v.y -= minY; }); });
m.list.forEach(function(n) {
var v = info[n.id];
out[n.id] = { x: v.x, y: v.y, w: v.w, h: v.h, rank: v.rank };
});
// edges: through the dummies; the ends spread over the node's side by the far end's y
var edges = m.edges.map(function(e, k) {
var c = chain[k];
return { e: e, pts: c ? c.map(function(v) { return { x: v.x, y: center(v), w: v.w, id: v.id }; }) : null };
});
var ports = {};
edges.forEach(function(le) {
if (!le.pts)
return;
var a = le.pts[0], b = le.pts[le.pts.length - 1];
(ports[a.id + '>'] = ports[a.id + '>'] || []).push({ p: a, other: le.pts[1].y });
(ports[b.id + '<'] = ports[b.id + '<'] || []).push({ p: b, other: le.pts[le.pts.length - 2].y });
});
Object.keys(ports).forEach(function(k) {
var l = ports[k], h = NODE_H * 0.6;
l.sort(function(a, b) { return a.other - b.other; });
l.forEach(function(q, i) {
q.p.dy = l.length > 1 ? -h / 2 + h * i / (l.length - 1) : 0;
});
});
edges.forEach(function(le) {
if (!le.pts)
return;
le.pts = le.pts.map(function(p, i) {
var last = i == le.pts.length - 1;
return { x: i == 0 ? p.x + p.w : p.x, y: p.y + (i == 0 || last ? p.dy || 0 : 0) };
});
});
return { nodes: out, edges: edges, width: maxX, height: maxY - minY, ranks: maxRank + 1 };
}
// --- live state (mihomo API) -------------------------------------------------
// live(m, proxies, connections) -> what each group uses, alive nodes per provider and
// where the connections go: { now: {id: name}, edges: {i: {n, rate}}, nodes: {id: {n}}, ... }
// proxies: GET /proxies .proxies; connections: GET /connections .connections
// prev: the previous result (byte counters -> rates)
function live(m, proxies, connections, prev) {
proxies = proxies || {};
var L = { now: {}, delay: {}, provider: {}, edges: {}, nodes: {}, bytes: {}, total: 0, unmatched: 0, at: Date.now() };
var edgeIndex = {};
m.edges.forEach(function(e, i) { edgeIndex[e.from + '\n' + e.to] = i; });
var lastDelay = function(p) {
var h = p && p.history;
return h && h.length ? h[h.length - 1].delay : 0;
};
Object.keys(proxies).forEach(function(name) {
var p = proxies[name];
if (m.groups[name] && p.now != null) {
L.now['g:' + name] = p.now;
L.delay['g:' + name] = lastDelay(proxies[p.now]);
}
var pv = p['provider-name'];
if (pv && m.providers[pv] && !m.groups[name]) {
var s = L.provider['v:' + pv] = L.provider['v:' + pv] || { n: 0, alive: 0 };
s.n++;
if (p.alive)
s.alive++;
}
});
// a proxy name of the API -> node id: groups, own proxies, provider nodes, built-ins
var idOf = function(name, user) {
if (m.groups[name])
return 'g:' + name;
if (m.proxies[name])
return 'p:' + name;
var p = proxies[name];
if (p && p['provider-name'] && m.providers[p['provider-name']])
return 'v:' + p['provider-name'];
return 'b:' + name + '@' + user;
};
// from a node on: the dialer-proxy chain and the groups' current choice
var tail = function(id, path) {
for (var guard = 0; guard < 24; guard++) {
var n = m.nodes[id], next = null;
if (!n)
break;
if (n.kind == 'group' && L.now[id] != null)
next = idOf(L.now[id], id);
else if (n.kind == 'proxy' || n.kind == 'provider') {
var d = n.kind == 'proxy' ? n.data.def['dialer-proxy']
: n.data.def.override && n.data.def.override['dialer-proxy'];
if (d)
next = m.ref(d, id);
}
if (!next || path.indexOf(next) >= 0)
break;
path.push(next);
id = next;
}
return path;
};
L.tail = function(id) { return tail(id, [ id ]); };
var prevBytes = prev && prev.bytes || {}, dt = prev ? (L.at - prev.at) / 1000 : 0;
(connections || []).forEach(function(c) {
var rid = m.ruleIndex[ruleKey(c.rule || '', c.rulePayload || '')];
if (!rid) {
L.unmatched++;
return;
}
var b = (c.upload || 0) + (c.download || 0);
L.bytes[c.id] = b;
var rate = dt > 0 && prevBytes[c.id] != null ? Math.max(0, b - prevBytes[c.id]) / dt : 0;
var path = [ rid ], user = rid;
(c.chains || []).slice().reverse().forEach(function(name) {
var id = idOf(name, user);
if (m.nodes[id] && path[path.length - 1] != id)
path.push(id);
user = id;
});
tail(path[path.length - 1], path);
L.total++;
path.forEach(function(id, i) {
var s = L.nodes[id] = L.nodes[id] || { n: 0, rate: 0 };
s.n++;
s.rate += rate;
if (i == 0)
return;
var k = edgeIndex[path[i - 1] + '\n' + id];
if (k == null)
return;
var es = L.edges[k] = L.edges[k] || { n: 0, rate: 0 };
es.n++;
es.rate += rate;
});
});
return L;
}
// --- view --------------------------------------------------------------------
var CSS = '' +
'.mkg{--bg:#fff;--fg:#1f2328;--mute:#6b7280;--line:#9aa4b2;--rule:#f3f4f6;--rule-b:#c9ced6;' +
'--group:#e8f0ff;--group-b:#4c7cf0;--prov:#e7f6ec;--prov-b:#2f9e5b;--proxy:#fff3df;--proxy-b:#d9900f;' +
'--bi:#eef0f3;--bi-b:#9aa4b2;--miss:#ffe3e3;--miss-b:#e03131;--dial:#8b5cf6;--fetch:#2f9e5b;' +
'--now:#4c7cf0;--flow:#f76707;position:relative;color:var(--fg);font:12px/1.3 system-ui,-apple-system,"Segoe UI",sans-serif}' +
'.mkg.mkg-dark{--bg:#16181d;--fg:#e6e8eb;--mute:#9aa1ab;--line:#6b7480;--rule:#23272e;--rule-b:#454c57;' +
'--group:#1b2740;--group-b:#5b8cff;--prov:#15301f;--prov-b:#3fbf74;--proxy:#33270f;--proxy-b:#f0a830;' +
'--bi:#262a31;--bi-b:#6b7480;--miss:#3b1717;--miss-b:#ff6b6b;--dial:#a78bfa;--fetch:#3fbf74;--now:#5b8cff;--flow:#ff922b}' +
'.mkg-bar{display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;margin:0 0 6px}' +
'.mkg-bar label{display:inline-flex;gap:4px;align-items:center;cursor:pointer}' +
'.mkg-legend{display:flex;flex-wrap:wrap;gap:4px 12px;color:var(--mute);font-size:11px}' +
'.mkg-legend i{display:inline-block;width:10px;height:10px;border-radius:3px;border:1.5px solid;vertical-align:-1px;margin-right:4px}' +
'.mkg-legend s{display:inline-block;width:22px;height:0;border-top:2px solid;vertical-align:3px;margin-right:4px;text-decoration:none}' +
'.mkg-stage{position:relative;height:72vh;min-height:360px;border:1px solid var(--rule-b);border-radius:6px;overflow:hidden;' +
'background:var(--bg);touch-action:none;cursor:grab}' +
'.mkg-stage.drag{cursor:grabbing}' +
'.mkg svg{display:block;width:100%;height:100%;user-select:none}' +
'.mkg .n rect{stroke-width:1.5}' +
'.mkg .n text{fill:var(--fg);font-size:12px;font-weight:600}' +
'.mkg .n text.s{fill:var(--mute);font-size:10.5px;font-weight:400}' +
'.mkg .n{cursor:pointer}' +
'.mkg .n.rule rect{fill:var(--rule);stroke:var(--rule-b)}' +
'.mkg .n.group rect{fill:var(--group);stroke:var(--group-b)}' +
'.mkg .n.provider rect{fill:var(--prov);stroke:var(--prov-b)}' +
'.mkg .n.proxy rect{fill:var(--proxy);stroke:var(--proxy-b)}' +
'.mkg .n.builtin rect{fill:var(--bi);stroke:var(--bi-b)}' +
'.mkg .n.missing rect{fill:var(--miss);stroke:var(--miss-b)}' +
'.mkg .n.reject text.s{fill:var(--miss-b)}' +
'.mkg .n .live-bits rect.badge{fill:var(--flow);stroke:none}.mkg .n .live-bits text.bt{fill:#fff;font-size:10px;font-weight:700}' +
'.mkg .e{fill:none;stroke:var(--line);stroke-width:1.3;stroke-opacity:.55}' +
'.mkg .e.dialer{stroke:var(--dial);stroke-dasharray:6 3;stroke-opacity:.8}' +
'.mkg .e.fetch{stroke:var(--fetch);stroke-dasharray:2 4;stroke-width:1.5;stroke-opacity:.8}' +
'.mkg .e.file{stroke:var(--fetch);stroke-dasharray:1 3;stroke-opacity:.6}' +
'.mkg .lbl{fill:var(--mute);font-size:10px;paint-order:stroke;stroke:var(--bg);stroke-width:3px;stroke-linejoin:round}' +
'.mkg .live .e.off{stroke-opacity:.15}' +
'.mkg .e.now{stroke:var(--now);stroke-opacity:.95;stroke-width:2}' +
'.mkg .e.flow{stroke:var(--flow);stroke-opacity:.95;stroke-dasharray:8 6;animation:mkg-flow 1s linear infinite}' +
'@keyframes mkg-flow{to{stroke-dashoffset:-14}}' +
'@media (prefers-reduced-motion:reduce){.mkg .e.flow{animation:none}}' +
'.mkg .focus .n:not(.hl){opacity:.25}.mkg .focus .e:not(.hl),.mkg .focus .lbl:not(.hl){opacity:.08}' +
'.mkg .focus .e.hl{stroke-opacity:1;stroke-width:2.2}' +
'.mkg .n.sel rect{stroke-width:3}' +
'.mkg-info{margin-top:8px;padding:8px 10px;border:1px solid var(--rule-b);border-radius:6px;background:var(--bg);display:none}' +
'.mkg-info h4{margin:0 0 4px;font-size:13px}' +
'.mkg-info table{border-collapse:collapse}.mkg-info td{padding:1px 10px 1px 0;vertical-align:top}' +
'.mkg-info td:first-child{color:var(--mute);white-space:nowrap}' +
'.mkg-info code{font-size:11px;word-break:break-all}' +
'.mkg-info ul{margin:2px 0;padding-left:18px;max-height:14em;overflow:auto}' +
'.mkg-warn{color:var(--miss-b);font-size:11px}' +
'.mkg-zoom{position:absolute;right:8px;bottom:8px;display:flex;gap:4px}' +
'.mkg-zoom button{min-width:28px}';
function el(tag, attrs, kids) {
var svg = /^(svg|g|rect|text|path|defs|marker|title|tspan)$/.test(tag);
var e = svg ? document.createElementNS('http://www.w3.org/2000/svg', tag) : document.createElement(tag);
Object.keys(attrs || {}).forEach(function(k) {
if (k == 'text')
e.textContent = attrs[k];
else if (/^on/.test(k))
e.addEventListener(k.slice(2), attrs[k]);
else if (attrs[k] != null)
e.setAttribute(k, attrs[k]);
});
(kids || []).forEach(function(c) { if (c != null) e.appendChild(typeof c == 'string' ? document.createTextNode(c) : c); });
return e;
}
function fmtRate(b) {
if (b < 1024)
return Math.round(b) + ' Б/с';
if (b < 1048576)
return (b / 1024).toFixed(b < 10240 ? 1 : 0) + ' КБ/с';
return (b / 1048576).toFixed(1) + ' МБ/с';
}
function isDark(node) {
for (var n = node; n && n.nodeType == 1; n = n.parentNode) {
var c = getComputedStyle(n).backgroundColor;
var m = /rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?/.exec(c);
if (m && (m[4] == null || +m[4] > 0.5))
return (0.299 * m[1] + 0.587 * m[2] + 0.114 * m[3]) < 128;
}
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}
// view(container) -> { show(cfg), live(proxies, connections), destroy() }
function view(container) {
if (!document.getElementById('mkg-style'))
document.head.appendChild(el('style', { id: 'mkg-style', text: CSS }));
var canvas = document.createElement('canvas').getContext('2d');
var measure = function(s, px) {
canvas.font = (px == 12 ? '600 ' : '') + px + 'px system-ui,-apple-system,"Segoe UI",sans-serif';
return canvas.measureText(String(s)).width;
};
var root = el('div', { 'class': 'mkg' });
var showLive = el('input', { type: 'checkbox', checked: 'checked' });
var onlyNow = el('input', { type: 'checkbox' });
var stat = el('span', { 'class': 'mkg-legend' });
var legend = el('span', { 'class': 'mkg-legend' }, [
el('span', {}, [ el('i', { style: 'background:var(--rule);border-color:var(--rule-b)' }), 'правила (сверху вниз — порядок)' ]),
el('span', {}, [ el('i', { style: 'background:var(--group);border-color:var(--group-b)' }), 'группы' ]),
el('span', {}, [ el('i', { style: 'background:var(--prov);border-color:var(--prov-b)' }), 'подписки' ]),
el('span', {}, [ el('i', { style: 'background:var(--proxy);border-color:var(--proxy-b)' }), 'серверы' ]),
el('span', {}, [ el('s', { style: 'border-color:var(--dial);border-top-style:dashed' }), 'dialer-proxy' ]),
el('span', {}, [ el('s', { style: 'border-color:var(--fetch);border-top-style:dotted' }), 'качается через' ]),
el('span', {}, [ el('s', { style: 'border-color:var(--now)' }), 'выбрано сейчас' ]),
el('span', {}, [ el('s', { style: 'border-color:var(--flow);border-top-style:dashed' }), 'трафик' ])
]);
var bar = el('div', { 'class': 'mkg-bar' }, [
el('label', {}, [ showLive, 'живое состояние' ]),
el('label', { title: 'скрыть члены групп, которые сейчас не выбраны' }, [ onlyNow, 'только выбранное' ]),
stat
]);
var svg = el('svg', {});
var world = el('g', {});
svg.appendChild(el('defs', {}, [
el('marker', { id: 'mkg-arrow', viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: 'auto-start-reverse' },
[ el('path', { d: 'M0,0L10,5L0,10z', style: 'fill:var(--fetch)' }) ])
]));
svg.appendChild(world);
var stage = el('div', { 'class': 'mkg-stage' }, [ svg ]);
var info = el('div', { 'class': 'mkg-info' });
var warn = el('div', { 'class': 'mkg-warn' });
root.appendChild(bar);
root.appendChild(legend);
root.appendChild(el('div', { style: 'height:6px' }));
root.appendChild(stage);
root.appendChild(warn);
root.appendChild(info);
container.appendChild(root);
root.classList.toggle('mkg-dark', isDark(container));
var m = null, lay = null, L = null, nodeEls = {}, edgeEls = [], selected = null;
var view = { x: 0, y: 0, k: 1 };
var apply = function() { world.setAttribute('transform', 'translate(' + view.x + ',' + view.y + ') scale(' + view.k + ')'); };
var fit = function() {
if (!lay)
return;
var W = stage.clientWidth || 800, H = stage.clientHeight || 500, pad = 16;
view.k = Math.min(1.2, (W - pad * 2) / Math.max(lay.width, 1), (H - pad * 2) / Math.max(lay.height, 1));
view.k = Math.max(view.k, 0.35);
view.x = pad;
view.y = Math.max(pad, (H - lay.height * view.k) / 2);
apply();
};
stage.appendChild(el('div', { 'class': 'mkg-zoom' }, [
el('button', { 'class': 'btn cbi-button', title: 'крупнее', onclick: function() { zoomAt(1.25); } }, [ '+' ]),
el('button', { 'class': 'btn cbi-button', title: 'мельче', onclick: function() { zoomAt(0.8); } }, [ '−' ]),
el('button', { 'class': 'btn cbi-button', title: 'весь граф', onclick: fit }, [ '⤢' ])
]));
var zoomAt = function(f, cx, cy) {
if (cx == null) {
cx = stage.clientWidth / 2;
cy = stage.clientHeight / 2;
}
var k = Math.max(0.2, Math.min(3, view.k * f));
view.x = cx - (cx - view.x) * k / view.k;
view.y = cy - (cy - view.y) * k / view.k;
view.k = k;
apply();
};
stage.addEventListener('wheel', function(ev) {
ev.preventDefault();
var r = stage.getBoundingClientRect();
zoomAt(Math.exp(-ev.deltaY * 0.0015), ev.clientX - r.left, ev.clientY - r.top);
}, { passive: false });
var drag = null;
stage.addEventListener('pointerdown', function(ev) {
if (ev.target.closest && ev.target.closest('.n, button'))
return;
drag = { x: ev.clientX, y: ev.clientY, vx: view.x, vy: view.y, moved: false };
stage.classList.add('drag');
stage.setPointerCapture(ev.pointerId);
});
stage.addEventListener('pointermove', function(ev) {
if (!drag)
return;
view.x = drag.vx + ev.clientX - drag.x;
view.y = drag.vy + ev.clientY - drag.y;
drag.moved = drag.moved || Math.abs(ev.clientX - drag.x) + Math.abs(ev.clientY - drag.y) > 3;
apply();
});
var endDrag = function() {
if (drag && !drag.moved)
select(null);
drag = null;
stage.classList.remove('drag');
};
stage.addEventListener('pointerup', endDrag);
stage.addEventListener('pointercancel', endDrag);
// everything a node reaches and everything that reaches it
var reach = function(id) {
var set = {}, es = {};
var walk = function(start, fwd) {
var stack = [ start ];
while (stack.length) {
var cur = stack.pop();
m.edges.forEach(function(e, i) {
if (e.kind == 'fetch' || e.kind == 'file')
return;
if (onlyNow.checked && edgeEls[i] && edgeEls[i].path.style.display == 'none')
return;
var a = fwd ? e.from : e.to, b = fwd ? e.to : e.from;
if (a != cur)
return;
es[i] = 1;
if (!set[b]) {
set[b] = 1;
stack.push(b);
}
});
}
};
set[id] = 1;
walk(id, true);
walk(id, false);
// fetch / file edges of the node itself
m.edges.forEach(function(e, i) {
if ((e.kind == 'fetch' || e.kind == 'file') && (e.from == id || e.to == id)) {
es[i] = 1;
set[e.from] = set[e.to] = 1;
}
});
return { nodes: set, edges: es };
};
var focus = function(id) {
world.classList.toggle('focus', !!id);
var r = id ? reach(id) : { nodes: {}, edges: {} };
Object.keys(nodeEls).forEach(function(k) { nodeEls[k].classList.toggle('hl', !!r.nodes[k]); });
edgeEls.forEach(function(x, i) {
if (!x)
return;
x.path.classList.toggle('hl', !!r.edges[i]);
if (x.label)
x.label.classList.toggle('hl', !!r.edges[i]);
});
};
var row = function(k, v) { return el('tr', {}, [ el('td', { text: k }), el('td', {}, [].concat(v)) ]); };
var details = function(n) {
var d = n.data.def || {}, rows = [];
var kind = { rule: 'Правила', group: 'Группа', provider: 'Подписка (proxy-provider)', proxy: 'Сервер',
builtin: 'Встроенный выход', missing: 'Не найдено' }[n.kind];
if (n.kind == 'rule') {
rows.push(row('куда', n.data.items[0].target));
n.data.ruleProviders.forEach(function(rp) {
if (rp.def)
rows.push(row('rule-set ' + rp.name, el('code', { text: (rp.def.type || '') + ' ' + (rp.def.behavior || '') + ' ' +
(rp.def.url ? maskUrl(rp.def.url) : rp.def.path || '') })));
});
rows.push(row('строки', el('ul', {}, n.data.items.map(function(r) { return el('li', {}, [ el('code', { text: '#' + (r.i + 1) + ' ' + r.text }) ]); }))));
} else if (n.kind == 'group') {
rows.push(row('тип', d.type || ''));
if (d.proxies)
rows.push(row('proxies', d.proxies.join(', ')));
if (d.use)
rows.push(row('use', d.use.join(', ')));
[ 'filter', 'exclude-filter', 'exclude-type', 'url', 'interval', 'tolerance', 'lazy' ].forEach(function(k) {
if (d[k] != null)
rows.push(row(k, el('code', { text: String(d[k]) })));
});
if (L && L.now[n.id] != null)
rows.push(row('сейчас', L.now[n.id] + (L.delay[n.id] ? ' · ' + L.delay[n.id] + ' мс' : '')));
} else if (n.kind == 'provider') {
rows.push(row('тип', d.type || ''));
if (d.url)
rows.push(row('url', el('code', { text: maskUrl(d.url) })));
if (d.path)
rows.push(row('path', el('code', { text: d.path })));
if (d.proxy)
rows.push(row('качается через', d.proxy));
[ 'filter', 'exclude-filter' ].forEach(function(k) {
if (d[k] != null)
rows.push(row(k, el('code', { text: String(d[k]) })));
});
if (d.override && Object.keys(d.override).length)
rows.push(row('override', el('code', { text: JSON.stringify(d.override) })));
if (L && L.provider[n.id])
rows.push(row('ноды', L.provider[n.id].n + ', живых ' + L.provider[n.id].alive));
} else if (n.kind == 'proxy') {
[ 'type', 'server', 'port', 'network', 'interface-name', 'dialer-proxy' ].forEach(function(k) {
if (d[k] != null)
rows.push(row(k, String(d[k])));
});
}
if (L && L.nodes[n.id])
rows.push(row('соединений', L.nodes[n.id].n + (L.nodes[n.id].rate ? ' · ' + fmtRate(L.nodes[n.id].rate) : '')));
if (L && n.kind != 'rule') {
var t = L.tail(n.id);
if (t.length > 1)
rows.push(row('путь сейчас', t.map(function(id) { return m.nodes[id] ? m.nodes[id].label : id; }).join(' → ')));
}
info.style.display = '';
while (info.firstChild)
info.removeChild(info.firstChild);
info.appendChild(el('h4', { text: kind + ': ' + n.label }));
info.appendChild(el('table', {}, rows));
};
var select = function(id) {
if (selected && nodeEls[selected])
nodeEls[selected].classList.remove('sel');
selected = id;
if (id && nodeEls[id])
nodeEls[id].classList.add('sel');
focus(id);
if (id)
details(m.nodes[id]);
else
info.style.display = 'none';
};
var curve = function(pts) {
var d = 'M' + pts[0].x + ',' + pts[0].y;
for (var i = 1; i < pts.length; i++) {
var a = pts[i - 1], b = pts[i], dx = Math.max(24, (b.x - a.x) / 2);
d += 'C' + (a.x + dx) + ',' + a.y + ' ' + (b.x - dx) + ',' + b.y + ' ' + b.x + ',' + b.y;
}
return d;
};
// fetch / file edges run against the flow: from under the node into the target's side
var arc = function(a, b, kind) {
var ay = a.y + a.h / 2, by = b.y + b.h / 2;
if (kind == 'file')
return 'M' + a.x + ',' + ay + 'C' + (a.x - 40) + ',' + ay + ' ' + (b.x - 40) + ',' + by + ' ' + b.x + ',' + by;
var ax = a.x + a.w / 2, bx = b.x + b.w, low = a.y + a.h + 30;
return 'M' + ax + ',' + (a.y + a.h) + 'C' + ax + ',' + low + ' ' + (bx + 60) + ',' + by + ' ' + bx + ',' + by;
};
var draw = function() {
while (world.firstChild)
world.removeChild(world.firstChild);
nodeEls = {};
edgeEls = [];
var ge = el('g', {}), gl = el('g', {}), gn = el('g', {});
lay.edges.forEach(function(le, i) {
var e = le.e, a = lay.nodes[e.from], b = lay.nodes[e.to];
if (!a || !b)
return;
var d = le.pts && le.pts.length > 1 ? curve(le.pts) : arc(a, b, e.kind);
var p = el('path', { 'class': 'e ' + e.kind, d: d,
'marker-end': e.kind == 'fetch' ? 'url(#mkg-arrow)' : null });
p.appendChild(el('title', { text: (m.nodes[e.from].label + ' → ' + m.nodes[e.to].label) + (e.label ? '\n' + e.label : '') }));
ge.appendChild(p);
var x = { path: p, label: null };
// filters on the way into a subscription: halfway along the last stretch
if (e.kind == 'use' && e.label && le.pts) {
var q = le.pts[le.pts.length - 1], o = le.pts[le.pts.length - 2];
x.label = el('text', { 'class': 'lbl', x: (o.x + q.x) / 2, y: (o.y + q.y) / 2 - 3, 'text-anchor': 'middle', text: cut(e.label, 30) });
gl.appendChild(x.label);
}
edgeEls[i] = x;
});
m.list.forEach(function(n) {
var b = lay.nodes[n.id];
var g = el('g', { 'class': 'n ' + n.kind + (/^REJECT/.test(n.data.end || '') ? ' reject' : ''), transform: 'translate(' + b.x + ',' + b.y + ')' }, [
el('rect', { width: b.w, height: b.h, rx: n.kind == 'builtin' ? b.h / 2 : 6 }),
el('text', { x: 10, y: n.sub ? 15 : 22, text: n.label }),
n.sub ? el('text', { 'class': 's', x: 10, y: 29, text: n.sub }) : null,
el('title', { text: n.label + (n.sub ? '\n' + n.sub : '') })
]);
g.addEventListener('mouseenter', function() { if (!selected) focus(n.id); });
g.addEventListener('mouseleave', function() { if (!selected) focus(null); });
g.addEventListener('click', function(ev) {
ev.stopPropagation();
select(selected == n.id ? null : n.id);
});
nodeEls[n.id] = g;
gn.appendChild(g);
});
world.appendChild(ge);
world.appendChild(gl);
world.appendChild(gn);
};
var paint = function() {
if (!m)
return;
var on = showLive.checked && L;
world.classList.toggle('live', !!on);
edgeEls.forEach(function(x, i) {
if (!x)
return;
var e = m.edges[i], now = on && L.now[e.from];
var isNow = false, isOff = false;
if (now != null && (e.kind == 'member' || e.kind == 'use')) {
var target = m.nodes[e.to];
isNow = target && (target.label == now && e.kind == 'member' ||
e.kind == 'use' && L.nodeOfNow && L.nodeOfNow[e.from] == e.to);
isOff = !isNow;
}
var f = on && L.edges[i];
x.path.classList.toggle('now', !!isNow && !f);
x.path.classList.toggle('off', !!isOff && !f);
x.path.classList.toggle('flow', !!f);
x.path.style.strokeWidth = f ? Math.min(7, 2 + Math.log(1 + f.n) + (f.rate ? Math.log(1 + f.rate / 4096) : 0)) + 'px' : '';
var hide = onlyNow.checked && on && isOff && !f;
x.path.style.display = hide ? 'none' : '';
if (x.label)
x.label.style.display = hide ? 'none' : '';
});
m.list.forEach(function(n) {
var g = nodeEls[n.id], b = lay.nodes[n.id];
var old = g.querySelector('.live-bits');
if (old)
g.removeChild(old);
var sub = g.querySelector('text.s');
var text = n.sub;
if (on && n.kind == 'group' && L.now[n.id] != null)
text = '→ ' + L.now[n.id] + (L.delay[n.id] ? ' · ' + L.delay[n.id] + ' мс' : '');
if (on && n.kind == 'provider' && L.provider[n.id])
text = L.provider[n.id].alive + '/' + L.provider[n.id].n + ' живы · ' + n.sub;
if (sub)
sub.textContent = cut(text, Math.max(12, Math.floor((b.w - 18) / 5.6)));
var s = on && L.nodes[n.id];
if (s) {
var t = String(s.n), w = 10 + t.length * 6.5;
g.appendChild(el('g', { 'class': 'live-bits', transform: 'translate(' + (b.w - w / 2) + ',0)' }, [
el('rect', { 'class': 'badge', x: -w / 2, y: -8, width: w, height: 16, rx: 8 }),
el('text', { 'class': 'bt', x: 0, y: 4, 'text-anchor': 'middle', text: t }),
el('title', { text: 'соединений: ' + s.n + (s.rate ? ', ' + fmtRate(s.rate) : '') })
]));
}
});
stat.textContent = on ? 'соединений: ' + L.total + (L.unmatched ? ' (без правила в графе: ' + L.unmatched + ')' : '') +
' · обновлено ' + new Date(L.at).toLocaleTimeString() : '';
if (selected)
focus(selected);
if (selected && m.nodes[selected])
details(m.nodes[selected]);
};
showLive.addEventListener('change', paint);
onlyNow.addEventListener('change', paint);
var proxiesLive = null;
return {
show: function(cfg) {
m = model(cfg);
lay = layout(m, measure);
L = null;
selected = null;
info.style.display = 'none';
warn.textContent = m.warnings.length ? '⚠ ' + m.warnings.join('; ') : '';
draw();
fit();
paint();
return m;
},
// proxies: GET /proxies .proxies; connections: GET /connections .connections
live: function(proxies, connections) {
if (!m)
return;
if (proxies)
proxiesLive = proxies;
L = live(m, proxiesLive, connections, L);
// which subscription the current choice of a group comes from
L.nodeOfNow = {};
Object.keys(L.now).forEach(function(g) {
var p = proxiesLive[L.now[g]];
if (p && p['provider-name'])
L.nodeOfNow[g] = 'v:' + p['provider-name'];
});
paint();
},
fit: fit,
destroy: function() { container.removeChild(root); }
};
}
return {
model: model,
layout: layout,
live: live,
view: view,
parseRule: parseRule
};
});