// VoteScript for Node 18+ (also Deno and Bun). Server side only. import { randomUUID } from 'node:crypto'; const TYPES = new Set('vip group permission title teleport storage until unlock xp boost effect outfit mount spell badge run custom'.split(' ')); /** 'vip/gold' -> { type: 'vip', args: ['gold'] }; '995' -> { type: 'item', args: ['995'] }. Check args before you use them. */ export function parseKey(key) { const [type, ...args] = key.split('/'); if (!args.length || !TYPES.has(type)) return { type: 'item', args: [key] }; return { type, args: type === 'custom' ? [args.join('/')] : args }; } export class VoteScript { /** @param types what you can give, such as ['item', 'vip/gold', 'badge']: rewards with anything else stay waiting. Empty: everything is handed out. */ constructor(url, key, types = []) { this.types = types.join(','); this.base = url.replace(/\/+$/, '') + '/index.php?r=api/v1/'; this.key = key; } /** Claims everything waiting. Store ref before calling and reuse it on retry. */ claim(player, ref = randomUUID()) { return this.#post('claim', { player, ref }); } claimCode(player, code, ref = randomUUID()) { return this.#post('claim-code', { player, code, ref }); } async #post(method, form) { if (this.types) form = { ...form, types: this.types }; let last; for (let i = 0; i < 3; i++) { if (i) await new Promise((r) => setTimeout(r, 700 * i)); try { const r = await fetch(this.base + method, { method: 'POST', headers: { 'X-Api-Key': this.key }, body: new URLSearchParams(form), redirect: 'error', signal: AbortSignal.timeout(8000) }); if (r.status >= 500) { last = new Error('VoteScript answered ' + r.status); continue; } const d = await r.json(); if (r.status !== 200) throw Object.assign(new Error(d.error), { final: true }); return d; } catch (e) { if (e.final) throw e; last = e; } } throw last; } }