@haelp/teto
Version:
A typescript-based controllable TETR.IO client.
92 lines (91 loc) • 3.46 kB
JavaScript
import chalk from "chalk";
export const server = (get, _, options)=>{
const getDespool = async (endpoint, index)=>{
const req = await fetch(encodeURI(`https://${endpoint}/spool?${Date.now()}-${index}-${Math.floor(1e6 * Math.random())}`), {
method: "GET",
headers: {
// Authorization: `Bearer ${options.token}`,
"User-Agent": options.userAgent
}
});
const res = new Uint8Array(await req.arrayBuffer());
const parseSpoolData = (binary)=>{
const version = binary[0];
const flags = {
online: binary[1] & 0b10000000,
avoidDueToHighLoad: binary[1] & 0b01000000,
recentlyRestarted: binary[1] & 0b00100000,
backhaulDisrupted: binary[1] & 0b00010000,
unused5: binary[1] & 0b00001000,
unused6: binary[1] & 0b00000100,
unused7: binary[1] & 0b00000010,
unused8: binary[1] & 0b00000001
};
const load = [
0,
0,
0
];
const latency = binary[5] * 2;
load[0] = binary[2] / 0x100 * 4;
load[1] = binary[3] / 0x100 * 4;
load[2] = binary[4] / 0x100 * 4;
return {
version,
flags,
load,
latency,
str: `v${version} /${flags.avoidDueToHighLoad ? "Av" : ""}${flags.recentlyRestarted ? "Rr" : ""}${flags.backhaulDisrupted ? "Bd" : ""}/ ${load[0]}, ${load[1]}, ${load[2]}`
};
};
return parseSpoolData(res);
};
const findFastestAvailableSpool = async (spools)=>{
try {
return await Promise.any(spools.map(async (s, index)=>{
const spool = await getDespool(s.host, index.toString());
if (spool.flags.avoidDueToHighLoad || spool.flags.recentlyRestarted) throw new Error("Spool is unstable");
return s;
}));
} catch {
console.log(`${chalk.yellow("[🎀\u2009Ribbon]")}: All spools down or recently restarted (unstable). Falling back to root TETR.IO host.`);
}
return {
name: "tetr.io",
host: "tetr.io",
flag: "NL",
location: "osk"
};
};
return {
environment: async ()=>{
const result = await get({
uri: "server/environment"
});
if (result.success === false) throw new Error(result.error.msg);
return result;
},
spool: async (useSpools)=>{
const res = await get({
uri: "server/ribbon"
});
if (res.success === false) {
throw new Error(res.error.msg);
}
if (!useSpools || res.spools === null) return {
host: "tetr.io",
endpoint: res.endpoint.replace("/ribbon/", ""),
token: ""
};
else {
const lowestPingSpool = await findFastestAvailableSpool(res.spools.spools);
return {
host: lowestPingSpool.host,
endpoint: res.endpoint.replace("/ribbon/", ""),
token: res.spools.token
};
}
}
};
};
//# sourceMappingURL=server.js.map