// Banner Spin end-to-end test (2026-10-18). Boots server.js on its own port with a throwaway, seeded data dir (JSON store, // no DB, no mail key, devCode sign-in, no chain-writing keys), builds a Banner Spin with 3 banners through the Links // screen UI, then plays simulated visitors against /i/, /c/ and /s/ on a link domain and checks matching, fallback, // counters, headers, tier limits, URL tokens, conversions, the admin kill switch and the admin Member content pane. // Phase 3 + 4 (2026-10-20): image health auto-pause / resume (a corrupted upload, a dead target, the last live banner), // the winner badge, bots and servers kept apart, the "caches banners" flag, the traffic-source postback, the Reports // screen, the admin Banner Spin switch button, the chatbot answer, the Training lesson, Promo tools and the release draft. // node qa/bannerspin.mjs (from the site dir) // Env: PORT (default 8961), PW (playwright package dir), SHOTS (screenshot dir, default D:/tmp/banner-spin) import { pathToFileURL } from 'node:url'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import http from 'node:http'; import zlib from 'node:zlib'; import crypto from 'node:crypto'; import { spawn } from 'node:child_process'; const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default; const PORT = Number(process.env.PORT || 8961); const BASE = 'http://127.0.0.1:' + PORT; const SHOTS = process.env.SHOTS || 'D:/tmp/banner-spin'; const LINK = 'lnk-one.test', LINK2 = 'lnk-two.test'; const ADMIN_PW = 'localtest-bs'; const results = []; let failed = 0; const check = (ok, what, detail) => { results.push((ok ? 'PASS ' : 'FAIL ') + what + (detail ? ' :: ' + detail : '')); if (!ok) failed++; }; // ── tiny PNG writer: solid RGB, or noise (incompressible, for the 150 KB limit) ── 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 png(w, h, rgb, noise) { const chunk = (t, d) => { const l = Buffer.alloc(4); l.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc32(td)); return Buffer.concat([l, td, c]); }; const ih = Buffer.alloc(13); ih.writeUInt32BE(w, 0); ih.writeUInt32BE(h, 4); ih[8] = 8; ih[9] = 2; const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) { const o = y * (w * 3 + 1); for (let x = 0; x < w; x++) { const i = o + 1 + x * 3; if (noise) { raw[i] = crypto.randomInt(256); raw[i + 1] = crypto.randomInt(256); raw[i + 2] = crypto.randomInt(256); } else { const stripe = ((x >> 4) & 1) ? 30 : 0; raw[i] = Math.min(255, rgb[0] + stripe); raw[i + 1] = rgb[1]; raw[i + 2] = rgb[2]; } } } return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ih), chunk('IDAT', zlib.deflateSync(raw, { level: noise ? 0 : 9 })), chunk('IEND', Buffer.alloc(0))]); } const sha = b => crypto.createHash('sha1').update(b).digest('hex'); // ── seed: accounts (starter / builder / locked), chain index events (no chain), link domains ── const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'bs-qa-')); fs.mkdirSync(path.join(DATA, 'uploads')); const now = Date.now(); const acct = (email, username, memberId) => ({ email, username, code: username.slice(0, 7), memberId, created: now - 86400000, sponsorRef: '' }); const accounts = { v: 2, byEmail: { 'starter@bs.test': acct('starter@bs.test', 'bsstarter', 900001), 'builder@bs.test': acct('builder@bs.test', 'bsbuilder', 900002), 'locked@bs.test': acct('locked@bs.test', 'bslocked', 900003) }, byAddress: {}, byCode: {}, joins: 3, positions: {} }; for (const a of Object.values(accounts.byEmail)) accounts.byCode[a.code] = a.email; fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(accounts)); const ev = (type, o) => Object.assign({ type, block: 1, tx: '0x' + crypto.randomBytes(32).toString('hex'), li: 0, ts: now - 3600000 }, o); const events = [ev('Purchase', { buyerId: 900001, productId: 3, paidWei: '1', priceCents: 5000, creditType: 0, creditAmount: 5000 }), ev('Purchase', { buyerId: 900002, productId: 3, paidWei: '1', priceCents: 5000, creditType: 0, creditAmount: 5000 }), ev('Purchase', { buyerId: 900003, productId: 1, paidWei: '1', priceCents: 2000, creditType: 0, creditAmount: 2000 }), // a $20 buy: not enough for Banner Spin ev('BuyerCounted', { sponsorId: 900002, newBuyerId: 900010, newCount: 1 }), ev('BuyerCounted', { sponsorId: 900002, newBuyerId: 900011, newCount: 2 })]; fs.writeFileSync(path.join(DATA, 'chain-index.json'), JSON.stringify({ v: 1, lastBlock: 4e9, events, totals: { purchases: 3, paidInWei: '3', payouts: 0, payoutWei: '0', activations: 0 } })); fs.writeFileSync(path.join(DATA, 'site.json'), JSON.stringify({ linkDomains: LINK + ',' + LINK2, linkDomainChannels: LINK + ':social,' + LINK2 + ':email' })); const IMG = { a: png(468, 60, [200, 40, 40]), b: png(468, 60, [40, 160, 60]), c: png(468, 60, [40, 80, 220]), wrong: png(300, 250, [120, 120, 120]), big: png(300, 250, null, true), fb: png(468, 60, [240, 200, 0]) }; for (const [k, b] of Object.entries(IMG)) fs.writeFileSync(path.join(DATA, k + '.png'), b); fs.mkdirSync(SHOTS, { recursive: true }); // ── server ── const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: ADMIN_PW, ADMIN_EMAIL: 'admin@bs.test' }); delete env.NODE_ENV; delete env.DATABASE_URL; delete env.ENGINE_KEY; delete env.LS_SYNC_SECRET; delete env.OUTBOUND; delete env.LS_TESTERS; delete env.CURTAIN; const log = fs.createWriteStream(path.join(SHOTS, 'server.log')); const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'pipe', 'pipe'] }); srv.stdout.pipe(log); srv.stderr.pipe(log); const sleep = ms => new Promise(r => setTimeout(r, ms)); // raw HTTP with any Host / Referer / UA / client IP function req(method, p, o) { o = o || {}; return new Promise((resolve, reject) => { const headers = Object.assign({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) QA', Host: o.host || '127.0.0.1:' + PORT }, o.headers || {}); if (o.cookie) headers.Cookie = o.cookie; if (o.ip) headers['X-Forwarded-For'] = o.ip; if (o.referer) headers.Referer = o.referer; if (o.ua) headers['User-Agent'] = o.ua; let body = o.body; if (body && !Buffer.isBuffer(body)) { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; } if (body) headers['Content-Length'] = body.length; const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, buf, json: j }); }); }); r.on('error', reject); if (body) r.write(body); r.end(); }); } async function signIn(email) { const ip = '10.9.' + crypto.randomInt(250) + '.' + crypto.randomInt(250); const s = await req('POST', '/api/auth/email/start', { ip, body: { email, fts: Date.now() - 8000, hp_field_x9: '', pick: null } }); if (!s.json || !s.json.devCode) throw new Error('no devCode for ' + email + ': ' + s.buf.toString().slice(0, 200)); const v = await req('POST', '/api/auth/email/verify', { ip, body: { email, code: s.json.devCode } }); const sc = [].concat(v.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; '); if (!sc) throw new Error('no session cookie for ' + email); return sc; } let browser; try { for (let i = 0; i < 40; i++) { try { const r = await req('GET', '/api/config'); if (r.status === 200) break; } catch (e) {} await sleep(500); } // ── tiers and limits through the API ── const cS = await signIn('starter@bs.test'), cB = await signIn('builder@bs.test'), cL = await signIn('locked@bs.test'); const lS = await req('GET', '/api/my/bannerspins', { cookie: cS }); const lB = await req('GET', '/api/my/bannerspins', { cookie: cB }); const lL = await req('GET', '/api/my/bannerspins', { cookie: cL }); check(lS.json && lS.json.tier.key === 'starter' && lS.json.tier.spins === 2 && lS.json.tier.banners === 5, 'starter tier = 2 x 5', JSON.stringify(lS.json && lS.json.tier)); check(lB.json && lB.json.tier.key === 'builder' && lB.json.tier.spins === 5 && lB.json.tier.banners === 15, 'builder tier (2 qualifying buyers) = 5 x 15', JSON.stringify(lB.json && lB.json.tier)); check(lL.json && lL.json.tier.ok === false, 'a $20-only member is locked', lL.json && lL.json.tier.reason); const lockedCreate = await req('POST', '/api/my/bannerspins', { cookie: cL, body: { name: 'x', size: '468x60' } }); check(lockedCreate.status === 400 && /\$25/.test(lockedCreate.json.error), 'locked member cannot create', lockedCreate.json && lockedCreate.json.error); const lockedUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cL, body: IMG.a, headers: { 'Content-Type': 'image/png' } }); check(lockedUp.status === 403, 'locked member cannot upload', String(lockedUp.status)); // ════ phase 3 (2026-10-20): image health checks + the winner badge, on the builder's own Banner Spin ════ // Runs first, before the scheduled health pass (2 minutes after boot), so only the admin "run checks" passes below count. const AUTH = { Authorization: 'Bearer ' + ADMIN_PW }; const rotB = await req('POST', '/api/my/rotations', { cookie: cB, body: { name: 'Builder invite' } }); await req('POST', '/api/my/rotations/' + rotB.json.rotation.id + '/dest', { cookie: cB, body: { url: 'https://spin-dest.example/b', weight: 10 } }); const hsp = await req('POST', '/api/my/bannerspins', { cookie: cB, body: { name: 'Health test', size: '468x60', fallback: 'https://fallback.example/b' } }); const HID = hsp.json.spin.id, HCODE = hsp.json.spin.code; const hImg = [png(468, 60, [250, 120, 0]), png(468, 60, [0, 200, 200]), png(468, 60, [120, 0, 200])]; const hByHash = {}; hImg.forEach((b, i) => { hByHash[sha(b)] = i + 1; }); const hUp = []; for (const b of hImg) hUp.push((await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cB, body: b, headers: { 'Content-Type': 'image/png' } })).json); for (const [i, u] of hUp.entries()) await req('POST', '/api/my/bannerspins/' + HID + '/banner', { cookie: cB, body: i < 2 ? { image: u.url, link: rotB.json.rotation.id, label: 'H' + (i + 1), weight: 10 } : { image: u.url, target: 'https://nowhere.invalid/offer', label: 'H3 dead target', weight: 10 } }); const hFile = i => path.join(DATA, 'uploads', hUp[i].url.split('/').pop()); const hRun = async () => (await req('POST', '/api/admin/bannerspins/health', { headers: AUTH, body: { id: HID } })).json; const hGet = async () => (await req('GET', '/api/my/bannerspins', { cookie: cB })).json.spins.find(x => x.id === HID); const bOf = (sp, id) => sp.banners.find(b => b.id === id); const hDesc = sp => sp.banners.map(b => b.id + ':' + (b.health ? b.health.state + '/' + b.health.fails : '-') + (b.active ? ' live' : ' off') + (b.autoPaused ? ' auto' : '')).join(', '); const hr1 = await hRun(); let H = await hGet(); check(hr1 && hr1.checked === 3 && bOf(H, 1).health.state === 'ok' && bOf(H, 2).health.state === 'ok' && bOf(H, 3).health.state === 'dead' && bOf(H, 3).active, 'health: one pass checks image + target of every live banner (spin-link target ok, dead target failing, nothing paused yet)', (hr1 && hr1.checked) + ' checked; ' + hDesc(H)); const good1 = fs.readFileSync(hFile(0)), good2 = fs.readFileSync(hFile(1)); fs.writeFileSync(hFile(0), Buffer.from('this is not an image at all')); // simulate a broken image await hRun(); await hRun(); H = await hGet(); check(!bOf(H, 3).active && bOf(H, 3).autoPaused && bOf(H, 1).active && bOf(H, 1).health.state === 'image' && bOf(H, 1).health.fails === 2, 'health: 3 failing checks in a row pause a banner (dead target), 2 do not (broken image so far)', hDesc(H)); await hRun(); H = await hGet(); check(!bOf(H, 1).active && bOf(H, 1).autoPaused && /not a readable image/.test(bOf(H, 1).health.note), 'health: a broken image is auto-paused on its 3rd failing check', hDesc(H) + ' · ' + bOf(H, 1).health.note); let hSeenOff = 0; for (let i = 0; i < 30; i++) { const r = await req('GET', '/i/' + HCODE + '.gif', { host: LINK, ip: '10.20.0.' + i, referer: 'https://h.example/' }); const id = hByHash[sha(r.buf)]; if (id !== 2) hSeenOff++; } check(hSeenOff === 0, 'auto-paused banners never serve (30 loads, all the one live banner)', hSeenOff + ' of 30 were not banner 2'); fs.writeFileSync(hFile(1), Buffer.from('broken too')); await hRun(); await hRun(); await hRun(); H = await hGet(); check(bOf(H, 2).active && !bOf(H, 2).autoPaused && bOf(H, 2).health.fails >= 3 && /Kept live/.test(bOf(H, 2).health.note), 'health: the last live banner is never auto-paused', hDesc(H) + ' · ' + bOf(H, 2).health.note); fs.writeFileSync(hFile(0), good1); fs.writeFileSync(hFile(1), good2); // the images are fixed await hRun(); H = await hGet(); const oneClean = !bOf(H, 1).active; await hRun(); H = await hGet(); check(oneClean && bOf(H, 1).active && !bOf(H, 1).autoPaused && bOf(H, 2).active && bOf(H, 2).health.state === 'ok' && !bOf(H, 3).active, 'health: 2 clean passes resume the auto-paused banner (1 is not enough); the dead target stays paused', hDesc(H)); const hLog = await req('GET', '/api/admin/bannerspins', { headers: AUTH }); check(hLog.status === 200 && hLog.json.spins.some(x => x.id === HID), 'admin Banner Spin list still answers after the checks'); // winner badge: no badge until two live banners have 1,000 views each and one leads on CTR let wst = (await req('GET', '/api/my/bannerspins/' + HID + '/stats', { cookie: cB })).json; check(!wst.winner && wst.banners.every(b => !b.winner), 'no winner badge before 1,000 views each', JSON.stringify(wst.banners.map(b => [b.id, b.imps, b.clicks]))); for (let i = 0; i < 40; i++) await req('GET', '/c/' + HCODE + '?x=' + (i < 30 ? 1 : 2), { host: LINK, ip: '10.21.0.' + i, ua: 'Mozilla/5.0 Clicker' + i, referer: 'https://h.example/' }); // 1,500 views each, added straight to the counters file the way a second app copy's flush would (read, add, write) await sleep(6000); const cFile = path.join(DATA, 'bannerspin-counts.json'); const cj = JSON.parse(fs.readFileSync(cFile, 'utf8')); const ctToday = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date()); const hd = cj.d[String(HID)] = cj.d[String(HID)] || {}; const hdd = hd[ctToday] = hd[ctToday] || { b: {}, h: {}, u: {} }; hdd.b['1'] = (hdd.b['1'] || 0) + 1500; hdd.b['2'] = (hdd.b['2'] || 0) + 1500; fs.writeFileSync(cFile, JSON.stringify(cj)); await req('GET', '/i/' + HCODE + '.gif', { host: LINK, ip: '10.22.0.1', referer: 'https://h.example/' }); // marks the counters dirty, so the next flush reads the file back await sleep(6500); wst = (await req('GET', '/api/my/bannerspins/' + HID + '/stats', { cookie: cB })).json; check(wst.winner === 1 && wst.banners.find(b => b.id === 1).winner && !wst.banners.find(b => b.id === 2).winner, 'winner badge: banner 1 leads on CTR with 1,000+ views on both', JSON.stringify(wst.banners.map(b => [b.id, b.imps, b.clicks, b.ctr, b.winner]))); // a spin link of the starter's own, used as one banner's target const rot = await req('POST', '/api/my/rotations', { cookie: cS, body: { name: 'Main invite' } }); await req('POST', '/api/my/rotations/' + rot.json.rotation.id + '/dest', { cookie: cS, body: { url: 'https://spin-dest.example/landing', weight: 10 } }); const ROTCODE = rot.json.rotation.code; // ── the builder UI: create a Banner Spin, add 3 banners ── browser = await chromium.launch(); const ctx = await browser.newContext({ viewport: { width: 1360, height: 950 } }); await ctx.addCookies(cS.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; })); const page = await ctx.newPage(); const pageErrors = []; page.on('pageerror', e => pageErrors.push(e.message)); page.on('console', m => { if (m.type() === 'error' && !/favicon|fonts|status of 40[014]/.test(m.text())) pageErrors.push(m.text()); }); await page.goto(BASE + '/links#b', { waitUntil: 'domcontentloaded' }); await page.waitForSelector('#bsWs:not([hidden])', { timeout: 15000 }); await page.waitForSelector('#bsTier .tag', { timeout: 15000 }); check(/Starter/.test(await page.textContent('#bsTier')), 'builder shows the tier', (await page.textContent('#bsTier')).trim().slice(0, 120)); await page.click('#bsNewBtn2'); await page.fill('#dlg-name', 'Forum signature'); await page.selectOption('#bsNewSize', '468x60'); await page.fill('#dlg-fallback', 'https://fallback.example/home'); await page.click('#dlgOk'); await page.waitForSelector('#bsSel:not([hidden])', { timeout: 10000 }); // wrong size warns, too big blocks await page.setInputFiles('#bsFile', path.join(DATA, 'wrong.png')); await page.waitForSelector('#bsPrev .wm', { timeout: 5000 }); check(/300x250/.test(await page.textContent('#bsPrev')), 'wrong-size image warns in the builder', (await page.textContent('#bsPrev')).trim().slice(0, 120)); await page.setInputFiles('#bsFile', path.join(DATA, 'big.png')); await page.waitForSelector('#bsPrev .bm', { timeout: 5000 }); check(/150 KB/.test(await page.textContent('#bsPrev')), 'over-150 KB image is refused in the builder', (await page.textContent('#bsPrev')).trim().slice(0, 120)); const banners = [['a.png', 'url', 'https://target-a.example/offer?sub={lsid}', '10', 'Red'], ['b.png', 'url', 'https://target-b.example/page', '20', 'Green'], ['c.png', 'link', '', '30', 'Blue to my spin link']]; for (const [file, kind, url, w, label] of banners) { await page.setInputFiles('#bsFile', path.join(DATA, file)); await page.waitForSelector('#bsPrev .okm', { timeout: 5000 }); if (kind === 'url') { await page.selectOption('#bsTgtKind', 'url'); await page.fill('#bsTgtUrl', url); } else await page.selectOption('#bsTgtKind', String(rot.json.rotation.id)); await page.fill('#bsWeight', w); await page.fill('#bsLabel', label); const n0 = await page.locator('#bsRows .rw[data-bid]').count(); await page.click('#bsAddBtn'); await page.waitForFunction(n => document.querySelectorAll('#bsRows .rw[data-bid]').length > n, n0, { timeout: 10000 }); } check(await page.locator('#bsRows .rw[data-bid]').count() === 3, '3 banners added through the UI'); await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-banners.png'), fullPage: true }); await page.click('#bsTabs button[data-tab="code"]'); await page.selectOption('#bsHost', LINK); const codes = await page.$$eval('#bsCodes pre', ps => ps.map(p => p.textContent)); check(codes.length === 4, 'four embeds offered', String(codes.length)); await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-code.png'), fullPage: true }); await page.click('#bsTabs button[data-tab="settings"]'); await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-settings.png'), fullPage: true }); const list = (await req('GET', '/api/my/bannerspins', { cookie: cS })).json; const S = list.spins[0]; const CODE = S.code; const imgPath = '/i/' + CODE + '.gif', clickPath = '/c/' + CODE, jsPath = '/s/' + CODE + '.js'; // every URL a placement ever loads: the four embeds + what the script writes (uploads stay behind /i/, never in an embed) const jsOut = (await req('GET', jsPath, { host: LINK, ip: '10.0.0.250', ua: 'Mozilla/5.0 TokenCheck', referer: 'https://token.example/' })).buf.toString().replace(/\\"/g, '"'); const urls = (codes.join('\n') + '\n' + jsOut).match(/https?:\/\/[^\s"'\]\[<>]+/g) || []; const BADTOK = /\dx\d|banner|ads/i; const pathOf = x => x.replace(/^https?:\/\/[^/]+/, ''); check(urls.length >= 7 && urls.every(x => !BADTOK.test(pathOf(x))) && !BADTOK.test(CODE), 'no size / banner / ads tokens in any served URL path', (urls.filter(x => BADTOK.test(pathOf(x))).join(' ') || urls.length + ' URLs clean, e.g. ' + urls.slice(0, 3).map(pathOf).join(' '))); // the generator itself: 20,000 fresh codes, none with a token { const ALPHA = 'abcdefghjkmnpqrstuvwxyz23456789'; let bad = 0; const re = /ad|banner|\dx\d/; for (let i = 0; i < 20000; i++) { let c = ''; for (let k = 0; k < 7; k++) c += ALPHA[crypto.randomInt(ALPHA.length)]; if (re.test(c)) bad++; } check(bad > 0, 'sanity: the unfiltered alphabet does produce risky codes (' + bad + ' of 20000), so the server filter matters'); } check(codes[0].includes('https://' + LINK + '/i/' + CODE + '.gif') && codes[2].includes('https://' + LINK + '/s/' + CODE + '.js') && codes[3].startsWith('[url=https://' + LINK + '/c/' + CODE + ']'), 'embeds use the chosen link domain', codes[0].split('\n')[0]); // which banner an image body is, by its bytes const byHash = { [sha(IMG.a)]: 1, [sha(IMG.b)]: 2, [sha(IMG.c)]: 3 }; const expectTarget = { 1: /^https:\/\/target-a\.example\/offer\?sub=k[0-9a-f]{11}$/, 2: /^https:\/\/target-b\.example\/page$/, 3: new RegExp('^https://' + LINK.replace('.', '\\.') + '/r/' + ROTCODE + '$'), 0: /^https:\/\/fallback\.example\/home$/ }; // ── headers ── const h1 = await req('GET', imgPath, { host: LINK, ip: '10.1.1.1', referer: 'https://forum-a.example/t/1' }); const h2 = await req('GET', imgPath, { host: LINK, ip: '10.1.1.1', referer: 'https://forum-a.example/t/1' }); check(/no-store/.test(h1.headers['cache-control']) && /private/.test(h1.headers['cache-control']), 'image is Cache-Control: no-store, private', h1.headers['cache-control']); check(!!h1.headers.etag && h1.headers.etag !== h2.headers.etag, 'fresh ETag on every load', h1.headers.etag + ' vs ' + h2.headers.etag); check(h1.status === 200 && /^image\/png/.test(h1.headers['content-type']) && byHash[sha(h1.buf)], 'image body is one of the banners', h1.headers['content-type']); const h3 = await req('GET', imgPath, { host: LINK2, ip: '10.1.1.2', referer: 'https://x.example/' }); check(h3.status === 200 && byHash[sha(h3.buf)], 'a second link domain answers the same code'); const unknown = await req('GET', '/i/zzzzzzz.gif', { host: LINK }); check(unknown.status === 404, 'unknown code is 404'); // ── click matching: 3 visitors x 3 placements, interleaved, 40 rounds ── // record expected counted impressions: once per (visitor, banner) per minute (all of this runs inside a minute or two) await sleep(6000); const statsBase = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json.totals.imps; const visitors = [{ ip: '10.2.0.1', ua: 'Mozilla/5.0 (Windows NT 10.0) VisitorA' }, { ip: '10.2.0.2', ua: 'Mozilla/5.0 (iPhone) VisitorB' }, { ip: '10.2.0.3', ua: 'Mozilla/5.0 (Macintosh) VisitorC' }]; const hostsP = ['https://forum-a.example/thread/9', 'https://blog-b.example/post', 'https://safelist-c.example/mail?id=4']; let pairs = 0, ok = 0, lsids = []; const seen = new Set(); const shownBy = { 1: 0, 2: 0, 3: 0 }; const t0 = Date.now(); const misses = []; for (let round = 0; round < 40; round++) { // every visitor loads the banner on two different placements, then clicks on one of them (order shuffled) const loads = []; for (const [vi, v] of visitors.entries()) { const a = hostsP[(round + vi) % 3], b = hostsP[(round + vi + 1) % 3]; loads.push({ v, ref: a }, { v, ref: b }); } loads.sort(() => crypto.randomInt(3) - 1); const shown = new Map(); for (const L of loads) { const r = await req('GET', imgPath, { host: LINK, ip: L.v.ip, ua: L.v.ua, referer: L.ref }); const bid = byHash[sha(r.buf)]; shown.set(L.v.ip + '|' + new URL(L.ref).host, bid); shownBy[bid]++; seen.add(L.v.ip + '|' + bid); } for (const [vi, v] of visitors.entries()) { const ref = hostsP[(round + vi + (round % 2)) % 3]; const want = shown.get(v.ip + '|' + new URL(ref).host); const c = await req('GET', clickPath, { host: LINK, ip: v.ip, ua: v.ua, referer: ref }); pairs++; const loc = c.headers.location || ''; if (expectTarget[want].test(loc)) ok++; else misses.push(want + ' -> ' + loc); const m = /sub=(k[0-9a-f]{11})/.exec(loc); if (m) lsids.push(m[1]); } } const rate = ok / pairs; check(rate >= 0.95, 'clicks land on the matching banner target >= 95%', ok + '/' + pairs + ' = ' + (rate * 100).toFixed(1) + '%' + (misses.length ? ' misses: ' + misses.slice(0, 3).join(', ') : '')); check(shownBy[3] > shownBy[1], 'weights shape the rotation (30 vs 10)', JSON.stringify(shownBy)); const elapsed = Date.now() - t0; // ── fallback: a visitor who never saw the image ── const fbc = await req('GET', clickPath, { host: LINK, ip: '10.3.3.3', ua: 'Mozilla/5.0 NeverSaw', referer: 'https://forum-a.example/thread/9' }); check(expectTarget[0].test(fbc.headers.location || ''), 'no note -> fallback target', fbc.headers.location); // ── bots and prefetchers are not counted ── for (let i = 0; i < 5; i++) { await req('GET', imgPath, { host: LINK, ip: '10.4.0.' + i, ua: 'Googlebot/2.1', referer: 'https://forum-a.example/' }); await req('GET', imgPath, { host: LINK, ip: '10.5.0.' + i, ua: 'Mozilla/5.0 Pre', referer: 'https://forum-a.example/', headers: { 'Sec-Purpose': 'prefetch' } }); } // ── script embed: exact match ── const js = await req('GET', jsPath, { host: LINK, ip: '10.6.0.1', ua: 'Mozilla/5.0 ScriptUser', referer: 'https://blog-b.example/post' }); const xm = /\/c\/[a-z0-9]+\?x=(\d+)/.exec(js.buf.toString()); const xb = xm ? Number(xm[1]) : -1; check(js.status === 200 && /javascript/.test(js.headers['content-type']) && /no-store/.test(js.headers['cache-control']) && xb >= 1, 'script embed writes banner + its own click link', js.buf.toString().slice(0, 90)); const imgInJs = /src=\\"([^\\"]+)\\"/.exec(js.buf.toString()); const ji = imgInJs ? await req('GET', new URL(imgInJs[1]).pathname + new URL(imgInJs[1]).search, { host: LINK }) : null; check(ji && byHash[sha(ji.buf)] === xb, 'script image is the same banner its link names', imgInJs && imgInJs[1]); const jc = await req('GET', clickPath + '?x=' + xb, { host: LINK, ip: '10.6.0.99', ua: 'Mozilla/5.0 OtherDevice', referer: 'https://blog-b.example/post' }); check(expectTarget[xb].test(jc.headers.location || ''), 'script click goes to that exact banner target', jc.headers.location); seen.add('10.6.0.1|' + xb); // ── counters ── await sleep(6500); const st = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json; const expected = statsBase + seen.size; check(st.totals.imps === expected, 'impressions counted once per visitor per banner per minute, bots + prefetch excluded', 'counted ' + st.totals.imps + ', expected ' + expected + ' (loop took ' + Math.round(elapsed / 1000) + ' s)'); const plHosts = st.placements.map(p => p.host); check(['forum-a.example', 'blog-b.example', 'safelist-c.example'].every(h => plHosts.includes(h)), 'per-placement counters', plHosts.join(', ')); check(st.banners.every(b => b.imps > 0) && st.totals.clicks >= pairs, 'per-banner views + clicks move', st.banners.map(b => b.id + ':' + b.imps + '/' + b.clicks).join(' ')); check(st.totals.matchRate >= 95, 'match rate in stats', st.totals.matchRate + '%, unmatched ' + st.totals.unmatched); const countsFile = JSON.parse(fs.readFileSync(path.join(DATA, 'bannerspin-counts.json'), 'utf8')); check(!!countsFile.d[String(S.id)], 'counters flushed to the volume file (no row per load)', Object.keys(countsFile.d[String(S.id)] || {}).join(',')); // ── conversions credit the banner click (partner postback with the lsid) ── const pb = (await req('GET', '/api/my/postbacks', { cookie: cS })).json; const conv = lsids.length ? await req('GET', '/pb/in?key=' + pb.key + '&lsid=' + lsids[0] + '&event=sale&value=1.00') : null; const st2 = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json; check(conv && conv.status === 200 && st2.totals.conversions === 1, 'a conversion on a banner click id lands on the Banner Spin', conv && conv.buf.toString().slice(0, 100)); // ── pause and the admin kill switch ── const blankOf = r => r.buf.slice(0, 8).toString('hex') === '89504e470d0a1a0a' && r.buf.readUInt32BE(16) === 468 && r.buf.readUInt32BE(20) === 60 && !byHash[sha(r.buf)]; await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { paused: true } }); const pz = await req('GET', imgPath, { host: LINK, ip: '10.7.0.1', referer: 'https://forum-a.example/' }); check(blankOf(pz), 'paused with no fallback image -> blank image at the right size'); const fbUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cS, body: IMG.fb, headers: { 'Content-Type': 'image/png' } }); await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { fallbackImage: fbUp.json.url } }); const pz2 = await req('GET', imgPath, { host: LINK, ip: '10.7.0.1', referer: 'https://forum-a.example/' }); check(sha(pz2.buf) === sha(IMG.fb), 'paused -> the fallback banner image'); await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { paused: false } }); const auth = { Authorization: 'Bearer ' + ADMIN_PW }; await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { off: true, note: 'qa' } }); const off1 = await req('GET', imgPath, { host: LINK, ip: '10.8.0.1', referer: 'https://forum-a.example/' }); const offc = await req('GET', clickPath, { host: LINK, ip: '10.8.0.1', referer: 'https://forum-a.example/' }); check(blankOf(off1) && expectTarget[0].test(offc.headers.location || ''), 'admin kill switch: neutral blank image + fallback link', offc.headers.location); await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { off: false } }); await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { bannerId: 1, off: true } }); let saw1 = 0; for (let i = 0; i < 40; i++) { const r = await req('GET', imgPath, { host: LINK, ip: '10.8.1.' + i, referer: 'https://forum-a.example/' }); if (byHash[sha(r.buf)] === 1) saw1++; } check(saw1 === 0, 'one banner taken offline by admin never serves', saw1 + ' of 40'); await req('POST', '/api/admin/bannerspins/' + S.id, { headers: auth, body: { bannerId: 1, off: false } }); const adm = await req('GET', '/api/admin/content?type=bannerspin&fresh=1', { headers: auth }); const admS = adm.json && adm.json.items && adm.json.items.find(x => x.id === String(S.id)); // the builder's health-test Banner Spin is listed too since phase 3 check(admS && adm.json.items.length === 2 && admS.detail.banners.length === 3 && admS.actions.length === 4, 'admin Member content lists the Banner Spin with its banners + actions', adm.json && JSON.stringify(adm.json.totals.bannerspin)); // ── one-per-visitor mode: the same banner all day ── await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { mode: 'visitor' } }); const same = new Set(); for (let i = 0; i < 12; i++) { const r = await req('GET', imgPath, { host: LINK, ip: '10.9.9.9', ua: 'Mozilla/5.0 Loyal', referer: 'https://forum-a.example/' }); same.add(byHash[sha(r.buf)]); } check(same.size === 1, 'one-per-visitor mode shows one banner all day', [...same].join(',')); await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { mode: 'weight' } }); // ── tier limits: banners per Banner Spin (Starter 5), Banner Spins per member (Starter 2) ── const up = []; for (let i = 0; i < 3; i++) up.push((await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cS, body: png(468, 60, [i * 60, 10, 10]), headers: { 'Content-Type': 'image/png' } })).json); const add4 = await req('POST', '/api/my/bannerspins/' + S.id + '/banner', { cookie: cS, body: { image: up[0].url, target: 'https://t4.example/' } }); const add5 = await req('POST', '/api/my/bannerspins/' + S.id + '/banner', { cookie: cS, body: { image: up[1].url, target: 'https://t5.example/' } }); const add6 = await req('POST', '/api/my/bannerspins/' + S.id + '/banner', { cookie: cS, body: { image: up[2].url, target: 'https://t6.example/' } }); check(add4.status === 200 && add5.status === 200 && add6.status === 400 && /5 banners/.test(add6.json.error), 'Starter: 6th banner refused', add6.json && add6.json.error); const sp2 = await req('POST', '/api/my/bannerspins', { cookie: cS, body: { name: 'Second', size: '728x90' } }); const sp3 = await req('POST', '/api/my/bannerspins', { cookie: cS, body: { name: 'Third', size: '300x250' } }); check(sp2.status === 200 && sp3.status === 400 && /2 Banner Spins/.test(sp3.json.error), 'Starter: 3rd Banner Spin refused', sp3.json && sp3.json.error); const badSize = await req('POST', '/api/my/bannerspins', { cookie: cB, body: { name: 'x', size: '999x99' } }); check(badSize.status === 400, 'unsupported size refused'); const otherImg = await req('POST', '/api/my/bannerspins/' + sp2.json.spin.id + '/banner', { cookie: cB, body: { image: up[2].url, target: 'https://x.example/' } }); check(otherImg.status === 400, 'a member cannot use another member\'s Banner Spin', otherImg.json && otherImg.json.error); const bigUp = await req('POST', '/api/my/bannerspins/upload?size=468x60', { cookie: cS, body: IMG.big, headers: { 'Content-Type': 'image/png' } }).catch(e => ({ status: 'reset' })); check(bigUp.status === 400 || bigUp.status === 'reset', 'server refuses an image over 150 KB', String(bigUp.status) + ' (' + IMG.big.length + ' bytes)'); // ════ phase 3: traffic-source postback end to end on a Banner Spin click ════ const srcR = await req('POST', '/api/my/sources', { cookie: cS, body: { name: 'QA Network', template: 'custom', params: [{ key: 'clickid', token: '{clickid}' }], postbackUrl: 'https://example.com/pb?cid={clickid}&ev={event}&pay={payout}&ls={lsid}', events: ['join', 'lead', 'purchase', 'external'] } }); const SRC = srcR.json && srcR.json.source; const attach = SRC ? await req('POST', '/api/my/bannerspins/' + S.id, { cookie: cS, body: { sourceId: SRC.id } }) : null; check(!!SRC && attach && attach.status === 200 && attach.json.spin.sourceId === SRC.id, 'a traffic source attaches to the Banner Spin', srcR.buf.toString().slice(0, 120)); const pc = await req('GET', clickPath + '?x=1&clickid=NET-777', { host: LINK, ip: '10.12.0.1', ua: 'Mozilla/5.0 Buyer', referer: 'https://forum-a.example/' }); const pls = /sub=(k[0-9a-f]{11})/.exec(pc.headers.location || ''); const convBefore = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json.totals.conversions; const pin = pls ? await req('GET', '/pb/in?key=' + pb.key + '&lsid=' + pls[1] + '&event=sale&value=2.50') : null; // waits for the outbound postback (real network, example.com) let slog = null; for (let i = 0; i < 20 && SRC; i++) { const g = await req('GET', '/api/my/sources/' + SRC.id, { cookie: cS }); slog = ((g.json && g.json.log) || [])[0] || null; if (slog) break; await sleep(500); } check(pin && pin.status === 200 && slog && /cid=NET-777/.test(slog.url) && /ev=external/.test(slog.url) && /pay=2\.5/.test(slog.url) && slog.url.includes('ls=' + pls[1]), 'Banner Spin conversion fires the traffic source postback with the network click id, event, payout and lsid', slog ? slog.url + ' -> ' + (slog.ok ? 'delivered HTTP ' + slog.status : 'not delivered: ' + (slog.status || '') + ' ' + slog.note) : pin && pin.buf.toString().slice(0, 120)); const convAfter = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json.totals.conversions; check(convAfter === convBefore + 1, 'that conversion is credited to the Banner Spin', convBefore + ' -> ' + convAfter); // ════ phase 3: bots and servers kept apart, the "caches banners" flag ════ await sleep(6000); const stA = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json; for (let i = 0; i < 8; i++) await req('GET', imgPath, { host: LINK, ip: '10.13.0.1', ua: 'Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko Firefox/11.0 (via ggpht.com GoogleImageProxy)' }); // a mail image proxy, no referrer for (let i = 0; i < 12; i++) await req('GET', clickPath, { host: LINK, ip: '10.14.0.' + i, ua: 'Mozilla/5.0 Exchange' + i, referer: 'https://cachex.example/surf' }); // an exchange showing its own copy: clicks, no views await sleep(6500); const stB = (await req('GET', '/api/my/bannerspins/' + S.id + '/stats', { cookie: cS })).json; check(stB.totals.imps === stA.totals.imps && stB.totals.serverLoads >= stA.totals.serverLoads + 8 && stB.totals.botLoads >= 10, 'image-proxy and bot loads are shown separately, never as views', 'views ' + stA.totals.imps + ' -> ' + stB.totals.imps + ', server loads ' + stB.totals.serverLoads + ', bot loads ' + stB.totals.botLoads); const pCache = stB.placements.find(p => p.host === 'cachex.example'), pNone = stB.placements.find(p => p.host === '(none)'), pForum = stB.placements.find(p => p.host === 'forum-a.example'); const pSafe = stB.placements.find(p => p.host === 'safelist-c.example'); // more clicks than views in this test (clicks are not deduped) but every one matched: no flag check(pCache && /frozen/.test(pCache.caches) && pNone && /server/.test(pNone.caches) && pForum && !pForum.caches && pSafe && !pSafe.caches, '"caches banners" flag on the copying exchange and the image proxy, not on a normal placement', JSON.stringify([pCache && pCache.caches, pNone && pNone.caches, pForum && pForum.caches]).slice(0, 300)); check(Array.isArray(stB.country) && stB.device.some(d => d.k === 'mobile') && stB.device.some(d => d.k === 'desktop') && stB.days.length >= 1 && stB.days[stB.days.length - 1].day === ctToday, 'stats break clicks down by country and device, days are Central time', JSON.stringify(stB.device) + ' last day ' + (stB.days.slice(-1)[0] || {}).day); // ════ phase 3: the Reports screen (totals beside spin links, per banner, per placement) ════ const repS = (await req('GET', '/api/my/reports?days=30', { cookie: cS })).json; const rb = repS && repS.bannerSpins; check(rb && rb.count === 2 && rb.totals.imps === stB.totals.imps && rb.totals.clicks === stB.totals.clicks && rb.banners.some(b => b.spinId === S.id) && rb.placements.some(p => p.host === 'cachex.example' && p.caches) && repS.totals && repS.top, 'Reports API: Banner Spin totals match the Stats tab and sit beside the spin-link report', rb && JSON.stringify(rb.totals)); const repB = (await req('GET', '/api/my/reports?days=7', { cookie: cB })).json; check(repB.bannerSpins && repB.bannerSpins.banners.some(b => b.spinId === HID && b.id === 1 && b.winner), 'Reports API: the winner badge shows on Reports too', repB.bannerSpins && JSON.stringify(repB.bannerSpins.banners.map(b => [b.id, b.imps, b.ctr, b.winner]))); await page.goto(BASE + '/reports', { waitUntil: 'domcontentloaded' }); await page.waitForSelector('#bsRowsB .rw', { timeout: 15000 }); await page.waitForTimeout(600); check(await page.locator('#bsRowsP [data-caches="cachex.example"]').count() === 1 && /Banner views/.test(await page.textContent('#tiles')), 'Reports screen: Banner Spin section with the CACHED placement and the totals tiles'); await page.locator('#bsSect').scrollIntoViewIfNeeded(); await page.screenshot({ path: path.join(SHOTS, 'reports-desktop.png'), fullPage: true }); const ctxB = await browser.newContext({ viewport: { width: 1360, height: 950 } }); await ctxB.addCookies(cB.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; })); const pB = await ctxB.newPage(); pB.on('pageerror', e => pageErrors.push('builder: ' + e.message)); await pB.goto(BASE + '/reports', { waitUntil: 'domcontentloaded' }); await pB.waitForSelector('#bsRowsB [data-winner]', { timeout: 15000 }); await pB.locator('#bsSect').scrollIntoViewIfNeeded(); await pB.screenshot({ path: path.join(SHOTS, 'reports-winner.png'), fullPage: true }); check(true, 'Reports screen shows the WINNER badge'); // the builder: health status on every banner row, the winner on the Stats tab await pB.goto(BASE + '/links#b' + HID, { waitUntil: 'domcontentloaded' }); await pB.waitForSelector('#bsRows [data-bhealth]', { timeout: 15000 }); const rowsTxt = await pB.textContent('#bsRows'); check(await pB.locator('#bsRows [data-bhealth="ok"]').count() === 2 && await pB.locator('#bsRows [data-bhealth="paused"]').count() === 1 && /AUTO-PAUSED/.test(rowsTxt) && /Target page is down/.test(rowsTxt), 'builder shows each banner\'s health (2 OK, 1 auto-paused with the reason)', rowsTxt.replace(/\s+/g, ' ').slice(0, 300)); await pB.screenshot({ path: path.join(SHOTS, 'builder-health.png'), fullPage: true }); await pB.click('#bsTabs button[data-tab="stats"]'); await pB.waitForSelector('#bsStB [data-winner="1"]', { timeout: 10000 }); await pB.screenshot({ path: path.join(SHOTS, 'builder-stats-winner.png'), fullPage: true }); check(true, 'builder Stats tab shows the WINNER badge'); // ════ phase 4: the admin switch is a real button (Admin > Member content) ════ const ctxA = await browser.newContext({ viewport: { width: 1360, height: 950 } }); const pA = await ctxA.newPage(); pA.on('pageerror', e => pageErrors.push('admin: ' + e.message)); await pA.goto(BASE + '/admin#content', { waitUntil: 'domcontentloaded' }); await pA.fill('#adEmail', 'admin@bs.test'); await pA.click('#adSend'); await pA.waitForSelector('#adVerify:not([hidden])', { timeout: 10000 }); await pA.waitForFunction(() => document.getElementById('adCode').value.length > 0, null, { timeout: 10000 }); await pA.click('#adVerify'); await pA.waitForSelector('#pane-content:not([hidden])', { timeout: 15000 }).catch(async () => { await pA.click('.bo-menu [data-pane="content"]'); await pA.waitForSelector('#pane-content:not([hidden])', { timeout: 10000 }); }); await pA.waitForFunction(() => /Switch Banner Spin off/.test(document.getElementById('bsSwitchBtn').textContent) && !document.getElementById('bsSwitchBtn').disabled, null, { timeout: 15000 }); check(/live/.test(await pA.textContent('#bsSwitchState')), 'admin shows the Banner Spin switch, live', await pA.textContent('#bsSwitchState')); await pA.click('#bsSwitchBtn'); await pA.waitForSelector('#dlgOk', { timeout: 5000 }); await pA.screenshot({ path: path.join(SHOTS, 'admin-switch-confirm.png') }); await pA.click('#dlgOk'); await pA.waitForFunction(() => /switched off/.test(document.getElementById('bsSwitchState').textContent), null, { timeout: 10000 }); await pA.screenshot({ path: path.join(SHOTS, 'admin-switch-off.png') }); const gOff = (await req('GET', '/api/admin/bannerspins', { headers: AUTH })).json.settings.off; const offImg = await req('GET', imgPath, { host: LINK, ip: '10.15.0.1', referer: 'https://forum-a.example/' }); const offClk = await req('GET', clickPath, { host: LINK, ip: '10.15.0.1', referer: 'https://forum-a.example/' }); const memberSees = (await req('GET', '/api/my/bannerspins', { cookie: cS })).json.off; check(gOff === true && blankOf(offImg) && expectTarget[0].test(offClk.headers.location || '') && memberSees === true, 'admin button switches Banner Spin off: blank image, fallback click, members see the notice', 'off=' + gOff + ' member off=' + memberSees + ' click ' + offClk.headers.location); await pA.click('#bsSwitchBtn'); await pA.waitForFunction(() => /live/.test(document.getElementById('bsSwitchState').textContent), null, { timeout: 10000 }); const onImg = await req('GET', imgPath, { host: LINK, ip: '10.15.0.2', referer: 'https://forum-a.example/' }); const gOn = (await req('GET', '/api/admin/bannerspins', { headers: AUTH })).json.settings.off; check(gOn === false && onImg.status === 200 && !blankOf(onImg), 'admin button switches it back on and banners serve again', 'off=' + gOn + ', image ' + onImg.status + ' ' + onImg.buf.length + ' bytes'); await pA.click('#bsHealthBtn'); await pA.waitForTimeout(1500); // the "run banner checks" button answers (it checks every Banner Spin) await ctxA.close(); // ════ phase 4: chatbot, training, promo tools, release draft ════ const chat = await req('POST', '/api/chat', { body: { message: 'What is Banner Spin and how do I embed it?' } }); const ans = (chat.json && chat.json.reply) || ''; check(chat.json && chat.json.canned && /Banner Spin/.test(ans) && /\$25/.test(ans) && /Gmail/.test(ans) && /paid ad networks/.test(ans) && /25 banners/.test(ans) && !/—/.test(ans), 'chatbot: canned Banner Spin answer (tiers, embeds, Gmail + paid-network limits, no em dash)', ans.slice(0, 160)); const chat2 = await req('POST', '/api/chat', { body: { message: 'how do I edit my banner ad' } }); check(chat2.json && /Ads in your Control Room/.test(chat2.json.reply || ''), 'chatbot: the ad-editing answer still wins for "edit my banner ad"', (chat2.json.reply || '').slice(0, 80)); const tr = (await req('GET', '/api/training', { cookie: cS })).json; const trB = (tr.items || []).find(x => x.id === 'banner-spin'); check(trB && /Gmail/.test(trB.desc) && /1,000 views/.test(trB.desc) && !/—/.test(trB.desc), 'Training lists the Banner Spin lesson', trB && trB.title); const promoJs = (await req('GET', '/assets/promo.js')).buf.toString(); check(/What is Banner Spin\?/.test(promoJs) && /X · Banner Spin/.test(promoJs), 'Promo tools carry a Banner Spin entry (objection bank + social post)'); const rel = (await req('GET', '/api/releases')).json; const draft = JSON.parse(fs.readFileSync(path.join(site, 'docs', 'release-drafts', '2026-10-20-banner-spin.json'), 'utf8')); check(draft.title && draft.body && !/—/.test(draft.body) && !(rel.notes || []).some(n => /Banner Spin/.test(n.title)), 'release note is a draft file only, not published', draft.title); // ── phone width screenshots ── const ph = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true }); await ph.addCookies(cS.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; })); const pp = await ph.newPage(); pp.on('pageerror', e => pageErrors.push('phone: ' + e.message)); await pp.goto(BASE + '/links#b' + S.id, { waitUntil: 'domcontentloaded' }); await pp.waitForSelector('#bsSel:not([hidden])', { timeout: 15000 }); await pp.waitForTimeout(800); await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-banners.png'), fullPage: true }); const overflow = await pp.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); check(overflow <= 2, 'no horizontal page scroll at phone width', overflow + ' px'); await pp.click('#bsTabs button[data-tab="code"]'); await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-code.png'), fullPage: true }); await pp.click('#bsTabs button[data-tab="stats"]'); await pp.waitForTimeout(800); await pp.screenshot({ path: path.join(SHOTS, 'builder-phone-stats.png'), fullPage: true }); await page.goto(BASE + '/links#b' + S.id, { waitUntil: 'domcontentloaded' }); await page.waitForSelector('#bsSel:not([hidden])', { timeout: 15000 }); // the Reports step moved this page off /links await page.click('#bsTabs button[data-tab="stats"]'); await page.waitForSelector('#bsStP [data-caches]', { timeout: 10000 }); await page.screenshot({ path: path.join(SHOTS, 'builder-desktop-stats.png'), fullPage: true }); check(await page.locator('#bsStP [data-caches="cachex.example"]').count() === 1 && /mobile/.test(await page.textContent('#bsStD')) && /server/.test(await page.textContent('#bsStBots')), 'builder Stats tab: CACHED placement, device breakdown, bots and servers line'); await pp.goto(BASE + '/reports', { waitUntil: 'domcontentloaded' }); await pp.waitForSelector('#bsRowsB .rw', { timeout: 15000 }); await pp.waitForTimeout(600); await pp.screenshot({ path: path.join(SHOTS, 'reports-phone.png'), fullPage: true }); const rOverflow = await pp.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); check(rOverflow <= 2, 'Reports: no horizontal page scroll at phone width', rOverflow + ' px'); await page.click('#vsw button[data-v="links"]'); await page.waitForTimeout(800); check(!(await page.isHidden('#ws')) && await page.isHidden('#bsWs'), 'switching back to Spin links works'); check(pageErrors.length === 0, 'no page errors in the builder', pageErrors.slice(0, 3).join(' | ')); } catch (e) { check(false, 'test run crashed', e.stack); } finally { try { if (browser) await browser.close(); } catch (e) {} srv.kill(); console.log(results.join('\n')); console.log('\n' + (results.length - failed) + ' passed, ' + failed + ' failed. Screenshots + server log: ' + SHOTS + '. Data dir: ' + DATA); process.exit(failed ? 1 : 0); }