refactor: replace proxy-based analytics with static guild datasets

This commit is contained in:
Meghdad committed 2026-10-20 17:15:10 +03:30
1 parent d95898cd1a
commit f9a8f5fd95
19 files changed
+395 -176

No files matched your search

+17 -2
View File
@@ -4,6 +4,11 @@ on:
branches: [main, master]
pull_request:
workflow_dispatch:
inputs:
guild:
description: 'Optional full Europe guild name to add to the static analytics data'
required: false
type: string
permissions:
contents: read
concurrency:
@@ -19,13 +24,23 @@ jobs:
node-version: '24'
- name: Verify content and behavior
run: npm test
- name: Restore published analytics datasets
if: github.event_name != 'pull_request'
uses: actions/cache@v4
with:
path: public/data/intel
key: intel-data-${{ github.run_id }}
restore-keys: intel-data-
- name: Refresh static guild analytics
if: github.event_name != 'pull_request'
run: npm run sync:intel
env:
INTEL_GUILD_NAME: ${{ inputs.guild }}
- name: Download battle preview images
if: github.event_name != 'pull_request'
run: npm run sync:battles
- name: Build static pages
run: npm run build
env:
ONEUP_API_BASE_URL: ${{ vars.ONEUP_API_BASE_URL }}
- uses: actions/upload-pages-artifact@v4
if: github.event_name != 'pull_request'
with:
+52 -24
View File
@@ -18,6 +18,7 @@ Preview at `http://localhost:4173`. Restart after source or content changes to r
| `npm run build` | Generate the static website in `dist/` |
| `npm test` | Validate content, URL handling, preview metadata, and generated pages |
| `npm run sync:battles` | Download social preview images for configured AlbionBB reports |
| `npm run sync:intel` | Prepare static 60-day analytics datasets |
| `npm run import:battles` | Scan available battle history and import verified reports |
The build works offline. Battle image synchronization requires network access and preserves report links when previews are unavailable.
@@ -59,12 +60,12 @@ The GitHub Actions workflow validates pull requests. Pushes to `main` or `master
## Guild intelligence
Open `/intel/` or `/fa/intel/` to analyze any Europe guild by its exact full name.
The live report includes exact kill/death fame, K/D, recorded attendance and IP,
Open `/intel/` or `/fa/intel/` to analyze a prepared Europe guild by its exact full name.
The report includes exact kill/death fame, K/D, recorded attendance and IP,
daily fame, roles, weapons, player rankings, expandable encounter compositions,
source links, and CSV export. Filters and guild name are shareable in the URL.
- Time windows are rolling 7, 30 or 60 days. Battle times use UTC.
- Time windows cover 7, 30 or 60 days ending at the published data timestamp. Battle times use UTC.
- Minimum players means **all players from all guilds in each original battle**.
For example, 40 includes a 40-player fight even if only four belong to the searched
guild. Filtering happens before merging and applies to every reported statistic.
@@ -80,29 +81,56 @@ source links, and CSV export. Filters and guild name are shareable in the URL.
member is counted again in another encounter. Zero/missing IP is excluded from
the recorded-IP average. Role/weapon snapshots are not complete movement,
equipment-switch or in-game attendance telemetry.
- Every history page in the time range is scanned. Errors stop the analysis;
partial results are never labelled as a complete report. Retry and cancellation
are available. Requests use bounded concurrency and a short in-page cache.
- Every history page in the time range is scanned during data preparation. Errors
stop publication; partial data is never labelled as a complete report. The
browser caches versioned bundles for responsive filter changes.
### Live API hosting
### Static datasets, without proxies or keys
AlbionBB allows browser requests only from its own origin. Live reports therefore
require a small server-side read proxy; a GitHub Pages static artifact alone
cannot provide this endpoint. No API key is required.
The browser loads `data/intel/manifest.json` and a versioned JSON file for the
selected guild from this same static site. There is no project API, external CORS
proxy, account/key setup or cross-origin data request. Filters, grouping decisions,
composition, statistics, charts and CSV export run in the browser.
`npm run dev` provides `/api/albion/*` automatically. For production there are two options:
This deliberately trades arbitrary live lookup for reliable static hosting:
**only guilds with a published dataset are searchable**. The page lists available
guilds and displays their data timestamp. Windows end at that timestamp, rather
than claiming that an older dataset covers the present moment. Datasets older than
36 hours are explicitly marked. Complete coverage is 60 days per prepared guild.
1. Build with `npm run build`, then deploy `worker.mjs` and `dist/` to Cloudflare
Workers using the included `wrangler.jsonc` (e.g. `npx wrangler deploy`). This
serves both the existing site and the same-origin API. Deployment is a separate
operator action; the existing GitHub Pages workflow is unchanged.
2. Keep GitHub Pages and host the Worker separately. Set the Worker's `SITE_ORIGIN`
variable to the exact site origin (for this project, `https://oneup.megh.dad`).
Build the static site with
`ONEUP_API_BASE_URL=https://YOUR-WORKER.workers.dev/api/albion npm run build`.
For the existing CI workflow, set the repository variable `ONEUP_API_BASE_URL`
to that URL. Only the configured origin receives cross-origin access.
To refresh:
The proxy permits GET requests to a fixed Europe upstream and a small allowlist
of public report routes and parameters. It does not forward cookies or credentials.
Upstream timeouts and rate limits produce a visible error with a retry option.
```bash
npm run sync:intel
npm run build
```
`content/intel-guilds.json` lists full Europe guild names to prepare (initially
OneUP). Add a name there, or use `INTEL_GUILD_NAME="Full Guild Name" npm run sync:intel`.
The collector searches for an exact match, exhausts the history pages in the
60-day window and saves full guild detail, including recorded roles and weapons.
It retains other guilds' aggregate stats for grouping, but omits their player
rosters to keep files small. Raw files contain only public game data.
For all 7/30/60-day windows, the collector prepares the multi reports needed for
**every distinct total-player threshold**, not just a few preset values. Each is
fetched from AlbionBB's multi endpoint and its kill, death and fame totals are
verified against the originals. Browser grouping uses the same rules and reads
the corresponding saved multi. Failed or missing data is an error; no silently
approximated merged composition is presented.
The initial real dataset is committed in `public/data/intel/`, so a clean checkout
and normal build work offline. Subsequent refreshes reuse historical raw reports
and verified multi files. The manifest is replaced only after all requested guilds
have been collected successfully. New files have content hashes in their names.
The existing GitHub Pages workflow now refreshes datasets before publishing on
push or manual runs. Its optional **guild** input adds another prepared guild.
The Actions cache retains previously prepared guilds and reports for subsequent
runs. No runtime server is deployed and no new service subscription is required.
There is no scheduled refresh: the timestamp advances on the next publication.
Data collection uses the same public AlbionBB API as the battle importer. This
happens on the maintainer's computer or in CI, where browser CORS does not apply.
All analysis still happens in the visitor's browser. The normal `npm run build`
does not fetch anything from the network.
+3
View File
@@ -0,0 +1,3 @@
[
"OneUP"
]
+1
View File
@@ -10,6 +10,7 @@
"dev": "node scripts/serve.mjs",
"test": "node --test",
"sync:battles": "node scripts/sync-battles.mjs",
"sync:intel": "node scripts/sync-intel.mjs",
"import:battles": "node scripts/import-battles.mjs"
}
}
@@ -0,0 +1 @@
{"schemaVersion":1,"guild":{"Id":"SF2Zf4PrRsmdBAL5PaBV_A","Name":"OneUP"},"asOf":"2026-10-20T12:59:30.574Z","coverageDays":60,"battles":[{"albionId":450551865,"startedAt":"2026-10-20T10:59:11.72Z","finishedAt":"2026-10-20T11:00:53.44Z","totalFame":1005326,"totalKills":3,"totalPlayers":10,"guilds":[{"albionId":"zhgXCDFoQFS_IVosoGsxUA","name":"Utopia","alliance":"7UP","kills":1,"deaths":2,"killFame":492120,"players":7,"ip":1404},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":1,"deaths":0,"killFame":342136,"players":2,"ip":1403},{"albionId":"bE4mUn7HQMqvtT9NaFsA9A","name":"not really X","kills":1,"deaths":1,"killFame":171068,"players":1,"ip":1342}],"players":[{"name":"GODpori","guildName":"OneUP","allianceName":"CRSE","kills":0,"deaths":0,"killFame":171068,"deathFame":0,"ip":0,"heal":0,"damage":0,"role":"tank","weapon":{"name":"2H_IRONCLADEDSTAFF","type":"T5_2H_IRONCLADEDSTAFF@2","quality":2}},{"name":"AliSorena","guildName":"OneUP","allianceName":"CRSE","kills":1,"deaths":0,"killFame":171068,"deathFame":0,"ip":1403,"heal":0,"damage":0,"role":"tank","weapon":{"name":"2H_IRONCLADEDSTAFF","type":"T6_2H_IRONCLADEDSTAFF@1","quality":4}}]},{"albionId":450546118,"startedAt":"2026-10-20T10:33:06.52Z","finishedAt":"2026-10-20T10:34:52.685Z","totalFame":1728,"totalKills":3,"totalPlayers":7,"guilds":[{"albionId":"AQF3L97hRoSZrWh-23AGUQ","name":"Undead Outlaws","kills":0,"deaths":2,"killFame":1152,"players":2,"ip":1279},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":0,"deaths":1,"killFame":0,"players":1,"ip":1334},{"albionId":"-CsKqlyeTLeKzakW2tKUyg","name":"Legio Potens","alliance":"Halal","kills":0,"deaths":0,"killFame":0,"players":1,"ip":1349}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":0,"deaths":1,"killFame":0,"deathFame":1728,"ip":1334,"heal":0,"damage":0,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450534048,"startedAt":"2026-10-20T09:19:55.622Z","finishedAt":"2026-10-20T09:20:16.005Z","totalFame":29790,"totalKills":3,"totalPlayers":6,"guilds":[{"albionId":"ITaSge20T_6P7UVLBfe6ew","name":"AllianceOfScurletRoseAndCross","alliance":"Depth","kills":1,"deaths":0,"killFame":9930,"players":1,"ip":1362},{"albionId":"GlQrOQwEQAOWBrLhF7ZIhw","name":"EQMS","alliance":"MASS","kills":0,"deaths":0,"killFame":9930,"players":1,"ip":1351},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":2,"deaths":0,"killFame":9930,"players":1,"ip":1334},{"albionId":"6qu76pd6QCWueWE8FO856Q","name":"SkoZirys","alliance":"BLS","kills":0,"deaths":3,"killFame":0,"players":3,"ip":1244}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":2,"deaths":0,"killFame":9930,"deathFame":0,"ip":1334,"heal":0,"damage":16010,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450507553,"startedAt":"2026-10-20T07:12:31.324Z","finishedAt":"2026-10-20T07:12:56.134Z","totalFame":5832,"totalKills":3,"totalPlayers":6,"guilds":[{"albionId":"b24VSOcoTs-q6eUoVnvfbQ","name":"Enjoyers","alliance":"ASR","kills":2,"deaths":0,"killFame":1944,"players":1,"ip":1330},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":1,"deaths":0,"killFame":1944,"players":1,"ip":1334},{"albionId":"MJlWe-zCQ9aQY8x3OUi5sA","name":"MYDAKI","alliance":"ZOUZ","kills":0,"deaths":2,"killFame":0,"players":2,"ip":1332}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":1,"deaths":0,"killFame":1944,"deathFame":0,"ip":1334,"heal":0,"damage":7543,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450506733,"startedAt":"2026-10-20T07:07:30.518Z","finishedAt":"2026-10-20T07:08:01.052Z","totalFame":42120,"totalKills":3,"totalPlayers":6,"guilds":[{"albionId":"_MWi7UZQRzyXPdbJsgKzyg","name":"The Night","kills":2,"deaths":0,"killFame":18072,"players":1,"ip":1291},{"albionId":"e7CUFl8hSRq2Pg6pdSxhJA","name":"AQUAMARINE","alliance":"LOVER","kills":1,"deaths":0,"killFame":18072,"players":1,"ip":1330},{"albionId":"b24VSOcoTs-q6eUoVnvfbQ","name":"Enjoyers","alliance":"ASR","kills":0,"deaths":1,"killFame":0,"players":1,"ip":1330},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":0,"deaths":1,"killFame":0,"players":1,"ip":1334}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":0,"deaths":1,"killFame":0,"deathFame":15336,"ip":1334,"heal":0,"damage":0,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450502504,"startedAt":"2026-10-20T06:38:41.954Z","finishedAt":"2026-10-20T06:39:50.791Z","totalFame":578314,"totalKills":4,"totalPlayers":5,"guilds":[{"albionId":"qZbvq5VrQdWDbWB_-LHfmQ","name":"Forge of Battles","kills":4,"deaths":0,"killFame":578314,"players":1,"ip":1460},{"albionId":Line truncated
+14
View File
@@ -0,0 +1,14 @@
{
"schemaVersion": 1,
"updatedAt": "2026-10-20T12:59:30.574Z",
"guilds": [
{
"Id": "SF2Zf4PrRsmdBAL5PaBV_A",
"Name": "OneUP",
"file": "SF2Zf4PrRsmdBAL5PaBV_A-c3428e12a5db.json",
"asOf": "2026-10-20T12:59:30.574Z",
"coverageDays": 60,
"battleCount": 2020
}
]
}
-32
View File
@@ -1,32 +0,0 @@
// Shared by the local server and the optional Cloudflare Worker. No arbitrary upstream URLs.
const API = 'https://api.albionbb.com/eu';
export function upstreamUrl(requestUrl) {
const input = new URL(requestUrl), path = input.pathname.replace(/^\/api\/albion/, '');
const allowed = path === '/guilds/search' || path === '/battles' || path === '/battles/multi' || /^\/battles\/\d+$/.test(path);
if (!input.pathname.startsWith('/api/albion/') || !allowed) throw Error('Unsupported API path');
const url = new URL(API + path);
const allowedKeys = path === '/guilds/search' ? ['search'] : path === '/battles' ? ['guildId','page','minPlayers','minGuildPlayers'] : path === '/battles/multi' ? ['ids'] : [];
for (const [key, value] of input.searchParams) {
if (!allowedKeys.includes(key) || value.length > 2000) throw Error('Invalid API parameter');
url.searchParams.set(key, value);
}
if (path === '/guilds/search' && (!url.searchParams.get('search')?.trim() || url.searchParams.get('search').length > 100)) throw Error('Invalid guild name');
if (path === '/battles') {
if (!/^[\w-]{1,64}$/.test(url.searchParams.get('guildId') || '')) throw Error('Invalid guild ID');
for (const key of ['page','minPlayers','minGuildPlayers']) if (url.searchParams.has(key) && !/^\d{1,5}$/.test(url.searchParams.get(key))) throw Error('Invalid numeric parameter');
}
if (path === '/battles/multi' && !/^\d+(,\d+){1,99}$/.test(url.searchParams.get('ids') || '')) throw Error('Invalid battle IDs');
return url;
}
export async function proxyAlbion(request, fetchImpl = fetch) {
if (request.method !== 'GET') return Response.json({ error: 'Method not allowed' }, { status: 405, headers: { Allow: 'GET' } });
let url;
try { url = upstreamUrl(request.url); }
catch { return Response.json({ error: 'Invalid Albion API request' }, { status: 400 }); }
try {
const result = await fetchImpl(url, { headers: { Accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(30_000) });
if (!result.ok) return Response.json({ error: 'AlbionBB is temporarily unavailable', upstreamStatus: result.status }, { status: result.status === 429 ? 429 : 502 });
const body = await result.json();
return Response.json(body, { headers: { 'Cache-Control': 'public, max-age=120', 'X-Content-Type-Options': 'nosniff' } });
} catch { return Response.json({ error: 'Unable to reach AlbionBB' }, { status: 502 }); }
}
+3 -4
View File
@@ -13,7 +13,8 @@ const dist = new URL('../dist/', import.meta.url);
await rm(dist, { recursive: true, force: true });
await mkdir(new URL('assets/', dist), { recursive: true });
for (const [from,to] of [['src/styles.css','styles.css'],['src/app.js','app.js']]) await cp(new URL(from,root),new URL(`assets/${to}`,dist));
for (const name of ['intel.js','intel-core.js','intel-text.js','intel.css']) await cp(new URL(`src/${name}`,root),new URL(`assets/${name}`,dist));
for (const name of ['intel.js','intel-core.js','intel-data.js','intel-text.js','intel.css']) await cp(new URL(`src/${name}`,root),new URL(`assets/${name}`,dist));
try { await cp(new URL('public/data/',root),new URL('data/',dist),{recursive:true}); } catch(err) { if(err.code!=='ENOENT') throw err; }
try { await cp(new URL('public/assets/',root),new URL('assets/',dist),{ recursive:true }); } catch(err) { if(err.code !== 'ENOENT') throw err; }
await rm(new URL('assets/battles/previews.json',dist),{force:true});
const faviconLogo=(await readFile(new URL('public/assets/logo.jpg',root))).toString('base64');
@@ -84,9 +85,7 @@ for (const lang of ['en','fa']) {
await mkdir(folder,{recursive:true}); await writeFile(new URL('index.html',folder),render(lang));
const intelFolder=new URL('intel/',folder);
await mkdir(intelFolder,{recursive:true});
const apiBase=process.env.ONEUP_API_BASE_URL || '/api/albion';
if (apiBase !== '/api/albion' && (!apiBase.startsWith('https://') || new URL(apiBase).search || new URL(apiBase).hash)) throw Error('ONEUP_API_BASE_URL must be an HTTPS API base URL');
await writeFile(new URL('index.html',intelFolder),renderIntel(lang,origin,apiBase));
await writeFile(new URL('index.html',intelFolder),renderIntel(lang,origin));
}
await Promise.all([
writeFile(new URL('CNAME',dist),new URL(origin).hostname+'\n'),
+5 -4
View File
@@ -1,7 +1,7 @@
import { escapeHtml as e } from './lib.mjs';
import { textFor } from '../src/intel-text.js';
export function renderIntel(lang, origin, apiBase = '/api/albion') {
export function renderIntel(lang, origin) {
const fa = lang === 'fa', t = textFor(lang), base = fa ? '../../' : '../';
return `<!doctype html><html lang="${lang}" dir="${fa ? 'rtl' : 'ltr'}"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
@@ -10,15 +10,16 @@ export function renderIntel(lang, origin, apiBase = '/api/albion') {
<link rel="icon" href="${base}assets/favicon.svg"><link rel="stylesheet" href="${base}assets/styles.css"><link rel="stylesheet" href="${base}assets/intel.css">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@500;600;700;800&family=Barlow:wght@400;500;600;700&family=Vazirmatn:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script type="module" src="${base}assets/intel.js"></script></head>
<body class="intel-page" data-api-base="${e(apiBase)}">
<body class="intel-page">
<a class="skip-link" href="#intel-main">${fa ? 'رفتن به محتوا' : 'Skip to content'}</a>
<header class="intel-header"><a class="brand" href="${base}${fa ? 'fa/' : ''}" aria-label="OneUP"><img src="${base}assets/logo.jpg" alt="" width="44" height="44"><span>ONE<span class="brand-up">UP</span><small>GUILD INTELLIGENCE</small></span></a>
<a class="intel-back" href="${base}${fa ? 'fa/' : ''}">${e(t.back)} <span aria-hidden="true">↗</span></a>
<div class="languages"><a href="${base}intel/" lang="en" data-intel-language ${!fa ? 'aria-current="page"' : ''}>EN</a><span>/</span><a href="${base}fa/intel/" lang="fa" data-intel-language ${fa ? 'aria-current="page"' : ''}>فا</a></div></header>
<main id="intel-main" class="intel-main">
<section class="intel-hero"><div><p class="eyebrow">${e(t.eyebrow)}</p><h1>${e(t.hero)}<br><span>${e(t.accent)}</span></h1><p class="intel-intro">${e(t.intro)}</p></div><div class="intel-signal" aria-hidden="true"><div class="signal-orbit"></div><div class="signal-orbit orbit-inner"></div><span class="signal-center">1<span>UP</span></span><i></i><b>EU / INTEL</b></div><div class="intel-source"><span class="live-dot"></span>${e(t.region)}<span class="source-divider">/</span>${e(t.live)}</div></section>
<section class="intel-dataset"><div><span class="live-dot"></span><p id="snapshot-status" role="status">${e(t.loadingData)}</p></div><div id="available-guilds" aria-label="${e(t.availableGuilds)}"></div><p>${e(t.snapshotHelp)}</p></section>
<section class="intel-controls" aria-label="${e(t.title)}"><form id="intel-form">
<div class="intel-search"><label for="guild-name">${e(t.guild)}</label><div class="search-field"><span aria-hidden="true">⌕</span><input id="guild-name" name="guild" placeholder="${e(t.placeholder)}" dir="ltr" required minlength="2" maxlength="100" autocomplete="off" spellcheck="false"></div></div>
<div class="intel-search"><label for="guild-name">${e(t.guild)}</label><div class="search-field"><span aria-hidden="true">⌕</span><input id="guild-name" name="guild" placeholder="${e(t.placeholder)}" dir="ltr" required minlength="2" maxlength="100" autocomplete="off" spellcheck="false" list="prepared-guilds"><datalist id="prepared-guilds"></datalist></div></div>
<fieldset class="period-field"><legend>${e(t.period)}</legend><div class="period-options">${[7,30,60].map(days => `<label><input type="radio" name="days" value="${days}" ${days === 7 ? 'checked' : ''}><span>${days} <small>${e(t.days)}</small></span></label>`).join('')}</div></fieldset>
<div class="minimum-field"><label for="min-members">${e(t.minimum)}</label><input id="min-members" name="minimum" type="number" min="1" max="1000" step="1" value="10" required aria-describedby="min-help"></div>
<button class="button intel-submit" type="submit">${e(t.analyze)} <span aria-hidden="true">↗</span></button>
@@ -29,6 +30,6 @@ export function renderIntel(lang, origin, apiBase = '/api/albion') {
<div id="intel-results" hidden></div>
<details class="intel-method"><summary>${e(t.methodology)} <span aria-hidden="true">+</span></summary><p>${e(t.caveat)}</p><p>${e(t.mergeHelp)}</p><p>${e(t.minimumHelp)}</p></details>
</main><footer class="intel-footer"><span>ONE<span>UP</span> / INTELLIGENCE</span><p>${e(t.service)}</p><a href="https://europe.albionbb.com/" target="_blank" rel="noopener noreferrer">ALBIONBB ↗</a></footer>
<noscript><p class="intel-error">${fa ? 'برای دریافت گزارش زنده، جاوااسکریپت مرورگر را فعال کن.' : 'Enable JavaScript to load live reports.'}</p></noscript>
<noscript><p class="intel-error">${fa ? 'برای تحلیل گزارش، جاوااسکریپت مرورگر را فعال کن.' : 'Enable JavaScript to analyze reports.'}</p></noscript>
</body></html>`;
}
+1 -7
View File
@@ -2,18 +2,12 @@ import http from 'node:http';
import { readFile, stat } from 'node:fs/promises';
import { resolve, extname, sep } from 'node:path';
import { spawnSync } from 'node:child_process';
import { proxyAlbion } from './albion-proxy.mjs';
const built = spawnSync(process.execPath, ['scripts/build.mjs'], { stdio:'inherit' });
if (built.status) process.exit(built.status);
const root=resolve('dist');
const types={'.html':'text/html; charset=utf-8','.css':'text/css','.js':'text/javascript','.jpg':'image/jpeg','.png':'image/png','.webp':'image/webp','.svg':'image/svg+xml','.xml':'application/xml','.txt':'text/plain'};
const types={'.json':'application/json; charset=utf-8','.html':'text/html; charset=utf-8','.css':'text/css','.js':'text/javascript','.jpg':'image/jpeg','.png':'image/png','.webp':'image/webp','.svg':'image/svg+xml','.xml':'application/xml','.txt':'text/plain'};
http.createServer(async(req,res)=>{
try {
if (new URL(req.url,'http://localhost').pathname.startsWith('/api/albion/')) {
const response = await proxyAlbion(new Request(new URL(req.url,'http://localhost'), { method: req.method }));
res.writeHead(response.status, Object.fromEntries(response.headers)).end(Buffer.from(await response.arrayBuffer()));
return;
}
let path=resolve(root, '.'+decodeURIComponent(new URL(req.url,'http://localhost').pathname));
if(path!==root && !path.startsWith(root+sep)){res.writeHead(403).end();return;}
if((await stat(path)).isDirectory()) path=resolve(path,'index.html');
+104
View File
@@ -0,0 +1,104 @@
import { readFile, writeFile, mkdir, rename, readdir, rm } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { pathToFileURL } from 'node:url';
import { fetchJson } from './fetch-battles.mjs';
import { groupReports, ownGuild, ownPlayers, normalizeName, selectBattles, scanListings, mapLimit } from '../src/intel-core.js';
import { validateIndex } from '../src/intel-data.js';
const API = 'https://api.albionbb.com/eu';
export const groupKey = ids => [...ids].map(Number).sort((a,b)=>a-b).join(',');
export function compactBattle(raw, guildId) {
const guild = ownGuild(raw,guildId);
if (!guild || !Array.isArray(raw.players) || !Number.isFinite(Date.parse(raw.startedAt)) || !Number.isFinite(Date.parse(raw.finishedAt))) throw Error('Incomplete guild report');
return {
albionId:raw.albionId,startedAt:raw.startedAt,finishedAt:raw.finishedAt,
totalFame:raw.totalFame,totalKills:raw.totalKills,totalPlayers:raw.totalPlayers,
guilds:raw.guilds,players:ownPlayers(raw,guildId),
};
}
export function requiredMultis(battles, guildId, asOf) {
const needed = new Map(), until = Date.parse(asOf);
// Every attendance value changes inclusion only at one of these boundaries.
// Preload multi reports for ALL supported day windows and player thresholds.
for (const days of [7,30,60]) {
const rows = selectBattles(battles,guildId,{since:until-days*86_400_000,until,minPlayers:1});
const thresholds = new Set([1,...rows.map(b=>b.totalPlayers+1)]);
for (const minPlayers of thresholds) {
for (const group of groupReports(rows.filter(b=>b.totalPlayers>=minPlayers),guildId)) {
if (group.length>1) needed.set(groupKey(group.map(b=>b.albionId)),group);
}
}
}
return needed;
}
export async function collectGuild(name, previous, {request,asOf=new Date().toISOString(),log=()=>{}}) {
const candidates = await request('/guilds/search',{search:name});
const matches = candidates.filter(g=>normalizeName(g.Name)===normalizeName(name));
if (matches.length!==1) throw Error(`Expected one exact Europe guild match for ${name}; found ${matches.length}`);
const guild = matches[0], until = Date.parse(asOf), since = until-60*86_400_000;
if (!/^[\w-]{1,64}$/.test(guild.Id)) throw Error('Invalid guild identity');
const listings = await scanListings(request,guild.Id,since,undefined,(page,count)=>log(`${guild.Name}: history page ${page}, ${count} battles`));
const cached = new Map((previous?.guild?.Id===guild.Id?previous.battles||[]:[]).map(b=>[b.albionId,b]));
let done = 0;
const battles = await mapLimit(listings.filter(b=>Date.parse(b.startedAt)<=until),3,async row=>{
const old = cached.get(row.albionId);
const raw = old && until-Date.parse(row.startedAt)>86_400_000 ? old : await request(`/battles/${row.albionId}`);
if (raw.albionId!==row.albionId) throw Error('Mismatched battle ID');
const detail = compactBattle(raw,guild.Id);
if (++done%25===0 || done===listings.length) log(`${guild.Name}: details ${done}/${listings.length}`);
return detail;
});
const required = requiredMultis(battles,guild.Id,asOf), multis = {};
log(`${guild.Name}: ${required.size} unique combined reports across all filters`);
done = 0;
await mapLimit([...required],2,async([key,group])=>{
const old = previous?.guild?.Id===guild.Id && previous.multis?.[key];
const fresh = group.some(b=>until-Date.parse(b.startedAt)<86_400_000);
const raw = old && !fresh ? old : await request('/battles/multi',{ids:key});
const total = ownGuild(raw,guild.Id);
for (const field of ['kills','deaths','killFame']) {
if (total?.[field]!==group.reduce((sum,b)=>sum+(ownGuild(b,guild.Id)[field]||0),0)) throw Error(`Unverified multi ${key}: ${field}`);
}
multis[key] = compactBattle(raw,guild.Id);
if (++done%10===0 || done===required.size) log(`${guild.Name}: combined reports ${done}/${required.size}`);
});
return {schemaVersion:1,guild,asOf,coverageDays:60,battles,multis};
}
if (process.argv[1] && import.meta.url===pathToFileURL(process.argv[1]).href) {
const directory = new URL('../public/data/intel/',import.meta.url);
await mkdir(directory,{recursive:true});
let manifest = {schemaVersion:1,guilds:[]};
try { manifest=validateIndex(JSON.parse(await readFile(new URL('manifest.json',directory),'utf8'))); } catch(error) { if(error.code!=='ENOENT')throw error; }
const configured = JSON.parse(await readFile(new URL('../content/intel-guilds.json',import.meta.url),'utf8'));
const supplied = process.env.INTEL_GUILD_NAME?.trim();
const names = [...new Map([...configured,...manifest.guilds.map(g=>g.Name),...(supplied?[supplied]:[])].map(name=>[normalizeName(name),name.trim()])).values()];
let nextStart = 0;
const request = async(path,query={})=>{
const start = Math.max(Date.now(),nextStart); nextStart = start+220;
await new Promise(resolve=>setTimeout(resolve,Math.max(0,start-Date.now())));
const url = new URL(API+path);
for (const [key,value] of Object.entries(query)) url.searchParams.set(key,value);
return fetchJson(url);
};
const entries = [], asOf = new Date().toISOString();
for (const name of names) {
const old = manifest.guilds.find(g=>normalizeName(g.Name)===normalizeName(name));
let previous;
if (old) previous=JSON.parse(await readFile(new URL(old.file,directory),'utf8'));
const snapshot = await collectGuild(name,previous,{request,asOf,log:console.log});
const json = JSON.stringify(snapshot);
const digest = createHash('sha256').update(json).digest('hex').slice(0,12);
const file = `${snapshot.guild.Id}-${digest}.json`;
await writeFile(new URL(file,directory),json+'\n');
entries.push({...snapshot.guild,file,asOf,coverageDays:60,battleCount:snapshot.battles.length});
}
const result = {schemaVersion:1,updatedAt:asOf,guilds:entries};
await writeFile(new URL('manifest.json.tmp',directory),JSON.stringify(result,null,2)+'\n');
await rename(new URL('manifest.json.tmp',directory),new URL('manifest.json',directory));
const retained = new Set(['manifest.json',...entries.map(g=>g.file)]);
for (const file of await readdir(directory)) {
if (/^[\w-]+\.json$/.test(file) && !retained.has(file)) await rm(new URL(file,directory));
}
console.log(`Published ${entries.length} complete guild datasets in public/data/intel/`);
}
+12 -9
View File
@@ -30,16 +30,19 @@ export function groupReports(battles, guildId, merge = true) {
const sorted = [...new Map(battles.map(b => [b.albionId, b])).values()]
.sort((a, b) => millis(a.startedAt) - millis(b.startedAt) || a.albionId - b.albionId);
const groups = [];
let active = [];
for (const battle of sorted) {
const candidates = merge ? groups.filter(group => {
const last = group.at(-1);
const end = Math.max(...[...group, battle].map(b => millis(b.finishedAt || b.startedAt)));
return millis(battle.startedAt) - millis(last.finishedAt || last.startedAt) <= 20 * 60_000 &&
end - millis(group[0].startedAt) <= 90 * 60_000 &&
compatible(last, battle, guildId) && compatible(group[0], battle, guildId);
}) : [];
candidates.sort((a, b) => millis(b.at(-1).finishedAt) - millis(a.at(-1).finishedAt));
if (candidates.length) candidates[0].push(battle); else groups.push([battle]);
const start = millis(battle.startedAt), end = millis(battle.finishedAt || battle.startedAt);
// Old encounters can never match a later battle. Keep only the bounded active window.
active = active.filter(g => start-g.lastEnd<=20*60_000 && start-g.firstStart<=90*60_000);
const candidates = merge ? active.filter(g => Math.max(g.end,end)-g.firstStart<=90*60_000 &&
compatible(g.rows.at(-1),battle,guildId) && compatible(g.rows[0],battle,guildId)) : [];
candidates.sort((a,b)=>b.lastEnd-a.lastEnd);
if (candidates.length) {
const chosen=candidates[0];chosen.rows.push(battle);chosen.lastEnd=end;chosen.end=Math.max(chosen.end,end);
} else {
const rows=[battle];groups.push(rows);active.push({rows,firstStart:start,lastEnd:end,end});
}
}
return groups;
}
+56
View File
@@ -0,0 +1,56 @@
// The browser reads only JSON files hosted with this static site.
export class DataError extends Error {
constructor(code) { super(code); this.name='DataError'; this.code=code; }
}
export const groupKey = ids => [...ids].map(Number).sort((a,b)=>a-b).join(',');
export function validateIndex(index) {
if (index?.schemaVersion!==1 || !Array.isArray(index.guilds)) throw new DataError('invalid');
const seen = new Set();
for (const guild of index.guilds) {
if (!/^[\w-]{1,64}$/.test(guild.Id) || typeof guild.Name!=='string' || !guild.Name.trim() ||
!/^[\w-]+\.json$/.test(guild.file) || !Number.isFinite(Date.parse(guild.asOf)) || guild.coverageDays!==60 || seen.has(guild.Id)) throw new DataError('invalid');
seen.add(guild.Id);
}
return index;
}
export function validateSnapshot(snapshot, entry) {
if (snapshot?.schemaVersion!==1 || snapshot.guild?.Id!==entry.Id || snapshot.guild?.Name!==entry.Name ||
snapshot.asOf!==entry.asOf || snapshot.coverageDays!==60 || !Array.isArray(snapshot.battles) ||
!snapshot.multis || typeof snapshot.multis!=='object' || Array.isArray(snapshot.multis)) throw new DataError('invalid');
const seen = new Set();
for (const battle of snapshot.battles) {
if (!Number.isSafeInteger(battle.albionId) || seen.has(battle.albionId) || !Number.isSafeInteger(battle.totalPlayers) || battle.totalPlayers<0 ||
!Number.isFinite(Date.parse(battle.startedAt)) || !Number.isFinite(Date.parse(battle.finishedAt)) ||
!Array.isArray(battle.players) || !battle.guilds?.some(g=>g.albionId===entry.Id)) throw new DataError('invalid');
seen.add(battle.albionId);
}
for (const key of Object.keys(snapshot.multis)) if (!/^\d+(,\d+)+$/.test(key) || key.split(',').some(id=>!seen.has(Number(id)))) throw new DataError('invalid');
return snapshot;
}
export function createDataSource({ baseUrl=new URL('../data/intel/',import.meta.url), fetchImpl=fetch }={}) {
const base = new URL(baseUrl), cache = new Map();
async function read(file, signal) {
signal?.throwIfAborted();
try {
const response = await fetchImpl(new URL(file,base), { mode:'same-origin', credentials:'omit',cache:'no-cache',signal });
if (!response.ok) throw new DataError(response.status===404?'missing':'network');
return await response.json();
} catch(error) {
if (signal?.aborted) throw signal.reason;
throw error instanceof DataError?error:new DataError('network');
}
}
return {
async index(signal) { return validateIndex(await read('manifest.json',signal)); },
async load(entry, signal) {
signal?.throwIfAborted();
// Validate filenames before constructing a request, even for callers other than index().
validateIndex({schemaVersion:1,guilds:[entry]});
if (cache.has(entry.file)) return cache.get(entry.file);
const snapshot = validateSnapshot(await read(entry.file,signal),entry);
cache.set(entry.file,snapshot);
if (cache.size>8) cache.delete(cache.keys().next().value);
return snapshot;
},
};
}
+10 -4
View File
@@ -6,7 +6,7 @@ const messages = {
accent: ['A clearer picture.', 'تصویری روشن‌تر.'],
intro: ['Read the guild behind the numbers. Explore its kill fame, fighting strength and the compositions it brings to battle.', 'پشت هر عدد، یک گیلد است. فیم به‌دست‌آمده، قدرت حضور و ترکیب نیروهایش را در نبردها بررسی کن.'],
region: ['EUROPE SERVER', 'سرور اروپا'],
live: ['LIVE REPORTS', 'گزارش‌های زنده'],
live: ['PUBLISHED BATTLE DATA', 'دادهٔ منتشرشدهٔ نبردها'],
guild: ['Full guild name', 'نام کامل گیلد'],
placeholder: ['e.g. OneUP', 'مثلاً OneUP'],
period: ['Time window', 'بازهٔ زمانی'],
@@ -18,7 +18,7 @@ const messages = {
analyze: ['Analyze guild', 'تحلیل گیلد'],
cancel: ['Cancel', 'لغو'],
idleTitle: ['Your next opponent. Your own guild.', 'رقیب بعدی‌ات؛ یا گیلد خودت.'],
idleCopy: ['Enter an exact guild name to build a report from real AlbionBB battle data.', 'نام کامل یک گیلد را وارد کن تا گزارش آن از داده‌های واقعی AlbionBB ساخته شود.'],
idleCopy: ['Choose a prepared guild or enter its full name to explore real AlbionBB battle data.', 'یکی از گیلدهای آماده را انتخاب کن یا نام کامل آن را بنویس تا داده‌های واقعی AlbionBB تحلیل شوند.'],
step1: ['Find the guild', 'پیدا کردن گیلد'],
step2: ['Connect the battles', 'کنار هم گذاشتن نبردها'],
step3: ['Read the composition', 'شناخت ترکیب نیروها'],
@@ -29,10 +29,16 @@ const messages = {
battles: ['battles', 'بتل'],
details: ['Loading battle details', 'در حال دریافت جزئیات بتل‌ها'],
merging: ['Building combined reports', 'در حال ساخت گزارش‌های ادغام‌شده'],
notFound: ['No exact match. Check the full guild name on the Europe server.', 'گیلدی با این نام دقیق پیدا نشد. نام کامل گیلد را در سرور اروپا بررسی کن.'],
notFound: ['No published dataset matches this guild. Choose one of the prepared guilds above.', 'برای این نام گیلد، دادهٔ آماده پیدا نشد. یکی از گیلدهای آمادهٔ بالا را انتخاب کن.'],
ambiguous: ['Several guilds have this name. Select the intended guild:', 'چند گیلد با این نام پیدا شد. گیلد موردنظر را انتخاب کن:'],
error: ['The report could not be completed. Check your connection and try again. No incomplete totals are shown.', 'گزارش کامل نشد. اتصال را بررسی کن و دوباره تلاش کن. آمار ناقص به‌عنوان نتیجه نمایش داده نمی‌شود.'],
proxyError: ['The report service is unavailable. On static hosting, configure the Albion API Worker described in the project README.', 'سرویس گزارش در دسترس نیست. برای میزبانی استاتیک، واسط API توضیح‌داده‌شده در README پروژه باید فعال باشد.'],
loadingData: ['Loading published datasets…', 'در حال دریافت داده‌های منتشرشده…'],
availableGuilds: ['Prepared guilds', 'گیلدهای آمادهٔ تحلیل'],
snapshotHelp: ['Analysis uses the published dataset. Time windows end at the dataset update time. New guilds are added when site data is refreshed.', 'تحلیل از دادهٔ منتشرشده انجام می‌شود. بازه‌ها تا زمان آخرین دریافت داده محاسبه می‌شوند. گیلد جدید هنگام به‌روزرسانی دادهٔ سایت اضافه می‌شود.'],
snapshotAt: ['Data as of', 'داده تا'],
staleSnapshot: ['This dataset is over 36 hours old; refresh the site data for newer fights.', 'بیش از ۳۶ ساعت از دریافت داده گذشته است؛ برای نبردهای جدید، دادهٔ سایت باید به‌روز شود.'],
dataError: ['The published dataset could not be loaded. Retry or refresh the site data. No incomplete totals are shown.', 'دادهٔ منتشرشده دریافت نشد. دوباره تلاش کن یا دادهٔ سایت را به‌روز کن. آمار ناقص به‌عنوان نتیجه نمایش داده نمی‌شود.'],
missingData: ['No dataset has been published for this guild yet. Choose a prepared guild above, or add the guild when refreshing the site data.', 'برای این گیلد هنوز داده‌ای منتشر نشده است. یکی از گیلدهای آماده را انتخاب کن یا نام این گیلد را هنگام به‌روزرسانی دادهٔ سایت اضافه کن.'],
retry: ['Try again', 'تلاش دوباره'],
cancelled: ['Analysis cancelled. Adjust the filters and try again.', 'تحلیل لغو شد. فیلترها را تنظیم کن و دوباره شروع کن.'],
emptyTitle: ['No battles in this window.', 'در این بازه بتلی پیدا نشد.'],
+1
View File
@@ -7,5 +7,6 @@
@media(max-width:760px){.intel-header{padding:18px 5%;gap:15px}.intel-header .brand img{width:35px;height:35px}.intel-header .brand{gap:8px}.intel-back{font-size:10px}.intel-header .languages{font-size:10px}.intel-main{padding-inline:5%;padding-bottom:35px}.intel-hero{padding:37px 0 55px;min-height:0}.intel-hero h1{font-size:55px}.intel-intro{max-width:100%;font-size:12px}.intel-signal{display:none}.intel-source{position:static;margin-top:22px;font-size:7px}.intel-controls{padding:20px 18px 0}.intel-controls form{grid-template-columns:1fr 1fr;gap:18px 12px}.intel-search{grid-column:1/-1}.intel-controls label,.intel-controls legend{font-size:10px}.minimum-field input{height:46px}.intel-submit{font-size:12px}.intel-control-bottom{flex-direction:column;align-items:flex-start;gap:12px;padding-block:16px}.intel-control-bottom p{border:0;padding:0;font-size:10px}.intel-status{min-height:65px;font-size:9px}.intel-empty{padding:37px 20px}.intel-empty h2{font-size:29px}.intel-empty>p:not(.eyebrow){font-size:11px}.intel-steps{gap:14px;flex-wrap:wrap}.intel-steps span{font-size:9px}.intel-result-heading h2{font-size:36px}.intel-result-heading{align-items:flex-start;margin-top:12px}.intel-download{font-size:9px;padding:7px 9px}.intel-result-heading p:not(.eyebrow){font-size:10px}.intel-metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.intel-metric{padding:16px}.intel-metric strong{font-size:36px}.intel-analysis-grid,.intel-detail-grid{grid-template-columns:1fr;gap:16px}.intel-panel{padding:20px}.composition-body{flex-direction:row;gap:24px;min-height:190px}.role-donut{width:145px}.role-donut>div{inset:14px}.role-legend>div{font-size:10px}.role-legend small{font-size:8px;min-width:30px}.fame-chart svg{height:190px}.chart-scale{padding-bottom:25px}.chart-key{font-size:7px}.panel-heading h3{font-size:26px}.intel-footer{padding:20px 5%;flex-wrap:wrap;gap:8px 18px}.intel-footer p{flex-basis:100%;order:3;font-size:9px}.intel-footer a{margin-inline-start:auto}.encounter>summary{grid-template-columns:65px 1fr 85px 18px;gap:12px;padding:16px}.encounter-stat:not(.encounter-kd){grid-row:2}.encounter-stat:nth-child(3){grid-column:2}.encounter-stat:nth-child(4){grid-column:3}.encounter-kd{grid-column:3;grid-row:1;text-align:end}.encounter-expand{grid-column:4;grid-row:1}.encounter-date{grid-row:1/3}.encounter-name{grid-column:2;grid-row:1}.encounter-name h4{font-size:11px}.encounter-stat strong{font-size:23px}.encounter-stat small{font-size:8px}.encounter-type{font-size:7px}.encounter-weapons{grid-template-columns:repeat(2,minmax(0,1fr));gap:0 16px}.encounter-body{padding:16px}.ledger-controls select{min-width:120px;font-size:10px}.ledger-controls input{font-size:10px}.intel-detail-grid{margin-bottom:30px}[dir=rtl] .intel-hero h1{font-size:39px;letter-spacing:-1.5px;line-height:1.65}[dir=rtl] .intel-hero{padding-block:30px 35px}[dir=rtl] .intel-empty h2{font-size:22px}[dir=rtl] .panel-heading h3{font-size:18px}}
@media(max-width:390px){.intel-back{display:none}.intel-controls form{grid-template-columns:1fr}.period-field,.minimum-field{grid-column:1/-1}.composition-body{gap:15px}.role-donut{width:120px}.role-donut>div{inset:12px}.role-donut strong{font-size:30px}.role-donut span{font-size:7px}.role-legend>div{font-size:9px}.intel-metric>span{font-size:9px}.intel-download{max-width:90px}.encounter-weapons{grid-template-columns:1fr}}
.intel-dataset{margin-bottom:16px;border:1px solid var(--line);border-radius:6px;padding:14px 17px;background:#17191970}.intel-dataset>div:first-child{display:flex;align-items:center;gap:9px}.intel-dataset p{font-size:10px;color:#a5a59d;line-height:1.9;margin:0}.intel-dataset>p{margin-top:8px;font-size:9px;color:#8c948e}#available-guilds{display:flex;flex-wrap:wrap;gap:7px;margin-top:10px}#available-guilds button{background:#66313b44;border:1px solid #a9576b55;border-radius:4px;padding:4px 12px;font-size:11px;color:#e1bfc7}#available-guilds button:hover{background:#66313b88}
/* Keep branding anchored in both writing directions and numerical units together. */
.intel-header .brand{margin-inline-end:0}.intel-back{margin-inline-start:auto}.intel-metric strong{white-space:nowrap;font-variant-numeric:tabular-nums}.intel-table td:nth-child(3){white-space:nowrap}.encounter-stat strong{unicode-bidi:plaintext}.encounter-detail-top{flex-wrap:wrap}@media(max-width:390px){.intel-header .languages{margin-inline-start:auto}}
+36 -45
View File
@@ -1,12 +1,13 @@
import { ROLES, normalizeName, ownGuild, groupReports, selectBattles, makeReport, summarize, mapLimit, scanListings } from './intel-core.js';
import { ROLES, normalizeName, ownGuild, groupReports, selectBattles, makeReport, summarize, mapLimit } from './intel-core.js';
import { textFor } from './intel-text.js';
import { createDataSource, DataError, groupKey } from './intel-data.js';
const fa = document.documentElement.lang === 'fa', t = textFor(fa ? 'fa' : 'en');
const locale = fa ? 'fa-IR' : 'en-GB', form = document.querySelector('#intel-form');
const results = document.querySelector('#intel-results'), empty = document.querySelector('#intel-empty');
const errorBox = document.querySelector('#intel-error'), status = document.querySelector('#intel-status');
const cancel = document.querySelector('#intel-cancel'), cache = new Map();
const apiBase = document.body.dataset.apiBase.replace(/\/$/, '');
const cancel = document.querySelector('#intel-cancel');
const source = createDataSource();
const e = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' }[c]));
const number = (value, decimals = 0) => new Intl.NumberFormat(locale, { maximumFractionDigits: decimals }).format(value);
const compact = value => {
@@ -21,32 +22,6 @@ const roleColor = { tank:'#d5a65c', healer:'#6ac5a3', support:'#9d8de2', range:'
let controller, generation = 0, loaded, forcedGuild;
class ReportError extends Error {}
async function api(path, query = {}, signal) {
const url = `${apiBase}${path}${Object.keys(query).length ? `?${new URLSearchParams(query)}` : ''}`;
const cached = cache.get(url);
if (cached && Date.now() - cached.at < 120_000) return cached.data;
for (let attempt = 0; attempt < 3; attempt++) {
signal?.throwIfAborted();
let response;
try {
response = await fetch(url, { signal: AbortSignal.any([signal || new AbortController().signal, AbortSignal.timeout(35_000)]), headers: { Accept:'application/json' } });
if (response.status === 404 || !response.headers.get('content-type')?.includes('application/json')) throw new ReportError(t.proxyError);
if (!response.ok) throw Error(`HTTP ${response.status}`);
const data = await response.json();
cache.set(url, { at:Date.now(), data });
if (cache.size > 2500) cache.delete(cache.keys().next().value);
return data;
} catch (error) {
if (signal?.aborted || error instanceof ReportError || attempt === 2) throw error;
await new Promise((resolve, reject) => {
const done = () => { signal?.removeEventListener('abort', abort); resolve(); };
const timer = setTimeout(done, 700 * (attempt + 1));
const abort = () => { clearTimeout(timer); reject(signal.reason); };
signal?.addEventListener('abort', abort, { once:true });
});
}
}
}
function progress(message, run) {
if (run !== generation) return;
document.querySelector('#status-text').textContent = message;
@@ -76,8 +51,9 @@ async function analyze(event) {
results.setAttribute('aria-busy','true');
progress(t.finding, run);
try {
const candidates = await api('/guilds/search', { search:config.name }, signal);
if (!Array.isArray(candidates)) throw Error('Invalid guild search');
const index = await source.index(signal);
showAvailable(index);
const candidates = index.guilds;
const exact = candidates.filter(g => normalizeName(g.Name) === normalizeName(config.name));
if (!exact.length) throw new ReportError(t.notFound);
if (forcedGuild && !exact.some(g => g.Id === forcedGuild)) forcedGuild = undefined;
@@ -93,21 +69,17 @@ async function analyze(event) {
return;
}
const guild = exact.find(g => g.Id === forcedGuild) || exact[0];
const until = Date.now(), since = until - config.days * 86_400_000;
const listings = await scanListings(api, guild.Id, since, signal,
(page, count) => progress(`${t.scanning} · ${t.page} ${number(page)} · ${number(count)} ${t.battles}`, run), config.minimum);
let count = 0;
const battles = await mapLimit(listings, 4, async row => {
const detail = await api(`/battles/${row.albionId}`, {}, signal);
if (detail.albionId !== row.albionId || !ownGuild(detail, guild.Id) || !Array.isArray(detail.players)) throw new ReportError(t.partial);
progress(`${t.details} · ${number(++count)} / ${number(listings.length)}`, run);
return detail;
});
const snapshot = await source.load(guild,signal);
const until = Date.parse(snapshot.asOf), since = until - config.days * 86_400_000;
const battles = snapshot.battles;
const stamp = new Intl.DateTimeFormat(locale,{dateStyle:'medium',timeStyle:'short',timeZone:'UTC'}).format(new Date(until));
document.querySelector('#snapshot-status').textContent = `${guild.Name} · ${t.snapshotAt} ${stamp} UTC${Date.now()-until>36*3_600_000 ? ` · ${t.staleSnapshot}` : ''}`;
const selected = selectBattles(battles, guild.Id, { since, until, minPlayers:config.minimum });
const groups = groupReports(selected, guild.Id, config.merge);
count = 0;
let count = 0;
const reports = await mapLimit(groups, 2, async group => {
const combined = group.length > 1 ? await api('/battles/multi', { ids:group.map(b => b.albionId).join(',') }, signal) : null;
const combined = group.length > 1 ? snapshot.multis[groupKey(group.map(b => b.albionId))] : null;
if (group.length>1 && !combined) throw new DataError('invalid');
if (combined) {
const guildTotal = ownGuild(combined, guild.Id);
for (const key of ['kills', 'deaths', 'killFame']) {
@@ -129,8 +101,8 @@ async function analyze(event) {
if (cancelled) {
empty.hidden = false; progress(t.cancelled, run);
} else {
showError(error instanceof ReportError ? error.message : t.error);
progress(t.error, run);
showError(error instanceof DataError ? t.dataError : error instanceof ReportError ? error.message : t.error);
progress(error instanceof DataError ? t.dataError : t.error, run);
}
} finally {
if (run === generation) {
@@ -237,6 +209,16 @@ function exportCsv() {
const url = URL.createObjectURL(blob), a = document.createElement('a');
a.href = url; a.download = `guild-intelligence-${loaded.config.days}d.csv`; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
}
function showAvailable(index) {
const container = document.querySelector('#available-guilds');
const datalist = document.querySelector('#prepared-guilds');
container.replaceChildren(); datalist.replaceChildren();
for (const guild of index.guilds) {
const button = document.createElement('button');button.type='button';button.textContent=guild.Name;
button.addEventListener('click',()=>{form.elements.guild.value=guild.Name;analyze();});container.append(button);
const option = document.createElement('option');option.value=guild.Name;datalist.append(option);
}
}
form.addEventListener('submit', analyze);
cancel.addEventListener('click', () => controller?.abort());
document.querySelector('#intel-retry').addEventListener('click', () => analyze());
@@ -246,4 +228,13 @@ if (['7','30','60'].includes(query.get('days'))) form.elements.days.value = quer
if (/^\d+$/.test(query.get('minimum') || '') && Number(query.get('minimum')) >= 1 && Number(query.get('minimum')) <= 1000) form.elements.minimum.value = query.get('minimum');
if (query.get('merge') === '0') form.elements.merge.checked = false;
document.querySelectorAll('[data-intel-language]').forEach(a => { a.search = query.toString(); });
async function initialize() {
try {
const index = await source.index();
showAvailable(index);
document.querySelector('#snapshot-status').textContent = `${t.availableGuilds}: ${index.guilds.map(g=>g.Name).join(' / ')}`;
if (!form.elements.guild.value && index.guilds.length) form.elements.guild.value=index.guilds[0].Name;
if (form.elements.guild.value) analyze();
} catch { document.querySelector('#snapshot-status').textContent=t.dataError; }
}
initialize();
+79 -19
View File
@@ -1,8 +1,11 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { selectBattles, groupReports, makeReport, summarize, scanListings, mapLimit, normalizeName } from '../src/intel-core.js';
import { proxyAlbion, upstreamUrl } from '../scripts/albion-proxy.mjs';
import { createDataSource, validateIndex, validateSnapshot, DataError } from '../src/intel-data.js';
import { collectGuild, requiredMultis, compactBattle } from '../scripts/sync-intel.mjs';
import { renderIntel } from '../scripts/render-intel.mjs';
import { readFile } from 'node:fs/promises';
import { groupBattles } from '../scripts/import-battles.mjs';
const battle = (id, minute = 0, options = {}) => ({
albionId:id, startedAt:new Date(Date.UTC(2026,9,20,10,minute)).toISOString(), finishedAt:new Date(Date.UTC(2026,9,20,10,minute+2)).toISOString(),
@@ -30,6 +33,11 @@ test('merge requires time, roster AND other-team continuity and supports disable
b.players=b.players.map(p=>({...p,name:`other-${p.name}`}));
assert.equal(groupReports([a,b],'guild').length,2);
});
test('bounded active-window grouping preserves the existing real archive grouping',async()=>{
const source=JSON.parse(await readFile(new URL('../docs/battle-source.json',import.meta.url),'utf8'));
const rows=source.battles.map(b=>({...b,players:b.ownPlayers.map(name=>({name,guildName:b.guilds.find(g=>g.albionId===source.guildId).name}))}));
assert.deepEqual(groupReports(rows,source.guildId).map(g=>g.map(b=>b.albionId)),groupBattles(source.battles,source.guildId).map(g=>g.map(b=>b.albionId)));
});
test('summary uses merged roster once, maintains exact fame and recovers end time from originals', () => {
const a=battle(1),b=battle(2,10),combined=battle(1);
combined.finishedAt=a.finishedAt;
@@ -71,29 +79,81 @@ test('bounded concurrency preserves order and propagates failures', async () =>
assert.deepEqual(out,[2,4,6,8,10]);assert.equal(peak,2);
await assert.rejects(mapLimit([1,2],1,async()=>{throw Error('failed report');}),/failed report/);
});
test('proxy only permits public whitelisted read endpoints and strips browser headers', async () => {
assert.throws(()=>upstreamUrl('https://oneup.test/api/albion/https://evil.test'));
assert.throws(()=>upstreamUrl('https://oneup.test/api/albion/battles?url=https://evil.test'));
assert.throws(()=>upstreamUrl('https://oneup.test/api/albion/battles/multi?ids=1,evil'));
assert.equal(upstreamUrl('https://oneup.test/api/albion/guilds/search?search=OneUP').hostname,'api.albionbb.com');
const request=new Request('https://oneup.test/api/albion/battles/123',{headers:{Authorization:'private',Cookie:'private'}});
const result=await proxyAlbion(request,async(url,options)=>{
assert.equal(url.href,'https://api.albionbb.com/eu/battles/123');
assert.deepEqual(options.headers,{Accept:'application/json'});
return Response.json({albionId:123});
test('static collector fetches complete details and verified multis for all filter boundaries', async () => {
const rows=[battle(1),battle(2,10),battle(3,20,{total:60})];
const merged={...battle(1),guilds:[{...rows[0].guilds[0],kills:6,deaths:3,killFame:3000},rows[0].guilds[1]]};
const pair={...battle(1),guilds:[{...rows[0].guilds[0],kills:4,deaths:2,killFame:2000},rows[0].guilds[1]]};
const calls=[];
const request=async(path,query={})=>{
calls.push([path,query]);
if(path==='/guilds/search')return [{Id:'guild',Name:'OneUP'}];
if(path==='/battles')return rows;
if(path==='/battles/multi')return query.ids==='1,2,3'?merged:pair;
return rows.find(b=>path===`/battles/${b.albionId}`);
};
const snapshot=await collectGuild('OneUP',null,{request,asOf:'2026-10-20T12:00:00Z'});
assert.equal(snapshot.battles.length,3);assert.equal(snapshot.coverageDays,60);
assert.ok(snapshot.multis['1,2,3']);
assert.equal(calls.filter(([p])=>p==='/battles').length,1);
await assert.rejects(collectGuild('OneUP',null,{asOf:snapshot.asOf,request:async(p,q)=>p==='/battles/multi'?{...merged,guilds:[{...merged.guilds[0],kills:99}]}:request(p,q)}),/Unverified multi/);
});
assert.deepEqual(await result.json(),{albionId:123});
assert.equal((await proxyAlbion(new Request(request.url,{method:'POST'}))).status,405);
assert.equal((await proxyAlbion(request,async()=>new Response('',{status:429}))).status,429);
test('precomputed multis cover non-default total-player thresholds and time windows',()=>{
const rows=[battle(1,0,{total:40}),battle(2,10,{total:60}),battle(3,20,{total:80})];
const groups=requiredMultis(rows,'guild','2026-10-20T12:00:00Z');
assert.ok(groups.has('1,2,3'));assert.ok(groups.has('2,3'));
for(const minimum of [1,40,41,50,60,61,80,81]){
for(const group of groupReports(rows.filter(b=>b.totalPlayers>=minimum),'guild')) {
if(group.length>1)assert.ok(groups.has(group.map(b=>b.albionId).join(',')));
}
}
const source=battle(9);source.players.push({name:'enemy',guildName:'Enemy'});
assert.equal(compactBattle(source,'guild').players.length,4);
assert.equal(compactBattle(source,'guild').guilds.length,2);
});
test('bilingual page has accessible filters, correct total-player copy and escaped configuration', () => {
assert.equal(normalizeName(' OneUP '),'oneup');
test('static loader requests only same-origin data and validates bundle identity',async()=>{
const entry={Id:'guild',Name:'OneUP',file:'guild-123abc.json',asOf:'2026-10-20T12:00:00Z',coverageDays:60};
const snapshot={schemaVersion:1,guild:{Id:'guild',Name:'OneUP'},asOf:entry.asOf,coverageDays:60,battles:[battle(1)],multis:{}};
const index={schemaVersion:1,guilds:[entry]};
const calls=[];
const source=createDataSource({baseUrl:'https://oneup.test/data/intel/',fetchImpl:async(url,options)=>{
calls.push(url.href);assert.equal(url.origin,'https://oneup.test');assert.equal(options.mode,'same-origin');assert.equal(options.credentials,'omit');
return Response.json(url.pathname.endsWith('manifest.json')?index:snapshot);
}});
const manifest=await source.index();assert.deepEqual(manifest,index);
assert.deepEqual(await source.load(manifest.guilds[0]),snapshot);
await source.load(entry);assert.equal(calls.length,2);
assert.throws(()=>validateIndex({...index,guilds:[{...entry,file:'../../evil.json'}]}),DataError);
assert.throws(()=>validateSnapshot({...snapshot,guild:{Id:'other'}},entry),DataError);
assert.throws(()=>validateSnapshot({...snapshot,battles:[battle(1),battle(1)]},entry),DataError);
});
test('missing files and cancellation cannot masquerade as empty reports',async()=>{
const source=createDataSource({baseUrl:'https://oneup.test/data/intel/',fetchImpl:async()=>new Response('',{status:404})});
await assert.rejects(source.index(),error=>error.code==='missing');
const controller=new AbortController();controller.abort();
await assert.rejects(source.index(controller.signal),{name:'AbortError'});
});
test('published real datasets contain every required multi and verified guild totals',async()=>{
const directory=new URL('../public/data/intel/',import.meta.url);
const index=validateIndex(JSON.parse(await readFile(new URL('manifest.json',directory),'utf8')));
assert.ok(index.guilds.some(g=>normalizeName(g.Name)==='oneup'));
for(const entry of index.guilds){
const snapshot=validateSnapshot(JSON.parse(await readFile(new URL(entry.file,directory),'utf8')),entry);
for(const [key,group] of requiredMultis(snapshot.battles,entry.Id,snapshot.asOf)){
const multi=snapshot.multis[key];assert.ok(multi,`Missing multi ${key}`);
for(const field of ['kills','deaths','killFame']){
assert.equal(multi.guilds.find(g=>g.albionId===entry.Id)[field],group.reduce((sum,b)=>sum+b.guilds.find(g=>g.albionId===entry.Id)[field],0));
}
}
}
});
test('bilingual static page exposes prepared guilds and contains no proxy setup',()=>{
for(const lang of ['en','fa']){
const html=renderIntel(lang,'https://oneup.test','/api/albion');
const html=renderIntel(lang,'https://oneup.test');
assert.match(html,new RegExp(`<html lang="${lang}" dir="${lang==='fa'?'rtl':'ltr'}">`));
assert.match(html,/value="7" checked/);assert.match(html,/value="30"/);assert.match(html,/value="60"/);
assert.match(html,/aria-live="polite"/);assert.match(html,/id="min-help"/);
assert.ok(!html.includes('undefined'));
assert.match(html,/id="snapshot-status"/);assert.match(html,/id="prepared-guilds"/);
assert.ok(!html.includes('undefined'));assert.ok(!html.includes('/api/albion'));
assert.ok(!html.includes('connection-form'));assert.ok(!html.includes('apiKey'));
}
assert.match(renderIntel('en','https://oneup.test'),/All guilds combined, before merging/);
assert.match(renderIntel('fa','https://oneup.test'),/مجموع بازیکنان همهٔ گیلدها/);
-20
View File
@@ -1,20 +0,0 @@
import { proxyAlbion } from './scripts/albion-proxy.mjs';
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname.startsWith('/api/albion/')) {
// An optional separately hosted API only shares public reports with the configured site.
const origin = request.headers.get('Origin');
const allowed = !origin || origin === url.origin || origin === env.SITE_ORIGIN;
if (!allowed) return new Response('Forbidden', { status: 403 });
const response = await proxyAlbion(request);
if (origin && origin === env.SITE_ORIGIN) {
response.headers.set('Access-Control-Allow-Origin', origin);
response.headers.set('Vary', 'Origin');
}
return response;
}
return env.ASSETS.fetch(request);
},
};
-6
View File
@@ -1,6 +0,0 @@
{
"name": "oneup-guild",
"main": "worker.mjs",
"compatibility_date": "2026-10-20",
"assets": { "directory": "./dist", "binding": "ASSETS", "run_worker_first": ["/api/albion/*"] }
}