Files
linkspin/bannerspin.js
martbost 98e3ed36d8 Conversion tracking fixes (Marty approved 2026-10-26): own clicks are tests on every click type, Banner Spin straight-to-page clicks carry lsclk
1. Own clicks: a goal owner's own click on ANY click type (LinkSpin/InstantAdPay ads, spin links, Banner Spins) is kept as a test, never counted, never fires a goal postback. Own = ad click flagged self for that owner, a spin-link / Banner Spin click marked at click time (signed in as the owner, or from an owner soft key: markOwnClick in server.js), or the clicking or converting browser's soft key is one the owner signs in from. auth.onSeen notes LinkSpin session soft keys (throttled, kept 31 days in convtrack.json S.own); /api/partner/clicks takes owners [{owner, sk, ts}] from InstantAdPay before the clicks, so IAP members' own browsers are known too. Linked positions share the owner's email. X-LS-Result adds ;self. partnerSummary returns selfTests for the IAP card. Conversions screen copy: test with Send a test conversion and the &test=1 page check, own clicks never count (conversions.js ?v=20261026a).
3. Banner Spin: a click whose target is a direct page (not a /r/ spin link) gets ?lsclk=<k click id> when the owner tracks goals (string insert like lsconv.withClickId: params kept, before #hash, an existing lsclk never replaced). convtrack.lookup resolves k ids through bannerspin.clickById; conversions record k:'bspin' with the Banner Spin, banner, page and source; report By Banner Spin, CSV site 'Banner Spin', postback ctx with its sub ids.
Guides: /conversion-tracking (Banner Spin straight to a page now counted, own clicks on every type are tests, By Banner Spin), /refuel tile. Chatbot CANNED + FACTS, KNOWLEDGE_DATE 2026-10-26.
QA: convpixel 77/77 (new: owner soft keys, own ad/spin/Banner Spin/IAP clicks as tests, stranger still counts, own-browser conversion, withClickId, Banner Spin lsclk + By Banner Spin + spin-link banner untouched, selfTests in the IAP summary, no postback for own clicks); lsid 31/31; fuel all pass (engine.js / engine-room.js / kit.js untouched, byte-identical with InstantAdPay); bannerspin 75/75; member walk 0 bugs; public 0 bugs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 06:19:54 -05:00

484 lines
46 KiB
JavaScript

// Banner Spin (LinkSpin, 2026-10-18, plan approved by Marty the same day): one image URL + one click URL that rotate up to
// 25 banners, each with its own target. Phase 1 (engine) + phase 2 (builder) of "LinkSpin Banner Spin: plan".
//
// Serving. /i/<code>.gif picks a banner on every load (weighted pick, pause, dayparting, fallback: the rotator's own rules)
// and answers with the image itself (uploaded files from DATA_DIR/uploads, hot ones cached in memory) or a no-store 302
// to a pasted https image. Every image response is Cache-Control: no-store, private with a fresh ETag, so a browser asks
// again on every page view. /s/<code>.js writes the banner AND its own click link in one go (exact match). /c/<code> is the
// click. Paths are neutral on purpose: no size token and never the words banner or ads (EasyList), and codes never
// contain "ad". Every link domain answers every code, like /r/.
//
// Click matching (the image and the click are two separate requests). On each image load the server keeps a note in
// memory: visitor key + referring page host -> the banner it showed, for 15 minutes. The visitor key is the same
// daily-salted hash spin links use (no IP stored). On a click the note for that key + host is looked up (the most recent
// one when there are several) and the visitor goes to that banner's target; no note -> the fallback target, logged as
// unmatched. /s/ clicks carry the banner (?x=) and match exactly. Rotation modes: random by weight (default) or one per
// visitor (the same banner all day, a stable hash of the visitor key).
//
// Counting. Impressions are COUNTERS (per banner, per placement host, per Central day, plus a small uniques sample), kept
// as pending deltas in memory and merged into DATA_DIR/bannerspin-counts.json every few seconds (read, add, atomic
// write, so two app copies during a deploy overlap both land). Bots and prefetchers are not counted; one visitor's
// reloads count once per minute per banner. Clicks are rows like spin-link clicks, with the usual lsid click id
// ('k' + 11 hex, never valid hex so it can never collide with a rotator id), so joins / wallets / purchases and partner
// postbacks credit the banner (rotator.convert falls through to convert() here), and a traffic source's postback fires.
// Since 2026-10-26 a click that goes straight to a page also gets ?lsclk=<click id> when the owner tracks goals, so the
// conversion pixel (convtrack.js, clickById below) counts goals from Banner Spin banners that skip a spin link.
//
// Access. Members with at least one own package of $25 or more. Starter 2 Banner Spins x 5 banners; Builder (level 2
// open, 2 qualifying buyers) 5 x 15; Leader (level 3 open, 5 qualifying buyers) 10 x 25. Facts come from server.js
// (chain + positions); once seen they are remembered here so a rolling chain window never takes a tier away. Dropping
// below a tier keeps everything serving; it only stops new ones.
//
// Moderation. Admin can take one banner or a whole Banner Spin offline (a neutral blank image + the fallback link), or
// switch the whole feature off (a button in Admin > Member content since phase 3). Store: DATA_DIR/bannerspin.json (atomic writes).
//
// Phase 3 (2026-10-20, "Reports and health"): every image load is also counted raw per placement (bots, prefetches and
// servers / mail image proxies kept apart from views), which feeds the "caches banners" flag; stats() and summary() share
// one aggregation (per banner, per placement, by Central day, country and device, a winner once two banners have 1,000
// views each); health.js checks each live banner's image and target every 30 minutes (b.health, b.autoPaused).
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
let DATA_DIR = null, UPLOADS_DIR = null, rotator = null, geo = null, SOURCES = null, OWN_HOSTS = () => [], FACTS = async () => ({ ownBuy: false, buyers: 0 }), ADMIN = '';
const DAY = 86400000;
const SIZES = { '468x60': [468, 60], '728x90': [728, 90], '300x250': [300, 250], '125x125': [125, 125], '160x600': [160, 600], '120x600': [120, 600], '336x280': [336, 280], '250x250': [250, 250], '320x50': [320, 50] };
const TIERS = {
starter: { key: 'starter', label: 'Starter', spins: 2, banners: 5, need: 'your own package of $25 or more' },
builder: { key: 'builder', label: 'Builder', spins: 5, banners: 15, need: 'level 2 open, 2 qualifying buyers' },
leader: { key: 'leader', label: 'Leader', spins: 10, banners: 25, need: 'level 3 open, 5 qualifying buyers' }
};
const ORDER = ['starter', 'builder', 'leader'];
const MAX_BYTES = 150 * 1024, MAX_BANNERS = 25;
const NOTE_TTL = 15 * 60000, DEDUPE_MS = 60000, FLUSH_MS = 5000, UNIQ_CAP = 500, HOSTS_CAP = 200;
const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i;
const norm = e => String(e || '').trim().toLowerCase();
const CT_FMT = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit' });
const ctDay = ts => CT_FMT.format(new Date(ts || Date.now()));
const LOCAL_IMG = /^\/uploads\/([a-f0-9]{24}\.(png|jpg|gif))$/;
const MIME = { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' };
const httpsUrl = u => { let s = String(u || '').trim(); if (s && !/^[a-z][a-z0-9+.-]*:\/\//i.test(s) && /^[^\s\/]+\.[^\s]+/.test(s)) s = 'https://' + s; return /^https:\/\/[^\s"'<>]+$/i.test(s) && s.length <= 500 ? s : null; };
function writeAtomic(file, data) { try { const tmp = file + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, data); fs.renameSync(tmp, file); } catch (e) { console.error('bannerspin save', e.message); } }
const J = { db: null, FILE: () => path.join(DATA_DIR, 'bannerspin.json'),
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = null; } if (!this.db || typeof this.db !== 'object') this.db = { v: 1 };
for (const k of ['spins', 'clicks', 'conv']) if (!Array.isArray(this.db[k])) this.db[k] = [];
for (const k of ['images', 'grants', 'qual', 'settings']) if (!this.db[k] || typeof this.db[k] !== 'object') this.db[k] = {}; },
save() { writeAtomic(this.FILE(), JSON.stringify(this.db)); } };
// impression counters: d[spinId][day] = { b: { bid: n }, h: { host: { bid: n } }, u: { bid: [visitor prefixes] } }
const C = { db: { v: 1, d: {} }, FILE: () => path.join(DATA_DIR, 'bannerspin-counts.json'),
read() { try { const x = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); return x && x.d ? x : { v: 1, d: {} }; } catch (e) { return { v: 1, d: {} }; } } };
let PENDING = { d: {} }, DIRTY = false, timer = null, lastPrune = 0;
// conversion pixel (2026-10-26): a click that goes straight to a page (not a spin link) gets ?lsclk=<this click id> when
// the owner tracks goals, the same rule spin links follow. server.js hands in the goal check and convtrack's string insert.
let WANTS_CLICK_ID = () => false, WITH_CLICK_ID = (u) => u;
function init(opts) {
DATA_DIR = opts.dataDir; UPLOADS_DIR = opts.uploadsDir || path.join(DATA_DIR, 'uploads'); rotator = opts.rotator || null; geo = opts.geo || null; SOURCES = opts.sources || null;
OWN_HOSTS = opts.ownHosts || OWN_HOSTS; FACTS = opts.facts || FACTS; ADMIN = norm(opts.adminEmail);
if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; if (opts.withClickId) WITH_CLICK_ID = opts.withClickId;
J.load(); C.db = C.read();
if (opts.schedule !== false) { timer = setInterval(() => { flush(); sweep(); }, FLUSH_MS); if (timer.unref) timer.unref(); }
}
// ── codes: 7 chars, no 0/1/i/l/o, never containing "ad" or digit-x-digit (EasyList), unique among Banner Spins ──
const ALPHA = 'abcdefghjkmnpqrstuvwxyz23456789';
const BAD_CODE = /ad|banner|\dx\d/; // no digit-x-digit run either, so nothing reads like a size
function newCode() { for (;;) { let s = ''; for (let i = 0; i < 7; i++) s += ALPHA[crypto.randomInt(ALPHA.length)]; if (!BAD_CODE.test(s) && !J.db.spins.some(x => x.code === s)) return s; } }
// ── visitor key: the rotator's daily-salted hash (UTC day | ip | ua), nothing stored but the hash ──
const ipOf = req => String(req.headers['x-forwarded-for'] || (req.socket && req.socket.remoteAddress) || '').split(',')[0].trim();
const vkey = (req, ts) => crypto.createHash('sha256').update(new Date(ts || Date.now()).toISOString().slice(0, 10) + '|' + ipOf(req) + '|' + String(req.headers['user-agent'] || '')).digest('hex').slice(0, 16);
// keys to try for a click: today's, and yesterday's for the first 15 minutes after UTC midnight (a note made at 23:59 still matches)
function vkeys(req) { const now = Date.now(); const k = [vkey(req, now)]; if (now % DAY < NOTE_TTL) k.push(vkey(req, now - DAY)); return k; }
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT.test(ua); };
const isPrefetch = req => /prefetch|prerender|preview/i.test([req.headers.purpose, req.headers['sec-purpose'], req.headers['x-purpose'], req.headers['x-moz']].filter(Boolean).join(' '));
// a server fetching the image, not a browser (phase 3, 2026-10-20): mail image proxies and plain HTTP libraries. Kept out of
// impressions like bots, but counted per placement, because a site that copies banners to its own server shows up this way.
const PROXY = /GoogleImageProxy|ggpht\.com|YahooMailProxy|ImageProxy|^(php|java|go-http-client|okhttp|axios|node-fetch|undici|libwww-perl|apache-httpclient|guzzlehttp|ruby)\b/i;
// '' = a browser view (counted), 'pre' = prefetch, 'bot' = bot or no UA, 'srv' = a server or image proxy
const loaderKind = req => isPrefetch(req) ? 'pre' : isBot(req) ? 'bot' : PROXY.test(String(req.headers['user-agent'] || '')) ? 'srv' : '';
// the placement: the page the banner sits on (the browser's referrer, else its origin), www stripped
function hostOf(req) { try { return new URL(String(req.headers.referer || req.headers.origin || '')).hostname.toLowerCase().replace(/^www\./, '').slice(0, 80); } catch (e) { return ''; } }
// ── in-memory notes: visitor key -> [{ s, h, b, ts }] (newest last), 15 min ──
const NOTES = new Map(); const SEEN = new Map(); // SEEN: v|spin|bid -> ts of the last counted impression
function note(v, s, h, b) { let a = NOTES.get(v); if (!a) { if (NOTES.size > 200000) return; a = []; NOTES.set(v, a); } a.push({ s, h, b, ts: Date.now() }); if (a.length > 12) a.splice(0, a.length - 12); }
function findNote(keys, s, h) {
const now = Date.now(); let best = null, any = null;
for (const v of keys) for (const n of (NOTES.get(v) || [])) { if (n.s !== s || now - n.ts > NOTE_TTL) continue; if (!any || n.ts >= any.ts) any = n; if (n.h === h && (!best || n.ts >= best.ts)) best = n; }
// a click with no referrer (strict privacy settings) takes the visitor's most recent note on this Banner Spin
return best || (!h ? any : null);
}
function sweep() { const now = Date.now(); for (const [k, a] of NOTES) { const keep = a.filter(n => now - n.ts <= NOTE_TTL); if (keep.length) NOTES.set(k, keep); else NOTES.delete(k); } for (const [k, t] of SEEN) if (now - t > DEDUPE_MS) SEEN.delete(k); }
// ── counters ──
// a day record: b = counted views per banner, h = per placement host per banner, u = uniques sample per banner,
// bt = bot + prefetch loads, sv = server / image-proxy loads, z = per placement host { r: every load, s: loads with no browser, k: top loaders sample }
const dayRec = sid => { const day = ctDay(); const s = PENDING.d[sid] = PENDING.d[sid] || {}; return s[day] = s[day] || { b: {}, h: {}, u: {}, z: {} }; };
function bump(sid, bid, host, v) {
const d = dayRec(sid);
d.b[bid] = (d.b[bid] || 0) + 1; const hk = host || '(none)'; const hh = d.h[hk] = d.h[hk] || {}; hh[bid] = (hh[bid] || 0) + 1;
const u = d.u[bid] = d.u[bid] || []; const p = v.slice(0, 8); if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p);
DIRTY = true;
}
// every image load (counted or not), for bots shown separately and the "caches banners" flag
const LOADERS_CAP = 10;
function rawLoad(sid, host, v, kind) {
const d = dayRec(sid); const hk = host || '(none)'; const z = d.z[hk] = d.z[hk] || { r: 0, s: 0, k: {} };
z.r++; if (kind === 'bot' || kind === 'srv') z.s++;
const p = v.slice(0, 8); if (z.k[p] != null || Object.keys(z.k).length < LOADERS_CAP) z.k[p] = (z.k[p] || 0) + 1;
if (kind === 'bot' || kind === 'pre') d.bt = (d.bt || 0) + 1; else if (kind === 'srv') d.sv = (d.sv || 0) + 1;
DIRTY = true;
}
function mergeInto(base, add) {
for (const [sid, days] of Object.entries(add.d)) { const s = base.d[sid] = base.d[sid] || {};
for (const [day, x] of Object.entries(days)) { const d = s[day] = s[day] || { b: {}, h: {}, u: {} };
for (const [b, n] of Object.entries(x.b || {})) d.b[b] = (d.b[b] || 0) + n;
for (const [h, m] of Object.entries(x.h || {})) { let hh = d.h[h]; if (!hh) { if (Object.keys(d.h).length >= HOSTS_CAP) { hh = d.h['(other)'] = d.h['(other)'] || {}; } else hh = d.h[h] = {}; } for (const [b, n] of Object.entries(m)) hh[b] = (hh[b] || 0) + n; }
for (const [b, arr] of Object.entries(x.u || {})) { const u = d.u[b] = d.u[b] || []; for (const p of arr) if (u.length < UNIQ_CAP && !u.includes(p)) u.push(p); }
if (x.bt) d.bt = (d.bt || 0) + x.bt; if (x.sv) d.sv = (d.sv || 0) + x.sv;
if (x.z) { d.z = d.z || {}; for (const [h, zz] of Object.entries(x.z)) { let z = d.z[h]; if (!z) { const key = Object.keys(d.z).length >= HOSTS_CAP ? '(other)' : h; z = d.z[key] = d.z[key] || { r: 0, s: 0, k: {} }; }
z.r += zz.r || 0; z.s += zz.s || 0; for (const [p, n] of Object.entries(zz.k || {})) if (z.k[p] != null || Object.keys(z.k).length < LOADERS_CAP) z.k[p] = (z.k[p] || 0) + n; } } } }
return base;
}
function flush() {
if (!DIRTY || !DATA_DIR) return; const add = PENDING; PENDING = { d: {} }; DIRTY = false;
const base = mergeInto(C.read(), add); // read-add-write: another app copy's deltas (deploy overlap) are kept
if (Date.now() - lastPrune > 3600000) { lastPrune = Date.now(); const cut = ctDay(Date.now() - 400 * DAY); const live = new Set(J.db.spins.map(s => String(s.id))); for (const sid of Object.keys(base.d)) { if (!live.has(sid)) { delete base.d[sid]; continue; } for (const day of Object.keys(base.d[sid])) if (day < cut) delete base.d[sid][day]; } }
writeAtomic(C.FILE(), JSON.stringify(base)); C.db = base;
}
// counted impressions for one spin, flushed + pending, as { day: { b, h, u } }
function countsOf(sid) { const out = {}; for (const src of [C.db.d[sid] || {}, PENDING.d[sid] || {}]) mergeInto({ d: { x: out } }, { d: { x: src } }); return out; }
// ── tiers ──
async function tierFor(email) {
const e = norm(email); if (!e) return none('Sign in first.');
const grant = J.db.grants[e];
let f = { ownBuy: false, buyers: 0 }; try { f = Object.assign(f, await FACTS(e)); } catch (er) {}
const q = J.db.qual[e] || {}; const own = !!(f.ownBuy || q.own); const buyers = Math.max(Number(f.buyers) || 0, Number(q.buyers) || 0);
if ((own && !q.own) || buyers > (Number(q.buyers) || 0)) { J.db.qual[e] = { own, buyers, ts: Date.now() }; J.save(); } // once seen, kept
let key = !own ? null : buyers >= 5 ? 'leader' : buyers >= 2 ? 'builder' : 'starter';
if (e === ADMIN) key = 'leader';
if (grant && TIERS[grant] && (!key || ORDER.indexOf(grant) > ORDER.indexOf(key))) key = grant;
if (!key) return Object.assign(none('Banner Spin opens with your own package of $25 or more. Buy one under Credits and it unlocks right away.'), { buyers, ownBuy: own });
const t = TIERS[key]; const nx = TIERS[ORDER[ORDER.indexOf(key) + 1]];
return { ok: true, key, label: t.label, spins: t.spins, banners: t.banners, ownBuy: own, buyers, granted: !!grant, next: nx ? { label: nx.label, spins: nx.spins, banners: nx.banners, need: nx.need } : null };
}
const none = reason => ({ ok: false, key: '', label: 'Locked', spins: 0, banners: 0, reason, next: { label: TIERS.starter.label, spins: TIERS.starter.spins, banners: TIERS.starter.banners, need: TIERS.starter.need } });
// ── member CRUD ──
const mine = owner => J.db.spins.filter(s => s.owner === norm(owner));
const findMine = (owner, id) => J.db.spins.find(s => s.id === Number(id) && s.owner === norm(owner)) || null;
function cleanImage(owner, img) {
const s = String(img || '').trim(); if (!s) return { error: 'Add the banner image: upload one or paste an https image address.' };
const m = LOCAL_IMG.exec(s);
if (m) { const rec = J.db.images[m[1]]; if (!rec || rec.owner !== norm(owner)) return { error: 'Upload that image again from this screen.' }; return { image: s, w: rec.w, h: rec.h, bytes: rec.bytes }; }
const u = httpsUrl(s); if (!u) return { error: 'An image address must start with https://' };
return { image: u, w: 0, h: 0, bytes: 0 };
}
function cleanTarget(owner, body) {
if (body.link != null && String(body.link) !== '') { const rid = Number(body.link); const r = rotator && rotator.findMine ? rotator.findMine(owner, rid) : null; if (!r) return { error: 'Pick one of your own spin links.' }; return { target: '', link: rid }; }
const u = httpsUrl(body.target); if (!u) return { error: 'Where should a click go? Paste an https:// address or pick one of your spin links.' };
return { target: u, link: 0 };
}
const sizeWarn = (spin, w, h) => { const [W, H] = SIZES[spin.size]; return w && h && (w !== W || h !== H) ? 'This image is ' + w + 'x' + h + ' and this Banner Spin is ' + spin.size + '. It will be stretched to fit.' : ''; };
function pub(s, extra) {
const cl = {}; for (const c of J.db.clicks) if (c.s === s.id && !c.bot) { const o = cl[c.b] = cl[c.b] || { n: 0, m: 0 }; o.n++; if (c.m !== 'none' && c.m !== 'off') o.m++; }
const cnt = countsOf(s.id); const imps = {}; const since = ctDay(Date.now() - 30 * DAY); const imps30 = {};
for (const [day, d] of Object.entries(cnt)) for (const [b, n] of Object.entries(d.b)) { imps[b] = (imps[b] || 0) + n; if (day >= since) imps30[b] = (imps30[b] || 0) + n; }
const sum = o => Object.values(o).reduce((a, b) => a + (typeof b === 'number' ? b : b.n), 0);
const conv = J.db.conv.filter(c => c.s === s.id).length;
return Object.assign({ id: s.id, code: s.code, name: s.name, size: s.size, mode: s.mode || 'weight', owner: s.owner, created: s.created, paused: !!s.paused, adminOff: !!s.adminOff, adminNote: s.adminNote || '',
fallback: s.fallback || '', fallbackImage: s.fallbackImage || '', hours: s.hours || null, tz: s.tz || 'visitor', sourceId: s.sourceId || '',
banners: s.banners.map(b => ({ id: b.id, label: b.label || '', image: b.image, w: b.w || 0, h: b.h || 0, bytes: b.bytes || 0, target: b.target || '', link: b.link || 0, weight: b.weight, active: !!b.active, adminOff: !!b.adminOff, hours: b.hours || null, added: b.added,
imps: imps[b.id] || 0, imps30: imps30[b.id] || 0, clicks: (cl[b.id] || {}).n || 0, matched: (cl[b.id] || {}).m || 0, warn: sizeWarn(s, b.w, b.h),
autoPaused: b.autoPaused || 0, health: b.health ? { state: b.health.state, note: b.health.note || '', checkedAt: b.health.checkedAt || 0, fails: b.health.fails || 0, image: b.health.image || null, target: b.health.target || null } : null })),
imps: sum(imps), imps30: sum(imps30), fallbackImps: imps[0] || 0, clicks: sum(cl), matched: Object.values(cl).reduce((a, o) => a + o.m, 0), conversions: conv }, extra || {});
}
async function list(owner) { return mine(owner).map(s => pub(s)); }
async function create(owner, body) {
const t = await tierFor(owner); if (!t.ok) return { error: t.reason, tier: t };
if (mine(owner).length >= t.spins) return { error: 'Your ' + t.label + ' tier holds ' + t.spins + ' Banner Spins.' + (t.next ? ' ' + t.next.label + ' (' + t.next.need + ') holds ' + t.next.spins + '.' : ''), tier: t };
const name = String(body.name || '').trim().slice(0, 80); if (!name) return { error: 'Give the Banner Spin a name.' };
const size = String(body.size || ''); if (!SIZES[size]) return { error: 'Pick one of the sizes: ' + Object.keys(SIZES).join(', ') + '.' };
const s = { id: J.db.spins.reduce((m, x) => Math.max(m, x.id), 0) + 1, owner: norm(owner), name, code: newCode(), size, mode: body.mode === 'visitor' ? 'visitor' : 'weight', fallback: httpsUrl(body.fallback) || '', fallbackImage: '', banners: [], nextBanner: 1, paused: false, created: Date.now() };
J.db.spins.push(s); J.save(); return { ok: true, spin: pub(s) };
}
async function update(owner, id, body) {
const s = findMine(owner, id); if (!s) return { error: 'No such Banner Spin.' };
if (body.remove) { J.db.spins = J.db.spins.filter(x => x !== s); J.save(); return { ok: true, removed: true }; }
if (body.name != null) { const n = String(body.name).trim().slice(0, 80); if (n) s.name = n; }
if (body.paused != null) s.paused = !!body.paused;
if (body.mode != null) s.mode = body.mode === 'visitor' ? 'visitor' : 'weight';
if (body.fallback != null) { const f = String(body.fallback).trim(); if (f && !httpsUrl(f)) return { error: 'The fallback must be an https:// address.' }; s.fallback = f ? httpsUrl(f) : ''; }
if (body.fallbackImage != null) { const f = String(body.fallbackImage).trim(); if (!f) s.fallbackImage = ''; else { const im = cleanImage(owner, f); if (im.error) return im; s.fallbackImage = im.image; } }
if (body.hours !== undefined) { const h = rotator.cleanHours(body.hours); if (h.error) return h; if (h.hours) s.hours = h.hours; else delete s.hours; }
if (body.tz !== undefined) { const t = rotator.cleanTz(body.tz); if (t.error) return t; if (t.tz === 'visitor') delete s.tz; else s.tz = t.tz; }
if (body.sourceId !== undefined) { const sid = String(body.sourceId || '').trim(); if (!sid) delete s.sourceId; else { if (!/^[a-f0-9]{10}$/.test(sid) || !SOURCES || !SOURCES.find(owner, sid)) return { error: 'No such source.' }; s.sourceId = sid; } }
J.save(); return { ok: true, spin: pub(s) };
}
async function addBanner(owner, id, body) {
const s = findMine(owner, id); if (!s) return { error: 'No such Banner Spin.' };
const t = await tierFor(owner); const cap = Math.min(MAX_BANNERS, t.ok ? t.banners : 0);
if (!t.ok) return { error: t.reason, tier: t };
if (s.banners.length >= cap) return { error: 'Your ' + t.label + ' tier holds ' + cap + ' banners per Banner Spin.' + (t.next ? ' ' + t.next.label + ' (' + t.next.need + ') holds ' + t.next.banners + '.' : ''), tier: t };
const im = cleanImage(owner, body.image); if (im.error) return im;
const tg = cleanTarget(owner, body); if (tg.error) return tg;
if (!im.w && body.w && body.h) { im.w = Math.min(4000, Math.max(0, Math.round(Number(body.w) || 0))); im.h = Math.min(4000, Math.max(0, Math.round(Number(body.h) || 0))); } // pasted image: the size the builder measured, for the warning only
const b = { id: s.nextBanner++, label: String(body.label || '').trim().slice(0, 60), image: im.image, w: im.w, h: im.h, bytes: im.bytes, target: tg.target, link: tg.link, weight: Math.max(1, Math.min(100, Math.round(Number(body.weight) || 10))), active: true, added: Date.now() };
s.banners.push(b); J.save(); return { ok: true, spin: pub(s), warn: sizeWarn(s, b.w, b.h) };
}
async function updateBanner(owner, id, bid, body) {
const s = findMine(owner, id); if (!s) return { error: 'No such Banner Spin.' };
const b = s.banners.find(x => x.id === Number(bid)); if (!b) return { error: 'No such banner.' };
if (body.remove) { s.banners = s.banners.filter(x => x !== b); J.save(); return { ok: true, spin: pub(s) }; }
if (body.weight != null) b.weight = Math.max(1, Math.min(100, Math.round(Number(body.weight) || 1)));
if (body.active != null) { b.active = !!body.active; delete b.autoPaused; } // the owner's own pause / resume wins over the health checker
if (body.label != null) b.label = String(body.label).trim().slice(0, 60);
if (body.image != null) { const im = cleanImage(owner, body.image); if (im.error) return im; Object.assign(b, { image: im.image, w: im.w, h: im.h, bytes: im.bytes }); delete b.health; }
if (body.target != null || body.link != null) { const tg = cleanTarget(owner, body); if (tg.error) return tg; b.target = tg.target; b.link = tg.link; delete b.health; }
if (body.hours !== undefined) { const h = rotator.cleanHours(body.hours); if (h.error) return h; if (h.hours) b.hours = h.hours; else delete b.hours; }
J.save(); return { ok: true, spin: pub(s) };
}
// an uploaded image (server.js checked type, magic and the 150 KB limit, and wrote the file): remember owner + size
function noteImage(owner, name, w, h, bytes, mime) { J.db.images[name] = { owner: norm(owner), w, h, bytes, mime, ts: Date.now() }; J.save(); }
// image dimensions from the header bytes: PNG IHDR, GIF logical screen, JPEG SOFn
function dims(buf, mime) {
try {
if (mime === 'image/png' && buf.length > 24) return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
if (mime === 'image/gif' && buf.length > 10) return { w: buf.readUInt16LE(6), h: buf.readUInt16LE(8) };
if (mime === 'image/jpeg') { let i = 2; while (i + 9 < buf.length) { if (buf[i] !== 0xff) { i++; continue; } const mk = buf[i + 1]; const len = buf.readUInt16BE(i + 2);
if (mk >= 0xc0 && mk <= 0xcf && mk !== 0xc4 && mk !== 0xc8 && mk !== 0xcc) return { h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) }; i += 2 + len; } }
} catch (e) {}
return { w: 0, h: 0 };
}
// ── serving ──
const live = () => !J.db.settings.off;
const byCode = code => J.db.spins.find(s => s.code === norm(code)) || null;
function cellFor(s, req) { let country = ''; try { country = geo && geo.countryOf ? (geo.countryOf(ipOf(req)) || '') : ''; } catch (e) {} return { cell: rotator.cellAt(rotator.zoneFor(s, country)), country }; }
function pick(s, cell, v) {
const lv = s.banners.filter(b => b.active && !b.adminOff && rotator.isOn(b.hours, cell)); if (!lv.length) return null;
const total = lv.reduce((n, b) => n + b.weight, 0);
let x = s.mode === 'visitor' ? parseInt(crypto.createHash('sha256').update(v + '|' + s.id).digest('hex').slice(0, 8), 16) % total : crypto.randomInt(total);
for (const b of lv) { x -= b.weight; if (x < 0) return b; } return lv[lv.length - 1];
}
// what to show right now: { banner, fallback, blank } plus the note/count side effects (count = false for an exact ?x= fetch)
function choose(s, req, opts) {
opts = opts || {};
if (!live() || s.adminOff) return { blank: true };
if (opts.x != null) { const b = s.banners.find(q => q.id === Number(opts.x) && !q.adminOff); return b ? { banner: b } : { blank: true }; }
const v = vkey(req); const { cell } = cellFor(s, req);
const off = s.paused || !rotator.isOn(s.hours, cell);
const b = off ? null : pick(s, cell, v);
const out = b ? { banner: b } : (s.fallbackImage ? { fallback: true } : { blank: true, fallback: true });
const kind = loaderKind(req); rawLoad(String(s.id), hostOf(req), v, kind);
if (!kind) {
const bid = b ? b.id : 0; const host = hostOf(req);
note(v, s.id, host, bid);
const k = v + '|' + s.id + '|' + bid; const last = SEEN.get(k);
if (!last || Date.now() - last >= DEDUPE_MS) { SEEN.set(k, Date.now()); bump(String(s.id), bid, host, v); }
}
return out;
}
// the image source for a choice: { local: name } | { url } | { blank: [w, h] }
function sourceOf(s, ch) {
const img = ch.banner ? ch.banner.image : ch.fallback && s.fallbackImage ? s.fallbackImage : '';
if (!img) return { blank: SIZES[s.size] };
const m = LOCAL_IMG.exec(img); return m ? { local: m[1] } : { url: img };
}
async function image(code, req, x) { const s = byCode(code); if (!s) return null; const ch = choose(s, req, { x }); return Object.assign({ size: SIZES[s.size] }, sourceOf(s, ch)); }
// the script embed: picks, counts and writes the banner with its own click link (exact match)
async function script(code, req, base) {
const s = byCode(code); if (!s) return null;
const ch = choose(s, req); const [w, h] = SIZES[s.size];
const x = ch.banner ? ch.banner.id : 0;
const src = ch.banner && !LOCAL_IMG.test(ch.banner.image) ? ch.banner.image : base + '/i/' + s.code + '.gif' + (x ? '?x=' + x : '?x=0');
const href = base + '/c/' + s.code + '?x=' + x;
const html = '<a href="' + href.replace(/"/g, '&quot;') + '" target="_blank" rel="noopener"><img src="' + src.replace(/"/g, '&quot;') + '" width="' + w + '" height="' + h + '" alt="" style="border:0;max-width:100%;height:auto"></a>';
const js = JSON.stringify(html).replace(/</g, '\\u003c');
return '(function(){var h=' + js + ',s=document.currentScript;if(!s){var a=document.getElementsByTagName("script");for(var i=a.length-1;i>=0;i--){if((a[i].src||"").indexOf("/s/' + s.code + '.js")>-1){s=a[i];break;}}}var d=document.createElement("span");d.innerHTML=h;if(s&&s.parentNode){s.parentNode.insertBefore(d.firstChild,s.nextSibling);}else{document.write(h);}})();';
}
// the click: { url, lsid } or null (unknown code). reqHost = the link domain the click came in on (spin-link targets stay on it).
async function click(code, req, reqHost) {
const s = byCode(code); if (!s) return null;
const bot = isBot(req) ? 1 : 0; const h = hostOf(req); const keys = vkeys(req);
const u = new URL(req.url, 'http://x'); const xs = u.searchParams.get('x');
let b = null, m = 'none';
if (!live() || s.adminOff) m = 'off';
else if (xs != null && /^\d{1,4}$/.test(xs)) { b = Number(xs) ? s.banners.find(q => q.id === Number(xs) && !q.adminOff) || null : null; m = 'exact'; }
else { const n = findNote(keys, s.id, h); if (n) { b = n.b ? s.banners.find(q => q.id === n.b && !q.adminOff) || null : null; m = 'note'; } }
// where to: the banner's target (its spin link, on the same link domain), else the fallback
let url = null;
if (b) { if (b.link) { const r = rotator && rotator.rawRotations ? rotator.rawRotations().find(x => x.id === b.link && x.owner === s.owner) : null; url = r ? 'https://' + (reqHost || 'linkspin.app') + '/r/' + r.code : null; } else url = b.target; }
if (!url) { url = s.fallback || null; if (b) b = null; }
if (!url) { const first = s.banners.find(q => q.active && !q.adminOff && q.target); url = first ? first.target : null; } // no fallback set: the first live banner beats a dead end
let country = ''; try { country = geo && geo.countryOf ? (geo.countryOf(ipOf(req)) || '') : ''; } catch (e) {}
const ua = String(req.headers['user-agent'] || ''); const device = /mobile|android|iphone|ipad/i.test(ua) ? 'mobile' : 'desktop';
const q = {}; { let n = 0; for (const [k, val] of u.searchParams) { const key = String(k).toLowerCase(); if (n >= 20) break; if (/^(clickid|click_id|cid|subid|sub_id|s[1-5]|sub[1-5]|t[1-5]|aff_sub[1-5]?|utm_(source|medium|campaign|term|content)|src|source|campaign|zone|placement|cost|creative|site|banner|keyword|geo|os|browser|device|carrier|format|external_id|visitor_id)$/.test(key)) { q[key] = String(val).slice(0, 200); n++; } } }
const id = 'k' + crypto.randomBytes(6).toString('hex').slice(0, 11);
J.db.clicks.push({ id, s: s.id, b: b ? b.id : 0, ts: Date.now(), v: keys[0], h: h || undefined, m, bot, c: country || undefined, dv: device, q: Object.keys(q).length ? q : undefined, sr: s.sourceId || undefined });
if (J.db.clicks.length > 200000) J.db.clicks = J.db.clicks.slice(-150000);
J.save();
if (url) {
const vals = { clickid: q.clickid || q.cid || q.click_id || '', subid: q.subid || q.sub_id || q.s1 || '', s1: q.s1 || q.sub1 || '', s2: q.s2 || q.sub2 || '', s3: q.s3 || q.sub3 || '', s4: q.s4 || q.sub4 || '', s5: q.s5 || q.sub5 || '', source: h || 'direct', country, device, lsid: id, code: s.code };
for (const [k, val] of Object.entries(q)) if (vals[k] == null) vals[k] = val;
url = url.replace(/\{([a-z0-9_]{1,24})\}/gi, (mm, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()]));
try { const t = new URL(url); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid') && !/^\/r\//.test(t.pathname)) { t.searchParams.set('lsid', id); url = t.toString(); } } catch (e) {}
// straight to a page: the click id rides along for the landing tag (a spin-link target adds its own on the /r/ hop)
if (!bot) { let spinHop = false; try { spinHop = /^\/r\/[a-z0-9]{4,12}$/i.test(new URL(url).pathname); } catch (e) {} if (!spinHop) { try { if (WANTS_CLICK_ID(s.owner)) url = WITH_CLICK_ID(url, id); } catch (e) {} } }
}
return { url, lsid: id, banner: b, matched: m, owner: s.owner };
}
// conversion pixel (2026-10-26): a Banner Spin click by id, with its Banner Spin, banner and where it went
function clickById(id) {
id = String(id || ''); if (!/^k[a-f0-9]{11}$/.test(id)) return null;
const list = J.db.clicks; let c = null; for (let i = list.length - 1; i >= 0; i--) if (list[i].id === id) { c = list[i]; break; }
if (!c) return null;
const s = J.db.spins.find(x => x.id === c.s); if (!s) return null;
const b = c.b ? s.banners.find(x => x.id === c.b) || null : null;
return { click: c, owner: s.owner, spin: { id: s.id, code: s.code, name: s.name || '' }, banner: b ? { id: b.id, label: b.label || '' } : null, destUrl: b && !b.link ? (b.target || '') : (b ? '' : (s.fallback || '')) };
}
// conversions (rotator.convert falls through to here for a 'k' click id): dedupe per click + event
async function convert(lsid, ev, facts) {
const c = J.db.clicks.find(x => x.id === String(lsid)); if (!c) return null;
const s = J.db.spins.find(x => x.id === c.s); if (!s) return null;
if (!J.db.conv.some(x => x.lsid === c.id && x.ev === ev)) { J.db.conv.push({ lsid: c.id, s: s.id, b: c.b, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: c.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); }
return { owner: s.owner, code: s.code, rotationId: 0, bannerSpinId: s.id, bannerId: c.b, q: c.q || {}, s: c.h || 'direct', c: c.c || '', dv: c.dv, sourceId: c.sr || '' };
}
// ── stats (phase 3, 2026-10-20): one aggregation for the builder's Stats tab and the Reports screen ──
// Views are the counted impressions (bots, prefetches and servers left out); bots and server loads are reported beside
// them. Clicks are rows (bots flagged), so day / country / device come from human clicks, the same way spin links report.
// sinceTs = 0 means all time (the builder); Reports passes its range. Day keys are Central time.
const WIN_MIN = 1000; // a winner needs this many views on every banner it is compared with
const ctrOf = o => o.imps ? Math.round(o.clicks / o.imps * 10000) / 100 : null;
const mrOf = o => o.clicks ? Math.round(o.matched / o.clicks * 100) : null;
function agg(spins, sinceTs) {
const sinceDay = sinceTs ? ctDay(sinceTs) : '';
const ids = new Set(spins.map(s => s.id));
const blank = () => ({ imps: 0, clicks: 0, matched: 0, unmatched: 0, uniq: 0, conv: 0, bots: 0, botClicks: 0, srv: 0, raw: 0, top: {} });
const at = (o, k) => (o[k] = o[k] || blank());
const per = {}, hosts = {}, days = {}, T = blank();
for (const s of spins) for (const [day, d] of Object.entries(countsOf(s.id))) {
if (sinceDay && day < sinceDay) continue;
const dd = at(days, day);
for (const [b, n] of Object.entries(d.b || {})) { at(per, s.id + ':' + b).imps += n; dd.imps += n; T.imps += n; }
for (const [b, arr] of Object.entries(d.u || {})) { at(per, s.id + ':' + b).uniq += arr.length; dd.uniq += arr.length; T.uniq += arr.length; }
for (const [h, m] of Object.entries(d.h || {})) for (const n of Object.values(m)) at(hosts, h).imps += n;
dd.bots += d.bt || 0; T.bots += d.bt || 0; dd.srv += d.sv || 0; T.srv += d.sv || 0;
for (const [h, z] of Object.entries(d.z || {})) { const o = at(hosts, h); o.raw += z.r || 0; o.srv += z.s || 0; for (const [k, n] of Object.entries(z.k || {})) o.top[k] = (o.top[k] || 0) + n; }
}
const country = {}, device = {};
for (const c of J.db.clicks) {
if (!ids.has(c.s) || (sinceTs && c.ts < sinceTs)) continue;
const dd = at(days, ctDay(c.ts));
if (c.bot) { T.botClicks++; dd.botClicks++; continue; }
const ok = c.m === 'exact' || c.m === 'note';
for (const o of [at(per, c.s + ':' + c.b), at(hosts, c.h || '(none)'), dd, T]) { o.clicks++; if (ok) o.matched++; else if (c.m === 'none') o.unmatched++; }
const k = c.c || '(none)'; country[k] = (country[k] || 0) + 1; const dv = c.dv || '(none)'; device[dv] = (device[dv] || 0) + 1;
}
const convBy = {};
for (const c of J.db.conv) { if (!ids.has(c.s) || (sinceTs && c.ts < sinceTs)) continue; at(per, c.s + ':' + c.b).conv++; T.conv++; at(days, ctDay(c.ts)).conv++; const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; }
return { per, hosts, days, T, country, device, convBy };
}
// the "caches banners" flag: a placement whose image loads come from a server instead of browsers, or whose clicks
// cannot be tied to a view (a copied image never asks us, so the click arrives with no note). '' when it looks normal.
function cacheFlag(o) {
if (o.srv >= 5 && o.srv >= o.raw * 0.5) return 'Most image loads here come from a server, not a browser (' + o.srv + ' of ' + o.raw + '). This site most likely copies banners to its own server, so the rotation is frozen there.';
const top = Math.max(0, ...Object.values(o.top || {}));
if (o.raw >= 50 && top >= o.raw * 0.8 && o.clicks <= o.raw * 0.01) return 'One loader made ' + Math.round(top / o.raw * 100) + '% of the ' + o.raw + ' image loads here and almost nobody clicks. This site most likely caches banners, so the rotation is frozen there.';
// more clicks than views alone is not enough (one visitor's reloads count once a minute, clicks are not deduped): a copy also leaves the clicks unmatched
if (o.clicks >= 10 && o.clicks > o.imps && o.matched / o.clicks < 0.5) return 'More clicks (' + o.clicks + ') than views we served (' + o.imps + '). This site shows a copy of the banner, so the rotation is frozen there and clicks go to the fallback.';
if (o.clicks >= 10 && o.matched / o.clicks < 0.3) return 'Only ' + Math.round(o.matched / o.clicks * 100) + '% of clicks here match a view. This site most likely caches banners, so the rotation is frozen there.';
return '';
}
// winner: among the live banners of one Banner Spin with at least WIN_MIN views each, the one with the best CTR (strictly ahead)
function winnerOf(rows) {
const q = rows.filter(r => r.imps >= WIN_MIN && r.ctr != null).sort((a, b) => b.ctr - a.ctr);
return q.length >= 2 && q[0].ctr > q[1].ctr ? q[0].id : 0;
}
const listOf = m => Object.entries(m).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n }));
const dayRows = (days, sinceDay) => Object.entries(days).filter(([d]) => !sinceDay || d >= sinceDay).sort().map(([day, o]) => ({ day, imps: o.imps, clicks: o.clicks, bots: o.bots, botClicks: o.botClicks, servers: o.srv, conv: o.conv }));
const placementRows = hosts => Object.entries(hosts).map(([host, o]) => ({ host, imps: o.imps, clicks: o.clicks, ctr: ctrOf(o), matchRate: mrOf(o), loads: o.raw, serverLoads: o.srv, caches: cacheFlag(o) }))
.filter(p => p.imps || p.clicks || p.loads).sort((a, b) => b.imps - a.imps || b.clicks - a.clicks).slice(0, 30);
async function stats(owner, id) {
const s = findMine(owner, id); if (!s) return null;
const A = agg([s], 0); const z = blank0();
const banners = s.banners.map(b => { const o = A.per[s.id + ':' + b.id] || z; return { id: b.id, label: b.label || '', image: b.image, active: !!b.active, imps: o.imps, uniques: o.uniq, clicks: o.clicks, matched: o.matched, ctr: ctrOf(o), matchRate: mrOf(o), conversions: o.conv }; });
const win = winnerOf(banners.filter(b => b.active)); for (const b of banners) b.winner = b.id === win;
const fb = A.per[s.id + ':0'] || z;
return { spin: pub(s), totals: { imps: A.T.imps, clicks: A.T.clicks, ctr: ctrOf(A.T), matchRate: mrOf(A.T), matched: A.T.matched, unmatched: A.T.unmatched, uniquesSampled: A.T.uniq, conversions: A.T.conv, bots: A.T.botClicks, botLoads: A.T.bots, serverLoads: A.T.srv },
banners, winner: win, winMin: WIN_MIN, fallback: { imps: fb.imps, clicks: fb.clicks, ctr: ctrOf(fb) },
placements: placementRows(A.hosts), days: dayRows(A.days, ctDay(Date.now() - 30 * DAY)), country: listOf(A.country), device: listOf(A.device),
conversions: Object.entries(A.convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) };
}
const blank0 = () => ({ imps: 0, clicks: 0, matched: 0, unmatched: 0, uniq: 0, conv: 0 });
// Reports screen: every Banner Spin the member owns over the last `days`, totals + per banner + per placement + day / country / device
async function summary(owner, days) {
const list = mine(owner); const n = Math.max(1, Math.min(365, Number(days) || 30)); const since = Date.now() - n * DAY;
const A = agg(list, since); const z = blank0(); const banners = [];
for (const s of list) {
const rows = s.banners.map(b => { const o = A.per[s.id + ':' + b.id] || z; return { spinId: s.id, spin: s.name, code: s.code, size: s.size, id: b.id, label: b.label || 'Banner ' + b.id, image: b.image, active: !!b.active, autoPaused: !!b.autoPaused, imps: o.imps, uniques: o.uniq, clicks: o.clicks, ctr: ctrOf(o), matchRate: mrOf(o), conversions: o.conv }; });
const win = winnerOf(rows.filter(r => r.active)); for (const r of rows) { r.winner = r.id === win; banners.push(r); }
}
banners.sort((a, b) => b.imps - a.imps || b.clicks - a.clicks);
const spins = list.map(s => { let imps = 0, clicks = 0, conv = 0; for (const b of s.banners.concat([{ id: 0 }])) { const o = A.per[s.id + ':' + b.id]; if (o) { imps += o.imps; clicks += o.clicks; conv += o.conv; } } return { id: s.id, name: s.name, code: s.code, size: s.size, imps, clicks, ctr: imps ? Math.round(clicks / imps * 10000) / 100 : null, conversions: conv }; }).sort((a, b) => b.imps - a.imps);
return { count: list.length, totals: { imps: A.T.imps, uniques: A.T.uniq, clicks: A.T.clicks, ctr: ctrOf(A.T), matchRate: mrOf(A.T), matched: A.T.matched, unmatched: A.T.unmatched, conversions: A.T.conv, bots: A.T.bots, botClicks: A.T.botClicks, serverLoads: A.T.srv },
days: dayRows(A.days, ctDay(since)), country: listOf(A.country), device: listOf(A.device), banners: banners.slice(0, 50), placements: placementRows(A.hosts), spins, winMin: WIN_MIN,
conversions: Object.entries(A.convBy).sort((a, b) => b[1] - a[1]).map(([k, c]) => ({ k, n: c })) };
}
// ── admin ──
function adminAll() {
const cl = {}; for (const c of J.db.clicks) if (!c.bot) cl[c.s] = (cl[c.s] || 0) + 1;
return J.db.spins.map(s => { let imps = 0; for (const d of Object.values(countsOf(s.id))) for (const n of Object.values(d.b)) imps += n;
return { id: s.id, code: s.code, name: s.name, owner: s.owner, size: s.size, mode: s.mode || 'weight', created: s.created, paused: !!s.paused, adminOff: !!s.adminOff, adminNote: s.adminNote || '', fallback: s.fallback || '', fallbackImage: s.fallbackImage || '', sourceId: s.sourceId || '', dayparted: !!s.hours,
banners: s.banners.map(b => ({ id: b.id, label: b.label || '', image: b.image, target: b.target || '', link: b.link || 0, weight: b.weight, active: !!b.active, adminOff: !!b.adminOff })), imps, clicks: cl[s.id] || 0, conversions: J.db.conv.filter(c => c.s === s.id).length }; });
}
function adminSet(id, body) {
const s = J.db.spins.find(x => x.id === Number(id)); if (!s) return { error: 'No such Banner Spin.' };
const nt = body.note != null ? String(body.note).slice(0, 200) : null;
if (body.bannerId != null) { const b = s.banners.find(x => x.id === Number(body.bannerId)); if (!b) return { error: 'No such banner.' }; if (body.off != null) b.adminOff = !!body.off; if (nt != null) b.adminNote = nt; }
else { if (body.off != null) s.adminOff = !!body.off; if (nt != null) s.adminNote = nt; }
J.save(); return { ok: true, spin: adminAll().find(x => x.id === s.id) };
}
function setGlobal(body) { if (body.off != null) J.db.settings.off = !!body.off; if (body.grant && body.email) { const e = norm(body.email); if (body.grant === 'none') delete J.db.grants[e]; else if (TIERS[body.grant]) J.db.grants[e] = body.grant; else return { error: 'Grant is starter, builder, leader or none.' }; } J.save(); return { ok: true, off: !!J.db.settings.off, grants: J.db.grants }; }
function settings() { return { off: !!J.db.settings.off, grants: J.db.grants }; }
// image files Banner Spins use, for the admin upload list (file name -> owner + where)
function imageRefs() { const out = {}; for (const s of J.db.spins) for (const im of s.banners.map(b => b.image).concat(s.fallbackImage || [])) { const m = LOCAL_IMG.exec(im || ''); if (m) out[m[1]] = { email: s.owner, where: 'Banner Spin ' + s.code }; } for (const [n, r] of Object.entries(J.db.images)) if (!out[n]) out[n] = { email: r.owner, where: '' }; return out; }
function totals() { return { spins: J.db.spins.length, banners: J.db.spins.reduce((n, s) => n + s.banners.length, 0), clicks: J.db.clicks.length }; }
// a transparent PNG at the exact banner size, for the blank image (admin off, nothing to show); cached per size
const BLANK = new Map();
function crc32(buf) { let c, crc = 0xffffffff; for (let n = 0; n < buf.length; n++) { c = (crc ^ buf[n]) & 0xff; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crc = (crc >>> 8) ^ c; } return (crc ^ 0xffffffff) >>> 0; }
function blankPng(w, h) {
const key = w + 'x' + h; if (BLANK.has(key)) return BLANK.get(key);
const zlib = require('zlib'); const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(td)); return Buffer.concat([len, td, crc]); };
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 6; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; // 8-bit RGBA, all zero = transparent
const raw = Buffer.alloc((w * 4 + 1) * h); // filter byte 0 + transparent pixels per row
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw, { level: 9 })), chunk('IEND', Buffer.alloc(0))]);
BLANK.set(key, png); return png;
}
// hot uploaded images in memory (each at most 150 KB, 32 MB in all)
const IMG = new Map(); let IMG_BYTES = 0;
function readImage(name) {
const hit = IMG.get(name); if (hit) { IMG.delete(name); IMG.set(name, hit); return hit; }
let buf; try { buf = fs.readFileSync(path.join(UPLOADS_DIR, name)); } catch (e) { return null; }
const rec = { buf, mime: MIME[name.split('.').pop()] || 'application/octet-stream' };
if (buf.length <= MAX_BYTES) { IMG.set(name, rec); IMG_BYTES += buf.length; while (IMG_BYTES > 32 * 1024 * 1024) { const [k, v] = IMG.entries().next().value; IMG.delete(k); IMG_BYTES -= v.buf.length; } }
return rec;
}
// raw access for health.js (phase 3): the same store and save, and where a banner image lives ({ file } on disk or { url })
const rawSpins = () => J.db.spins;
const save = () => J.save();
function imageSource(img) { const m = LOCAL_IMG.exec(String(img || '')); return m ? { file: path.join(UPLOADS_DIR, m[1]) } : /^https:\/\//i.test(String(img || '')) ? { url: String(img) } : null; }
const _test = { notes: () => NOTES, flush, vkey, cacheFlag, winnerOf };
module.exports = { init, SIZES, TIERS, MAX_BYTES, tierFor, list, create, update, addBanner, updateBanner, noteImage, dims, image, script, click, clickById, convert, stats, summary, adminAll, adminSet, setGlobal, settings, imageRefs, totals, blankPng, readImage, flush, findMine, rawSpins, save, imageSource, live, _test };